id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
4,497
EditMethodDialog.cpp
rizinorg_cutter/src/dialogs/EditMethodDialog.cpp
#include "EditMethodDialog.h" #include "ui_EditMethodDialog.h" #include <QComboBox> EditMethodDialog::EditMethodDialog(bool classFixed, QWidget *parent) : QDialog(parent), ui(new Ui::EditMethodDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); if (classFixed) { classLabel = new QLabel(this); ui->formLayout->setItem(0, QFormLayout::FieldRole, new QWidgetItem(classLabel)); } else { classComboBox = new QComboBox(this); ui->formLayout->setItem(0, QFormLayout::FieldRole, new QWidgetItem(classComboBox)); for (auto &cls : Core()->getAllAnalysisClasses(true)) { classComboBox->addItem(cls, cls); } } updateVirtualUI(); validateInput(); connect(ui->virtualCheckBox, &QCheckBox::stateChanged, this, &EditMethodDialog::updateVirtualUI); connect(ui->nameEdit, &QLineEdit::textChanged, this, &EditMethodDialog::validateInput); connect(ui->realNameEdit, &QLineEdit::textChanged, this, &EditMethodDialog::updateName); connect(ui->autoRenameCheckBox, &QCheckBox::stateChanged, this, &EditMethodDialog::updateAutoRenameEnabled); } EditMethodDialog::~EditMethodDialog() {} void EditMethodDialog::on_buttonBox_accepted() {} void EditMethodDialog::on_buttonBox_rejected() { close(); } void EditMethodDialog::updateVirtualUI() { bool enabled = ui->virtualCheckBox->isChecked(); ui->vtableOffsetEdit->setEnabled(enabled); ui->vtableOffsetLabel->setEnabled(enabled); } void EditMethodDialog::validateInput() { for (auto button : ui->buttonBox->buttons()) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) { button->setEnabled(inputValid()); return; } } } void EditMethodDialog::updateName() { if (ui->autoRenameCheckBox->isChecked()) { ui->nameEdit->setText(convertRealNameToName(ui->realNameEdit->text())); } validateInput(); } void EditMethodDialog::updateAutoRenameEnabled() { ui->nameEdit->setEnabled(!ui->autoRenameCheckBox->isChecked()); if (ui->autoRenameCheckBox->isChecked()) { ui->nameEdit->setText(convertRealNameToName(ui->realNameEdit->text())); } } bool EditMethodDialog::inputValid() { if (ui->nameEdit->text().isEmpty() || ui->realNameEdit->text().isEmpty()) { return false; } // TODO: do more checks here, for example for name clashes return true; } QString EditMethodDialog::convertRealNameToName(const QString &realName) { return fromOwnedCharPtr(rz_str_sanitize_sdb_key(realName.toUtf8().constData())); } void EditMethodDialog::setClass(const QString &className) { if (classComboBox) { if (className.isEmpty()) { classComboBox->setCurrentIndex(0); return; } for (int i = 0; i < classComboBox->count(); i++) { QString cls = classComboBox->itemData(i).toString(); if (cls == className) { classComboBox->setCurrentIndex(i); break; } } } else { classLabel->setText(className); fixedClass = className; } validateInput(); } void EditMethodDialog::setMethod(const AnalysisMethodDescription &desc) { ui->nameEdit->setText(desc.name); ui->realNameEdit->setText(desc.realName); ui->addressEdit->setText(desc.addr != RVA_INVALID ? RzAddressString(desc.addr) : nullptr); if (desc.vtableOffset >= 0) { ui->virtualCheckBox->setChecked(true); ui->vtableOffsetEdit->setText(QString::number(desc.vtableOffset)); } else { ui->virtualCheckBox->setChecked(false); ui->vtableOffsetEdit->setText(nullptr); } // Check if auto-rename should be enabled bool enableAutoRename = ui->nameEdit->text().isEmpty() || ui->nameEdit->text() == convertRealNameToName(ui->realNameEdit->text()); ui->autoRenameCheckBox->setChecked(enableAutoRename); // Set focus to real name edit widget if auto-rename is enabled if (enableAutoRename) { ui->realNameEdit->setFocus(); } updateVirtualUI(); validateInput(); } QString EditMethodDialog::getClass() const { if (classComboBox) { int index = classComboBox->currentIndex(); if (index < 0) { return nullptr; } return classComboBox->itemData(index).toString(); } else { return fixedClass; } } AnalysisMethodDescription EditMethodDialog::getMethod() const { AnalysisMethodDescription ret; ret.name = ui->nameEdit->text(); ret.realName = ui->realNameEdit->text(); ret.addr = Core()->num(ui->addressEdit->text()); if (!ui->virtualCheckBox->isChecked()) { ret.vtableOffset = -1; } else { ret.vtableOffset = Core()->num(ui->vtableOffsetEdit->text()); } return ret; } bool EditMethodDialog::showDialog(const QString &title, bool classFixed, QString *className, AnalysisMethodDescription *desc, QWidget *parent) { EditMethodDialog dialog(classFixed, parent); dialog.setWindowTitle(title); dialog.setClass(*className); dialog.setMethod(*desc); int result = dialog.exec(); *className = dialog.getClass(); *desc = dialog.getMethod(); return result == QDialog::DialogCode::Accepted; } void EditMethodDialog::newMethod(QString className, const QString &meth, QWidget *parent) { AnalysisMethodDescription desc; desc.name = convertRealNameToName(meth); desc.realName = meth; desc.vtableOffset = -1; desc.addr = Core()->getOffset(); if (!showDialog(tr("Create Method"), false, &className, &desc, parent)) { return; } Core()->setAnalysisMethod(className, desc); } void EditMethodDialog::editMethod(const QString &className, const QString &meth, QWidget *parent) { AnalysisMethodDescription desc; if (!Core()->getAnalysisMethod(className, meth, &desc)) { return; } QString classNameCopy = className; if (!showDialog(tr("Edit Method"), false, &classNameCopy, &desc, parent)) { return; } if (desc.name != meth) { Core()->renameAnalysisMethod(className, meth, desc.name); } Core()->setAnalysisMethod(className, desc); }
6,314
C++
.cpp
181
29.254144
97
0.67743
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,498
FlagDialog.cpp
rizinorg_cutter/src/dialogs/FlagDialog.cpp
#include "FlagDialog.h" #include "ui_FlagDialog.h" #include <QIntValidator> #include "core/Cutter.h" FlagDialog::FlagDialog(RVA offset, QWidget *parent) : QDialog(parent), ui(new Ui::FlagDialog), offset(offset), flagName(""), flagOffset(RVA_INVALID) { // Setup UI ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); RzFlagItem *flag = rz_flag_get_i(Core()->core()->flags, offset); if (flag) { flagName = QString(flag->name); flagOffset = flag->offset; } auto size_validator = new QIntValidator(ui->sizeEdit); size_validator->setBottom(1); ui->sizeEdit->setValidator(size_validator); if (flag) { ui->nameEdit->setText(flag->name); ui->labelAction->setText(tr("Edit flag at %1").arg(RzAddressString(offset))); } else { ui->labelAction->setText(tr("Add flag at %1").arg(RzAddressString(offset))); } // Connect slots connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &FlagDialog::buttonBoxAccepted); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &FlagDialog::buttonBoxRejected); } FlagDialog::~FlagDialog() {} void FlagDialog::buttonBoxAccepted() { RVA size = ui->sizeEdit->text().toULongLong(); QString name = ui->nameEdit->text(); if (name.isEmpty()) { if (flagOffset != RVA_INVALID) { // Empty name and flag exists -> delete the flag Core()->delFlag(flagOffset); } else { // Flag was not existing and we gave an empty name, do nothing } } else { if (flagOffset != RVA_INVALID) { // Name provided and flag exists -> rename the flag Core()->renameFlag(flagName, name); } else { // Name provided and flag does not exist -> create the flag Core()->addFlag(offset, name, size); } } close(); this->setResult(QDialog::Accepted); } void FlagDialog::buttonBoxRejected() { close(); this->setResult(QDialog::Rejected); }
2,044
C++
.cpp
57
29.947368
100
0.642244
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,499
HexdumpRangeDialog.cpp
rizinorg_cutter/src/dialogs/HexdumpRangeDialog.cpp
#include "HexdumpRangeDialog.h" #include "ui_HexdumpRangeDialog.h" #include <QRegularExpressionValidator> #include <QPushButton> #include <cstdint> #include "core/Cutter.h" HexdumpRangeDialog::HexdumpRangeDialog(QWidget *parent, bool allowEmpty) : QDialog(parent), ui(new Ui::HexdumpRangeDialog), allowEmpty(allowEmpty) { ui->setupUi(this); QRegularExpressionValidator *v = new QRegularExpressionValidator(QRegularExpression("(?:0[xX])?[0-9a-fA-F]+"), this); ui->lengthLineEdit->setValidator(v); ui->startAddressLineEdit->setValidator(v); ui->endAddressLineEdit->setValidator(v); // subscribe to a text change slot connect(ui->startAddressLineEdit, &QLineEdit::textEdited, this, &HexdumpRangeDialog::textEdited); connect(ui->endAddressLineEdit, &QLineEdit::textEdited, this, &HexdumpRangeDialog::textEdited); connect(ui->lengthLineEdit, &QLineEdit::textEdited, this, &HexdumpRangeDialog::textEdited); connect(ui->endAddressRadioButton, &QRadioButton::clicked, this, &HexdumpRangeDialog::on_radioButtonClicked); connect(ui->lengthRadioButton, &QRadioButton::clicked, this, &HexdumpRangeDialog::on_radioButtonClicked); } HexdumpRangeDialog::~HexdumpRangeDialog() { delete ui; } bool HexdumpRangeDialog::empty() { return emptyRange; } unsigned long long HexdumpRangeDialog::getStartAddress() const { return startAddress; } unsigned long long HexdumpRangeDialog::getEndAddress() const { return endAddress; } bool HexdumpRangeDialog::getEndAddressRadioButtonChecked() const { return ui->endAddressRadioButton->isChecked(); } bool HexdumpRangeDialog::getLengthRadioButtonChecked() const { return ui->lengthRadioButton->isChecked(); } void HexdumpRangeDialog::setStartAddress(ut64 start) { ui->startAddressLineEdit->setText(QString("0x%1").arg(start, 0, 16)); } void HexdumpRangeDialog::open(ut64 start) { setStartAddress(start); setModal(false); show(); activateWindow(); raise(); } bool HexdumpRangeDialog::validate() { bool warningVisibile = false; startAddress = Core()->math(ui->startAddressLineEdit->text()); endAddress = 0; ut64 length = 0; emptyRange = true; if (ui->endAddressRadioButton->isChecked()) { endAddress = Core()->math(ui->endAddressLineEdit->text()); if (endAddress > startAddress) { length = endAddress - startAddress; ui->lengthLineEdit->setText(QString("0x%1").arg(length, 0, 16)); this->endAddress = endAddress - 1; emptyRange = false; } else if (endAddress == startAddress) { ui->lengthLineEdit->setText("0"); return allowEmpty; } else { ui->lengthLineEdit->setText("Invalid"); return false; } } else { // we edited the length, so update the end address to be start address + length length = Core()->math(ui->lengthLineEdit->text()); if (length == 0) { ui->endAddressLineEdit->setText("Empty"); return allowEmpty; } else if (UINT64_MAX - startAddress < length - 1) { ui->endAddressLineEdit->setText("Invalid"); return false; } else { endAddress = startAddress + length - 1; emptyRange = false; if (endAddress == UINT64_MAX) { ui->endAddressLineEdit->setText(QString("2^64")); } else { ui->endAddressLineEdit->setText(QString("0x%1").arg(endAddress + 1, 0, 16)); } } } // Warn the user for potentially heavy operation if (length > 0x25000) { warningVisibile = true; } ui->selectionWarningLabel->setVisible(warningVisibile); return true; } void HexdumpRangeDialog::textEdited() { bool valid = validate(); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid); } void HexdumpRangeDialog::on_radioButtonClicked(bool checked) { if (sender() == ui->endAddressRadioButton && checked == true) { ui->lengthLineEdit->setEnabled(false); ui->endAddressLineEdit->setEnabled(true); ui->endAddressLineEdit->setFocus(); } else if (sender() == ui->lengthRadioButton && checked == true) { ui->lengthLineEdit->setEnabled(true); ui->endAddressLineEdit->setEnabled(false); ui->lengthLineEdit->setFocus(); } }
4,428
C++
.cpp
125
29.528
99
0.676697
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,500
AsyncTaskDialog.cpp
rizinorg_cutter/src/dialogs/AsyncTaskDialog.cpp
#include "AsyncTaskDialog.h" #include "common/AsyncTask.h" #include "ui_AsyncTaskDialog.h" AsyncTaskDialog::AsyncTaskDialog(AsyncTask::Ptr task, QWidget *parent) : QDialog(parent), ui(new Ui::AsyncTaskDialog), task(task) { ui->setupUi(this); QString title = task->getTitle(); if (!title.isNull()) { setWindowTitle(title); } connect(task.data(), &AsyncTask::logChanged, this, &AsyncTaskDialog::updateLog); connect(task.data(), &AsyncTask::finished, this, [this]() { close(); }); updateLog(task->getLog()); connect(&timer, &QTimer::timeout, this, &AsyncTaskDialog::updateProgressTimer); timer.setInterval(1000); timer.setSingleShot(false); timer.start(); updateProgressTimer(); } AsyncTaskDialog::~AsyncTaskDialog() {} void AsyncTaskDialog::updateLog(const QString &log) { ui->logTextEdit->setPlainText(log); } void AsyncTaskDialog::updateProgressTimer() { int secondsElapsed = (task->getElapsedTime() + 500) / 1000; int minutesElapsed = secondsElapsed / 60; int hoursElapsed = minutesElapsed / 60; QString label = tr("Running for") + " "; if (hoursElapsed) { label += tr("%n hour", "%n hours", hoursElapsed); label += " "; } if (minutesElapsed) { label += tr("%n minute", "%n minutes", minutesElapsed % 60); label += " "; } label += tr("%n seconds", "%n second", secondsElapsed % 60); ui->timeLabel->setText(label); } void AsyncTaskDialog::closeEvent(QCloseEvent *event) { if (interruptOnClose) { task->interrupt(); task->wait(); } QWidget::closeEvent(event); } void AsyncTaskDialog::reject() { task->interrupt(); }
1,698
C++
.cpp
54
27.055556
84
0.666053
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,501
EditStringDialog.cpp
rizinorg_cutter/src/dialogs/EditStringDialog.cpp
#include "EditStringDialog.h" #include "ui_EditStringDialog.h" EditStringDialog::EditStringDialog(QWidget *parent) : QDialog(parent), ui(new Ui::EditStringDialog {}) { ui->setupUi(this); ui->spinBox_size->setMinimum(0); ui->lineEdit_address->setMinimumWidth(150); ui->spinBox_size->setFocus(); ui->comboBox_type->addItems({ "Auto", "ASCII/Latin1", "UTF-8" }); connect(ui->checkBox_autoSize, &QCheckBox::toggled, ui->spinBox_size, &QSpinBox::setDisabled); } EditStringDialog::~EditStringDialog() {} void EditStringDialog::setStringStartAddress(uint64_t address) { ui->lineEdit_address->setText(QString::number(address, 16)); } bool EditStringDialog::getStringStartAddress(uint64_t &returnValue) const { bool status = false; returnValue = ui->lineEdit_address->text().toLongLong(&status, 16); return status; } void EditStringDialog::setStringSizeValue(uint32_t size) { ui->spinBox_size->setValue(size); } int EditStringDialog::getStringSizeValue() const { if (ui->checkBox_autoSize->isChecked()) { return -1; } return ui->spinBox_size->value(); } EditStringDialog::StringType EditStringDialog::getStringType() const { const int indexVal = ui->comboBox_type->currentIndex(); switch (indexVal) { case 0: { return EditStringDialog::StringType::Auto; } case 1: { return EditStringDialog::StringType::ASCII_LATIN1; } case 2: { return EditStringDialog::StringType::UTF8; } default: return EditStringDialog::StringType::Auto; } }
1,570
C++
.cpp
51
26.862745
98
0.713245
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,502
GlobalVariableDialog.cpp
rizinorg_cutter/src/dialogs/GlobalVariableDialog.cpp
#include "GlobalVariableDialog.h" #include "ui_GlobalVariableDialog.h" #include <QIntValidator> #include "core/Cutter.h" GlobalVariableDialog::GlobalVariableDialog(RVA offset, QWidget *parent) : QDialog(parent), ui(new Ui::GlobalVariableDialog), offset(offset), globalVariableName(""), globalVariableOffset(RVA_INVALID) { // Setup UI ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); RzAnalysisVarGlobal *globalVariable = rz_analysis_var_global_get_byaddr_at(Core()->core()->analysis, offset); if (globalVariable) { globalVariableName = QString(globalVariable->name); globalVariableOffset = globalVariable->addr; } if (globalVariable) { ui->nameEdit->setText(globalVariable->name); QString globalVarType = Core()->getGlobalVariableType(globalVariable->name); ui->typeEdit->setText(globalVarType); ui->labelAction->setText(tr("Edit global variable at %1").arg(RzAddressString(offset))); } else { ui->labelAction->setText(tr("Add global variable at %1").arg(RzAddressString(offset))); } // Connect slots connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &GlobalVariableDialog::buttonBoxAccepted); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &GlobalVariableDialog::buttonBoxRejected); } GlobalVariableDialog::~GlobalVariableDialog() {} void GlobalVariableDialog::buttonBoxAccepted() { QString name = ui->nameEdit->text(); QString typ = ui->typeEdit->text(); if (name.isEmpty()) { if (globalVariableOffset != RVA_INVALID) { // Empty name and global variable exists -> delete the global variable Core()->delGlobalVariable(globalVariableOffset); } else { // GlobalVariable was not existing and we gave an empty name, do nothing } } else { if (globalVariableOffset != RVA_INVALID) { // Name provided and global variable exists -> rename the global variable Core()->modifyGlobalVariable(globalVariableOffset, name, typ); } else { // Name provided and global variable does not exist -> create the global variable Core()->addGlobalVariable(offset, name, typ); } } close(); this->setResult(QDialog::Accepted); } void GlobalVariableDialog::buttonBoxRejected() { close(); this->setResult(QDialog::Rejected); }
2,500
C++
.cpp
63
33.222222
96
0.682997
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,503
WriteCommandsDialogs.cpp
rizinorg_cutter/src/dialogs/WriteCommandsDialogs.cpp
#include "WriteCommandsDialogs.h" #include "ui_Base64EnDecodedWriteDialog.h" #include "ui_IncrementDecrementDialog.h" #include "ui_DuplicateFromOffsetDialog.h" #include "Cutter.h" #include <cmath> #include <QFontDatabase> Base64EnDecodedWriteDialog::Base64EnDecodedWriteDialog(QWidget *parent) : QDialog(parent), ui(new Ui::Base64EnDecodedWriteDialog) { ui->setupUi(this); ui->decodeRB->click(); } Base64EnDecodedWriteDialog::Mode Base64EnDecodedWriteDialog::getMode() const { return ui->decodeRB->isChecked() ? Decode : Encode; } QByteArray Base64EnDecodedWriteDialog::getData() const { return ui->base64LineEdit->text().toUtf8(); } IncrementDecrementDialog::IncrementDecrementDialog(QWidget *parent) : QDialog(parent), ui(new Ui::IncrementDecrementDialog) { ui->setupUi(this); ui->incrementRB->click(); ui->nBytesCB->addItems(QStringList() << tr("Byte") << tr("Word") << tr("Dword") << tr("Qword")); ui->valueLE->setValidator( new QRegularExpressionValidator(QRegularExpression("[0-9a-fA-Fx]{1,18}"), ui->valueLE)); } IncrementDecrementDialog::Mode IncrementDecrementDialog::getMode() const { return ui->incrementRB->isChecked() ? Increase : Decrease; } uint8_t IncrementDecrementDialog::getNBytes() const { // Shift left to keep index powered by two // This is used to create the w1, w2, w4 and w8 commands based on the selected index. return static_cast<uint8_t>(1 << ui->nBytesCB->currentIndex()); } uint64_t IncrementDecrementDialog::getValue() const { return Core()->math(ui->valueLE->text()); } DuplicateFromOffsetDialog::DuplicateFromOffsetDialog(QWidget *parent) : QDialog(parent), ui(new Ui::DuplicateFromOffsetDialog) { ui->setupUi(this); ui->bytesLabel->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); ui->offsetLE->setValidator(new QRegularExpressionValidator( QRegularExpression("[0-9a-fA-Fx]{1,18}"), ui->offsetLE)); connect(ui->offsetLE, &QLineEdit::textChanged, this, &DuplicateFromOffsetDialog::refresh); connect(ui->nBytesSB, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &DuplicateFromOffsetDialog::refresh); } RVA DuplicateFromOffsetDialog::getOffset() const { return Core()->math(ui->offsetLE->text()); } size_t DuplicateFromOffsetDialog::getNBytes() const { return static_cast<size_t>(ui->nBytesSB->value()); } void DuplicateFromOffsetDialog::refresh() { QSignalBlocker sb(Core()); RzCoreLocked core(Core()); auto buf = Core()->ioRead(getOffset(), (int)getNBytes()); // Add space every two characters for word wrap in hex sequence QRegularExpression re { "(.{2})" }; auto bytes = QString(buf).replace(re, "\\1 ").trimmed(); ui->bytesLabel->setText(bytes); }
2,790
C++
.cpp
73
34.876712
100
0.735011
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,504
LayoutManager.cpp
rizinorg_cutter/src/dialogs/LayoutManager.cpp
#include "LayoutManager.h" #include "ui_LayoutManager.h" #include <QIntValidator> #include <QInputDialog> using namespace Cutter; LayoutManager::LayoutManager(QMap<QString, Cutter::CutterLayout> &layouts, QWidget *parent) : QDialog(parent), ui(new Ui::LayoutManager), layouts(layouts) { ui->setupUi(this); connect(ui->renameButton, &QPushButton::clicked, this, &LayoutManager::renameCurrentLayout); connect(ui->deleteButton, &QPushButton::clicked, this, &LayoutManager::deleteLayout); connect(ui->layoutSelector, &QComboBox::currentTextChanged, this, &LayoutManager::updateButtons); refreshNameList(); } LayoutManager::~LayoutManager() {} void LayoutManager::refreshNameList(QString selection) { ui->layoutSelector->clear(); for (auto it = layouts.begin(), end = layouts.end(); it != end; ++it) { if (!Cutter::isBuiltinLayoutName(it.key())) { ui->layoutSelector->addItem(it.key()); } } if (!selection.isEmpty()) { ui->layoutSelector->setCurrentText(selection); } updateButtons(); } void LayoutManager::renameCurrentLayout() { QString current = ui->layoutSelector->currentText(); if (layouts.contains(current)) { QString newName; while (newName.isEmpty() || isBuiltinLayoutName(newName) || layouts.contains(newName)) { if (!newName.isEmpty()) { QMessageBox::warning(this, tr("Rename layout error"), tr("'%1' is already used.").arg(newName)); } newName = QInputDialog::getText(this, tr("Save layout"), tr("Enter name"), QLineEdit::Normal, current); if (newName.isEmpty()) { return; } } auto layout = layouts.take(current); layouts.insert(newName, layout); refreshNameList(newName); } } void LayoutManager::deleteLayout() { auto selected = ui->layoutSelector->currentText(); auto answer = QMessageBox::question(this, tr("Delete"), tr("Do you want to delete '%1'").arg(selected)); if (answer == QMessageBox::Yes) { layouts.remove(selected); refreshNameList(); } } void LayoutManager::updateButtons() { bool hasSelection = !ui->layoutSelector->currentText().isEmpty(); ui->renameButton->setEnabled(hasSelection); ui->deleteButton->setEnabled(hasSelection); }
2,474
C++
.cpp
66
30.121212
96
0.637234
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,505
NativeDebugDialog.cpp
rizinorg_cutter/src/dialogs/NativeDebugDialog.cpp
#include "NativeDebugDialog.h" #include "ui_NativeDebugDialog.h" #include <QMessageBox> NativeDebugDialog::NativeDebugDialog(QWidget *parent) : QDialog(parent), ui(new Ui::NativeDebugDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); } NativeDebugDialog::~NativeDebugDialog() {} QString NativeDebugDialog::getArgs() const { return ui->argEdit->toPlainText(); } void NativeDebugDialog::setArgs(const QString &args) { ui->argEdit->setPlainText(args); ui->argEdit->selectAll(); }
552
C++
.cpp
19
26.526316
71
0.765152
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,506
AttachProcDialog.cpp
rizinorg_cutter/src/dialogs/AttachProcDialog.cpp
#include "core/MainWindow.h" #include "core/Cutter.h" #include "AttachProcDialog.h" #include "ui_AttachProcDialog.h" #include "common/Helpers.h" #include <QScrollBar> // ------------ // ProcessModel // ------------ ProcessModel::ProcessModel(QObject *parent) : QAbstractListModel(parent) { updateData(); } void ProcessModel::updateData() { beginResetModel(); processes = Core()->getAllProcesses(); endResetModel(); } int ProcessModel::rowCount(const QModelIndex &) const { return processes.count(); } int ProcessModel::columnCount(const QModelIndex &) const { return ProcessModel::ColumnCount; } QVariant ProcessModel::data(const QModelIndex &index, int role) const { if (index.row() >= processes.count()) return QVariant(); const ProcessDescription &proc = processes.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case PidColumn: return proc.pid; case UidColumn: return proc.uid; case StatusColumn: return proc.status; case PathColumn: return proc.path; default: return QVariant(); } case ProcDescriptionRole: return QVariant::fromValue(proc); default: return QVariant(); } } QVariant ProcessModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case PidColumn: return tr("PID"); case UidColumn: return tr("UID"); case StatusColumn: return tr("Status"); case PathColumn: return tr("Path"); default: return QVariant(); } default: return QVariant(); } } bool ProcessModel::lessThan(const ProcessDescription &leftProc, const ProcessDescription &rightProc, int column) { switch (column) { case ProcessModel::PidColumn: return leftProc.pid < rightProc.pid; case ProcessModel::UidColumn: return leftProc.uid < rightProc.uid; case ProcessModel::StatusColumn: return leftProc.status < rightProc.status; case ProcessModel::PathColumn: return leftProc.path < rightProc.path; default: break; } return leftProc.pid < rightProc.pid; } // ------------------------------ // ProcessBeingAnalysedProxyModel // ------------------------------ ProcessBeingAnalysedProxyModel::ProcessBeingAnalysedProxyModel(ProcessModel *sourceModel, QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(sourceModel); // @SEE: Should there be a getFilename() in Core()? Not the first time I use this processBeingAnalysedFilename = processPathToFilename(Core()->getConfig("file.path")); } QString ProcessBeingAnalysedProxyModel::processPathToFilename(const QString &path) const { // removes the arguments and gets filename from the process path return path.section(QLatin1Char(' '), 0, 0).section(QLatin1Char('/'), -1); } bool ProcessBeingAnalysedProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); ProcessDescription item = index.data(ProcessModel::ProcDescriptionRole).value<ProcessDescription>(); QString procFilename = processPathToFilename(item.path); return procFilename == processBeingAnalysedFilename; } bool ProcessBeingAnalysedProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { ProcessDescription leftProc = left.data(ProcessModel::ProcDescriptionRole).value<ProcessDescription>(); ProcessDescription rightProc = right.data(ProcessModel::ProcDescriptionRole).value<ProcessDescription>(); return ProcessModel::lessThan(leftProc, rightProc, left.column()); } // ----------------- // ProcessProxyModel // ----------------- ProcessProxyModel::ProcessProxyModel(ProcessModel *sourceModel, QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(sourceModel); } bool ProcessProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); ProcessDescription item = index.data(ProcessModel::ProcDescriptionRole).value<ProcessDescription>(); return qhelpers::filterStringContains(item.path, this); } bool ProcessProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { ProcessDescription leftProc = left.data(ProcessModel::ProcDescriptionRole).value<ProcessDescription>(); ProcessDescription rightProc = right.data(ProcessModel::ProcDescriptionRole).value<ProcessDescription>(); return ProcessModel::lessThan(leftProc, rightProc, left.column()); } // ---------------- // AttachProcDialog // ---------------- AttachProcDialog::AttachProcDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AttachProcDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); processModel = new ProcessModel(this); processProxyModel = new ProcessProxyModel(processModel, this); processBeingAnalyzedProxyModel = new ProcessBeingAnalysedProxyModel(processModel, this); // View of all processes auto allView = ui->allProcView; allView->setModel(processProxyModel); allView->sortByColumn(ProcessModel::PidColumn, Qt::DescendingOrder); // View of the processes with the same name as the one being analyzed auto smallView = ui->procBeingAnalyzedView; smallView->setModel(processBeingAnalyzedProxyModel); smallView->setCurrentIndex(smallView->model()->index(0, 0)); // To get the 'FocusIn' events allView->installEventFilter(this); smallView->installEventFilter(this); // focus on filter line ui->filterLineEdit->setFocus(); connect(ui->filterLineEdit, &QLineEdit::textChanged, processProxyModel, &QSortFilterProxyModel::setFilterWildcard); // Update the processes every 'updateIntervalMs' seconds timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &AttachProcDialog::updateModelData); timer->start(updateIntervalMs); } AttachProcDialog::~AttachProcDialog() { timer->stop(); delete timer; delete processBeingAnalyzedProxyModel; delete processProxyModel; delete processModel; } void AttachProcDialog::updateModelData() { auto allView = ui->allProcView; auto smallView = ui->procBeingAnalyzedView; // Save the old selection and scroll position so that we can update and // model and then restore it. bool allViewHadSelection = allView->selectionModel()->hasSelection(); bool smallViewHadSelection = smallView->selectionModel()->hasSelection(); int allViewPrevScrollPos = 0; int smallViewPrevScrollPos = 0; int allViewPrevPID = 0; int smallViewPrevPID = 0; if (allViewHadSelection) { allViewPrevScrollPos = allView->verticalScrollBar()->value(); allViewPrevPID = allView->selectionModel() ->currentIndex() .data(ProcessModel::ProcDescriptionRole) .value<ProcessDescription>() .pid; } if (smallViewHadSelection) { smallViewPrevScrollPos = smallView->verticalScrollBar()->value(); smallViewPrevPID = smallView->selectionModel() ->currentIndex() .data(ProcessModel::ProcDescriptionRole) .value<ProcessDescription>() .pid; } // Let the model update processModel->updateData(); // Restore the selection and scroll position if (allViewHadSelection) { QModelIndexList idx = allView->model()->match(allView->model()->index(0, 0), Qt::DisplayRole, QVariant::fromValue(allViewPrevPID)); if (!idx.isEmpty()) { allView->setCurrentIndex(idx.first()); allView->verticalScrollBar()->setValue(allViewPrevScrollPos); } } if (smallViewHadSelection) { QModelIndexList idx = smallView->model()->match(smallView->model()->index(0, 0), Qt::DisplayRole, QVariant::fromValue(smallViewPrevPID)); if (!idx.isEmpty()) { smallView->setCurrentIndex(idx.first()); smallView->verticalScrollBar()->setValue(smallViewPrevScrollPos); } } // Init selection if nothing was ever selected yet, and a new process with the same name // as the one being analysed was launched. if (!allView->selectionModel()->hasSelection() && !smallView->selectionModel()->hasSelection()) { smallView->setCurrentIndex(smallView->model()->index(0, 0)); } } void AttachProcDialog::on_buttonBox_accepted() {} void AttachProcDialog::on_buttonBox_rejected() { close(); } bool AttachProcDialog::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::FocusIn) { if (obj == ui->allProcView) { ui->procBeingAnalyzedView->selectionModel()->clearSelection(); wasAllProcViewLastPressed = true; return true; } else if (obj == ui->procBeingAnalyzedView) { ui->allProcView->selectionModel()->clearSelection(); wasAllProcViewLastPressed = false; return true; } } return false; } int AttachProcDialog::getPID() { int pid; // Here we need to know which table was selected last to get the proper PID if (wasAllProcViewLastPressed && ui->allProcView->selectionModel()->hasSelection()) { pid = ui->allProcView->selectionModel() ->currentIndex() .data(ProcessModel::ProcDescriptionRole) .value<ProcessDescription>() .pid; } else if (!wasAllProcViewLastPressed && ui->procBeingAnalyzedView->selectionModel()->hasSelection()) { pid = ui->procBeingAnalyzedView->selectionModel() ->currentIndex() .data(ProcessModel::ProcDescriptionRole) .value<ProcessDescription>() .pid; } else { // Error attaching. No process selected! Happens when you press ENTER but // there was no process with the same name as the one being analyzed. pid = -1; } return pid; } void AttachProcDialog::on_allProcView_doubleClicked(const QModelIndex &index) { Q_UNUSED(index); accept(); } void AttachProcDialog::on_procBeingAnalyzedView_doubleClicked(const QModelIndex &index) { Q_UNUSED(index); accept(); }
11,016
C++
.cpp
293
30.150171
100
0.656672
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,507
WelcomeDialog.cpp
rizinorg_cutter/src/dialogs/WelcomeDialog.cpp
#include "core/MainWindow.h" #include "CutterConfig.h" #include "common/Helpers.h" #include "WelcomeDialog.h" #include "AboutDialog.h" #include "ui_WelcomeDialog.h" /** * @brief Constructs a WelcomeDialog object * @param parent */ WelcomeDialog::WelcomeDialog(QWidget *parent) : QDialog(parent), ui(new Ui::WelcomeDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); ui->logoSvgWidget->load(Config()->getLogoFile()); ui->versionLabel->setText("<font color='#a4a9b2'>" + tr("Version ") + CUTTER_VERSION_FULL + "</font>"); ui->themeComboBox->setCurrentIndex(Config()->getInterfaceTheme()); QSignalBlocker s(ui->updatesCheckBox); ui->updatesCheckBox->setChecked(Config()->getAutoUpdateEnabled()); QStringList langs = Config()->getAvailableTranslations(); ui->languageComboBox->addItems(langs); QString curr = Config()->getCurrLocale().nativeLanguageName(); if (!langs.contains(curr)) { curr = "English"; } ui->languageComboBox->setCurrentText(curr); connect(ui->languageComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &WelcomeDialog::onLanguageComboBox_currentIndexChanged); Config()->adjustColorThemeDarkness(); } /** * @brief Destroys the WelcomeDialog */ WelcomeDialog::~WelcomeDialog() { delete ui; } /** * @brief change Cutter's QT Theme as selected by the user * @param index - a Slot being called after theme's value changes its index */ void WelcomeDialog::on_themeComboBox_currentIndexChanged(int index) { Config()->setInterfaceTheme(index); // make sure that Cutter's logo changes its color according to the selected theme ui->logoSvgWidget->load(Config()->getLogoFile()); } /** * @brief change Cutter's interface language as selected by the user * @param index - a Slot being called after language combo box value changes its index */ void WelcomeDialog::onLanguageComboBox_currentIndexChanged(int index) { QString language = ui->languageComboBox->itemText(index); Config()->setLocaleByName(language); QMessageBox mb; mb.setWindowTitle(tr("Language settings")); mb.setText(tr("Language will be changed after next application start.")); mb.setIcon(QMessageBox::Information); mb.setStandardButtons(QMessageBox::Ok); mb.exec(); } /** * @brief show Cutter's About dialog */ void WelcomeDialog::on_checkUpdateButton_clicked() { AboutDialog *a = new AboutDialog(this); a->setAttribute(Qt::WA_DeleteOnClose); a->open(); } /** * @brief accept user preferences, close the window and continue Cutter's execution */ void WelcomeDialog::on_continueButton_clicked() { accept(); } void WelcomeDialog::on_updatesCheckBox_stateChanged(int) { Config()->setAutoUpdateEnabled(!Config()->getAutoUpdateEnabled()); }
2,906
C++
.cpp
84
30.988095
93
0.725783
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,508
BreakpointsDialog.cpp
rizinorg_cutter/src/dialogs/BreakpointsDialog.cpp
#include "BreakpointsDialog.h" #include "ui_BreakpointsDialog.h" #include "Cutter.h" #include "Helpers.h" #include <QPushButton> #include <QCompleter> #include <QCheckBox> BreakpointsDialog::BreakpointsDialog(bool editMode, QWidget *parent) : QDialog(parent), ui(new Ui::BreakpointsDialog), editMode(editMode) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); connect(ui->breakpointPosition, &QLineEdit::textChanged, this, &BreakpointsDialog::refreshOkButton); refreshOkButton(); if (editMode) { setWindowTitle(tr("Edit breakpoint")); } else { setWindowTitle(tr("New breakpoint")); } struct { QString label; QString tooltip; BreakpointDescription::PositionType type; } positionTypes[] = { { tr("Address"), tr("Address or expression calculated when creating breakpoint"), BreakpointDescription::Address }, { tr("Named"), tr("Expression - stored as expression"), BreakpointDescription::Named }, { tr("Module offset"), tr("Offset relative to module"), BreakpointDescription::Module }, }; int index = 0; for (auto &item : positionTypes) { ui->positionType->addItem(item.label, item.type); ui->positionType->setItemData(index, item.tooltip, Qt::ToolTipRole); index++; } connect(ui->positionType, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &BreakpointsDialog::onTypeChanged); onTypeChanged(); auto modules = Core()->getMemoryMap(); QSet<QString> moduleNames; for (const auto &module : modules) { moduleNames.insert(module.fileName); } for (const auto &module : moduleNames) { ui->moduleName->addItem(module); } ui->moduleName->setCurrentText(""); // Suggest completion when user tries to enter file name not only full path ui->moduleName->completer()->setFilterMode(Qt::MatchContains); ui->breakpointCondition->setCompleter(nullptr); // Don't use examples for completing configureCheckboxRestrictions(); } BreakpointsDialog::BreakpointsDialog(const BreakpointDescription &breakpoint, QWidget *parent) : BreakpointsDialog(true, parent) { switch (breakpoint.type) { case BreakpointDescription::Address: ui->breakpointPosition->setText(RzAddressString(breakpoint.addr)); break; case BreakpointDescription::Named: ui->breakpointPosition->setText(breakpoint.positionExpression); break; case BreakpointDescription::Module: ui->breakpointPosition->setText(QString::number(breakpoint.moduleDelta)); ui->moduleName->setCurrentText(breakpoint.positionExpression); break; } for (int i = 0; i < ui->positionType->count(); i++) { if (ui->positionType->itemData(i) == breakpoint.type) { ui->positionType->setCurrentIndex(i); } } ui->breakpointCommand->setPlainText(breakpoint.command); ui->breakpointCondition->setEditText(breakpoint.condition); if (breakpoint.hw) { ui->radioHardware->setChecked(true); ui->hwRead->setChecked(breakpoint.permission & RZ_PERM_R); ui->hwWrite->setChecked(breakpoint.permission & RZ_PERM_W); ui->hwExecute->setChecked(breakpoint.permission & RZ_PERM_X); ui->breakpointSize->setCurrentText(QString::number(breakpoint.size)); } else { ui->radioSoftware->setChecked(true); } ui->checkTrace->setChecked(breakpoint.trace); ui->checkEnabled->setChecked(breakpoint.enabled); refreshOkButton(); } BreakpointsDialog::BreakpointsDialog(RVA address, QWidget *parent) : BreakpointsDialog(false, parent) { if (address != RVA_INVALID) { ui->breakpointPosition->setText(RzAddressString(address)); } refreshOkButton(); } BreakpointsDialog::~BreakpointsDialog() {} BreakpointDescription BreakpointsDialog::getDescription() { BreakpointDescription breakpoint; auto positionType = ui->positionType->currentData().value<BreakpointDescription::PositionType>(); switch (positionType) { case BreakpointDescription::Address: breakpoint.addr = Core()->math(ui->breakpointPosition->text()); break; case BreakpointDescription::Named: breakpoint.positionExpression = ui->breakpointPosition->text().trimmed(); break; case BreakpointDescription::Module: breakpoint.moduleDelta = static_cast<int64_t>(Core()->math(ui->breakpointPosition->text())); breakpoint.positionExpression = ui->moduleName->currentText().trimmed(); break; } breakpoint.type = positionType; breakpoint.size = Core()->num(ui->breakpointSize->currentText()); breakpoint.condition = ui->breakpointCondition->currentText().trimmed(); breakpoint.command = ui->breakpointCommand->toPlainText().trimmed(); if (ui->radioHardware->isChecked()) { breakpoint.hw = true; breakpoint.permission = getHwPermissions(); } else { breakpoint.hw = false; } breakpoint.trace = ui->checkTrace->isChecked(); breakpoint.enabled = ui->checkEnabled->isChecked(); return breakpoint; } void BreakpointsDialog::createNewBreakpoint(RVA address, QWidget *parent) { BreakpointsDialog editDialog(address, parent); if (editDialog.exec() == QDialog::Accepted) { Core()->addBreakpoint(editDialog.getDescription()); } } void BreakpointsDialog::editBreakpoint(const BreakpointDescription &breakpoint, QWidget *parent) { BreakpointsDialog editDialog(breakpoint, parent); if (editDialog.exec() == QDialog::Accepted) { Core()->updateBreakpoint(breakpoint.index, editDialog.getDescription()); } } void BreakpointsDialog::refreshOkButton() { auto button = ui->buttonBox->button(QDialogButtonBox::StandardButton::Ok); button->setDisabled(ui->breakpointPosition->text().isEmpty()); } void BreakpointsDialog::onTypeChanged() { bool moduleEnabled = ui->positionType->currentData() == QVariant(BreakpointDescription::Module); ui->moduleLabel->setEnabled(moduleEnabled); ui->moduleName->setEnabled(moduleEnabled); ui->breakpointPosition->setPlaceholderText( ui->positionType->currentData(Qt::ToolTipRole).toString()); } void BreakpointsDialog::configureCheckboxRestrictions() { auto atLeastOneChecked = [this]() { if (this->getHwPermissions() == 0) { this->ui->hwExecute->setChecked(true); } }; auto rwRule = [this, atLeastOneChecked](bool checked) { if (checked) { this->ui->hwExecute->setChecked(false); } else { atLeastOneChecked(); } }; connect(ui->hwRead, &QCheckBox::toggled, this, rwRule); connect(ui->hwWrite, &QCheckBox::toggled, this, rwRule); auto execRule = [this, atLeastOneChecked](bool checked) { if (checked) { this->ui->hwRead->setChecked(false); this->ui->hwWrite->setChecked(false); } else { atLeastOneChecked(); } }; connect(ui->hwExecute, &QCheckBox::toggled, this, execRule); } int BreakpointsDialog::getHwPermissions() { int result = 0; if (ui->hwRead->isChecked()) { result |= RZ_PERM_R; } if (ui->hwWrite->isChecked()) { result |= RZ_PERM_W; } if (ui->hwExecute->isChecked()) { result |= RZ_PERM_X; } return result; }
7,484
C++
.cpp
197
32.091371
100
0.687397
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,509
RemoteDebugDialog.cpp
rizinorg_cutter/src/dialogs/RemoteDebugDialog.cpp
#include "RemoteDebugDialog.h" #include "ui_RemoteDebugDialog.h" #include <QHostAddress> #include <QFileInfo> #include <QMessageBox> #include <QSettings> enum DbgBackendType { GDB = 0, WINDBG = 1 }; struct DbgBackend { DbgBackendType type; QString name; QString prefix; }; static const QList<DbgBackend> dbgBackends = { { GDB, "GDB", "gdb://" }, { WINDBG, "WinKd - Pipe", "winkd://" } }; RemoteDebugDialog::RemoteDebugDialog(QWidget *parent) : QDialog(parent), ui(new Ui::RemoteDebugDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); // Fill in debugger Combo ui->debuggerCombo->clear(); for (auto &backend : dbgBackends) { ui->debuggerCombo->addItem(backend.name); } // Fill ip list fillRecentIpList(); ui->ipEdit->setFocus(); // Connect statements for right click action and itemClicked action ui->recentsIpListWidget->addAction(ui->actionRemoveItem); ui->recentsIpListWidget->addAction(ui->actionRemoveAll); connect(ui->actionRemoveAll, &QAction::triggered, this, &RemoteDebugDialog::clearAll); connect(ui->actionRemoveItem, &QAction::triggered, this, &RemoteDebugDialog::removeItem); connect(ui->recentsIpListWidget, &QListWidget::itemClicked, this, &RemoteDebugDialog::itemClicked); } RemoteDebugDialog::~RemoteDebugDialog() {} bool RemoteDebugDialog::validate() { int debugger = getDebugger(); if (debugger == GDB) { return validatePort() && validateIp(); } else if (debugger == WINDBG) { return validatePath(); } QMessageBox msgBox; msgBox.setText(tr("Invalid debugger")); msgBox.exec(); return false; } bool RemoteDebugDialog::validateIp() { QMessageBox msgBox; QString ip = getIpOrPath(); if (QHostAddress(ip).isNull()) { msgBox.setText(tr("Invalid IP address")); msgBox.exec(); return false; } return true; } bool RemoteDebugDialog::validatePath() { QMessageBox msgBox; QString path = getIpOrPath(); if (!QFileInfo(path).exists()) { msgBox.setText(tr("Path does not exist")); msgBox.exec(); return false; } return true; } bool RemoteDebugDialog::validatePort() { QMessageBox msgBox; int port = getPort(); if (port < 1 || port > 65535) { msgBox.setText(tr("Invalid port")); msgBox.exec(); return false; } return true; } void RemoteDebugDialog::on_buttonBox_accepted() {} void RemoteDebugDialog::on_buttonBox_rejected() { close(); } void RemoteDebugDialog::removeItem() { QListWidgetItem *item = ui->recentsIpListWidget->currentItem(); if (item == nullptr) return; QVariant data = item->data(Qt::UserRole); QString sitem = data.toString(); // Remove the item from recentIpList QSettings settings; QStringList ips = settings.value("recentIpList").toStringList(); ips.removeAll(sitem); settings.setValue("recentIpList", ips); // Also remove the line from list ui->recentsIpListWidget->takeItem(ui->recentsIpListWidget->currentRow()); checkIfEmpty(); } void RemoteDebugDialog::clearAll() { QSettings settings; ui->recentsIpListWidget->clear(); QStringList ips = settings.value("recentIpList").toStringList(); ips.clear(); settings.setValue("recentIpList", ips); checkIfEmpty(); } void RemoteDebugDialog::fillFormData(QString formdata) { QString ipText = ""; QString portText = ""; const DbgBackend *backend = nullptr; for (auto &back : dbgBackends) { if (formdata.startsWith(back.prefix)) { backend = &back; } } if (!backend) { return; } if (backend->type == GDB) { // Format is | prefix | IP | : | PORT | int lastColon = formdata.lastIndexOf(QString(":")); portText = formdata.mid(lastColon + 1, formdata.length()); ipText = formdata.mid(backend->prefix.length(), lastColon - backend->prefix.length()); } else if (backend->type == WINDBG) { // Format is | prefix | PATH | ipText = formdata.mid(backend->prefix.length()); } ui->debuggerCombo->setCurrentText(backend->name); ui->ipEdit->setText(ipText); ui->portEdit->setText(portText); } QString RemoteDebugDialog::getUri() const { int debugger = getDebugger(); if (debugger == WINDBG) { return QString("%1%2").arg(dbgBackends[WINDBG].prefix, getIpOrPath()); } else if (debugger == GDB) { return QString("%1%2:%3").arg(dbgBackends[GDB].prefix, getIpOrPath(), QString::number(getPort())); } return "- uri error"; } bool RemoteDebugDialog::fillRecentIpList() { QSettings settings; // Fetch recentIpList QStringList ips = settings.value("recentIpList").toStringList(); QMutableListIterator<QString> it(ips); while (it.hasNext()) { const QString ip = it.next(); const QString text = QString("%1").arg(ip); QListWidgetItem *item = new QListWidgetItem(text); item->setData(Qt::UserRole, ip); // Fill recentsIpListWidget ui->recentsIpListWidget->addItem(item); } if (!ips.isEmpty()) { fillFormData(ips[0]); } checkIfEmpty(); return !ips.isEmpty(); } void RemoteDebugDialog::checkIfEmpty() { QSettings settings; QStringList ips = settings.value("recentIpList").toStringList(); if (ips.isEmpty()) { ui->recentsIpListWidget->setVisible(false); ui->line->setVisible(false); } else { // TODO: Find a way to make the list widget not to high } } void RemoteDebugDialog::itemClicked(QListWidgetItem *item) { QVariant data = item->data(Qt::UserRole); QString ipport = data.toString(); fillFormData(ipport); } QString RemoteDebugDialog::getIpOrPath() const { return ui->ipEdit->text(); } int RemoteDebugDialog::getPort() const { return ui->portEdit->text().toInt(); } int RemoteDebugDialog::getDebugger() const { return ui->debuggerCombo->currentIndex(); }
6,162
C++
.cpp
199
25.839196
94
0.664697
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,510
SetToDataDialog.cpp
rizinorg_cutter/src/dialogs/SetToDataDialog.cpp
#include "SetToDataDialog.h" #include "ui_SetToDataDialog.h" #include <QIntValidator> SetToDataDialog::SetToDataDialog(RVA startAddr, QWidget *parent) : QDialog(parent), ui(new Ui::SetToDataDialog), startAddress(startAddr) { ui->setupUi(this); auto validator = new QIntValidator(this); validator->setBottom(1); ui->sizeEdit->setValidator(validator); ui->repeatEdit->setValidator(validator); ui->startAddrLabel->setText(RzAddressString(startAddr)); updateEndAddress(); } SetToDataDialog::~SetToDataDialog() { delete ui; } int SetToDataDialog::getItemSize() { return ui->sizeEdit->text().toInt(); } int SetToDataDialog::getItemCount() { return ui->repeatEdit->text().toInt(); } void SetToDataDialog::updateEndAddress() { RVA endAddr = startAddress + (getItemSize() * getItemCount()); ui->endAddrLabel->setText(RzAddressString(endAddr)); } void SetToDataDialog::on_sizeEdit_textChanged(const QString &arg1) { Q_UNUSED(arg1); updateEndAddress(); } void SetToDataDialog::on_repeatEdit_textChanged(const QString &arg1) { Q_UNUSED(arg1); updateEndAddress(); }
1,128
C++
.cpp
41
24.682927
75
0.750926
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,511
CommentsDialog.cpp
rizinorg_cutter/src/dialogs/CommentsDialog.cpp
#include "CommentsDialog.h" #include "ui_CommentsDialog.h" #include <QErrorMessage> #include "core/Cutter.h" CommentsDialog::CommentsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CommentsDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); // Event filter for capturing Ctrl/Cmd+Return ui->textEdit->installEventFilter(this); } CommentsDialog::~CommentsDialog() {} void CommentsDialog::on_buttonBox_accepted() {} void CommentsDialog::on_buttonBox_rejected() { close(); } QString CommentsDialog::getComment() { QString ret = ui->textEdit->document()->toPlainText(); return ret; } void CommentsDialog::setComment(const QString &comment) { ui->textEdit->document()->setPlainText(comment); } void CommentsDialog::addOrEditComment(RVA offset, QWidget *parent) { QString comment = Core()->getCommentAt(offset); CommentsDialog dialog(parent); if (comment.isNull() || comment.isEmpty()) { dialog.setWindowTitle(tr("Add Comment at %1").arg(RzAddressString(offset))); } else { dialog.setWindowTitle(tr("Edit Comment at %1").arg(RzAddressString(offset))); } dialog.setComment(comment); if (dialog.exec()) { comment = dialog.getComment(); if (comment.isEmpty()) { Core()->delComment(offset); } else { Core()->setComment(offset, comment); } } } bool CommentsDialog::eventFilter(QObject * /*obj*/, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); // Confirm comment by pressing Ctrl/Cmd+Return if ((keyEvent->modifiers() & Qt::ControlModifier) && ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))) { this->accept(); return true; } } return false; }
1,908
C++
.cpp
58
27.913793
93
0.66594
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,512
RizinPluginsDialog.cpp
rizinorg_cutter/src/dialogs/RizinPluginsDialog.cpp
#include "RizinPluginsDialog.h" #include "ui_RizinPluginsDialog.h" #include "core/Cutter.h" #include "common/Helpers.h" #include "plugins/PluginManager.h" RizinPluginsDialog::RizinPluginsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::RizinPluginsDialog) { ui->setupUi(this); for (const auto &plugin : Core()->getBinPluginDescriptions()) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, plugin.name); item->setText(1, plugin.description); item->setText(2, plugin.license); item->setText(3, plugin.type); ui->RzBinTreeWidget->addTopLevelItem(item); } ui->RzBinTreeWidget->sortByColumn(0, Qt::AscendingOrder); qhelpers::adjustColumns(ui->RzBinTreeWidget, 0); for (const auto &plugin : Core()->getRIOPluginDescriptions()) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, plugin.name); item->setText(1, plugin.description); item->setText(2, plugin.license); item->setText(3, plugin.permissions); ui->RzIOTreeWidget->addTopLevelItem(item); } ui->RzIOTreeWidget->sortByColumn(0, Qt::AscendingOrder); qhelpers::adjustColumns(ui->RzIOTreeWidget, 0); for (const auto &plugin : Core()->getRCorePluginDescriptions()) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, plugin.name); item->setText(1, plugin.description); item->setText(2, plugin.license); ui->RzCoreTreeWidget->addTopLevelItem(item); } ui->RzCoreTreeWidget->sortByColumn(0, Qt::AscendingOrder); qhelpers::adjustColumns(ui->RzCoreTreeWidget, 0); for (const auto &plugin : Core()->getRAsmPluginDescriptions()) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, plugin.name); item->setText(1, plugin.architecture); item->setText(2, plugin.cpus); item->setText(3, plugin.version); item->setText(4, plugin.description); item->setText(5, plugin.license); item->setText(6, plugin.author); ui->RzAsmTreeWidget->addTopLevelItem(item); } ui->RzAsmTreeWidget->sortByColumn(0, Qt::AscendingOrder); qhelpers::adjustColumns(ui->RzAsmTreeWidget, 0); } RizinPluginsDialog::~RizinPluginsDialog() { delete ui; }
2,309
C++
.cpp
56
35.035714
69
0.685663
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,513
ArenaInfoDialog.cpp
rizinorg_cutter/src/dialogs/ArenaInfoDialog.cpp
#include "ArenaInfoDialog.h" #include "ui_ArenaInfoDialog.h" ArenaInfoDialog::ArenaInfoDialog(Arena &arena, QWidget *parent) : QDialog(parent), ui(new Ui::ArenaInfoDialog), arena(arena) { ui->setupUi(this); setWindowTitle("Arena @ " + RzAddressString(arena.offset)); updateContents(); } void ArenaInfoDialog::updateContents() { ui->lineEditTop->setText(RzAddressString(arena.top)); ui->lineEditLastRem->setText(RzAddressString(arena.last_remainder)); ui->lineEditNext->setText(RzAddressString(arena.next)); ui->lineEditNextfree->setText(RzAddressString(arena.next_free)); ui->lineEditSysMem->setText(RzAddressString(arena.system_mem)); ui->lineEditMaxMem->setText(RzAddressString(arena.max_system_mem)); } ArenaInfoDialog::~ArenaInfoDialog() { delete ui; }
804
C++
.cpp
22
33.409091
72
0.762516
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,514
RizinTaskDialog.cpp
rizinorg_cutter/src/dialogs/RizinTaskDialog.cpp
#include "RizinTaskDialog.h" #include "common/RizinTask.h" #include <QCloseEvent> #include "ui_RizinTaskDialog.h" RizinTaskDialog::RizinTaskDialog(RizinTask::Ptr task, QWidget *parent) : QDialog(parent), ui(new Ui::RizinTaskDialog), task(task) { ui->setupUi(this); connect(task.data(), &RizinTask::finished, this, [this]() { close(); }); connect(&timer, &QTimer::timeout, this, &RizinTaskDialog::updateProgressTimer); timer.setInterval(1000); timer.setSingleShot(false); timer.start(); elapsedTimer.start(); updateProgressTimer(); } RizinTaskDialog::~RizinTaskDialog() {} void RizinTaskDialog::updateProgressTimer() { int secondsElapsed = elapsedTimer.elapsed() / 1000; int minutesElapsed = secondsElapsed / 60; int hoursElapsed = minutesElapsed / 60; QString label = tr("Running for") + " "; if (hoursElapsed) { label += tr("%n hour", "%n hours", hoursElapsed); label += " "; } if (minutesElapsed) { label += tr("%n minute", "%n minutes", minutesElapsed % 60); label += " "; } label += tr("%n seconds", "%n second", secondsElapsed % 60); ui->timeLabel->setText(label); } void RizinTaskDialog::setDesc(const QString &label) { ui->descLabel->setText(label); } void RizinTaskDialog::closeEvent(QCloseEvent *event) { if (breakOnClose) { task->breakTask(); setDesc("Attempting to stop the task..."); event->ignore(); } else { QWidget::closeEvent(event); } } void RizinTaskDialog::reject() { task->breakTask(); setDesc("Attempting to stop the task..."); }
1,627
C++
.cpp
53
26.377358
83
0.665173
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,515
XrefsDialog.cpp
rizinorg_cutter/src/dialogs/XrefsDialog.cpp
#include "XrefsDialog.h" #include "ui_XrefsDialog.h" #include "common/TempConfig.h" #include "common/Helpers.h" #include "core/MainWindow.h" #include <QJsonArray> XrefsDialog::XrefsDialog(MainWindow *parent, bool hideXrefFrom) : QDialog(parent), addr(0), toModel(this), fromModel(this), ui(new Ui::XrefsDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); ui->toTreeWidget->setMainWindow(parent); ui->fromTreeWidget->setMainWindow(parent); ui->toTreeWidget->setModel(&toModel); ui->fromTreeWidget->setModel(&fromModel); // Modify the splitter's location to show more Disassembly instead of empty space. Not possible // via Designer ui->splitter->setSizes(QList<int>() << 300 << 400); // Increase asm text edit margin QTextDocument *asm_docu = ui->previewTextEdit->document(); asm_docu->setDocumentMargin(10); setupPreviewColors(); setupPreviewFont(); // Highlight current line connect(ui->previewTextEdit, &QPlainTextEdit::cursorPositionChanged, this, &XrefsDialog::highlightCurrentLine); connect(Config(), &Configuration::fontsUpdated, this, &XrefsDialog::setupPreviewFont); connect(Config(), &Configuration::colorsUpdated, this, &XrefsDialog::setupPreviewColors); connect(ui->toTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &XrefsDialog::onToTreeWidgetItemSelectionChanged); connect(ui->fromTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &XrefsDialog::onFromTreeWidgetItemSelectionChanged); // Don't create recursive xref dialogs auto toContextMenu = ui->toTreeWidget->getItemContextMenu(); connect(toContextMenu, &AddressableItemContextMenu::xrefsTriggered, this, &QWidget::close); auto fromContextMenu = ui->fromTreeWidget->getItemContextMenu(); connect(fromContextMenu, &AddressableItemContextMenu::xrefsTriggered, this, &QWidget::close); connect(ui->toTreeWidget, &QAbstractItemView::doubleClicked, this, &QWidget::close); connect(ui->fromTreeWidget, &QAbstractItemView::doubleClicked, this, &QWidget::close); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(&toModel, XrefModel::COMMENT); qhelpers::emitColumnChanged(&fromModel, XrefModel::COMMENT); }); if (hideXrefFrom) { hideXrefFromSection(); } } XrefsDialog::~XrefsDialog() {} QString XrefsDialog::normalizeAddr(const QString &addr) const { QString ret = addr; if (addr.length() < 10) { ret = ret.mid(3).rightJustified(8, QLatin1Char('0')); ret.prepend(QStringLiteral("0x")); } return ret; } void XrefsDialog::setupPreviewFont() { ui->previewTextEdit->setFont(Config()->getBaseFont()); } void XrefsDialog::setupPreviewColors() { ui->previewTextEdit->setStyleSheet( QString("QPlainTextEdit { background-color: %1; color: %2; }") .arg(ConfigColor("gui.background").name()) .arg(ConfigColor("btext").name())); } void XrefsDialog::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> extraSelections; if (ui->previewTextEdit->isReadOnly()) { QTextEdit::ExtraSelection selection = QTextEdit::ExtraSelection(); selection.format.setBackground(ConfigColor("lineHighlight")); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = ui->previewTextEdit->textCursor(); selection.cursor.clearSelection(); extraSelections.append(selection); ui->previewTextEdit->setExtraSelections(extraSelections); } } void XrefsDialog::onFromTreeWidgetItemSelectionChanged() { auto index = ui->fromTreeWidget->currentIndex(); if (!ui->fromTreeWidget->selectionModel()->hasSelection() || !index.isValid()) { return; } ui->toTreeWidget->clearSelection(); updatePreview(fromModel.address(index)); } void XrefsDialog::onToTreeWidgetItemSelectionChanged() { auto index = ui->toTreeWidget->currentIndex(); if (!ui->toTreeWidget->selectionModel()->hasSelection() || !index.isValid()) { return; } ui->fromTreeWidget->clearSelection(); updatePreview(toModel.address(index)); } void XrefsDialog::updatePreview(RVA addr) { TempConfig tempConfig; tempConfig.set("scr.html", true); tempConfig.set("scr.color", COLOR_MODE_16M); tempConfig.set("asm.lines", false); tempConfig.set("asm.bytes", false); QString disas = Core()->getFunctionExecOut( [](RzCore *core) { ut64 offset = core->offset; if (!rz_core_prevop_addr(core, core->offset, 20, &offset)) { offset = rz_core_prevop_addr_force(core, core->offset, 20); } rz_core_seek(core, offset, true); rz_core_print_disasm(core, core->offset, core->block, (int)core->blocksize, 40, NULL, NULL); return true; }, addr); ui->previewTextEdit->document()->setHtml(disas); // Does it make any sense? ui->previewTextEdit->find(normalizeAddr(RzAddressString(addr)), QTextDocument::FindBackward); ui->previewTextEdit->moveCursor(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); } void XrefsDialog::updateLabels(QString name) { ui->label_xTo->setText(tr("X-Refs to %1 (%2 results):").arg(name).arg(toModel.rowCount())); ui->label_xFrom->setText( tr("X-Refs from %1 (%2 results):").arg(name).arg(fromModel.rowCount())); } void XrefsDialog::updateLabelsForVariables(QString name) { ui->label_xTo->setText(tr("Writes to %1").arg(name)); ui->label_xFrom->setText(tr("Reads from %1").arg(name)); } void XrefsDialog::hideXrefFromSection() { ui->label_xFrom->hide(); ui->fromTreeWidget->hide(); } void XrefsDialog::fillRefsForAddress(RVA addr, QString name, bool whole_function) { setWindowTitle(tr("X-Refs for %1").arg(name)); toModel.readForOffset(addr, true, whole_function); fromModel.readForOffset(addr, false, whole_function); updateLabels(name); // Adjust columns to content qhelpers::adjustColumns(ui->fromTreeWidget, fromModel.columnCount(), 0); qhelpers::adjustColumns(ui->toTreeWidget, toModel.columnCount(), 0); // Automatically select the first line if (!qhelpers::selectFirstItem(ui->toTreeWidget)) { qhelpers::selectFirstItem(ui->fromTreeWidget); } } void XrefsDialog::fillRefsForVariable(QString nameOfVariable, RVA offset) { setWindowTitle(tr("X-Refs for %1").arg(nameOfVariable)); updateLabelsForVariables(nameOfVariable); // Initialize Model toModel.readForVariable(nameOfVariable, true, offset); fromModel.readForVariable(nameOfVariable, false, offset); // Hide irrelevant column 1: which shows type ui->fromTreeWidget->hideColumn(XrefModel::Columns::TYPE); ui->toTreeWidget->hideColumn(XrefModel::Columns::TYPE); // Adjust columns to content qhelpers::adjustColumns(ui->fromTreeWidget, fromModel.columnCount(), 0); qhelpers::adjustColumns(ui->toTreeWidget, toModel.columnCount(), 0); // Automatically select the first line if (!qhelpers::selectFirstItem(ui->toTreeWidget)) { qhelpers::selectFirstItem(ui->fromTreeWidget); } } QString XrefModel::xrefTypeString(const QString &type) { if (type == "CODE") { return QStringLiteral("Code"); } else if (type == "CALL") { return QStringLiteral("Call"); } else if (type == "DATA") { return QStringLiteral("Data"); } else if (type == "STRING") { return QStringLiteral("String"); } return type; } XrefModel::XrefModel(QObject *parent) : AddressableItemModel(parent) {} void XrefModel::readForOffset(RVA offset, bool to, bool whole_function) { beginResetModel(); this->to = to; xrefs = Core()->getXRefs(offset, to, whole_function); endResetModel(); } void XrefModel::readForVariable(QString nameOfVariable, bool write, RVA offset) { beginResetModel(); this->to = write; xrefs = Core()->getXRefsForVariable(nameOfVariable, write, offset); endResetModel(); } int XrefModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return xrefs.size(); } int XrefModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return Columns::COUNT; } QVariant XrefModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= xrefs.count()) { return QVariant(); } const XrefDescription &xref = xrefs.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case OFFSET: return to ? xref.from_str : xref.to_str; case TYPE: return xrefTypeString(xref.type); case CODE: if (to || xref.type != "DATA") { return Core()->disassembleSingleInstruction(xref.from); } else { return QString(); } case COMMENT: return to ? Core()->getCommentAt(xref.from) : Core()->getCommentAt(xref.to); } return QVariant(); case FlagDescriptionRole: return QVariant::fromValue(xref); default: break; } return QVariant(); } QVariant XrefModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation) switch (role) { case Qt::DisplayRole: switch (section) { case OFFSET: return tr("Address"); case TYPE: return tr("Type"); case CODE: return tr("Code"); case COMMENT: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA XrefModel::address(const QModelIndex &index) const { const auto &xref = xrefs.at(index.row()); return to ? xref.from : xref.to; }
10,061
C++
.cpp
265
32.030189
99
0.68117
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,516
NewFileDialog.cpp
rizinorg_cutter/src/dialogs/NewFileDialog.cpp
#include "InitialOptionsDialog.h" #include "core/MainWindow.h" #include "dialogs/NewFileDialog.h" #include "dialogs/AboutDialog.h" #include "ui_NewFileDialog.h" #include "common/Helpers.h" #include "common/HighDpiPixmap.h" #include <QFileDialog> #include <QtGui> #include <QMessageBox> #include <QDir> #include <QPushButton> #include <QLineEdit> const int NewFileDialog::MaxRecentFiles; static QColor getColorFor(int pos) { static const QList<QColor> colors = { QColor(29, 188, 156), // Turquoise QColor(52, 152, 219), // Blue QColor(155, 89, 182), // Violet QColor(52, 73, 94), // Grey QColor(231, 76, 60), // Red QColor(243, 156, 17) // Orange }; return colors[pos % colors.size()]; } static QIcon getIconFor(const QString &str, int pos) { // Add to the icon list int w = 64; int h = 64; HighDpiPixmap pixmap(w, h); pixmap.fill(Qt::transparent); QPainter pixPaint(&pixmap); pixPaint.setPen(Qt::NoPen); pixPaint.setRenderHint(QPainter::Antialiasing); pixPaint.setBrush(getColorFor(pos)); pixPaint.drawEllipse(1, 1, w - 2, h - 2); pixPaint.setPen(Qt::white); QFont font = Config()->getBaseFont(); font.setBold(true); font.setPointSize(18); pixPaint.setFont(font); pixPaint.drawText(0, 0, w, h - 2, Qt::AlignCenter, QString(str).toUpper().mid(0, 2)); return QIcon(pixmap); } NewFileDialog::NewFileDialog(MainWindow *main) : QDialog(nullptr), // no parent on purpose, using main causes weird positioning ui(new Ui::NewFileDialog), main(main) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); setAcceptDrops(true); ui->recentsListWidget->addAction(ui->actionRemove_item); ui->recentsListWidget->addAction(ui->actionClear_all); ui->projectsListWidget->addAction(ui->actionRemove_project); ui->projectsListWidget->addAction(ui->actionClearProjects); ui->logoSvgWidget->load(Config()->getLogoFile()); fillRecentFilesList(); fillIOPluginsList(); fillProjectsList(); // Set last clicked tab ui->tabWidget->setCurrentIndex(Config()->getNewFileLastClicked()); /* Set focus on the TextInput */ ui->newFileEdit->setFocus(); /* Install an event filter for shellcode text edit to enable ctrl+return event */ ui->shellcodeText->installEventFilter(this); updateLoadProjectButton(); } NewFileDialog::~NewFileDialog() {} void NewFileDialog::on_loadFileButton_clicked() { loadFile(ui->newFileEdit->text()); } void NewFileDialog::on_selectFileButton_clicked() { QString currentDir = Config()->getRecentFolder(); const QString &fileName = QDir::toNativeSeparators( QFileDialog::getOpenFileName(this, tr("Select file"), currentDir)); if (!fileName.isEmpty()) { ui->newFileEdit->setText(fileName); ui->loadFileButton->setFocus(); Config()->setRecentFolder(QFileInfo(fileName).absolutePath()); } } void NewFileDialog::on_selectProjectFileButton_clicked() { const QString &fileName = QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Project"))); if (!fileName.isEmpty()) { ui->projectFileEdit->setText(fileName); ui->loadProjectButton->setFocus(); } } void NewFileDialog::on_loadProjectButton_clicked() { loadProject(ui->projectFileEdit->text()); } void NewFileDialog::on_shellcodeButton_clicked() { QString shellcode = ui->shellcodeText->toPlainText(); QString extractedCode = ""; static const QRegularExpression rx("([0-9a-f]{2})", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatchIterator i = rx.globalMatch(shellcode); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); extractedCode.append(match.captured(1)); } int size = extractedCode.size() / 2; if (size > 0) { loadShellcode(extractedCode, size); } } void NewFileDialog::on_recentsListWidget_itemClicked(QListWidgetItem *item) { QVariant data = item->data(Qt::UserRole); QString sitem = data.toString(); ui->newFileEdit->setText(sitem); } void NewFileDialog::on_recentsListWidget_itemDoubleClicked(QListWidgetItem *item) { loadFile(item->data(Qt::UserRole).toString()); } void NewFileDialog::on_projectFileEdit_textChanged() { updateLoadProjectButton(); } void NewFileDialog::on_projectsListWidget_itemClicked(QListWidgetItem *item) { ui->projectFileEdit->setText(item->data(Qt::UserRole).toString()); } void NewFileDialog::on_projectsListWidget_itemDoubleClicked(QListWidgetItem *item) { loadProject(item->data(Qt::UserRole).toString()); } void NewFileDialog::on_aboutButton_clicked() { AboutDialog *a = new AboutDialog(this); a->setAttribute(Qt::WA_DeleteOnClose); a->open(); } void NewFileDialog::on_actionRemove_item_triggered() { // Remove selected item from recents list QListWidgetItem *item = ui->recentsListWidget->currentItem(); if (item == nullptr) { return; } QString sitem = item->data(Qt::UserRole).toString(); QStringList files = Config()->getRecentFiles(); files.removeAll(sitem); Config()->setRecentFiles(files); ui->recentsListWidget->takeItem(ui->recentsListWidget->currentRow()); ui->newFileEdit->clear(); } void NewFileDialog::on_actionClear_all_triggered() { Config()->setRecentFiles({}); ui->recentsListWidget->clear(); ui->newFileEdit->clear(); } void NewFileDialog::on_actionRemove_project_triggered() { QListWidgetItem *item = ui->projectsListWidget->currentItem(); if (item == nullptr) { return; } QString sitem = item->data(Qt::UserRole).toString(); QStringList files = Config()->getRecentProjects(); files.removeAll(sitem); Config()->setRecentProjects(files); ui->projectsListWidget->takeItem(ui->projectsListWidget->currentRow()); ui->projectFileEdit->clear(); } void NewFileDialog::on_actionClearProjects_triggered() { Config()->setRecentProjects({}); ui->projectsListWidget->clear(); ui->projectFileEdit->clear(); } void NewFileDialog::dragEnterEvent(QDragEnterEvent *event) { // Accept drag & drop events only if they provide a URL if (event->mimeData()->hasUrls()) { event->acceptProposedAction(); } } void NewFileDialog::dropEvent(QDropEvent *event) { // Accept drag & drop events only if they provide a URL if (event->mimeData()->urls().count() == 0) { qWarning() << "No URL in drop event, ignoring it."; return; } event->acceptProposedAction(); loadFile(event->mimeData()->urls().first().toLocalFile()); } /* * @brief Add the existing files from the list to the widget. * @return the list of files that actually exist */ static QStringList fillFilesList(QListWidget *widget, const QStringList &files) { QStringList updatedFiles = files; QMutableListIterator<QString> it(updatedFiles); int i = 0; while (it.hasNext()) { // Get the file name const QString &fullpath = QDir::toNativeSeparators(it.next()); const QString homepath = QDir::homePath(); const QString basename = fullpath.section(QDir::separator(), -1); QString filenameHome = fullpath; filenameHome.replace(homepath, "~"); filenameHome.replace(basename, ""); filenameHome.chop(1); // Remove last character that will be a path separator // Get file info QFileInfo info(fullpath); if (!info.exists()) { it.remove(); } else { // Format the text and add the item to the file list const QString text = QString("%1\n%2\nSize: %3") .arg(basename, filenameHome, qhelpers::formatBytecount(info.size())); QListWidgetItem *item = new QListWidgetItem(getIconFor(basename, i++), text); item->setData(Qt::UserRole, fullpath); widget->addItem(item); } } return updatedFiles; } bool NewFileDialog::fillRecentFilesList() { QStringList files = Config()->getRecentFiles(); files = fillFilesList(ui->recentsListWidget, files); // Removed files were deleted from the stringlist. Save it again. Config()->setRecentFiles(files); return !files.isEmpty(); } bool NewFileDialog::fillProjectsList() { QStringList files = Config()->getRecentProjects(); files = fillFilesList(ui->projectsListWidget, files); Config()->setRecentProjects(files); return !files.isEmpty(); } void NewFileDialog::fillIOPluginsList() { ui->ioPlugin->clear(); ui->ioPlugin->addItem("file://"); ui->ioPlugin->setItemData(0, tr("Open a file without additional options/settings."), Qt::ToolTipRole); int index = 1; QList<RzIOPluginDescription> ioPlugins = Core()->getRIOPluginDescriptions(); for (const RzIOPluginDescription &plugin : ioPlugins) { // Hide debug plugins if (plugin.permissions.contains('d')) { continue; } const auto &uris = plugin.uris; for (const auto &uri : uris) { if (uri == "file://") { continue; } ui->ioPlugin->addItem(uri); ui->ioPlugin->setItemData(index, plugin.description, Qt::ToolTipRole); index++; } } } void NewFileDialog::updateLoadProjectButton() { ui->loadProjectButton->setEnabled(!ui->projectFileEdit->text().trimmed().isEmpty()); } void NewFileDialog::loadFile(const QString &filename) { const QString &nativeFn = QDir::toNativeSeparators(filename); if (ui->ioPlugin->currentIndex() == 0 && !Core()->tryFile(nativeFn, false) && !ui->checkBox_FilelessOpen->isChecked()) { QMessageBox msgBox(this); msgBox.setText(tr("Select a new program or a previous one before continuing.")); msgBox.exec(); return; } // Add file to recent file list QSettings settings; QStringList files = Config()->getRecentFiles(); files.removeAll(nativeFn); files.prepend(nativeFn); while (files.size() > MaxRecentFiles) files.removeLast(); Config()->setRecentFiles(files); // Close dialog and open MainWindow/InitialOptionsDialog QString ioFile = ""; if (ui->ioPlugin->currentIndex()) { ioFile = ui->ioPlugin->currentText(); } ioFile += nativeFn; InitialOptions options; options.filename = ioFile; main->openNewFile(options, ui->checkBox_FilelessOpen->isChecked()); close(); } void NewFileDialog::loadProject(const QString &project) { MainWindow *main = new MainWindow(); if (!main->openProject(project)) { return; } close(); } void NewFileDialog::loadShellcode(const QString &shellcode, const int size) { MainWindow *main = new MainWindow(); InitialOptions options; options.filename = QString("malloc://%1").arg(size); options.shellcode = shellcode; main->openNewFile(options); close(); } void NewFileDialog::on_tabWidget_currentChanged(int index) { Config()->setNewFileLastClicked(index); } bool NewFileDialog::eventFilter(QObject * /*obj*/, QEvent *event) { QString shellcode = ui->shellcodeText->toPlainText(); QString extractedCode = ""; static const QRegularExpression rx("([0-9a-f]{2})", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatchIterator i = rx.globalMatch(shellcode); int size = 0; if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); // Confirm comment by pressing Ctrl/Cmd+Return if ((keyEvent->modifiers() & Qt::ControlModifier) && ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))) { while (i.hasNext()) { QRegularExpressionMatch match = i.next(); extractedCode.append(match.captured(1)); } size = extractedCode.size() / 2; if (size > 0) { loadShellcode(extractedCode, size); } return true; } } return false; }
12,197
C++
.cpp
350
29.551429
99
0.677687
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,517
GlibcHeapInfoDialog.cpp
rizinorg_cutter/src/dialogs/GlibcHeapInfoDialog.cpp
#include "GlibcHeapInfoDialog.h" #include <utility> #include "ui_GlibcHeapInfoDialog.h" GlibcHeapInfoDialog::GlibcHeapInfoDialog(RVA offset, QString status, QWidget *parent) : QDialog(parent), ui(new Ui::GlibcHeapInfoDialog), offset(offset), status(std::move(status)) { ui->setupUi(this); // set window title QString windowTitle = tr("Chunk @ ") + RzAddressString(offset); if (!this->status.isEmpty()) { windowTitle += QString("(" + this->status + ")"); } this->setWindowTitle(windowTitle); connect(ui->saveButton, &QPushButton::clicked, this, &GlibcHeapInfoDialog::saveChunkInfo); updateFields(); } GlibcHeapInfoDialog::~GlibcHeapInfoDialog() { delete ui; } void GlibcHeapInfoDialog::updateFields() { // get data about the heap chunk from the API RzHeapChunkSimple *chunk = Core()->getHeapChunk(offset); if (!chunk) { return; } // Update the information in the widget this->ui->baseEdit->setText(RzAddressString(offset)); this->ui->sizeEdit->setText(RzHexString(chunk->size)); this->ui->bkEdit->setText(RzAddressString(chunk->bk)); this->ui->fdEdit->setText(RzAddressString(chunk->fd)); this->ui->bknsEdit->setText(RzAddressString(chunk->bk_nextsize)); this->ui->fdnsEdit->setText(RzAddressString(chunk->fd_nextsize)); this->ui->prevSizeEdit->setText(RzHexString(chunk->prev_size)); if (chunk->is_mmapped) { this->ui->rbIM->setChecked(true); } else { this->ui->rbIM->setChecked(false); } if (chunk->prev_inuse) { this->ui->rbPI->setChecked(true); } else { this->ui->rbPI->setChecked(false); } if (chunk->non_main_arena) { this->ui->rbNMA->setChecked(true); } else { this->ui->rbNMA->setChecked(false); } free(chunk); } void GlibcHeapInfoDialog::saveChunkInfo() { QMessageBox msgBox; msgBox.setText("Do you want to overwrite chunk metadata?"); msgBox.setInformativeText( "Any field which cannot be converted to a valid integer will be saved as zero"); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Save: // Save was clicked RzHeapChunkSimple chunkSimple; chunkSimple.size = Core()->math(ui->sizeEdit->text()); chunkSimple.fd = Core()->math(ui->fdEdit->text()); chunkSimple.bk = Core()->math(ui->bkEdit->text()); chunkSimple.fd_nextsize = Core()->math(ui->fdnsEdit->text()); chunkSimple.bk_nextsize = Core()->math(ui->bknsEdit->text()); chunkSimple.addr = offset; if (ui->rbIM->isChecked()) { chunkSimple.is_mmapped = true; } else { chunkSimple.is_mmapped = false; } if (ui->rbNMA->isChecked()) { chunkSimple.non_main_arena = true; } else { chunkSimple.non_main_arena = false; } if (ui->rbPI->isChecked()) { chunkSimple.prev_inuse = true; } else { chunkSimple.prev_inuse = false; } if (Core()->writeHeapChunk(&chunkSimple)) { updateFields(); QMessageBox::information(this, tr("Chunk saved"), tr("Chunk header successfully overwritten")); } else { QMessageBox::information(this, tr("Chunk not saved"), tr("Chunk header not successfully overwritten")); } break; case QMessageBox::Cancel: // Cancel was clicked break; } }
3,662
C++
.cpp
100
29.42
97
0.626689
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,518
MapFileDialog.cpp
rizinorg_cutter/src/dialogs/MapFileDialog.cpp
#include "MapFileDialog.h" #include "ui_MapFileDialog.h" #include "common/Configuration.h" #include <QFileDialog> MapFileDialog::MapFileDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MapFileDialog) { ui->setupUi(this); } MapFileDialog::~MapFileDialog() {} void MapFileDialog::on_selectFileButton_clicked() { QString currentDir = Config()->getRecentFolder(); QString fileName = QFileDialog::getOpenFileName(this, tr("Select file"), currentDir); if (!fileName.isEmpty()) { ui->filenameLineEdit->setText(fileName); Config()->setRecentFolder(QFileInfo(fileName).absolutePath()); } } void MapFileDialog::on_buttonBox_accepted() { const QString &filePath = QDir::toNativeSeparators(ui->filenameLineEdit->text()); RVA mapAddress = RVA_INVALID; QString mapAddressStr = ui->mapAddressLineEdit->text(); if (!mapAddressStr.isEmpty()) { mapAddress = Core()->math(mapAddressStr); } if (!Core()->mapFile(filePath, mapAddress)) { QMessageBox::critical(this, tr("Map new file"), tr("Failed to map a new file")); return; } close(); } void MapFileDialog::on_buttonBox_rejected() { close(); }
1,186
C++
.cpp
36
29.027778
90
0.706398
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,519
GlibcHeapBinsDialog.cpp
rizinorg_cutter/src/dialogs/GlibcHeapBinsDialog.cpp
#include <HeapBinsGraphView.h> #include "GlibcHeapBinsDialog.h" #include "ui_GlibcHeapBinsDialog.h" #include "GlibcHeapInfoDialog.h" GlibcHeapBinsDialog::GlibcHeapBinsDialog(RVA m_state, MainWindow *main, QWidget *parent) : QDialog(parent), ui(new Ui::GlibcHeapBinsDialog), m_state(m_state), binsModel(new BinsModel(m_state, this)), main(main) { ui->setupUi(this); ui->viewBins->setModel(binsModel); ui->viewBins->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); ui->viewBins->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); ui->viewBins->verticalHeader()->hide(); ui->viewBins->resizeColumnsToContents(); connect(ui->viewBins->selectionModel(), &QItemSelectionModel::currentChanged, this, &GlibcHeapBinsDialog::onCurrentChanged); connect(ui->lineEdit, &QLineEdit::returnPressed, this, &GlibcHeapBinsDialog::showHeapInfoDialog); binsModel->reload(); ui->viewBins->resizeColumnsToContents(); graphView = nullptr; this->setWindowTitle(tr("Bins info for arena @ ") + RzAddressString(m_state)); } GlibcHeapBinsDialog::~GlibcHeapBinsDialog() { delete ui; } void GlibcHeapBinsDialog::onCurrentChanged(const QModelIndex &current, const QModelIndex &prev) { Q_UNUSED(current); Q_UNUSED(prev); auto currentIndex = ui->viewBins->selectionModel()->currentIndex(); setChainInfo(currentIndex.row()); setGraphView(currentIndex.row()); } void GlibcHeapBinsDialog::setChainInfo(int index) { // get chunks for the selected bin and construct chain info string RzListIter *iter; RzHeapChunkListItem *item; RzList *chunks = binsModel->getChunks(index); QString chainInfo; CutterRzListForeach (chunks, iter, RzHeapChunkListItem, item) { chainInfo += " → " + RzAddressString(item->addr); } // Add bin message at the end of the list // responsible for messages like corrupted list, double free QString message = binsModel->getBinMessage(index); if (!message.isEmpty()) { chainInfo += " " + message; } ui->chainInfoEdit->setPlainText(chainInfo); } void GlibcHeapBinsDialog::showHeapInfoDialog() { QString str = ui->lineEdit->text(); if (!str.isEmpty()) { // summon glibcHeapInfoDialog box with the offset entered RVA offset = Core()->math(str); if (!offset) { ui->lineEdit->setText(QString()); return; } GlibcHeapInfoDialog dialog(offset, QString(), this); dialog.exec(); } } void GlibcHeapBinsDialog::setGraphView(int index) { if (graphView) { ui->horizontalLayout->removeWidget(graphView); delete graphView; } graphView = new HeapBinsGraphView(this, binsModel->values[index], main); ui->horizontalLayout->addWidget(graphView); graphView->refreshView(); } BinsModel::BinsModel(RVA arena_addr, QObject *parent) : QAbstractTableModel(parent), arena_addr(arena_addr) { } void BinsModel::reload() { beginResetModel(); clearData(); values = Core()->getHeapBins(arena_addr); endResetModel(); } int BinsModel::rowCount(const QModelIndex &) const { return values.size(); } int BinsModel::columnCount(const QModelIndex &) const { return ColumnCount; } QVariant BinsModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= values.count()) return QVariant(); const auto &item = values.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case BinNumColumn: return item->bin_num; case FdColumn: return (item->fd == 0) ? tr("N/A") : RzAddressString(item->fd); case BkColumn: return (item->bk == 0) ? tr("N/A") : RzAddressString(item->bk); case TypeColumn: return tr(item->type); case CountColumn: return rz_list_length(item->chunks); case SizeColumn: return (item->size == 0) ? tr("N/A") : RzHexString(item->size); default: return QVariant(); } default: return QVariant(); } } QVariant BinsModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); switch (role) { case Qt::DisplayRole: switch (section) { case BinNumColumn: return tr("#"); case FdColumn: return tr("Fd"); case BkColumn: return tr("Bk"); case TypeColumn: return tr("Type"); case CountColumn: return tr("Chunks count"); case SizeColumn: return tr("Chunks size"); default: return QVariant(); } case Qt::ToolTipRole: switch (section) { case BinNumColumn: return tr("Bin number in NBINS or fastbinsY array"); case FdColumn: return tr("Pointer to first chunk of the bin"); case BkColumn: return tr("Pointer to last chunk of the bin"); case TypeColumn: return tr("Type of bin"); case CountColumn: return tr("Number of chunks in the bin"); case SizeColumn: return tr("Size of all chunks in the bin"); default: return QVariant(); } default: return QVariant(); } } void BinsModel::clearData() { for (auto item : values) { rz_heap_bin_free_64(item); } } RzList *BinsModel::getChunks(int index) { return values[index]->chunks; } QString BinsModel::getBinMessage(int index) { if (values[index]->message) { return QString(values[index]->message); } else { return QString(); } }
5,778
C++
.cpp
186
24.951613
95
0.648231
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,520
TypesInteractionDialog.cpp
rizinorg_cutter/src/dialogs/TypesInteractionDialog.cpp
#include "dialogs/TypesInteractionDialog.h" #include "ui_TypesInteractionDialog.h" #include "core/Cutter.h" #include "common/Configuration.h" #include "common/SyntaxHighlighter.h" #include "widgets/TypesWidget.h" #include <QFileDialog> #include <QTemporaryFile> TypesInteractionDialog::TypesInteractionDialog(QWidget *parent, bool readOnly) : QDialog(parent), ui(new Ui::TypesInteractionDialog) { ui->setupUi(this); QFont font = Config()->getBaseFont(); ui->plainTextEdit->setFont(font); ui->plainTextEdit->setPlainText(""); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) ui->plainTextEdit->setTabStopDistance(4 * QFontMetrics(font).horizontalAdvance(' ')); #endif syntaxHighLighter = Config()->createSyntaxHighlighter(ui->plainTextEdit->document()); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); ui->plainTextEdit->setReadOnly(readOnly); } TypesInteractionDialog::~TypesInteractionDialog() {} void TypesInteractionDialog::setTypeName(QString name) { this->typeName = name; } void TypesInteractionDialog::on_selectFileButton_clicked() { QString filename = QFileDialog::getOpenFileName(this, tr("Select file"), Config()->getRecentFolder(), "Header files (*.h *.hpp);;All files (*)"); if (filename.isEmpty()) { return; } Config()->setRecentFolder(QFileInfo(filename).absolutePath()); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), file.errorString()); on_selectFileButton_clicked(); return; } ui->filenameLineEdit->setText(filename); ui->plainTextEdit->setPlainText(file.readAll()); } void TypesInteractionDialog::on_plainTextEdit_textChanged() { if (ui->plainTextEdit->toPlainText().isEmpty()) { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); } else { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } } void TypesInteractionDialog::done(int r) { if (r == QDialog::Accepted) { RzCoreLocked core(Core()); bool success; if (!typeName.isEmpty()) { success = rz_type_db_edit_base_type( core->analysis->typedb, this->typeName.toUtf8().constData(), ui->plainTextEdit->toPlainText().toUtf8().constData()); } else { char *error_msg = NULL; success = rz_type_parse_string_stateless( core->analysis->typedb->parser, ui->plainTextEdit->toPlainText().toUtf8().constData(), &error_msg) == 0; if (error_msg) { RZ_LOG_ERROR("%s\n", error_msg); rz_mem_free(error_msg); } } if (success) { emit newTypesLoaded(); QDialog::done(r); return; } QMessageBox popup(this); popup.setWindowTitle(tr("Error")); popup.setText(tr("There was some error while loading new types")); popup.setStandardButtons(QMessageBox::Ok); popup.exec(); } else { QDialog::done(r); } } void TypesInteractionDialog::fillTextArea(QString content) { ui->layoutWidget->hide(); ui->plainTextEdit->setPlainText(content); }
3,342
C++
.cpp
92
29.119565
96
0.640432
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,521
VersionInfoDialog.cpp
rizinorg_cutter/src/dialogs/VersionInfoDialog.cpp
#include "VersionInfoDialog.h" #include "ui_VersionInfoDialog.h" #include "common/Helpers.h" #include <QJsonArray> #include <QStringList> #include <QJsonObject> #include <QJsonDocument> #include <QTreeWidget> VersionInfoDialog::VersionInfoDialog(QWidget *parent) : QDialog(parent), ui(new Ui::VersionInfoDialog), core(Core()) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); // Get version information fillVersionInfo(); } VersionInfoDialog::~VersionInfoDialog() {} void VersionInfoDialog::fillVersionInfo() { RzCoreLocked core(Core()); RzBinObject *bobj = rz_bin_cur_object(core->bin); if (!bobj) { return; } const RzBinInfo *info = rz_bin_object_get_info(bobj); if (!info || !info->rclass) { return; } // Case ELF if (strncmp("elf", info->rclass, 3) == 0) { // Set labels ui->leftLabel->setText("Version symbols"); ui->rightLabel->setText("Version need"); Sdb *sdb = sdb_ns_path(core->sdb, "bin/cur/info/versioninfo/versym", 0); if (!sdb) { return; } // Left tree QTreeWidgetItem *addrItemL = new QTreeWidgetItem(); addrItemL->setText(0, "Address:"); addrItemL->setText(1, RzAddressString(sdb_num_get(sdb, "addr"))); ui->leftTreeWidget->addTopLevelItem(addrItemL); QTreeWidgetItem *offItemL = new QTreeWidgetItem(); offItemL->setText(0, "Offset:"); offItemL->setText(1, RzAddressString(sdb_num_get(sdb, "offset"))); ui->leftTreeWidget->addTopLevelItem(offItemL); QTreeWidgetItem *entriesItemL = new QTreeWidgetItem(); entriesItemL->setText(0, "Entries:"); const ut64 num_entries = sdb_num_get(sdb, "num_entries"); for (size_t i = 0; i < num_entries; ++i) { auto key = QString("entry%0").arg(i); const char *const value = sdb_const_get(sdb, key.toStdString().c_str()); if (!value) { continue; } auto item = new QTreeWidgetItem(); item->setText(0, RzAddressString(i)); item->setText(1, value); entriesItemL->addChild(item); } ui->leftTreeWidget->addTopLevelItem(entriesItemL); // Adjust columns to content qhelpers::adjustColumns(ui->leftTreeWidget, 0); sdb = sdb_ns_path(core->sdb, "bin/cur/info/versioninfo/verneed", 0); // Right tree QTreeWidgetItem *addrItemR = new QTreeWidgetItem(); addrItemR->setText(0, "Address:"); addrItemR->setText(1, RzAddressString(sdb_num_get(sdb, "addr"))); ui->rightTreeWidget->addTopLevelItem(addrItemR); QTreeWidgetItem *offItemR = new QTreeWidgetItem(); offItemR->setText(0, "Offset:"); offItemR->setText(1, RzAddressString(sdb_num_get(sdb, "offset"))); ui->rightTreeWidget->addTopLevelItem(offItemR); QTreeWidgetItem *entriesItemR = new QTreeWidgetItem(); entriesItemR->setText(0, "Entries:"); for (size_t num_version = 0;; num_version++) { auto path_version = QString("bin/cur/info/versioninfo/verneed/version%0").arg(num_version); sdb = sdb_ns_path(core->sdb, path_version.toStdString().c_str(), 0); if (!sdb) { break; } const char *filename = sdb_const_get(sdb, "file_name"); auto *parentItem = new QTreeWidgetItem(); parentItem->setText(0, RzAddressString(sdb_num_get(sdb, "idx"))); parentItem->setText(1, QString("Version: %0\t" "File: %1") .arg(QString::number(sdb_num_get(sdb, "vn_version")), QString(filename))); int num_vernaux = 0; while (true) { auto path_vernaux = QString("%0/vernaux%1").arg(path_version, QString::number(num_vernaux++)); sdb = sdb_ns_path(core->sdb, path_vernaux.toStdString().c_str(), 0); if (!sdb) { break; } auto *childItem = new QTreeWidgetItem(); childItem->setText(0, RzAddressString(sdb_num_get(sdb, "idx"))); QString childString = QString("Name: %0\t" "Flags: %1\t" "Version: %2\t") .arg(sdb_const_get(sdb, "name"), sdb_const_get(sdb, "flags"), QString::number(sdb_num_get(sdb, "version"))); childItem->setText(1, childString); parentItem->addChild(childItem); } entriesItemR->addChild(parentItem); } ui->rightTreeWidget->addTopLevelItem(entriesItemR); // Adjust columns to content qhelpers::adjustColumns(ui->rightTreeWidget, 0); } // Case PE else if (strncmp("pe", info->rclass, 2) == 0) { // Set labels ui->leftLabel->setText("VS Fixed file info"); ui->rightLabel->setText("String table"); Sdb *sdb = NULL; // Left tree auto path_version = QString("bin/cur/info/vs_version_info/VS_VERSIONINFO%0").arg(0); auto path_fixedfileinfo = QString("%0/fixed_file_info").arg(path_version); sdb = sdb_ns_path(core->sdb, path_fixedfileinfo.toStdString().c_str(), 0); if (!sdb) { return; } ut32 file_version_ms = sdb_num_get(sdb, "FileVersionMS"); ut32 file_version_ls = sdb_num_get(sdb, "FileVersionLS"); auto file_version = QString("%0.%1.%2.%3") .arg(file_version_ms >> 16) .arg(file_version_ms & 0xFFFF) .arg(file_version_ls >> 16) .arg(file_version_ls & 0xFFFF); ut32 product_version_ms = sdb_num_get(sdb, "ProductVersionMS"); ut32 product_version_ls = sdb_num_get(sdb, "ProductVersionLS"); auto product_version = QString("%0.%1.%2.%3") .arg(product_version_ms >> 16) .arg(product_version_ms & 0xFFFF) .arg(product_version_ls >> 16) .arg(product_version_ls & 0xFFFF); auto item = new QTreeWidgetItem(); item->setText(0, "Signature"); item->setText(1, RzHexString(sdb_num_get(sdb, "Signature"))); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "StrucVersion"); item->setText(1, RzHexString(sdb_num_get(sdb, "StrucVersion"))); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "FileVersion"); item->setText(1, file_version); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "ProductVersion"); item->setText(1, product_version); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "FileFlagsMask"); item->setText(1, RzHexString(sdb_num_get(sdb, "FileFlagsMask"))); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "FileFlags"); item->setText(1, RzHexString(sdb_num_get(sdb, "FileFlags"))); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "FileOS"); item->setText(1, RzHexString(sdb_num_get(sdb, "FileOS"))); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "FileType"); item->setText(1, RzHexString(sdb_num_get(sdb, "FileType"))); ui->leftTreeWidget->addTopLevelItem(item); item = new QTreeWidgetItem(); item->setText(0, "FileSubType"); item->setText(1, RzHexString(sdb_num_get(sdb, "FileSubType"))); ui->leftTreeWidget->addTopLevelItem(item); // Adjust columns to content qhelpers::adjustColumns(ui->leftTreeWidget, 0); // Right tree for (int num_stringtable = 0;; num_stringtable++) { auto path_stringtable = QString("%0/string_file_info/stringtable%1") .arg(path_version) .arg(num_stringtable); sdb = sdb_ns_path(core->sdb, path_stringtable.toStdString().c_str(), 0); if (!sdb) { break; } for (int num_string = 0; sdb; num_string++) { auto path_string = QString("%0/string%1").arg(path_stringtable).arg(num_string); sdb = sdb_ns_path(core->sdb, path_string.toStdString().c_str(), 0); if (!sdb) { continue; } int lenkey = 0; int lenval = 0; ut8 *key_utf16 = sdb_decode(sdb_const_get(sdb, "key"), &lenkey); ut8 *val_utf16 = sdb_decode(sdb_const_get(sdb, "value"), &lenval); item = new QTreeWidgetItem(); item->setText(0, QString::fromUtf16(reinterpret_cast<const ushort *>(key_utf16))); item->setText(1, QString::fromUtf16(reinterpret_cast<const ushort *>(val_utf16))); ui->rightTreeWidget->addTopLevelItem(item); free(key_utf16); free(val_utf16); } } qhelpers::adjustColumns(ui->rightTreeWidget, 0); } }
9,839
C++
.cpp
210
34.238095
98
0.555417
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,522
EditFunctionDialog.cpp
rizinorg_cutter/src/dialogs/EditFunctionDialog.cpp
#include "EditFunctionDialog.h" #include "ui_EditFunctionDialog.h" EditFunctionDialog::EditFunctionDialog(QWidget *parent) : QDialog(parent), ui(new Ui::EditFunctionDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); } EditFunctionDialog::~EditFunctionDialog() {} QString EditFunctionDialog::getNameText() { QString ret = ui->nameLineEdit->text(); return ret; } void EditFunctionDialog::setNameText(const QString &name) { ui->nameLineEdit->setText(name); } QString EditFunctionDialog::getStartAddrText() { QString ret = ui->startLineEdit->text(); return ret; } void EditFunctionDialog::setStartAddrText(const QString &startAddr) { ui->startLineEdit->setText(startAddr); } QString EditFunctionDialog::getStackSizeText() { QString ret = ui->stackSizeLineEdit->text(); return ret; } void EditFunctionDialog::setStackSizeText(const QString &stackSize) { ui->stackSizeLineEdit->setText(stackSize); } void EditFunctionDialog::setCallConList(const QStringList &callConList) { ui->callConComboBox->addItems(callConList); } void EditFunctionDialog::setCallConSelected(const QString &selected) { ui->callConComboBox->setCurrentText(selected); } QString EditFunctionDialog::getCallConSelected() { return ui->callConComboBox->currentText(); } void EditFunctionDialog::on_buttonBox_accepted() {} void EditFunctionDialog::on_buttonBox_rejected() { close(); }
1,467
C++
.cpp
53
25.226415
71
0.78444
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,523
AsmOptionsWidget.cpp
rizinorg_cutter/src/dialogs/preferences/AsmOptionsWidget.cpp
#include <QLabel> #include <QFontDialog> #include "AsmOptionsWidget.h" #include "ui_AsmOptionsWidget.h" #include "PreferencesDialog.h" #include "common/Helpers.h" #include "common/Configuration.h" AsmOptionsWidget::AsmOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog), ui(new Ui::AsmOptionsWidget) { ui->setupUi(this); ui->syntaxComboBox->blockSignals(true); for (const auto &syntax : Core()->getConfigOptions("asm.syntax")) ui->syntaxComboBox->addItem(syntax, syntax); ui->syntaxComboBox->blockSignals(false); checkboxes = { { ui->describeCheckBox, "asm.describe" }, { ui->refptrCheckBox, "asm.refptr" }, { ui->xrefCheckBox, "asm.xrefs" }, { ui->bblineCheckBox, "asm.bb.line" }, { ui->varsubCheckBox, "asm.sub.var" }, { ui->varsubOnlyCheckBox, "asm.sub.varonly" }, { ui->lbytesCheckBox, "asm.lbytes" }, { ui->bytespaceCheckBox, "asm.bytes.space" }, { ui->bytesCheckBox, "asm.bytes" }, { ui->xrefCheckBox, "asm.xrefs" }, { ui->indentCheckBox, "asm.indent" }, { ui->offsetCheckBox, "asm.offset" }, { ui->relOffsetCheckBox, "asm.reloff" }, { ui->relOffFlagsCheckBox, "asm.reloff.flags" }, { ui->slowCheckBox, "asm.slow" }, { ui->linesCheckBox, "asm.lines" }, { ui->fcnlinesCheckBox, "asm.lines.fcn" }, { ui->flgoffCheckBox, "asm.flags.offset" }, { ui->emuCheckBox, "asm.emu" }, { ui->emuStrCheckBox, "emu.str" }, { ui->varsumCheckBox, "asm.var.summary" }, { ui->sizeCheckBox, "asm.size" }, { ui->realnameCheckBox, "asm.flags.real" } }; QList<ConfigCheckbox>::iterator confCheckbox; // Connect each checkbox from "checkboxes" to the generic signal "checkboxEnabler" for (confCheckbox = checkboxes.begin(); confCheckbox != checkboxes.end(); ++confCheckbox) { QString val = confCheckbox->config; QCheckBox &cb = *confCheckbox->checkBox; connect(confCheckbox->checkBox, &QCheckBox::stateChanged, [this, val, &cb]() { checkboxEnabler(&cb, val); }); } using indexSignalType = void (QComboBox::*)(int); connect(ui->commentsComboBox, static_cast<indexSignalType>(&QComboBox::currentIndexChanged), this, &AsmOptionsWidget::commentsComboBoxChanged); connect(ui->asmComboBox, static_cast<indexSignalType>(&QComboBox::currentIndexChanged), this, &AsmOptionsWidget::asmComboBoxChanged); connect(ui->offsetCheckBox, &QCheckBox::toggled, this, &AsmOptionsWidget::offsetCheckBoxToggled); connect(ui->relOffsetCheckBox, &QCheckBox::toggled, this, &AsmOptionsWidget::relOffCheckBoxToggled); connect(Core(), &CutterCore::asmOptionsChanged, this, &AsmOptionsWidget::updateAsmOptionsFromVars); connect(ui->varTooltipsCheckBox, &QCheckBox::toggled, [this](bool checked) { Config()->setShowVarTooltips(checked); triggerAsmOptionsChanged(); }); updateAsmOptionsFromVars(); } AsmOptionsWidget::~AsmOptionsWidget() {} void AsmOptionsWidget::updateAsmOptionsFromVars() { bool cmtRightEnabled = Config()->getConfigBool("asm.cmt.right"); ui->cmtcolSpinBox->blockSignals(true); ui->cmtcolSpinBox->setValue(Config()->getConfigInt("asm.cmt.col")); ui->cmtcolSpinBox->blockSignals(false); ui->cmtcolSpinBox->setEnabled(cmtRightEnabled); bool offsetsEnabled = Config()->getConfigBool("asm.offset") || Config()->getConfigBool("graph.offset"); ui->relOffsetLabel->setEnabled(offsetsEnabled); ui->relOffsetCheckBox->setEnabled(offsetsEnabled); ui->relOffFlagsCheckBox->setEnabled(Config()->getConfigBool("asm.offset") && Config()->getConfigBool("asm.reloff")); bool bytesEnabled = Config()->getConfigBool("asm.bytes"); ui->bytespaceCheckBox->setEnabled(bytesEnabled); ui->lbytesCheckBox->setEnabled(bytesEnabled); ui->nbytesSpinBox->blockSignals(true); ui->nbytesSpinBox->setValue(Config()->getConfigInt("asm.nbytes")); ui->nbytesSpinBox->blockSignals(false); ui->nbytesLabel->setEnabled(bytesEnabled); ui->nbytesSpinBox->setEnabled(bytesEnabled); bool varsubEnabled = Config()->getConfigBool("asm.sub.var"); ui->varsubOnlyCheckBox->setEnabled(varsubEnabled); ui->asmComboBox->blockSignals(true); if (Config()->getConfigBool("asm.esil")) { ui->asmComboBox->setCurrentIndex(1); } else if (Config()->getConfigBool("asm.pseudo")) { ui->asmComboBox->setCurrentIndex(2); } else { ui->asmComboBox->setCurrentIndex(0); } ui->asmComboBox->blockSignals(false); QString currentSyntax = Config()->getConfigString("asm.syntax"); for (int i = 0; i < ui->syntaxComboBox->count(); i++) { if (ui->syntaxComboBox->itemData(i) == currentSyntax) { ui->syntaxComboBox->blockSignals(true); ui->syntaxComboBox->setCurrentIndex(i); ui->syntaxComboBox->blockSignals(false); break; } } ui->caseComboBox->blockSignals(true); if (Config()->getConfigBool("asm.ucase")) { ui->caseComboBox->setCurrentIndex(1); } else if (Config()->getConfigBool("asm.capitalize")) { ui->caseComboBox->setCurrentIndex(2); } else { ui->caseComboBox->setCurrentIndex(0); } ui->caseComboBox->blockSignals(false); ui->asmTabsSpinBox->blockSignals(true); ui->asmTabsSpinBox->setValue(Config()->getConfigInt("asm.tabs")); ui->asmTabsSpinBox->blockSignals(false); ui->asmTabsOffSpinBox->blockSignals(true); ui->asmTabsOffSpinBox->setValue(Config()->getConfigInt("asm.tabs.off")); ui->asmTabsOffSpinBox->blockSignals(false); ui->previewCheckBox->blockSignals(true); ui->previewCheckBox->setChecked(Config()->getPreviewValue()); ui->previewCheckBox->blockSignals(false); qhelpers::setCheckedWithoutSignals(ui->varTooltipsCheckBox, Config()->getShowVarTooltips()); QList<ConfigCheckbox>::iterator confCheckbox; // Set the value for each checkbox in "checkboxes" as it exists in the configuration for (confCheckbox = checkboxes.begin(); confCheckbox != checkboxes.end(); ++confCheckbox) { qhelpers::setCheckedWithoutSignals(confCheckbox->checkBox, Config()->getConfigBool(confCheckbox->config)); } } void AsmOptionsWidget::resetToDefault() { Config()->resetToDefaultAsmOptions(); updateAsmOptionsFromVars(); triggerAsmOptionsChanged(); } void AsmOptionsWidget::triggerAsmOptionsChanged() { disconnect(Core(), &CutterCore::asmOptionsChanged, this, &AsmOptionsWidget::updateAsmOptionsFromVars); Core()->triggerAsmOptionsChanged(); connect(Core(), &CutterCore::asmOptionsChanged, this, &AsmOptionsWidget::updateAsmOptionsFromVars); } void AsmOptionsWidget::on_cmtcolSpinBox_valueChanged(int value) { Config()->setConfig("asm.cmt.col", value); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_bytesCheckBox_toggled(bool checked) { Config()->setConfig("asm.bytes", checked); ui->bytespaceCheckBox->setEnabled(checked); ui->lbytesCheckBox->setEnabled(checked); ui->nbytesLabel->setEnabled(checked); ui->nbytesSpinBox->setEnabled(checked); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_nbytesSpinBox_valueChanged(int value) { Config()->setConfig("asm.nbytes", value); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_syntaxComboBox_currentIndexChanged(int index) { Config()->setConfig("asm.syntax", ui->syntaxComboBox->itemData(index).toString().toUtf8().constData()); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_caseComboBox_currentIndexChanged(int index) { bool ucase; bool capitalize; switch (index) { // lowercase case 0: default: ucase = false; capitalize = false; break; // uppercase case 1: ucase = true; capitalize = false; break; case 2: ucase = false; capitalize = true; break; } Config()->setConfig("asm.ucase", ucase); Config()->setConfig("asm.capitalize", capitalize); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_asmTabsSpinBox_valueChanged(int value) { Config()->setConfig("asm.tabs", value); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_asmTabsOffSpinBox_valueChanged(int value) { Config()->setConfig("asm.tabs.off", value); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_varsubCheckBox_toggled(bool checked) { Config()->setConfig("asm.sub.var", checked); ui->varsubOnlyCheckBox->setEnabled(checked); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_previewCheckBox_toggled(bool checked) { Config()->setPreviewValue(checked); triggerAsmOptionsChanged(); } void AsmOptionsWidget::on_buttonBox_clicked(QAbstractButton *button) { switch (ui->buttonBox->buttonRole(button)) { case QDialogButtonBox::ButtonRole::ResetRole: resetToDefault(); break; default: break; } } void AsmOptionsWidget::commentsComboBoxChanged(int index) { // Check if comments should be set to right Config()->setConfig("asm.cmt.right", index != 1); // Check if comments are disabled ui->cmtcolSpinBox->setEnabled(index != 1); // Show\Hide comments in disassembly based on whether "Off" is selected Config()->setConfig("asm.comments", index != 2); // Enable comments-related checkboxes only if Comments are enabled ui->xrefCheckBox->setEnabled(index != 2); ui->refptrCheckBox->setEnabled(index != 2); ui->describeCheckBox->setEnabled(index != 2); triggerAsmOptionsChanged(); } void AsmOptionsWidget::asmComboBoxChanged(int index) { // Check if ESIL enabled Config()->setConfig("asm.esil", index == 1); // Check if Pseudocode enabled Config()->setConfig("asm.pseudo", index == 2); triggerAsmOptionsChanged(); } void AsmOptionsWidget::offsetCheckBoxToggled(bool checked) { ui->relOffsetLabel->setEnabled(checked || Config()->getConfigBool("graph.offset")); ui->relOffsetCheckBox->setEnabled(checked || Config()->getConfigBool("graph.offset")); ui->relOffFlagsCheckBox->setEnabled(checked && Config()->getConfigBool("asm.reloff")); } void AsmOptionsWidget::relOffCheckBoxToggled(bool checked) { ui->relOffFlagsCheckBox->setEnabled(checked && Config()->getConfigBool("asm.offset")); } /** * @brief A generic signal to handle the simple cases where a checkbox is toggled * while it only responsible for a single independent boolean configuration eval. * @param checkBox - The checkbox which is responsible for the siganl * @param config - the configuration string to be toggled */ void AsmOptionsWidget::checkboxEnabler(QCheckBox *checkBox, QString config) { Config()->setConfig(config, checkBox->isChecked()); triggerAsmOptionsChanged(); }
11,289
C++
.cpp
269
35.423792
97
0.682224
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,524
InitializationFileEditor.cpp
rizinorg_cutter/src/dialogs/preferences/InitializationFileEditor.cpp
#include <QLabel> #include <QFontDialog> #include <QTextEdit> #include <QDir> #include <QFile> #include <QTextStream> #include <QDialogButtonBox> #include <QUrl> #include "InitializationFileEditor.h" #include "ui_InitializationFileEditor.h" #include "PreferencesDialog.h" #include "common/Helpers.h" #include "common/Configuration.h" InitializationFileEditor::InitializationFileEditor(PreferencesDialog *dialog) : QDialog(dialog), ui(new Ui::InitializationFileEditor) { ui->setupUi(this); connect(ui->saveRC, &QDialogButtonBox::accepted, this, &InitializationFileEditor::saveCutterRC); connect(ui->executeNow, &QDialogButtonBox::accepted, this, &InitializationFileEditor::executeCutterRC); connect(ui->ConfigFileEdit, &QPlainTextEdit::modificationChanged, ui->saveRC, &QWidget::setEnabled); const QDir cutterRCDirectory = Core()->getCutterRCDefaultDirectory(); auto cutterRCFileInfo = QFileInfo(cutterRCDirectory, "rc"); QString cutterRCLocation = cutterRCFileInfo.absoluteFilePath(); ui->cutterRCLoaded->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->cutterRCLoaded->setOpenExternalLinks(true); ui->cutterRCLoaded->setText( tr("Script is loaded from <a href=\"%1\">%2</a>") .arg(QUrl::fromLocalFile(cutterRCDirectory.absolutePath()).toString(), cutterRCLocation.toHtmlEscaped())); ui->executeNow->button(QDialogButtonBox::Retry)->setText("Execute"); ui->ConfigFileEdit->clear(); if (cutterRCFileInfo.exists()) { QFile cutterRC(cutterRCLocation); if (cutterRC.open(QIODevice::ReadWrite | QIODevice::Text)) { ui->ConfigFileEdit->setPlainText(cutterRC.readAll()); } cutterRC.close(); } ui->saveRC->setDisabled(true); } InitializationFileEditor::~InitializationFileEditor() {}; void InitializationFileEditor::saveCutterRC() { const QDir cutterRCDirectory = Core()->getCutterRCDefaultDirectory(); if (!cutterRCDirectory.exists()) { cutterRCDirectory.mkpath("."); } auto cutterRCFileInfo = QFileInfo(cutterRCDirectory, "rc"); QString cutterRCLocation = cutterRCFileInfo.absoluteFilePath(); QFile cutterRC(cutterRCLocation); if (cutterRC.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { QTextStream out(&cutterRC); QString text = ui->ConfigFileEdit->toPlainText(); out << text; cutterRC.close(); } ui->ConfigFileEdit->document()->setModified(false); } void InitializationFileEditor::executeCutterRC() { saveCutterRC(); Core()->loadDefaultCutterRC(); }
2,661
C++
.cpp
65
35.569231
100
0.723791
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,525
AnalysisOptionsWidget.cpp
rizinorg_cutter/src/dialogs/preferences/AnalysisOptionsWidget.cpp
#include "AnalysisOptionsWidget.h" #include "ui_AnalysisOptionsWidget.h" #include "PreferencesDialog.h" #include "common/Helpers.h" #include "common/Configuration.h" #include "core/MainWindow.h" static const QHash<QString, QString> analysisBoundaries { { "io.maps.x", "All executable maps" }, { "io.maps", "All maps" }, { "io.map", "Current map" }, { "raw", "Raw" }, { "bin.section", "Current mapped section" }, { "bin.sections", "All mapped sections" }, }; AnalysisOptionsWidget::AnalysisOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog), ui(new Ui::AnalysisOptionsWidget) { ui->setupUi(this); checkboxes = { { ui->autonameCheckbox, "analysis.autoname" }, { ui->hasnextCheckbox, "analysis.hasnext" }, { ui->jmpRefCheckbox, "analysis.jmp.ref" }, { ui->jmpTblCheckbox, "analysis.jmp.tbl" }, { ui->pushRetCheckBox, "analysis.pushret" }, { ui->typesVerboseCheckBox, "analysis.types.verbose" }, { ui->verboseCheckBox, "analysis.verbose" } }; // Create list of options for the analysis.in selector createAnalysisInOptionsList(); // Connect each checkbox from "checkboxes" to the generic signal "checkboxEnabler" for (ConfigCheckbox &confCheckbox : checkboxes) { QString val = confCheckbox.config; QCheckBox &cb = *confCheckbox.checkBox; connect(confCheckbox.checkBox, &QCheckBox::stateChanged, this, [val, &cb]() { checkboxEnabler(&cb, val); }); } ui->analyzePushButton->setToolTip("Analyze the program using Rizin's \"aaa\" command"); auto *mainWindow = new MainWindow(this); connect(ui->analyzePushButton, &QPushButton::clicked, mainWindow, &MainWindow::on_actionAnalyze_triggered); connect<void (QComboBox::*)(int)>(ui->analysisInComboBox, &QComboBox::currentIndexChanged, this, &AnalysisOptionsWidget::updateAnalysisIn); connect<void (QSpinBox::*)(int)>(ui->ptrDepthSpinBox, &QSpinBox::valueChanged, this, &AnalysisOptionsWidget::updateAnalysisPtrDepth); connect(ui->preludeLineEdit, &QLineEdit::textChanged, this, &AnalysisOptionsWidget::updateAnalysisPrelude); updateAnalysisOptionsFromVars(); } AnalysisOptionsWidget::~AnalysisOptionsWidget() {} void AnalysisOptionsWidget::checkboxEnabler(QCheckBox *checkBox, const QString &config) { Config()->setConfig(config, checkBox->isChecked()); } void AnalysisOptionsWidget::updateAnalysisOptionsFromVars() { for (ConfigCheckbox &confCheckbox : checkboxes) { qhelpers::setCheckedWithoutSignals(confCheckbox.checkBox, Core()->getConfigb(confCheckbox.config)); } // Update the rest of analysis options that are not checkboxes ui->analysisInComboBox->setCurrentIndex( ui->analysisInComboBox->findData(Core()->getConfig("analysis.in"))); ui->ptrDepthSpinBox->setValue(Core()->getConfigi("analysis.ptrdepth")); ui->preludeLineEdit->setText(Core()->getConfig("analysis.prelude")); } void AnalysisOptionsWidget::updateAnalysisIn(int index) { Config()->setConfig("analysis.in", ui->analysisInComboBox->itemData(index).toString()); } void AnalysisOptionsWidget::updateAnalysisPtrDepth(int value) { Config()->setConfig("analysis.ptrdepth", value); } void AnalysisOptionsWidget::updateAnalysisPrelude(const QString &prelude) { Config()->setConfig("analysis.prelude", prelude); } void AnalysisOptionsWidget::createAnalysisInOptionsList() { QHash<QString, QString>::const_iterator mapIter; mapIter = analysisBoundaries.cbegin(); ui->analysisInComboBox->blockSignals(true); ui->analysisInComboBox->clear(); for (; mapIter != analysisBoundaries.cend(); ++mapIter) { ui->analysisInComboBox->addItem(mapIter.value(), mapIter.key()); } ui->analysisInComboBox->blockSignals(false); }
4,013
C++
.cpp
86
39.918605
100
0.691993
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,526
PreferencesDialog.cpp
rizinorg_cutter/src/dialogs/preferences/PreferencesDialog.cpp
#include "PreferencesDialog.h" #include "ui_PreferencesDialog.h" #include "AppearanceOptionsWidget.h" #include "AsmOptionsWidget.h" #include "GraphOptionsWidget.h" #include "DebugOptionsWidget.h" #include "PluginsOptionsWidget.h" #include "InitializationFileEditor.h" #include "AnalysisOptionsWidget.h" #include "PreferenceCategory.h" #include "common/Helpers.h" #include "common/Configuration.h" #include <QDialogButtonBox> PreferencesDialog::PreferencesDialog(QWidget *parent) : QDialog(parent), ui(new Ui::PreferencesDialog) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); QList<PreferenceCategory> prefs { { tr("Disassembly"), new AsmOptionsWidget(this), QIcon(":/img/icons/disas.svg"), { { "Graph", new GraphOptionsWidget(this), QIcon(":/img/icons/graph.svg") }, } }, { tr("Debug"), new DebugOptionsWidget(this), QIcon(":/img/icons/bug.svg") }, { tr("Appearance"), new AppearanceOptionsWidget(this), QIcon(":/img/icons/polar.svg") }, { tr("Plugins"), new PluginsOptionsWidget(this), QIcon(":/img/icons/plugins.svg") }, { tr("Initialization Script"), new InitializationFileEditor(this), QIcon(":/img/icons/initialization.svg") }, { tr("Analysis"), new AnalysisOptionsWidget(this), QIcon(":/img/icons/cog_light.svg") } }; for (auto &c : prefs) { c.addItem(*ui->configCategories, *ui->configPanel); } connect(ui->configCategories, &QTreeWidget::currentItemChanged, this, &PreferencesDialog::changePage); connect(ui->saveButtons, &QDialogButtonBox::accepted, this, &QWidget::close); QTreeWidgetItem *defitem = ui->configCategories->topLevelItem(0); ui->configCategories->setCurrentItem(defitem, 0); connect(Config(), &Configuration::interfaceThemeChanged, this, &PreferencesDialog::chooseThemeIcons); chooseThemeIcons(); } PreferencesDialog::~PreferencesDialog() {} void PreferencesDialog::showSection(PreferencesDialog::Section section) { QTreeWidgetItem *defitem; switch (section) { case Section::Appearance: ui->configPanel->setCurrentIndex(0); defitem = ui->configCategories->topLevelItem(0); ui->configCategories->setCurrentItem(defitem, 0); break; case Section::Disassembly: ui->configPanel->setCurrentIndex(1); defitem = ui->configCategories->topLevelItem(1); ui->configCategories->setCurrentItem(defitem, 1); break; } } void PreferencesDialog::changePage(QTreeWidgetItem *current, QTreeWidgetItem *previous) { if (!current) current = previous; int index = current->data(0, Qt::UserRole).toInt(); if (index) ui->configPanel->setCurrentIndex(index - 1); } void PreferencesDialog::chooseThemeIcons() { // List of QActions which have alternative icons in different themes const QList<QPair<QString, QString>> kCategoryIconsNames { { QStringLiteral("Debug"), QStringLiteral("bug.svg") }, { QStringLiteral("Assembly"), QStringLiteral("disas.svg") }, { QStringLiteral("Graph"), QStringLiteral("graph.svg") }, { QStringLiteral("Appearance"), QStringLiteral("polar.svg") }, { QStringLiteral("Plugins"), QStringLiteral("plugins.svg") }, { QStringLiteral("Initialization Script"), QStringLiteral("initialization.svg") }, { QStringLiteral("Analysis"), QStringLiteral("cog_light.svg") }, }; QList<QPair<void *, QString>> supportedIconsNames; foreach (const auto &p, kCategoryIconsNames) { QList<QTreeWidgetItem *> items = ui->configCategories->findItems(p.first, Qt::MatchContains | Qt::MatchRecursive, 0); if (items.isEmpty()) { continue; } supportedIconsNames.append({ items.first(), p.second }); } // Set the correct icon for the QAction qhelpers::setThemeIcons(supportedIconsNames, [](void *obj, const QIcon &icon) { // here we have our setter functor, in this case it is almost "unique" because it specified // the column in `setIcon` call static_cast<QTreeWidgetItem *>(obj)->setIcon(0, icon); }); }
4,290
C++
.cpp
98
37.561224
100
0.686556
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,527
AppearanceOptionsWidget.cpp
rizinorg_cutter/src/dialogs/preferences/AppearanceOptionsWidget.cpp
#include <QDir> #include <QFile> #include <QLabel> #include <QPainter> #include <QFontDialog> #include <QFileDialog> #include <QTranslator> #include <QInputDialog> #include <QSignalBlocker> #include <QStandardPaths> #include <QtSvg/QSvgRenderer> #include <QComboBox> #include <QtWidgets/QSpinBox> #include "PreferencesDialog.h" #include "AppearanceOptionsWidget.h" #include "ui_AppearanceOptionsWidget.h" #include "common/Helpers.h" #include "common/Configuration.h" #include "common/ColorThemeWorker.h" #include "dialogs/preferences/ColorThemeEditDialog.h" #include "widgets/ColorPicker.h" AppearanceOptionsWidget::AppearanceOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog), ui(new Ui::AppearanceOptionsWidget) { ui->setupUi(this); updateFromConfig(); QStringList langs = Config()->getAvailableTranslations(); ui->languageComboBox->addItems(langs); QString curr = Config()->getCurrLocale().nativeLanguageName(); if (!langs.contains(curr)) { curr = "English"; } ui->languageComboBox->setCurrentText(curr); auto setIcons = [this]() { QColor textColor = palette().text().color(); ui->editButton->setIcon(getIconFromSvg(":/img/icons/pencil_thin.svg", textColor)); ui->deleteButton->setIcon(getIconFromSvg(":/img/icons/trash_bin.svg", textColor)); ui->copyButton->setIcon(getIconFromSvg(":/img/icons/copy.svg", textColor)); ui->importButton->setIcon(getIconFromSvg(":/img/icons/download_black.svg", textColor)); ui->exportButton->setIcon(getIconFromSvg(":/img/icons/upload_black.svg", textColor)); ui->renameButton->setIcon(getIconFromSvg(":/img/icons/rename.svg", textColor)); }; setIcons(); connect(Config(), &Configuration::interfaceThemeChanged, this, setIcons); connect(ui->languageComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &AppearanceOptionsWidget::onLanguageComboBoxCurrentIndexChanged); connect(Config(), &Configuration::fontsUpdated, this, &AppearanceOptionsWidget::updateFontFromConfig); connect(ui->colorComboBox, &QComboBox::currentTextChanged, this, &AppearanceOptionsWidget::updateModificationButtons); connect(ui->fontZoomBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &AppearanceOptionsWidget::onFontZoomBoxValueChanged); ui->useDecompilerHighlighter->setChecked(Config()->isDecompilerAnnotationHighlighterEnabled()); connect(ui->useDecompilerHighlighter, &QCheckBox::toggled, this, [](bool checked) { Config()->enableDecompilerAnnotationHighlighter(checked); }); } AppearanceOptionsWidget::~AppearanceOptionsWidget() {} void AppearanceOptionsWidget::updateFontFromConfig() { QFont currentFont = Config()->getBaseFont(); ui->fontSelectionLabel->setText(currentFont.toString()); } void AppearanceOptionsWidget::updateThemeFromConfig(bool interfaceThemeChanged) { // Disconnect currentIndexChanged because clearing the comboxBox and refiling it causes its // index to change. QSignalBlocker signalBlockerThemeBox(ui->themeComboBox); ui->themeComboBox->clear(); for (auto &it : Configuration::cutterInterfaceThemesList()) { ui->themeComboBox->addItem(it.name); } int currInterfaceThemeIndex = Config()->getInterfaceTheme(); if (currInterfaceThemeIndex >= Configuration::cutterInterfaceThemesList().size()) { currInterfaceThemeIndex = 0; Config()->setInterfaceTheme(currInterfaceThemeIndex); } ui->themeComboBox->setCurrentIndex(currInterfaceThemeIndex); ui->colorComboBox->updateFromConfig(interfaceThemeChanged); updateModificationButtons(ui->colorComboBox->currentText()); } void AppearanceOptionsWidget::onFontZoomBoxValueChanged(int zoom) { qreal zoomFactor = zoom / 100.0; Config()->setZoomFactor(zoomFactor); } void AppearanceOptionsWidget::on_fontSelectionButton_clicked() { QFont currentFont = Config()->getBaseFont(); bool ok; QFont newFont = QFontDialog::getFont(&ok, currentFont, this, QString(), QFontDialog::DontUseNativeDialog); if (ok) { Config()->setFont(newFont); } } void AppearanceOptionsWidget::on_themeComboBox_currentIndexChanged(int index) { Config()->setInterfaceTheme(index); updateThemeFromConfig(); } void AppearanceOptionsWidget::on_editButton_clicked() { ColorThemeEditDialog dial; dial.setWindowTitle(tr("Theme Editor - <%1>").arg(ui->colorComboBox->currentText())); dial.exec(); ui->colorComboBox->updateFromConfig(false); } void AppearanceOptionsWidget::on_copyButton_clicked() { QString currColorTheme = ui->colorComboBox->currentText(); QString newThemeName; do { newThemeName = QInputDialog::getText(this, tr("Enter theme name"), tr("Name:"), QLineEdit::Normal, currColorTheme + tr(" - copy")) .trimmed(); if (newThemeName.isEmpty()) { return; } if (ThemeWorker().isThemeExist(newThemeName)) { QMessageBox::information(this, tr("Theme Copy"), tr("Theme named %1 already exists.").arg(newThemeName)); } else { break; } } while (true); ThemeWorker().copy(currColorTheme, newThemeName); Config()->setColorTheme(newThemeName); updateThemeFromConfig(false); } void AppearanceOptionsWidget::on_deleteButton_clicked() { QString currTheme = ui->colorComboBox->currentText(); if (!ThemeWorker().isCustomTheme(currTheme)) { QMessageBox::critical(nullptr, tr("Error"), ThemeWorker().deleteTheme(currTheme)); return; } int ret = QMessageBox::question( nullptr, tr("Delete"), tr("Are you sure you want to delete <b>%1</b>?").arg(currTheme)); if (ret == QMessageBox::Yes) { QString err = ThemeWorker().deleteTheme(currTheme); updateThemeFromConfig(false); if (!err.isEmpty()) { QMessageBox::critical(nullptr, tr("Error"), err); } } } void AppearanceOptionsWidget::on_importButton_clicked() { QString fileName = QFileDialog::getOpenFileName( this, "", QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); if (fileName.isEmpty()) { return; } QString err = ThemeWorker().importTheme(fileName); QString themeName = QFileInfo(fileName).fileName(); if (err.isEmpty()) { QMessageBox::information( this, tr("Success"), tr("Color theme <b>%1</b> was successfully imported.").arg(themeName)); Config()->setColorTheme(themeName); updateThemeFromConfig(false); } else { QMessageBox::critical(this, tr("Error"), err); } } void AppearanceOptionsWidget::on_exportButton_clicked() { QString theme = ui->colorComboBox->currentText(); QString file = QFileDialog::getSaveFileName( this, "", QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + QDir::separator() + theme); if (file.isEmpty()) { return; } // User already gave his consent for this in QFileDialog::getSaveFileName() if (QFileInfo(file).exists()) { QFile(file).remove(); } QString err = ThemeWorker().save(ThemeWorker().getTheme(theme), file); if (err.isEmpty()) { QMessageBox::information(this, tr("Success"), tr("Color theme <b>%1</b> was successfully exported.").arg(theme)); } else { QMessageBox::critical(this, tr("Error"), err); } } void AppearanceOptionsWidget::on_renameButton_clicked() { QString currColorTheme = Config()->getColorTheme(); QString newName = QInputDialog::getText(this, tr("Enter new theme name"), tr("Name:"), QLineEdit::Normal, currColorTheme); if (newName.isEmpty() || newName == currColorTheme) { return; } QString err = ThemeWorker().renameTheme(currColorTheme, newName); if (!err.isEmpty()) { QMessageBox::critical(this, tr("Error"), err); } else { Config()->setColorTheme(newName); updateThemeFromConfig(false); } } void AppearanceOptionsWidget::onLanguageComboBoxCurrentIndexChanged(int index) { QString language = ui->languageComboBox->itemText(index).toLower(); if (Config()->setLocaleByName(language)) { QMessageBox::information(this, tr("Language settings"), tr("Language will be changed after next application start.")); return; } qWarning() << tr("Cannot set language, not found in available ones"); } void AppearanceOptionsWidget::updateModificationButtons(const QString &theme) { bool editable = ThemeWorker().isCustomTheme(theme); ui->editButton->setEnabled(editable); ui->deleteButton->setEnabled(editable); ui->renameButton->setEnabled(editable); } void AppearanceOptionsWidget::updateFromConfig() { updateFontFromConfig(); updateThemeFromConfig(false); ui->fontZoomBox->setValue(qRound(Config()->getZoomFactor() * 100)); } QIcon AppearanceOptionsWidget::getIconFromSvg(const QString &fileName, const QColor &after, const QColor &before) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { return QIcon(); } QString data = file.readAll(); data.replace(QRegularExpression(QString("#%1").arg(before.isValid() ? before.name().remove(0, 1) : "[0-9a-fA-F]{6}")), QString("%1").arg(after.name())); QSvgRenderer svgRenderer(data.toUtf8()); QPixmap pix(svgRenderer.defaultSize()); pix.fill(Qt::transparent); QPainter pixPainter(&pix); svgRenderer.render(&pixPainter); return pix; }
10,019
C++
.cpp
245
34.142857
100
0.679951
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,528
DebugOptionsWidget.cpp
rizinorg_cutter/src/dialogs/preferences/DebugOptionsWidget.cpp
#include "DebugOptionsWidget.h" #include "ui_DebugOptionsWidget.h" #include <QLabel> #include <QTimer> #include <QComboBox> #include <QShortcut> #include <QFontDialog> #include "PreferencesDialog.h" #include "common/Helpers.h" #include "common/Configuration.h" DebugOptionsWidget::DebugOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog), ui(new Ui::DebugOptionsWidget) { ui->setupUi(this); updateDebugPlugin(); connect(ui->pluginComboBox, &QComboBox::currentTextChanged, this, &DebugOptionsWidget::onDebugPluginChanged); } DebugOptionsWidget::~DebugOptionsWidget() {} void DebugOptionsWidget::updateDebugPlugin() { ui->traceContinue->setChecked(Config()->getConfigBool("dbg.trace_continue")); connect(ui->traceContinue, &QCheckBox::toggled, this, [](bool checked) { Config()->setConfig("dbg.trace_continue", checked); }); ui->esilBreakOnInvalid->setChecked(Config()->getConfigBool("esil.breakoninvalid")); connect(ui->esilBreakOnInvalid, &QCheckBox::toggled, this, [](bool checked) { Config()->setConfig("esil.breakoninvalid", checked); }); disconnect(ui->pluginComboBox, &QComboBox::currentTextChanged, this, &DebugOptionsWidget::onDebugPluginChanged); QStringList plugins = Core()->getDebugPlugins(); for (const QString &str : plugins) ui->pluginComboBox->addItem(str); QString plugin = Core()->getActiveDebugPlugin(); ui->pluginComboBox->setCurrentText(plugin); connect(ui->pluginComboBox, &QComboBox::currentTextChanged, this, &DebugOptionsWidget::onDebugPluginChanged); QString stackSize = Core()->getConfig("esil.stack.size"); ui->stackSize->setText(stackSize); ui->stackSize->setPlaceholderText(stackSize); QString stackAddr = Core()->getConfig("esil.stack.addr"); ui->stackAddr->setText(stackAddr); ui->stackAddr->setPlaceholderText(stackAddr); connect(ui->stackAddr, &QLineEdit::editingFinished, this, &DebugOptionsWidget::updateStackAddr); connect(ui->stackSize, &QLineEdit::editingFinished, this, &DebugOptionsWidget::updateStackSize); } void DebugOptionsWidget::onDebugPluginChanged(const QString &plugin) { Core()->setDebugPlugin(plugin); } void DebugOptionsWidget::updateStackSize() { QString newSize = ui->stackSize->text(); Core()->setConfig("esil.stack.size", newSize); ui->stackSize->setPlaceholderText(newSize); } void DebugOptionsWidget::updateStackAddr() { QString newAddr = ui->stackAddr->text(); Core()->setConfig("esil.stack.addr", newAddr); ui->stackAddr->setPlaceholderText(newAddr); }
2,621
C++
.cpp
61
38.672131
100
0.741163
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,529
PluginsOptionsWidget.cpp
rizinorg_cutter/src/dialogs/preferences/PluginsOptionsWidget.cpp
#include "PluginsOptionsWidget.h" #include "PreferencesDialog.h" #include "common/Helpers.h" #include "common/Configuration.h" #include "plugins/PluginManager.h" #include "dialogs/RizinPluginsDialog.h" #include <QLabel> #include <QPushButton> #include <QTreeWidget> #include <QVBoxLayout> #include <QUrl> PluginsOptionsWidget::PluginsOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog) { auto layout = new QVBoxLayout(this); setLayout(layout); auto dirLabel = new QLabel(this); dirLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); dirLabel->setOpenExternalLinks(true); layout->addWidget(dirLabel); auto pluginPath = Plugins()->getUserPluginsDirectory(); dirLabel->setText( tr("Plugins are loaded from <a href=\"%1\">%2</a>") .arg(QUrl::fromLocalFile(pluginPath).toString(), pluginPath.toHtmlEscaped())); auto treeWidget = new QTreeWidget(this); layout->addWidget(treeWidget); treeWidget->setRootIsDecorated(false); treeWidget->setHeaderLabels({ tr("Name"), tr("Description"), tr("Version"), tr("Author") }); for (auto &plugin : Plugins()->getPlugins()) { auto item = new QTreeWidgetItem(); item->setText(0, plugin->getName()); item->setText(1, plugin->getDescription()); item->setText(2, plugin->getVersion()); item->setText(3, plugin->getAuthor()); treeWidget->addTopLevelItem(item); } qhelpers::adjustColumns(treeWidget, 0); auto rzPluginsButton = new QPushButton(this); layout->addWidget(rzPluginsButton); rzPluginsButton->setText(tr("Show Rizin plugin information")); connect(rzPluginsButton, &QPushButton::clicked, this, [this]() { RizinPluginsDialog dialog(this); dialog.exec(); }); } PluginsOptionsWidget::~PluginsOptionsWidget() {}
1,843
C++
.cpp
45
35.822222
98
0.708613
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,530
GraphOptionsWidget.cpp
rizinorg_cutter/src/dialogs/preferences/GraphOptionsWidget.cpp
#include <QLabel> #include <QFontDialog> #include "GraphOptionsWidget.h" #include "ui_GraphOptionsWidget.h" #include "PreferencesDialog.h" #include "common/Helpers.h" #include "common/Configuration.h" GraphOptionsWidget::GraphOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog), ui(new Ui::GraphOptionsWidget) { ui->setupUi(this); ui->checkTransparent->setChecked(Config()->getBitmapTransparentState()); ui->blockEntryCheckBox->setChecked(Config()->getGraphBlockEntryOffset()); ui->graphPreviewCheckBox->setChecked(Config()->getGraphPreview()); ui->bitmapGraphScale->setValue(Config()->getBitmapExportScaleFactor() * 100.0); updateOptionsFromVars(); connect<void (QDoubleSpinBox::*)(double)>(ui->bitmapGraphScale, (&QDoubleSpinBox::valueChanged), this, &GraphOptionsWidget::bitmapGraphScaleValueChanged); connect(ui->checkTransparent, &QCheckBox::stateChanged, this, &GraphOptionsWidget::checkTransparentStateChanged); connect(ui->blockEntryCheckBox, &QCheckBox::stateChanged, this, &GraphOptionsWidget::checkGraphBlockEntryOffsetChanged); connect(Core(), &CutterCore::graphOptionsChanged, this, &GraphOptionsWidget::updateOptionsFromVars); QSpinBox *graphSpacingWidgets[] = { ui->horizontalEdgeSpacing, ui->horizontalBlockSpacing, ui->verticalEdgeSpacing, ui->verticalBlockSpacing }; for (auto widget : graphSpacingWidgets) { connect<void (QSpinBox::*)(int)>(widget, &QSpinBox::valueChanged, this, &GraphOptionsWidget::layoutSpacingChanged); } } GraphOptionsWidget::~GraphOptionsWidget() {} void GraphOptionsWidget::updateOptionsFromVars() { qhelpers::setCheckedWithoutSignals(ui->graphOffsetCheckBox, Config()->getConfigBool("graph.offset")); ui->maxColsSpinBox->blockSignals(true); ui->maxColsSpinBox->setValue(Config()->getGraphBlockMaxChars()); ui->maxColsSpinBox->blockSignals(false); ui->minFontSizeSpinBox->blockSignals(true); ui->minFontSizeSpinBox->setValue(Config()->getGraphMinFontSize()); ui->minFontSizeSpinBox->blockSignals(false); auto blockSpacing = Config()->getGraphBlockSpacing(); ui->horizontalBlockSpacing->setValue(blockSpacing.x()); ui->verticalBlockSpacing->setValue(blockSpacing.y()); auto edgeSpacing = Config()->getGraphEdgeSpacing(); ui->horizontalEdgeSpacing->setValue(edgeSpacing.x()); ui->verticalEdgeSpacing->setValue(edgeSpacing.y()); } void GraphOptionsWidget::triggerOptionsChanged() { disconnect(Core(), &CutterCore::graphOptionsChanged, this, &GraphOptionsWidget::updateOptionsFromVars); Core()->triggerGraphOptionsChanged(); connect(Core(), &CutterCore::graphOptionsChanged, this, &GraphOptionsWidget::updateOptionsFromVars); } void GraphOptionsWidget::on_maxColsSpinBox_valueChanged(int value) { Config()->setGraphBlockMaxChars(value); triggerOptionsChanged(); } void GraphOptionsWidget::on_minFontSizeSpinBox_valueChanged(int value) { Config()->setGraphMinFontSize(value); triggerOptionsChanged(); } void GraphOptionsWidget::on_graphOffsetCheckBox_toggled(bool checked) { Config()->setConfig("graph.offset", checked); emit Core()->asmOptionsChanged(); triggerOptionsChanged(); } void GraphOptionsWidget::on_graphPreviewCheckBox_toggled(bool checked) { Config()->setGraphPreview(checked); triggerOptionsChanged(); } void GraphOptionsWidget::checkTransparentStateChanged(int checked) { Config()->setBitmapTransparentState(checked); } void GraphOptionsWidget::bitmapGraphScaleValueChanged(double value) { double value_decimal = value / (double)100.0; Config()->setBitmapExportScaleFactor(value_decimal); } void GraphOptionsWidget::layoutSpacingChanged() { QPoint blockSpacing { ui->horizontalBlockSpacing->value(), ui->verticalBlockSpacing->value() }; QPoint edgeSpacing { ui->horizontalEdgeSpacing->value(), ui->verticalEdgeSpacing->value() }; Config()->setGraphSpacing(blockSpacing, edgeSpacing); triggerOptionsChanged(); } void GraphOptionsWidget::checkGraphBlockEntryOffsetChanged(bool checked) { Config()->setGraphBlockEntryOffset(checked); triggerOptionsChanged(); }
4,410
C++
.cpp
100
38.18
100
0.73515
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,531
ColorThemeEditDialog.cpp
rizinorg_cutter/src/dialogs/preferences/ColorThemeEditDialog.cpp
#include "ColorThemeEditDialog.h" #include "ui_ColorThemeEditDialog.h" #include "common/ColorThemeWorker.h" #include "common/Configuration.h" #include "widgets/ColorThemeListView.h" #include "widgets/DisassemblyWidget.h" #include <QScreen> #include <QKeyEvent> #include <QSortFilterProxyModel> ColorThemeEditDialog::ColorThemeEditDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ColorThemeEditDialog), configSignalBlocker( Config()), // Blocks signals from Config to avoid updating of widgets during editing colorTheme(Config()->getColorTheme()) { showAlphaOptions = { "gui.overview.border", "gui.overview.fill", "wordHighlight", "lineHighlight" }; ui->setupUi(this); ui->colorComboBox->setShowOnlyCustom(true); previewDisasmWidget = new DisassemblyWidget(nullptr); previewDisasmWidget->setObjectName("Preview Disasm"); previewDisasmWidget->setPreviewMode(true); #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) // default size limit is acceptable if (auto screen = qApp->screenAt(previewDisasmWidget->pos())) { previewDisasmWidget->setMinimumSize(screen->size() * 0.5); } #endif previewDisasmWidget->setWindowTitle(tr("Disassembly Preview")); previewDisasmWidget->setFeatures(QDockWidget::NoDockWidgetFeatures); ui->colorPickerAndPreviewLayout->addWidget(previewDisasmWidget); connect(ui->colorThemeListView, &ColorThemeListView::blink, previewDisasmWidget, &DisassemblyWidget::colorsUpdatedSlot); connect(ui->colorThemeListView, &ColorThemeListView::itemChanged, this, [this](const QColor &color) { ui->colorPicker->updateColor(color); QString optionName = ui->colorThemeListView->currentIndex() .data(Qt::UserRole) .value<ColorOption>() .optionName; ui->colorPicker->setAlphaEnabled(showAlphaOptions.contains(optionName)); }); connect(ui->filterLineEdit, &QLineEdit::textChanged, this, [this](const QString &s) { static_cast<QSortFilterProxyModel *>(ui->colorThemeListView->model()) ->setFilterFixedString(s); }); ui->colorThemeListView->setCurrentIndex(ui->colorThemeListView->model()->index(0, 0)); connect(ui->colorPicker, &ColorPicker::colorChanged, this, &ColorThemeEditDialog::colorOptionChanged); connect(ui->colorComboBox, &ColorThemeComboBox::currentTextChanged, this, &ColorThemeEditDialog::editThemeChanged); } ColorThemeEditDialog::~ColorThemeEditDialog() { delete ui; previewDisasmWidget->deleteLater(); } void ColorThemeEditDialog::accept() { colorTheme = Config()->getColorTheme(); ColorThemeWorker::Theme sch = ui->colorThemeListView->colorSettingsModel()->getTheme(); if (ThemeWorker().isCustomTheme(colorTheme)) { QString err = ThemeWorker().save(sch, colorTheme); if (!err.isEmpty()) { QMessageBox::critical(this, tr("Error"), err); return; } } configSignalBlocker.unblock(); Config()->setColorTheme(colorTheme); QDialog::accept(); } void ColorThemeEditDialog::reject() { if (themeWasEdited(ui->colorComboBox->currentText()) && QMessageBox::question(this, tr("Unsaved changes"), tr("Are you sure you want to exit without saving? " "All changes will be lost.")) == QMessageBox::No) { return; } configSignalBlocker.unblock(); Config()->setColorTheme(colorTheme); QDialog::reject(); } void ColorThemeEditDialog::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Escape: if (ui->colorPicker->isPickingFromScreen()) { ui->colorPicker->stopPickingFromScreen(); } // fallthrough case Qt::Key_Return: event->accept(); return; default: QDialog::keyPressEvent(event); } } void ColorThemeEditDialog::colorOptionChanged(const QColor &newColor) { QModelIndex currIndex = ui->colorThemeListView->currentIndex(); if (!currIndex.isValid()) { return; } ColorOption currOption = currIndex.data(Qt::UserRole).value<ColorOption>(); currOption.color = newColor; currOption.changed = true; ui->colorThemeListView->model()->setData(currIndex, QVariant::fromValue(currOption)); Config()->setColor(currOption.optionName, currOption.color); if (!ColorThemeWorker::cutterSpecificOptions.contains(currOption.optionName)) { Core()->setColor(currOption.optionName, currOption.color.name()); } previewDisasmWidget->colorsUpdatedSlot(); } void ColorThemeEditDialog::editThemeChanged(const QString &newTheme) { if (themeWasEdited(colorTheme)) { int ret = QMessageBox::question(this, tr("Unsaved changes"), tr("Are you sure you want to exit without saving? " "All changes will be lost.")); if (ret == QMessageBox::No) { QSignalBlocker s(ui->colorComboBox); // avoid second call of this func int index = ui->colorComboBox->findText(colorTheme); index = index == -1 ? 0 : index; ui->colorComboBox->setCurrentIndex(index); Config()->setColorTheme(colorTheme); return; } } colorTheme = newTheme; ui->colorThemeListView->colorSettingsModel()->updateTheme(); previewDisasmWidget->colorsUpdatedSlot(); setWindowTitle(tr("Theme Editor - <%1>").arg(colorTheme)); } bool ColorThemeEditDialog::themeWasEdited(const QString &theme) const { auto model = ui->colorThemeListView->colorSettingsModel(); return ThemeWorker().getTheme(theme) != model->getTheme(); }
5,952
C++
.cpp
142
33.929577
98
0.665226
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,532
PreferenceCategory.cpp
rizinorg_cutter/src/dialogs/preferences/PreferenceCategory.cpp
#include "PreferenceCategory.h" PreferenceCategory::PreferenceCategory(const QString &name, const QIcon &icon) : name(name), icon(icon), widget(nullptr), children {} { } PreferenceCategory::PreferenceCategory(const QString &name, QWidget *widget, const QIcon &icon) : name(name), icon(icon), widget(widget), children {} { } PreferenceCategory::PreferenceCategory(const QString &name, QWidget *widget, const QIcon &icon, const QList<PreferenceCategory> &children) : name(name), icon(icon), widget(widget), children(children) { } PreferenceCategory::PreferenceCategory(const QString &name, const QIcon &icon, const QList<PreferenceCategory> &children) : name(name), icon(icon), widget(nullptr), children(children) { } void PreferenceCategory::addItem(QTreeWidget &tree, QStackedWidget &panel) { QTreeWidgetItem *w = new QTreeWidgetItem({ name }); tree.addTopLevelItem(w); for (auto &c : children) c.addItem(*w, panel); w->setExpanded(true); w->setIcon(0, icon); if (widget) { panel.addWidget(widget); w->setData(0, Qt::UserRole, panel.count()); } } void PreferenceCategory::addItem(QTreeWidgetItem &tree, QStackedWidget &panel) { QTreeWidgetItem *w = new QTreeWidgetItem({ name }); tree.addChild(w); for (auto &c : children) c.addItem(*w, panel); w->setExpanded(true); w->setIcon(0, icon); if (widget) { panel.addWidget(widget); w->setData(0, Qt::UserRole, panel.count()); } }
1,585
C++
.cpp
45
29.555556
95
0.668194
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,533
PluginManager.cpp
rizinorg_cutter/src/plugins/PluginManager.cpp
#include <cassert> #ifdef CUTTER_ENABLE_PYTHON_BINDINGS # include <Python.h> # include <cutterbindings_python.h> # include "PythonManager.h" #endif #include "PluginManager.h" #include "CutterPlugin.h" #include "CutterConfig.h" #include "common/Helpers.h" #include "common/ResourcePaths.h" #include <QDir> #include <QCoreApplication> #include <QPluginLoader> #include <QStandardPaths> #include <QDebug> Q_GLOBAL_STATIC(PluginManager, uniqueInstance) PluginManager *PluginManager::getInstance() { return uniqueInstance; } PluginManager::PluginManager() {} PluginManager::~PluginManager() {} void PluginManager::loadPlugins(bool enablePlugins) { assert(plugins.empty()); if (!enablePlugins) { // [#2159] list but don't enable the plugins return; } QString userPluginDir = getUserPluginsDirectory(); if (!userPluginDir.isEmpty()) { loadPluginsFromDir(QDir(userPluginDir), true); } const auto pluginDirs = getPluginDirectories(); for (auto &dir : pluginDirs) { if (dir.absolutePath() == userPluginDir) { continue; } loadPluginsFromDir(dir); } } void PluginManager::loadPluginsFromDir(const QDir &pluginsDir, bool writable) { qInfo() << "Plugins are loaded from" << pluginsDir.absolutePath(); int loadedPlugins = plugins.size(); if (!pluginsDir.exists()) { return; } QDir nativePluginsDir = pluginsDir; if (writable) { nativePluginsDir.mkdir("native"); } if (nativePluginsDir.cd("native")) { qInfo() << "Native plugins are loaded from" << nativePluginsDir.absolutePath(); loadNativePlugins(nativePluginsDir); } #ifdef CUTTER_ENABLE_PYTHON_BINDINGS QDir pythonPluginsDir = pluginsDir; if (writable) { pythonPluginsDir.mkdir("python"); } if (pythonPluginsDir.cd("python")) { qInfo() << "Python plugins are loaded from" << pythonPluginsDir.absolutePath(); loadPythonPlugins(pythonPluginsDir.absolutePath()); } #endif loadedPlugins = plugins.size() - loadedPlugins; qInfo() << "Loaded" << loadedPlugins << "plugin(s)."; } void PluginManager::PluginTerminator::operator()(CutterPlugin *plugin) const { plugin->terminate(); delete plugin; } void PluginManager::destroyPlugins() { plugins.clear(); } QVector<QDir> PluginManager::getPluginDirectories() const { QVector<QDir> result; QStringList locations = Cutter::standardLocations(QStandardPaths::AppDataLocation); for (auto &location : locations) { result.push_back(QDir(location).filePath("plugins")); } #if QT_VERSION < QT_VERSION_CHECK(5, 6, 0) && defined(Q_OS_UNIX) QChar listSeparator = ':'; #else QChar listSeparator = QDir::listSeparator(); #endif QString extra_plugin_dirs = CUTTER_EXTRA_PLUGIN_DIRS; for (auto &path : extra_plugin_dirs.split(listSeparator, CUTTER_QT_SKIP_EMPTY_PARTS)) { result.push_back(QDir(path)); } return result; } QString PluginManager::getUserPluginsDirectory() const { QString location = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); if (location.isEmpty()) { return QString(); } QDir pluginsDir(location); pluginsDir.mkpath("plugins"); if (!pluginsDir.cd("plugins")) { return QString(); } return pluginsDir.absolutePath(); } void PluginManager::loadNativePlugins(const QDir &directory) { for (const QString &fileName : directory.entryList(QDir::Files)) { if (!QLibrary::isLibrary(fileName)) { // Reduce amount of warnings, by not attempting files which are obviously not plugins continue; } QPluginLoader pluginLoader(directory.absoluteFilePath(fileName)); QObject *plugin = pluginLoader.instance(); if (!plugin) { auto errorString = pluginLoader.errorString(); if (!errorString.isEmpty()) { qWarning() << "Load Error for plugin" << fileName << ":" << errorString; } continue; } PluginPtr cutterPlugin { qobject_cast<CutterPlugin *>(plugin) }; if (!cutterPlugin) { continue; } cutterPlugin->setupPlugin(); plugins.push_back(std::move(cutterPlugin)); } } #ifdef CUTTER_ENABLE_PYTHON_BINDINGS void PluginManager::loadPythonPlugins(const QDir &directory) { Python()->addPythonPath(directory.absolutePath().toLocal8Bit().data()); for (const QString &fileName : directory.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { if (fileName == "__pycache__") { continue; } QString moduleName; if (fileName.endsWith(".py")) { moduleName = fileName.chopped(3); } else { moduleName = fileName; } PluginPtr cutterPlugin { loadPythonPlugin(moduleName.toLocal8Bit().constData()) }; if (!cutterPlugin) { continue; } cutterPlugin->setupPlugin(); plugins.push_back(std::move(cutterPlugin)); } PythonManager::ThreadHolder threadHolder; } CutterPlugin *PluginManager::loadPythonPlugin(const char *moduleName) { PythonManager::ThreadHolder threadHolder; PyObject *pluginModule = PyImport_ImportModule(moduleName); if (!pluginModule) { qWarning() << "Couldn't load module for plugin:" << QString(moduleName); PyErr_Print(); return nullptr; } PyObject *createPluginFunc = PyObject_GetAttrString(pluginModule, "create_cutter_plugin"); if (!createPluginFunc || !PyCallable_Check(createPluginFunc)) { qWarning() << "Plugin module does not contain create_cutter_plugin() function:" << QString(moduleName); if (createPluginFunc) { Py_DECREF(createPluginFunc); } Py_DECREF(pluginModule); return nullptr; } PyObject *pluginObject = PyObject_CallFunction(createPluginFunc, nullptr); Py_DECREF(createPluginFunc); Py_DECREF(pluginModule); if (!pluginObject) { qWarning() << "Plugin's create_cutter_plugin() function failed."; PyErr_Print(); return nullptr; } PythonToCppFunc pythonToCpp = Shiboken::Conversions::isPythonToCppPointerConvertible( # if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) reinterpret_cast<SbkObjectType *>(SbkCutterBindingsTypes[SBK_CUTTERPLUGIN_IDX]), # else reinterpret_cast<PyTypeObject **>(SbkCutterBindingsTypeStructs)[SBK_CUTTERPLUGIN_IDX], # endif pluginObject); if (!pythonToCpp) { qWarning() << "Plugin's create_cutter_plugin() function did not return an instance of " "CutterPlugin:" << QString(moduleName); return nullptr; } CutterPlugin *plugin; pythonToCpp(pluginObject, &plugin); if (!plugin) { qWarning() << "Error during the setup of CutterPlugin:" << QString(moduleName); return nullptr; } return plugin; } #endif
7,070
C++
.cpp
207
28.169082
98
0.669204
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,534
CutterSamplePlugin.cpp
rizinorg_cutter/src/plugins/sample-cpp/CutterSamplePlugin.cpp
#include <QLabel> #include <QHBoxLayout> #include <QPushButton> #include <QAction> #include "CutterSamplePlugin.h" #include <common/TempConfig.h> #include <common/Configuration.h> #include <MainWindow.h> #include <rz_core.h> void CutterSamplePlugin::setupPlugin() {} void CutterSamplePlugin::setupInterface(MainWindow *main) { CutterSamplePluginWidget *widget = new CutterSamplePluginWidget(main); main->addPluginDockWidget(widget); } CutterSamplePluginWidget::CutterSamplePluginWidget(MainWindow *main) : CutterDockWidget(main) { this->setObjectName("CutterSamplePluginWidget"); this->setWindowTitle("Sample C++ Plugin"); QWidget *content = new QWidget(); this->setWidget(content); QVBoxLayout *layout = new QVBoxLayout(content); content->setLayout(layout); text = new QLabel(content); text->setFont(Config()->getFont()); text->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); layout->addWidget(text); QPushButton *button = new QPushButton(content); button->setText("Want a fortune?"); button->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); button->setMaximumHeight(50); button->setMaximumWidth(200); layout->addWidget(button); layout->setAlignment(button, Qt::AlignHCenter); connect(Core(), &CutterCore::seekChanged, this, &CutterSamplePluginWidget::on_seekChanged); connect(button, &QPushButton::clicked, this, &CutterSamplePluginWidget::on_buttonClicked); } void CutterSamplePluginWidget::on_seekChanged(RVA addr) { Q_UNUSED(addr); RzCoreLocked core(Core()); TempConfig tempConfig; tempConfig.set("scr.color", 0); QString disasm = Core()->disassembleSingleInstruction(Core()->getOffset()); QString res = fromOwnedCharPtr(rz_core_clippy(core, disasm.toUtf8().constData())); text->setText(res); } void CutterSamplePluginWidget::on_buttonClicked() { RzCoreLocked core(Core()); auto fortune = fromOwned(rz_core_fortune_get_random(core)); if (!fortune) { return; } QString res = fromOwnedCharPtr(rz_core_clippy(core, fortune.get())); text->setText(res); }
2,135
C++
.cpp
57
33.754386
95
0.745164
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,535
BaseFindResultsDialog.cpp
rizinorg_cutter/src/tools/basefind/BaseFindResultsDialog.cpp
#include "BaseFindResultsDialog.h" #include "ui_BaseFindResultsDialog.h" #include <QClipboard> #include <QMessageBox> #include <core/Cutter.h> #include <CutterApplication.h> BaseFindResultsModel::BaseFindResultsModel(QList<BasefindResultDescription> *list, QObject *parent) : QAbstractListModel(parent), list(list) { } int BaseFindResultsModel::rowCount(const QModelIndex &) const { return list->count(); } int BaseFindResultsModel::columnCount(const QModelIndex &) const { return BaseFindResultsModel::ColumnCount; } QVariant BaseFindResultsModel::data(const QModelIndex &index, int role) const { if (index.row() >= list->count()) return QVariant(); const BasefindResultDescription &entry = list->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case ScoreColumn: return QString::asprintf("%u", entry.score); case CandidateColumn: return QString::asprintf("%#010llx", entry.candidate); default: return QVariant(); } case Qt::ToolTipRole: { return QString::asprintf("%#010llx", entry.candidate); } default: return QVariant(); } } QVariant BaseFindResultsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ScoreColumn: return tr("Score"); case CandidateColumn: return tr("Address"); default: return QVariant(); } default: return QVariant(); } } BaseFindResultsDialog::BaseFindResultsDialog(QList<BasefindResultDescription> results, QWidget *parent) : QDialog(parent), list(results), ui(new Ui::BaseFindResultsDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); model = new BaseFindResultsModel(&list, this); ui->tableView->setModel(model); ui->tableView->sortByColumn(BaseFindResultsModel::ScoreColumn, Qt::AscendingOrder); ui->tableView->verticalHeader()->hide(); ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu); blockMenu = new QMenu(this); actionCopyCandidate = new QAction(tr("Copy %1"), this); actionSetLoadAddr = new QAction(tr("Reopen Cutter with base address as %1"), this); actionSetMapAddr = new QAction(tr("Reopen Cutter with map address as %1"), this); connect(ui->tableView, &QWidget::customContextMenuRequested, this, &BaseFindResultsDialog::showItemContextMenu); connect(actionCopyCandidate, &QAction::triggered, this, &BaseFindResultsDialog::onActionCopyLine); connect(actionSetLoadAddr, &QAction::triggered, this, &BaseFindResultsDialog::onActionSetLoadAddr); connect(actionSetMapAddr, &QAction::triggered, this, &BaseFindResultsDialog::onActionSetMapAddr); blockMenu->addAction(actionSetLoadAddr); blockMenu->addAction(actionSetMapAddr); blockMenu->addAction(actionCopyCandidate); addActions(blockMenu->actions()); } void BaseFindResultsDialog::showItemContextMenu(const QPoint &pt) { auto index = ui->tableView->currentIndex(); if (index.isValid()) { const BasefindResultDescription &entry = list.at(index.row()); candidate = entry.candidate; auto addr = QString::asprintf("%#010llx", candidate); actionCopyCandidate->setText(tr("Copy %1").arg(addr)); actionSetLoadAddr->setText(tr("Reopen Cutter with base address as %1").arg(addr)); actionSetMapAddr->setText(tr("Reopen Cutter with map address as %1").arg(addr)); blockMenu->exec(this->mapToGlobal(pt)); } } void BaseFindResultsDialog::onActionCopyLine() { auto clipboard = QApplication::clipboard(); clipboard->setText(QString::asprintf("%#010llx", candidate)); } void BaseFindResultsDialog::onActionSetLoadAddr() { auto cutter = static_cast<CutterApplication *>(qApp); auto options = cutter->getInitialOptions(); auto oldValue = options.binLoadAddr; // override options to generate correct args options.binLoadAddr = candidate; cutter->setInitialOptions(options); auto args = cutter->getArgs(); // revert back options options.binLoadAddr = oldValue; cutter->setInitialOptions(options); cutter->launchNewInstance(args); } void BaseFindResultsDialog::onActionSetMapAddr() { auto cutter = static_cast<CutterApplication *>(qApp); auto options = cutter->getInitialOptions(); auto oldValue = options.mapAddr; // override options to generate correct args options.mapAddr = candidate; cutter->setInitialOptions(options); auto args = cutter->getArgs(); // revert back options options.mapAddr = oldValue; cutter->setInitialOptions(options); cutter->launchNewInstance(args); } BaseFindResultsDialog::~BaseFindResultsDialog() {} void BaseFindResultsDialog::on_buttonBox_rejected() {}
5,101
C++
.cpp
133
32.744361
99
0.709312
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,536
BaseFindDialog.cpp
rizinorg_cutter/src/tools/basefind/BaseFindDialog.cpp
#include "BaseFindDialog.h" #include "ui_BaseFindDialog.h" #include "BaseFindSearchDialog.h" #include <core/Cutter.h> #include <rz_th.h> BaseFindDialog::BaseFindDialog(QWidget *parent) : QDialog(parent), ui(new Ui::BaseFindDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); // Fill in N-thread Combo RzThreadNCores n_cores = rz_th_physical_core_number(); ui->nCoresCombo->clear(); for (size_t i = n_cores; i > 0; i--) { if (n_cores == i) { ui->nCoresCombo->addItem("All Cores"); continue; } ui->nCoresCombo->addItem(QString::number(i)); } ui->startAddressEdit->setText(Core()->getConfig("basefind.search.start")); ui->endAddressEdit->setText(Core()->getConfig("basefind.search.end")); ui->alignmentEdit->setText(Core()->getConfig("basefind.alignment")); ui->minStrLenEdit->setValue(Core()->getConfigut64("basefind.min.string")); ui->minScoreEdit->setValue(Core()->getConfigut64("basefind.min.score")); size_t selected_n_cores = Core()->getConfigut64("basefind.max.threads"); if (selected_n_cores < n_cores && selected_n_cores > 0) { ui->nCoresCombo->setCurrentIndex(n_cores - selected_n_cores); } } BaseFindDialog::~BaseFindDialog() {} RzThreadNCores BaseFindDialog::getNCores() const { RzThreadNCores n_cores = rz_th_physical_core_number(); return static_cast<RzThreadNCores>(n_cores - ui->nCoresCombo->currentIndex()); } ut32 BaseFindDialog::getPointerSize() const { auto index = ui->pointerSizeCombo->currentIndex(); QString value = ui->pointerSizeCombo->itemText(index); return value.toULong(nullptr, 0); } RVA BaseFindDialog::getStartAddress() const { QString value = ui->startAddressEdit->text(); return value.toULongLong(nullptr, 0); } RVA BaseFindDialog::getEndAddress() const { QString value = ui->endAddressEdit->text(); return value.toULongLong(nullptr, 0); } RVA BaseFindDialog::getAlignment() const { QString value = ui->alignmentEdit->text(); return value.toULongLong(nullptr, 0); } ut32 BaseFindDialog::getMinStrLen() const { return ui->minStrLenEdit->value(); } ut32 BaseFindDialog::getMinScore() const { return ui->minScoreEdit->value(); } void BaseFindDialog::on_buttonBox_accepted() { RzBaseFindOpt options = {}; options.max_threads = getNCores(); options.pointer_size = getPointerSize(); options.start_address = getStartAddress(); options.end_address = getEndAddress(); options.alignment = getAlignment(); options.min_score = getMinScore(); options.min_string_len = getMinStrLen(); options.callback = nullptr; options.user = nullptr; BaseFindSearchDialog *bfs = new BaseFindSearchDialog(parentWidget()); bfs->show(&options); } void BaseFindDialog::on_buttonBox_rejected() {}
2,874
C++
.cpp
80
32.0125
93
0.712279
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,537
BaseFindSearchDialog.cpp
rizinorg_cutter/src/tools/basefind/BaseFindSearchDialog.cpp
#include "BaseFindSearchDialog.h" #include "ui_BaseFindSearchDialog.h" #include "BaseFindResultsDialog.h" #include <QLabel> #include <QFormLayout> #include <core/Cutter.h> #include <rz_th.h> BaseFindSearchDialog::BaseFindSearchDialog(QWidget *parent) : QDialog(parent), basefind(new Basefind(Core())), ui(new Ui::BaseFindSearchDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); } BaseFindSearchDialog::~BaseFindSearchDialog() {} void BaseFindSearchDialog::show(RzBaseFindOpt *opts) { RzThreadNCores n_cores = rz_th_physical_core_number(); if (opts->max_threads > n_cores || opts->max_threads < 1) { opts->max_threads = n_cores; } QFormLayout *layout = new QFormLayout(); ui->scrollAreaWidgetContents->setLayout(layout); for (ut32 i = 0; i < opts->max_threads; ++i) { QString label = QString::asprintf("Core %u", i); QProgressBar *pbar = new QProgressBar(nullptr); layout->addRow(label, pbar); pbar->setRange(0, 100); bars.push_back(pbar); } if (!basefind->setOptions(opts)) { return; } connect(this, &BaseFindSearchDialog::cancelSearch, basefind.get(), &Basefind::cancel); connect(basefind.get(), &Basefind::progress, this, &BaseFindSearchDialog::onProgress); connect(basefind.get(), &Basefind::complete, this, &BaseFindSearchDialog::onCompletion); basefind->start(); this->QDialog::show(); } void BaseFindSearchDialog::onProgress(BasefindCoreStatusDescription status) { bars[status.index]->setValue(status.percentage); } void BaseFindSearchDialog::onCompletion() { auto results = basefind->results(); BaseFindResultsDialog *table = new BaseFindResultsDialog(results, parentWidget()); table->show(); this->close(); } void BaseFindSearchDialog::on_buttonBox_rejected() { emit cancelSearch(); }
1,900
C++
.cpp
53
31.811321
92
0.717557
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,538
GraphGridLayout.cpp
rizinorg_cutter/src/widgets/GraphGridLayout.cpp
#include "GraphGridLayout.h" #include <unordered_set> #include <unordered_map> #include <queue> #include <stack> #include <cassert> #include <queue> #include "common/BinaryTrees.h" /** @class GraphGridLayout Basic familiarity with graph algorithms is recommended. # Terms used: - **Vertex**, **node**, **block** - see the definition of graph. Within this text vertex/node/block are used interchangeably due to the code being purposed for visualizing basic block control flow graph. - **edge** - see the definition of graph. - **DAG** - directed acyclic graph, a graph using directed edges which doesn't have cycles. A DAG may contain loops if following them would require going in both directions of edges. Example 1->2 1->3 3->2 is a DAG, 2->1 1->3 3->2 isn't a DAG. - **DFS** - depth first search, a graph traversal algorithm - **toposort** - topological sorting, the process of ordering a DAG vertices that results in all edges going from vertices earlier in the toposort order to vertices later in toposort order. There are multiple algorithms implementing toposort. A single DAG can have multiple valid topological orderings, a toposort algorithm can be designed to prioritize a specific one from all valid toposort orders. Example: for graph 1->4, 2->1, 2->3, 3->4 valid topological orders are [2,1,3,4] and [2,3,1,4]. # High level algorithm structure 1. Select a subset of edges that form a DAG (remove cycles) 2. Toposort the DAG 3. Choose a subset of edges that form a tree and assign layers 4. Assign node positions within grid using tree structure, child subtrees are placed side by side with parent on top 5. Perform edge routing 6. Calculate column and row pixel positions based on node sizes and amount edges between the rows 7. [optional] Layout compacting Contrary to many other layered graph-drawing algorithms this implementation doesn't perform node reordering to minimize edge crossing. This simplifies the implementation, and preserves the original control-flow structure for conditional jumps ( true jump on one side, false jump on other). Due to most of the control flow resulting from structured programming constructs like if/then/else and loops, the resulting layout is usually readable without node reordering within layers. # Grid To simplify the layout algorithm, its initial steps assume that all nodes have the same size and that edges are zero-width. After nodes placement and edges rounting, the row/column of nodes is known as well as the amount of edges between each pair of rows. Using this information, positions are converted from grid cells to pixel coordinates. Routing zero-width edges between rows can also be interpreted as every second row and column being reserved for edges. The row numbers in code are using the first interpretation. To allow better centering of nodes one above other, each node is 2 columns wide and 1 row high. \image html graph_grid.svg # 1-2 Cycle removal and toposort Cycle removal and toposort are done in a single DFS traversal. In case the entrypoint is part of a loop, the DFS starts from the entrypoint. This ensures that the entrypoint is at the top of resulting layout, if possible. The resulting toposort order is used in many of the following layout steps that require calculating some property of a vertex based on a child property or the other way around. Using toposort order, such operations can be implemented by array iteration in either forward/backward direction. To prevent running out of stack memory when processing large graphs, DFS is implemented non-recursively. # Row assignment Rows are assigned in toposort order from top to bottom, with nodes row being max(predecessor.row)+1. This ensures that loop back-edges are the only edges going from lower to higher layers. To further simply node placement, a subset of edges is selected which forms a tree. This turns a DAG drawing problem into a tree drawing problem. For each node in level n the following nodes with level exactly n+1 are greedily assigned as child nodes in the tree. If a node already has a parent assigned then the corresponding edge is not part of the tree. # Node placement Since the graph has been reduced to a tree, node placement is more or less putting subtrees side by side with parent on top. There is some room for interpretation as to what exactly 'side by side' means and where exactly 'on top' is: drawing the graph either too dense or too sparse may make it less readable, so there are configuration options which allow choosing these things resulting in more or less dense layout. Once the subtrees are placed side by side, the parent node can be placed either in the middle of the horizontal bounds or in the middle of its direct children. The first option results in narrower layout and more vertical columns, while the second option results in more spread out layout which may help seeing where each edge goes. In compact mode two subtrees are placed side by side accounting for their shape. In wider mode the bounding box of the shorter subtree is used instead of its exact shape. This gives slightly sparser layout without being too wide. \image html graph_parent_placement.svg # Edge routing Edge routing can be split into: main column selection, rough routing, and segment offset calculation. Transition from source to target row is done using a single vertical segment. This segment is called the 'main column'. Main columns are computed using a sweep line: blocks and edges are processed as events top to bottom based off their row (max(start row, end row) for edges). Blocked columns are tracked in a tree structure which allows searching nearest column with at least last N rows empty. The column of the starting block is favored for the main column, otherwise the target block's column is chosen if it is not blocked. If both the source and target columns are blocked, nearest unblocked column is chosen. An empty column can always be found, in the worst case there are empty columns at the sides of drawing. If two columns are equally close, the tie is broken based on whether the edge is a true or false branch. In case of upward edges it is allowed to choose a column on the outside which is slightly further than nearest empty to reduce the chance of producing tilted figure 8 shaped crossing between two blocks. Due to nodes being placed in a grid, horizontal segments of edges can't intersect with any nodes. The path for edges is chosen so that it consists of at most 5 segments, typically resulting in sideways U shape or square Z shape: - short vertical segment from node to horizontal line - move to empty column - vertical segment between starting row and end row - horizontal segment to target node column - short vertical segment connecting to target node There are 3 special cases: - source and target nodes are in the same column with no nodes between - single vertical segment - column bellow stating node is empty - segments 1-3 are merged - column above target node is empty - segments 3-5 are merged After rough routing segment offsets are calculated relative to their corresponding edge column. This ensures that two segments don't overlap. Segment offsets within each column are assigned greedily with some heuristics for assignment order to reduce amount of edge crossings and result in more visually pleasing output for a typical CFG graph. Each segment gets assigned an offset that is maximum of previously assigned offsets overlapping with current segment + segment spacing. Assignment order is based on: - direction of previous and last segment - helps reducing crossings and place the segments between nodes - segment length - reduces crossing when segment endpoints have the same structure as valid parentheses expression - edge length - establishes some kind of order when single node is connected to many edges, typically a block with switch statement or block after switch statement. # Layout compacting Doing the layout on a grid limits the minimal spacing to the widest block within a column and tallest block within a row. One common case is a function-entry block being wider due to the function name, causing wide horizontal space between branching blocks. Another case is rows in two parallel columns being aligned. \image html layout_compacting.svg Both problems are mitigated by squishing the graph. Compressing in each of the two direction is done separately. The process is defined as liner program. Each variable represents a position of edge segment or node in the direction being optimized. The following constraints are used: - Keep the order with nearest segments. - If a node has two outgoing edges, one to the left and one to the right, keep them on the corresponding side of the node's center. - Equality constraint to keep relative position between nodes and and segments directly connected to them. - For all blocks connected by forward edge, keep the vertical distance at least as big as configured block vertical spacing. This helps when vertical block-spacing is set bigger than double edge spacing and an edge shadows relationship between two blocks. - Equality constraint to keep a node centered when control flow merges. In the vertical direction the objective function minimizes y positions of nodes and lengths of vertical segments. In the horizontal direction the objective function minimizes the lengths of horizontal segments. In the resulting linear program all constraints besides x_i >= 0 consist of exactly two variables: either x_i - x_j <= c_k or x_i = x_j + c_k. Since a perfect solution isn't necessary and to avoid worst case performance, the current implementation isn't using a general purpose linear solver. Instead, each variable is modified until a constraint is satisfied and afterwards variables are grouped and modified together. */ GraphGridLayout::GraphGridLayout(GraphGridLayout::LayoutType layoutType) : GraphLayout({}) { switch (layoutType) { case LayoutType::Narrow: tightSubtreePlacement = true; parentBetweenDirectChild = false; useLayoutOptimization = true; break; case LayoutType::Medium: tightSubtreePlacement = false; parentBetweenDirectChild = true; useLayoutOptimization = true; break; case LayoutType::Wide: tightSubtreePlacement = false; parentBetweenDirectChild = true; useLayoutOptimization = false; break; } } std::vector<ut64> GraphGridLayout::topoSort(LayoutState &state, ut64 entry) { auto &blocks = *state.blocks; // Run DFS to: // * select backwards/loop edges // * perform toposort std::vector<ut64> blockOrder; enum class State : uint8_t { NotVisited = 0, InStack, Visited }; std::unordered_map<ut64, State> visited; visited.reserve(state.blocks->size()); std::stack<std::pair<ut64, size_t>> stack; auto dfsFragment = [&visited, &blocks, &state, &stack, &blockOrder](ut64 first) { visited[first] = State::InStack; stack.push({ first, 0 }); while (!stack.empty()) { auto v = stack.top().first; auto edge_index = stack.top().second; const auto &block = blocks[v]; if (edge_index < block.edges.size()) { ++stack.top().second; auto target = block.edges[edge_index].target; auto &targetState = visited[target]; if (targetState == State::NotVisited) { targetState = State::InStack; stack.push({ target, 0 }); state.grid_blocks[v].dag_edge.push_back(target); } else if (targetState == State::Visited) { state.grid_blocks[v].dag_edge.push_back(target); } // else { targetState == 1 in stack, loop edge } } else { stack.pop(); visited[v] = State::Visited; blockOrder.push_back(v); } } }; // Start with entry so that if start of function block is part of loop it // is still kept at top unless it's impossible to do while maintaining // topological order. dfsFragment(entry); for (auto &blockIt : blocks) { if (visited[blockIt.first] == State::NotVisited) { dfsFragment(blockIt.first); } } return blockOrder; } void GraphGridLayout::assignRows(GraphGridLayout::LayoutState &state, const std::vector<unsigned long long> &blockOrder) { for (auto it = blockOrder.rbegin(), end = blockOrder.rend(); it != end; it++) { auto &block = state.grid_blocks[*it]; int nextLevel = block.row + 1; for (auto target : block.dag_edge) { auto &targetBlock = state.grid_blocks[target]; targetBlock.row = std::max(targetBlock.row, nextLevel); } } } void GraphGridLayout::selectTree(GraphGridLayout::LayoutState &state) { for (auto &blockIt : state.grid_blocks) { auto &block = blockIt.second; for (auto targetId : block.dag_edge) { auto &targetBlock = state.grid_blocks[targetId]; if (!targetBlock.has_parent && targetBlock.row == block.row + 1) { block.tree_edge.push_back(targetId); targetBlock.has_parent = true; } } } } void GraphGridLayout::CalculateLayout(GraphLayout::Graph &blocks, ut64 entry, int &width, int &height) const { LayoutState layoutState; layoutState.blocks = &blocks; if (blocks.empty()) { return; } if (blocks.find(entry) == blocks.end()) { entry = blocks.begin()->first; } for (auto &it : blocks) { GridBlock block; block.id = it.first; layoutState.grid_blocks[it.first] = block; } auto blockOrder = topoSort(layoutState, entry); computeAllBlockPlacement(blockOrder, layoutState); for (auto &blockIt : blocks) { layoutState.edge[blockIt.first].resize(blockIt.second.edges.size()); for (size_t i = 0; i < blockIt.second.edges.size(); i++) { layoutState.edge[blockIt.first][i].dest = blockIt.second.edges[i].target; blockIt.second.edges[i].arrow = GraphEdge::Down; } } for (const auto &edgeList : layoutState.edge) { auto &startBlock = layoutState.grid_blocks[edgeList.first]; startBlock.outputCount = edgeList.second.size(); for (auto &edge : edgeList.second) { auto &targetBlock = layoutState.grid_blocks[edge.dest]; targetBlock.inputCount++; } } layoutState.columns = 1; layoutState.rows = 1; for (auto &node : layoutState.grid_blocks) { // count is at least index + 1 layoutState.rows = std::max(layoutState.rows, size_t(node.second.row) + 1); // block is 2 column wide layoutState.columns = std::max(layoutState.columns, size_t(node.second.col) + 2); } layoutState.rowHeight.assign(layoutState.rows, 0); layoutState.columnWidth.assign(layoutState.columns, 0); for (auto &node : layoutState.grid_blocks) { const auto &inputBlock = blocks[node.first]; layoutState.rowHeight[node.second.row] = std::max(inputBlock.height, layoutState.rowHeight[node.second.row]); layoutState.columnWidth[node.second.col] = std::max(inputBlock.width / 2, layoutState.columnWidth[node.second.col]); layoutState.columnWidth[node.second.col + 1] = std::max(inputBlock.width / 2, layoutState.columnWidth[node.second.col + 1]); } routeEdges(layoutState); convertToPixelCoordinates(layoutState, width, height); if (useLayoutOptimization) { optimizeLayout(layoutState); cropToContent(blocks, width, height); } } void GraphGridLayout::findMergePoints(GraphGridLayout::LayoutState &state) const { for (auto &blockIt : state.grid_blocks) { auto &block = blockIt.second; GridBlock *mergeBlock = nullptr; int grandChildCount = 0; for (auto edge : block.tree_edge) { auto &targetBlock = state.grid_blocks[edge]; if (targetBlock.tree_edge.size()) { mergeBlock = &state.grid_blocks[targetBlock.tree_edge[0]]; } grandChildCount += targetBlock.tree_edge.size(); } if (!mergeBlock || grandChildCount != 1) { continue; } int blocksGoingToMerge = 0; int blockWithTreeEdge = 0; for (auto edge : block.tree_edge) { auto &targetBlock = state.grid_blocks[edge]; bool goesToMerge = false; for (auto secondEdgeTarget : targetBlock.dag_edge) { if (secondEdgeTarget == mergeBlock->id) { goesToMerge = true; break; } } if (goesToMerge) { if (targetBlock.tree_edge.size() == 1) { blockWithTreeEdge = blocksGoingToMerge; } blocksGoingToMerge++; } else { break; } } if (blocksGoingToMerge) { block.mergeBlock = mergeBlock->id; state.grid_blocks[block.tree_edge[blockWithTreeEdge]].col = blockWithTreeEdge * 2 - (blocksGoingToMerge - 1); } } } void GraphGridLayout::computeAllBlockPlacement(const std::vector<ut64> &blockOrder, LayoutState &layoutState) const { assignRows(layoutState, blockOrder); selectTree(layoutState); findMergePoints(layoutState); // Shapes of subtrees are maintained using linked lists. Each value within list is column // relative to previous row. This allows moving things around by changing only first value in // list. LinkedListPool<int> sides(blockOrder.size() * 2); // *2 = two sides for each node // Process nodes in the order from bottom to top. Ensures that all subtrees are processed before // parent node. for (auto blockId : blockOrder) { auto &block = layoutState.grid_blocks[blockId]; if (block.tree_edge.size() == 0) { block.row_count = 1; block.col = 0; block.lastRowRight = 2; block.lastRowLeft = 0; block.leftPosition = 0; block.rightPosition = 2; block.leftSideShape = sides.makeList(0); block.rightSideShape = sides.makeList(2); } else { auto &firstChild = layoutState.grid_blocks[block.tree_edge[0]]; auto leftSide = firstChild .leftSideShape; // left side of block children subtrees processed so far auto rightSide = firstChild.rightSideShape; block.row_count = firstChild.row_count; block.lastRowRight = firstChild.lastRowRight; block.lastRowLeft = firstChild.lastRowLeft; block.leftPosition = firstChild.leftPosition; block.rightPosition = firstChild.rightPosition; // Place children subtrees side by side for (size_t i = 1; i < block.tree_edge.size(); i++) { auto &child = layoutState.grid_blocks[block.tree_edge[i]]; int minPos = INT_MIN; int leftPos = 0; int rightPos = 0; auto leftIt = sides.head(rightSide); auto rightIt = sides.head(child.leftSideShape); int maxLeftWidth = 0; int minRightPos = child.col; while (leftIt && rightIt) { // process part of subtrees that touch when put side by side leftPos += *leftIt; rightPos += *rightIt; minPos = std::max(minPos, leftPos - rightPos); maxLeftWidth = std::max(maxLeftWidth, leftPos); minRightPos = std::min(minRightPos, rightPos); ++leftIt; ++rightIt; } int rightTreeOffset = 0; if (tightSubtreePlacement) { rightTreeOffset = minPos; // mode a) place subtrees as close as possible } else { // mode b) use bounding box for shortest subtree and full shape of other side if (leftIt) { rightTreeOffset = maxLeftWidth - child.leftPosition; } else { rightTreeOffset = block.rightPosition - minRightPos; } } // Calculate the new shape after putting the two subtrees side by side child.col += rightTreeOffset; if (leftIt) { *leftIt -= (rightTreeOffset + child.lastRowRight - leftPos); rightSide = sides.append(child.rightSideShape, sides.splitTail(rightSide, leftIt)); } else if (rightIt) { *rightIt += (rightPos + rightTreeOffset - block.lastRowLeft); leftSide = sides.append(leftSide, sides.splitTail(child.leftSideShape, rightIt)); rightSide = child.rightSideShape; block.lastRowRight = child.lastRowRight + rightTreeOffset; block.lastRowLeft = child.lastRowLeft + rightTreeOffset; } else { rightSide = child.rightSideShape; } *sides.head(rightSide) += rightTreeOffset; block.row_count = std::max(block.row_count, child.row_count); block.leftPosition = std::min(block.leftPosition, child.leftPosition + rightTreeOffset); block.rightPosition = std::max(block.rightPosition, rightTreeOffset + child.rightPosition); } int col = 0; // Calculate parent position if (parentBetweenDirectChild) { // mode a) keep one child to the left, other to the right for (auto target : block.tree_edge) { col += layoutState.grid_blocks[target].col; } col /= block.tree_edge.size(); } else { // mode b) somewhere between left most direct child and right most, preferably in // the middle of horizontal dimensions. Results layout looks more like single // vertical line. col = (block.rightPosition + block.leftPosition) / 2 - 1; col = std::max(col, layoutState.grid_blocks[block.tree_edge.front()].col - 1); col = std::min(col, layoutState.grid_blocks[block.tree_edge.back()].col + 1); } block.col += col; // += instead of = to keep offset calculated in previous steps block.row_count += 1; block.leftPosition = std::min(block.leftPosition, block.col); block.rightPosition = std::max(block.rightPosition, block.col + 2); *sides.head(leftSide) -= block.col; block.leftSideShape = sides.append(sides.makeList(block.col), leftSide); *sides.head(rightSide) -= block.col + 2; block.rightSideShape = sides.append(sides.makeList(block.col + 2), rightSide); // Keep children positions relative to parent so that moving parent moves whole subtree for (auto target : block.tree_edge) { auto &targetBlock = layoutState.grid_blocks[target]; targetBlock.col -= block.col; } } } // Calculate root positions. Typical function should have one root node that matches with // entrypoint. There can be more of them in case of switch statement analysis failure, // unreahable basic blocks or using the algorithm for non control flow graphs. int nextEmptyColumn = 0; for (auto &blockIt : layoutState.grid_blocks) { auto &block = blockIt.second; if (block.row == 0) { // place all the roots first auto offset = -block.leftPosition; block.col += nextEmptyColumn + offset; nextEmptyColumn = block.rightPosition + offset + nextEmptyColumn; } } // Visit all nodes top to bottom, converting relative positions to absolute. for (auto it = blockOrder.rbegin(), end = blockOrder.rend(); it != end; it++) { auto &block = layoutState.grid_blocks[*it]; assert(block.col >= 0); for (auto childId : block.tree_edge) { auto &childBlock = layoutState.grid_blocks[childId]; childBlock.col += block.col; } } } void GraphGridLayout::routeEdges(GraphGridLayout::LayoutState &state) const { calculateEdgeMainColumn(state); roughRouting(state); elaborateEdgePlacement(state); } void GraphGridLayout::calculateEdgeMainColumn(GraphGridLayout::LayoutState &state) const { // Find an empty column as close as possible to start or end block's column. // Use sweep line approach processing events sorted by row top to bottom. Use an appropriate // tree structure to contain blocks above sweep line and query for nearest column which isn't // blocked by a block. struct Event { ut64 blockId; size_t edgeId; int row; enum Type { Edge = 0, Block = 1 } type; }; // create events std::vector<Event> events; events.reserve(state.grid_blocks.size() * 2); for (const auto &it : state.grid_blocks) { events.push_back({ it.first, 0, it.second.row, Event::Block }); const auto &inputBlock = (*state.blocks)[it.first]; int startRow = it.second.row + 1; auto gridEdges = state.edge[it.first]; gridEdges.resize(inputBlock.edges.size()); for (size_t i = 0; i < inputBlock.edges.size(); i++) { auto targetId = inputBlock.edges[i].target; gridEdges[i].dest = targetId; const auto &targetGridBlock = state.grid_blocks[targetId]; int endRow = targetGridBlock.row; events.push_back({ it.first, i, std::max(startRow, endRow), Event::Edge }); } } std::sort(events.begin(), events.end(), [](const Event &a, const Event &b) { if (a.row != b.row) { return a.row < b.row; } return static_cast<int>(a.type) < static_cast<int>(b.type); }); // process events and choose main column for each edge PointSetMinTree blockedColumns(state.columns + 1, -1); for (const auto &event : events) { if (event.type == Event::Block) { auto block = state.grid_blocks[event.blockId]; blockedColumns.set(block.col + 1, event.row); } else { auto block = state.grid_blocks[event.blockId]; int column = block.col + 1; auto &edge = state.edge[event.blockId][event.edgeId]; const auto &targetBlock = state.grid_blocks[edge.dest]; auto topRow = std::min(block.row + 1, targetBlock.row); auto targetColumn = targetBlock.col + 1; // Prefer using the same column as starting node, it allows reducing amount of segments. if (blockedColumns.valueAtPoint(column) < topRow) { edge.mainColumn = column; } else if (blockedColumns.valueAtPoint(targetColumn) < topRow) { // next try target block column edge.mainColumn = targetColumn; } else { auto nearestLeft = blockedColumns.rightMostLessThan(column, topRow); auto nearestRight = blockedColumns.leftMostLessThan(column, topRow); // There should always be empty column at the sides of drawing assert(nearestLeft != -1 && nearestRight != -1); // Choose closest column. Take into account distance to source and target block // columns. auto distanceLeft = column - nearestLeft + abs(targetColumn - nearestLeft); auto distanceRight = nearestRight - column + abs(targetColumn - nearestRight); // For upward edges try to make a loop instead of 8 shape, // it is slightly longer but produces less crossing. if (targetBlock.row < block.row) { if (targetColumn < column && blockedColumns.valueAtPoint(column + 1) < topRow && column - targetColumn <= distanceLeft + 2) { edge.mainColumn = column + 1; continue; } else if (targetColumn > column && blockedColumns.valueAtPoint(column - 1) < topRow && targetColumn - column <= distanceRight + 2) { edge.mainColumn = column - 1; continue; } } if (distanceLeft != distanceRight) { edge.mainColumn = distanceLeft < distanceRight ? nearestLeft : nearestRight; } else { // In case of tie choose based on edge index. Should result in true branches // being mostly on one side, false branches on other side. edge.mainColumn = event.edgeId < state.edge[event.blockId].size() / 2 ? nearestLeft : nearestRight; } } } } } void GraphGridLayout::roughRouting(GraphGridLayout::LayoutState &state) const { auto getSpacingOverride = [this](int blockWidth, int edgeCount) { if (edgeCount == 0) { return 0; } int maxSpacing = blockWidth / edgeCount; if (maxSpacing < layoutConfig.edgeHorizontalSpacing) { return std::max(maxSpacing, 1); } return 0; }; for (auto &blockIt : state.grid_blocks) { auto &blockEdges = state.edge[blockIt.first]; for (size_t i = 0; i < blockEdges.size(); i++) { auto &edge = blockEdges[i]; const auto &start = blockIt.second; const auto &target = state.grid_blocks[edge.dest]; edge.addPoint(start.row + 1, start.col + 1); if (edge.mainColumn != start.col + 1) { edge.addPoint(start.row + 1, start.col + 1, edge.mainColumn < start.col + 1 ? -1 : 1); edge.addPoint(start.row + 1, edge.mainColumn, target.row <= start.row ? -2 : 0); } int mainColumnKind = 0; if (edge.mainColumn < start.col + 1 && edge.mainColumn < target.col + 1) { mainColumnKind = +2; } else if (edge.mainColumn > start.col + 1 && edge.mainColumn > target.col + 1) { mainColumnKind = -2; } else if (edge.mainColumn == start.col + 1 && edge.mainColumn != target.col + 1) { mainColumnKind = edge.mainColumn < target.col + 1 ? 1 : -1; } else if (edge.mainColumn == target.col + 1 && edge.mainColumn != start.col + 1) { mainColumnKind = edge.mainColumn < start.col + 1 ? 1 : -1; } edge.addPoint(target.row, edge.mainColumn, mainColumnKind); if (target.col + 1 != edge.mainColumn) { edge.addPoint(target.row, target.col + 1, target.row <= start.row ? 2 : 0); edge.addPoint(target.row, target.col + 1, target.col + 1 < edge.mainColumn ? 1 : -1); } // reduce edge spacing when there is large amount of edges connected to single block auto startSpacingOverride = getSpacingOverride((*state.blocks)[start.id].width, start.outputCount); auto targetSpacingOverride = getSpacingOverride((*state.blocks)[target.id].width, target.inputCount); edge.points.front().spacingOverride = startSpacingOverride; edge.points.back().spacingOverride = targetSpacingOverride; if (edge.points.size() <= 2) { if (startSpacingOverride && startSpacingOverride < targetSpacingOverride) { edge.points.back().spacingOverride = startSpacingOverride; } } else { edge.points[1].spacingOverride = startSpacingOverride; } int length = 0; for (size_t i = 1; i < edge.points.size(); i++) { length += abs(edge.points[i].row - edge.points[i - 1].row) + abs(edge.points[i].col - edge.points[i - 1].col); } edge.secondaryPriority = 2 * length + (target.row >= start.row ? 1 : 0); } } } namespace { /** * @brief Single segment of an edge. An edge can be drawn using multiple horizontal and vertical * segments. x y meaning matches vertical segments. For horizontal segments axis are swapped. */ struct EdgeSegment { int y0; int y1; int x; int edgeIndex; int secondaryPriority; int16_t kind; int16_t spacingOverride; //< segment spacing override, 0 if default spacing should be used }; struct NodeSide { int x; int y0; int y1; int size; //< block size in the x axis direction }; } /** * @brief Calculate segment offsets relative to their column * * Argument naming uses terms for vertical segments, but the function can be used for horizontal * segments as well. * * @param segments Segments that need to be processed. * @param edgeOffsets Output argument for returning segment offsets relative to their columns. * @param edgeColumnWidth InOut argument describing how much column with edges take. Initial value * used as minimal value. May be increased to depending on amount of segments in each column and how * tightly they are packed. * @param nodeRightSide Right side of nodes. Used to reduce space reserved for edges by placing them * between nodes. * @param nodeLeftSide Same as right side. * @param columnWidth * @param H All the segmement and node coordinates y0 and y1 are expected to be in range [0;H) * @param segmentSpacing The expected spacing between two segments in the same column. Actual * spacing may be smaller for nodes with many edges. */ void calculateSegmentOffsets(std::vector<EdgeSegment> &segments, std::vector<int> &edgeOffsets, std::vector<int> &edgeColumnWidth, std::vector<NodeSide> &nodeRightSide, std::vector<NodeSide> &nodeLeftSide, const std::vector<int> &columnWidth, size_t H, int segmentSpacing) { for (auto &segment : segments) { if (segment.y0 > segment.y1) { std::swap(segment.y0, segment.y1); } } std::sort(segments.begin(), segments.end(), [](const EdgeSegment &a, const EdgeSegment &b) { if (a.x != b.x) return a.x < b.x; if (a.kind != b.kind) return a.kind < b.kind; auto aSize = a.y1 - a.y0; auto bSize = b.y1 - b.y0; if (aSize != bSize) { if (a.kind != 1) { return aSize < bSize; } else { return aSize > bSize; } } if (a.kind != 1) { return a.secondaryPriority < b.secondaryPriority; } else { return a.secondaryPriority > b.secondaryPriority; } return false; }); auto compareNode = [](const NodeSide &a, const NodeSide &b) { return a.x < b.x; }; sort(nodeRightSide.begin(), nodeRightSide.end(), compareNode); sort(nodeLeftSide.begin(), nodeLeftSide.end(), compareNode); RangeAssignMaxTree maxSegment(H, INT_MIN); auto nextSegmentIt = segments.begin(); auto rightSideIt = nodeRightSide.begin(); auto leftSideIt = nodeLeftSide.begin(); while (nextSegmentIt != segments.end()) { int x = nextSegmentIt->x; int leftColumWidth = 0; if (x > 0) { leftColumWidth = columnWidth[x - 1]; } maxSegment.setRange(0, H, -leftColumWidth); while (rightSideIt != nodeRightSide.end() && rightSideIt->x + 1 < x) { rightSideIt++; } while (rightSideIt != nodeRightSide.end() && rightSideIt->x + 1 == x) { maxSegment.setRange(rightSideIt->y0, rightSideIt->y1 + 1, rightSideIt->size - leftColumWidth); rightSideIt++; } while (nextSegmentIt != segments.end() && nextSegmentIt->x == x && nextSegmentIt->kind <= 1) { int y = maxSegment.rangeMaximum(nextSegmentIt->y0, nextSegmentIt->y1 + 1); if (nextSegmentIt->kind != -2) { y = std::max(y, 0); } y += nextSegmentIt->spacingOverride ? nextSegmentIt->spacingOverride : segmentSpacing; maxSegment.setRange(nextSegmentIt->y0, nextSegmentIt->y1 + 1, y); edgeOffsets[nextSegmentIt->edgeIndex] = y; nextSegmentIt++; } auto firstRightSideSegment = nextSegmentIt; auto middleWidth = std::max(maxSegment.rangeMaximum(0, H), 0); int rightColumnWidth = 0; if (x < static_cast<int>(columnWidth.size())) { rightColumnWidth = columnWidth[x]; } maxSegment.setRange(0, H, -rightColumnWidth); while (leftSideIt != nodeLeftSide.end() && leftSideIt->x < x) { leftSideIt++; } while (leftSideIt != nodeLeftSide.end() && leftSideIt->x == x) { maxSegment.setRange(leftSideIt->y0, leftSideIt->y1 + 1, leftSideIt->size - rightColumnWidth); leftSideIt++; } while (nextSegmentIt != segments.end() && nextSegmentIt->x == x) { int y = maxSegment.rangeMaximum(nextSegmentIt->y0, nextSegmentIt->y1 + 1); y += nextSegmentIt->spacingOverride ? nextSegmentIt->spacingOverride : segmentSpacing; maxSegment.setRange(nextSegmentIt->y0, nextSegmentIt->y1 + 1, y); edgeOffsets[nextSegmentIt->edgeIndex] = y; nextSegmentIt++; } auto rightSideMiddle = std::max(maxSegment.rangeMaximum(0, H), 0); rightSideMiddle = std::max(rightSideMiddle, edgeColumnWidth[x] - middleWidth - segmentSpacing); for (auto it = firstRightSideSegment; it != nextSegmentIt; ++it) { edgeOffsets[it->edgeIndex] = middleWidth + (rightSideMiddle - edgeOffsets[it->edgeIndex]) + segmentSpacing; } edgeColumnWidth[x] = middleWidth + segmentSpacing + rightSideMiddle; } } /** * @brief Center the segments to the middle of edge columns when possible. * @param segmentOffsets offsets relative to the left side edge column. * @param edgeColumnWidth widths of edge columns * @param segments either all horizontal or all vertical edge segments */ static void centerEdges(std::vector<int> &segmentOffsets, const std::vector<int> &edgeColumnWidth, const std::vector<EdgeSegment> &segments) { /* Split segments in each edge column into non intersecting chunks. Center each chunk * separately. * * Process segment endpoints sorted by x and y. Maintain count of currently started segments. * When number of active segments reaches 0 there is empty space between chunks. */ struct Event { int x; int y; int index; bool start; }; std::vector<Event> events; events.reserve(segments.size() * 2); for (const auto &segment : segments) { auto offset = segmentOffsets[segment.edgeIndex]; // Exclude segments which are outside edge column and between the blocks. It's hard to // ensure that moving them doesn't cause overlap with blocks. if (offset >= 0 && offset <= edgeColumnWidth[segment.x]) { events.push_back({ segment.x, segment.y0, segment.edgeIndex, true }); events.push_back({ segment.x, segment.y1, segment.edgeIndex, false }); } } std::sort(events.begin(), events.end(), [](const Event &a, const Event &b) { if (a.x != b.x) return a.x < b.x; if (a.y != b.y) return a.y < b.y; // Process segment start events before end to ensure that activeSegmentCount doesn't go // negative and only reaches 0 at the end of chunk. return int(a.start) > int(b.start); }); auto it = events.begin(); while (it != events.end()) { int left, right; left = right = segmentOffsets[it->index]; auto chunkStart = it++; int activeSegmentCount = 1; while (activeSegmentCount > 0) { activeSegmentCount += it->start ? 1 : -1; int offset = segmentOffsets[it->index]; left = std::min(left, offset); right = std::max(right, offset); it++; } int spacing = (edgeColumnWidth[chunkStart->x] - (right - left)) / 2 - left; for (auto segment = chunkStart; segment != it; segment++) { if (segment->start) { segmentOffsets[segment->index] += spacing; } } } } /** * @brief Convert segment coordinates from arbitrary range to continuous range starting at 0. * @param segments * @param leftSides * @param rightSides * @return Size of compressed coordinate range. */ static int compressCoordinates(std::vector<EdgeSegment> &segments, std::vector<NodeSide> &leftSides, std::vector<NodeSide> &rightSides) { std::vector<int> positions; positions.reserve((segments.size() + leftSides.size()) * 2); for (const auto &segment : segments) { positions.push_back(segment.y0); positions.push_back(segment.y1); } for (const auto &segment : leftSides) { positions.push_back(segment.y0); positions.push_back(segment.y1); } // y0 and y1 in rightSides should match leftSides std::sort(positions.begin(), positions.end()); auto lastUnique = std::unique(positions.begin(), positions.end()); positions.erase(lastUnique, positions.end()); auto positionToIndex = [&](int position) { size_t index = std::lower_bound(positions.begin(), positions.end(), position) - positions.begin(); assert(index < positions.size()); return index; }; for (auto &segment : segments) { segment.y0 = positionToIndex(segment.y0); segment.y1 = positionToIndex(segment.y1); } assert(leftSides.size() == rightSides.size()); for (size_t i = 0; i < leftSides.size(); i++) { leftSides[i].y0 = rightSides[i].y0 = positionToIndex(leftSides[i].y0); leftSides[i].y1 = rightSides[i].y1 = positionToIndex(leftSides[i].y1); } return positions.size(); } void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state) const { int edgeIndex = 0; auto segmentFromPoint = [&edgeIndex](const Point &point, const GridEdge &edge, int y0, int y1, int x) { EdgeSegment segment; segment.y0 = y0; segment.y1 = y1; segment.x = x; segment.edgeIndex = edgeIndex++; segment.kind = point.kind; segment.spacingOverride = point.spacingOverride; segment.secondaryPriority = edge.secondaryPriority; return segment; }; std::vector<EdgeSegment> segments; std::vector<NodeSide> rightSides; std::vector<NodeSide> leftSides; std::vector<int> edgeOffsets; // Vertical segments for (auto &edgeListIt : state.edge) { for (const auto &edge : edgeListIt.second) { for (size_t j = 1; j < edge.points.size(); j += 2) { segments.push_back( segmentFromPoint(edge.points[j], edge, edge.points[j - 1].row * 2, // edges in even rows edge.points[j].row * 2, edge.points[j].col)); } } } for (auto &blockIt : state.grid_blocks) { auto &node = blockIt.second; auto width = (*state.blocks)[blockIt.first].width; auto leftWidth = width / 2; // not the same as leftWidth, you would think that one pixel offset isn't visible, but it is auto rightWidth = width - leftWidth; int row = node.row * 2 + 1; // blocks in odd rows leftSides.push_back({ node.col, row, row, leftWidth }); rightSides.push_back({ node.col + 1, row, row, rightWidth }); } state.edgeColumnWidth.assign(state.columns + 1, layoutConfig.blockHorizontalSpacing); state.edgeColumnWidth[0] = state.edgeColumnWidth.back() = layoutConfig.edgeHorizontalSpacing; edgeOffsets.resize(edgeIndex); calculateSegmentOffsets(segments, edgeOffsets, state.edgeColumnWidth, rightSides, leftSides, state.columnWidth, 2 * state.rows + 1, layoutConfig.edgeHorizontalSpacing); centerEdges(edgeOffsets, state.edgeColumnWidth, segments); edgeIndex = 0; auto copySegmentsToEdges = [&](bool col) { int edgeIndex = 0; for (auto &edgeListIt : state.edge) { for (auto &edge : edgeListIt.second) { for (size_t j = col ? 1 : 2; j < edge.points.size(); j += 2) { int offset = edgeOffsets[edgeIndex++]; if (col) { GraphBlock *block = nullptr; if (j == 1) { block = &(*state.blocks)[edgeListIt.first]; } else if (j + 1 == edge.points.size()) { block = &(*state.blocks)[edge.dest]; } if (block) { int blockWidth = block->width; int edgeColumWidth = state.edgeColumnWidth[edge.points[j].col]; offset = std::max(-blockWidth / 2 + edgeColumWidth / 2, offset); offset = std::min(edgeColumWidth / 2 + std::min(blockWidth, edgeColumWidth) / 2, offset); } } edge.points[j].offset = offset; } } } }; auto oldColumnWidths = state.columnWidth; adjustColumnWidths(state); for (auto &segment : segments) { auto &offset = edgeOffsets[segment.edgeIndex]; if (segment.kind == -2) { offset -= (state.edgeColumnWidth[segment.x - 1] / 2 + state.columnWidth[segment.x - 1]) - oldColumnWidths[segment.x - 1]; } else if (segment.kind == 2) { offset += (state.edgeColumnWidth[segment.x + 1] / 2 + state.columnWidth[segment.x]) - oldColumnWidths[segment.x]; } } calculateColumnOffsets(state.columnWidth, state.edgeColumnWidth, state.columnOffset, state.edgeColumnOffset); copySegmentsToEdges(true); // Horizontal segments // Use exact x coordinates obtained from vertical segment placement. segments.clear(); leftSides.clear(); rightSides.clear(); edgeIndex = 0; for (auto &edgeListIt : state.edge) { for (const auto &edge : edgeListIt.second) { for (size_t j = 2; j < edge.points.size(); j += 2) { int y0 = state.edgeColumnOffset[edge.points[j - 1].col] + edge.points[j - 1].offset; int y1 = state.edgeColumnOffset[edge.points[j + 1].col] + edge.points[j + 1].offset; segments.push_back( segmentFromPoint(edge.points[j], edge, y0, y1, edge.points[j].row)); } } } edgeOffsets.resize(edgeIndex); for (auto &blockIt : state.grid_blocks) { auto &node = blockIt.second; auto blockWidth = (*state.blocks)[node.id].width; int leftSide = state.edgeColumnOffset[node.col + 1] + state.edgeColumnWidth[node.col + 1] / 2 - blockWidth / 2; int rightSide = leftSide + blockWidth; int h = (*state.blocks)[blockIt.first].height; int freeSpace = state.rowHeight[node.row] - h; int topProfile = state.rowHeight[node.row]; int bottomProfile = h; if (verticalBlockAlignmentMiddle) { topProfile -= freeSpace / 2; bottomProfile += freeSpace / 2; } leftSides.push_back({ node.row, leftSide, rightSide, topProfile }); rightSides.push_back({ node.row, leftSide, rightSide, bottomProfile }); } state.edgeRowHeight.assign(state.rows + 1, layoutConfig.blockVerticalSpacing); state.edgeRowHeight[0] = state.edgeRowHeight.back() = layoutConfig.edgeVerticalSpacing; edgeOffsets.resize(edgeIndex); auto compressedCoordinates = compressCoordinates(segments, leftSides, rightSides); calculateSegmentOffsets(segments, edgeOffsets, state.edgeRowHeight, rightSides, leftSides, state.rowHeight, compressedCoordinates, layoutConfig.edgeVerticalSpacing); copySegmentsToEdges(false); } void GraphGridLayout::adjustColumnWidths(GraphGridLayout::LayoutState &state) const { state.rowHeight.assign(state.rows, 0); state.columnWidth.assign(state.columns, 0); for (auto &node : state.grid_blocks) { const auto &inputBlock = (*state.blocks)[node.first]; state.rowHeight[node.second.row] = std::max(inputBlock.height, state.rowHeight[node.second.row]); int edgeWidth = state.edgeColumnWidth[node.second.col + 1]; int columnWidth = (inputBlock.width - edgeWidth) / 2; state.columnWidth[node.second.col] = std::max(columnWidth, state.columnWidth[node.second.col]); state.columnWidth[node.second.col + 1] = std::max(columnWidth, state.columnWidth[node.second.col + 1]); } } int GraphGridLayout::calculateColumnOffsets(const std::vector<int> &columnWidth, std::vector<int> &edgeColumnWidth, std::vector<int> &columnOffset, std::vector<int> &edgeColumnOffset) { assert(edgeColumnWidth.size() == columnWidth.size() + 1); int position = 0; edgeColumnOffset.resize(edgeColumnWidth.size()); columnOffset.resize(columnWidth.size()); for (size_t i = 0; i < columnWidth.size(); i++) { edgeColumnOffset[i] = position; position += edgeColumnWidth[i]; columnOffset[i] = position; position += columnWidth[i]; } edgeColumnOffset.back() = position; position += edgeColumnWidth.back(); return position; } void GraphGridLayout::convertToPixelCoordinates(GraphGridLayout::LayoutState &state, int &width, int &height) const { // calculate row and column offsets width = calculateColumnOffsets(state.columnWidth, state.edgeColumnWidth, state.columnOffset, state.edgeColumnOffset); height = calculateColumnOffsets(state.rowHeight, state.edgeRowHeight, state.rowOffset, state.edgeRowOffset); // block pixel positions for (auto &block : (*state.blocks)) { const auto &gridBlock = state.grid_blocks[block.first]; block.second.x = state.edgeColumnOffset[gridBlock.col + 1] + state.edgeColumnWidth[gridBlock.col + 1] / 2 - block.second.width / 2; block.second.y = state.rowOffset[gridBlock.row]; if (verticalBlockAlignmentMiddle) { block.second.y += (state.rowHeight[gridBlock.row] - block.second.height) / 2; } } // edge pixel positions for (auto &it : (*state.blocks)) { auto &block = it.second; for (size_t i = 0; i < block.edges.size(); i++) { auto &resultEdge = block.edges[i]; resultEdge.polyline.clear(); resultEdge.polyline.push_back(QPointF(0, block.y + block.height)); const auto &edge = state.edge[it.first][i]; for (size_t j = 1; j < edge.points.size(); j++) { if (j & 1) { // vertical segment int column = edge.points[j].col; int x = state.edgeColumnOffset[column] + edge.points[j].offset; resultEdge.polyline.back().setX(x); resultEdge.polyline.push_back(QPointF(x, 0)); } else { // horizontal segment int row = edge.points[j].row; int y = state.edgeRowOffset[row] + edge.points[j].offset; resultEdge.polyline.back().setY(y); resultEdge.polyline.push_back(QPointF(0, y)); } } } } connectEdgeEnds(*state.blocks); } void GraphGridLayout::cropToContent(GraphLayout::Graph &graph, int &width, int &height) const { if (graph.empty()) { width = std::max(1, layoutConfig.edgeHorizontalSpacing); height = std::max(1, layoutConfig.edgeVerticalSpacing); return; } const auto &anyBlock = graph.begin()->second; int minPos[2] = { anyBlock.x, anyBlock.y }; int maxPos[2] = { anyBlock.x, anyBlock.y }; auto updateLimits = [&](int x, int y) { minPos[0] = std::min(minPos[0], x); minPos[1] = std::min(minPos[1], y); maxPos[0] = std::max(maxPos[0], x); maxPos[1] = std::max(maxPos[1], y); }; for (const auto &blockIt : graph) { auto &block = blockIt.second; updateLimits(block.x, block.y); updateLimits(block.x + block.width, block.y + block.height); for (auto &edge : block.edges) { for (auto &point : edge.polyline) { updateLimits(point.x(), point.y()); } } } minPos[0] -= layoutConfig.edgeHorizontalSpacing; minPos[1] -= layoutConfig.edgeVerticalSpacing; maxPos[0] += layoutConfig.edgeHorizontalSpacing; maxPos[1] += layoutConfig.edgeVerticalSpacing; for (auto &blockIt : graph) { auto &block = blockIt.second; block.x -= minPos[0]; block.y -= minPos[1]; for (auto &edge : block.edges) { for (auto &point : edge.polyline) { point -= QPointF(minPos[0], minPos[1]); } } } width = maxPos[0] - minPos[0]; height = maxPos[1] - minPos[1]; } void GraphGridLayout::connectEdgeEnds(GraphLayout::Graph &graph) const { for (auto &it : graph) { auto &block = it.second; for (size_t i = 0; i < block.edges.size(); i++) { auto &resultEdge = block.edges[i]; const auto &target = graph[resultEdge.target]; resultEdge.polyline[0].ry() = block.y + block.height; resultEdge.polyline.back().ry() = target.y; } } } /// Either equality or inequality x_i <= x_j + c using Constraint = std::pair<std::pair<int, int>, int>; /** * @brief Single pass of linear program optimizer. * Changes variables until a constraint is hit, afterwards the two variables are changed together. * @param n number of variables * @param objectiveFunction coefficients for function \f$\sum c_i x_i\f$ which needs to be minimized * @param inequalities inequality constraints \f$x_{e_i} - x_{f_i} \leq b_i\f$ * @param equalities equality constraints \f$x_{e_i} - x_{f_i} = b_i\f$ * @param solution input/output argument, returns results, needs to be initialized with a feasible * solution * @param stickWhenNotMoving variable grouping strategy */ static void optimizeLinearProgramPass(size_t n, std::vector<int> objectiveFunction, std::vector<Constraint> inequalities, std::vector<Constraint> equalities, std::vector<int> &solution, bool stickWhenNotMoving) { std::vector<int> group(n); std::iota(group.begin(), group.end(), 0); // initially each variable is in it's own group assert(n == objectiveFunction.size()); assert(n == solution.size()); std::vector<size_t> edgeCount(n); LinkedListPool<size_t> edgePool(inequalities.size() * 2); std::vector<decltype(edgePool)::List> edges(n); auto getGroup = [&](int v) { while (group[v] != v) { group[v] = group[group[v]]; v = group[v]; } return v; }; auto joinGroup = [&](int a, int b) { group[getGroup(b)] = getGroup(a); }; for (auto &constraint : inequalities) { int a = constraint.first.first; int b = constraint.first.second; size_t index = &constraint - &inequalities.front(); edges[a] = edgePool.append(edges[a], edgePool.makeList(index)); edges[b] = edgePool.append(edges[b], edgePool.makeList(index)); edgeCount[a]++; edgeCount[b]++; } std::vector<uint8_t> processed(n); // Smallest variable value in the group relative to main one, this is used to maintain implicit // x_i >= 0 constraint std::vector<int> groupRelativeMin(n, 0); auto joinSegmentGroups = [&](int a, int b) { a = getGroup(a); b = getGroup(b); joinGroup(a, b); edgeCount[a] += edgeCount[b]; objectiveFunction[a] += objectiveFunction[b]; int internalEdgeCount = 0; auto writeIt = edgePool.head(edges[b]); // update inequalities and remove some of the constraints between variables that are now // grouped for (auto it = edgePool.head(edges[b]); it; ++it) { auto &constraint = inequalities[*it]; int other = constraint.first.first + constraint.first.second - b; if (getGroup(other) == a) { // skip inequalities where both variables are now in the same group internalEdgeCount++; continue; } *writeIt++ = *it; // Modify the inequalities for the group being attached relative to the main variable in // the group to which it is being attached. int diff = solution[a] - solution[b]; if (b == constraint.first.first) { constraint.first.first = a; constraint.second += diff; } else { constraint.first.second = a; constraint.second -= diff; } } edges[a] = edgePool.append(edges[a], edgePool.splitHead(edges[b], writeIt)); edgeCount[a] -= internalEdgeCount; groupRelativeMin[a] = std::min(groupRelativeMin[a], groupRelativeMin[b] + solution[b] - solution[a]); }; for (auto &equality : equalities) { // process equalities, assumes that initial solution is feasible solution and matches // equality constraints int a = getGroup(equality.first.first); int b = getGroup(equality.first.second); if (a == b) { equality = { { 0, 0 }, 0 }; continue; } // always join smallest group to bigger one if (edgeCount[a] > edgeCount[b]) { std::swap(a, b); // Update the equality equation so that later variable values can be calculated by // simply iterating through them without need to check which direction the group joining // was done. std::swap(equality.first.first, equality.first.second); equality.second = -equality.second; } joinSegmentGroups(b, a); equality = { { a, b }, solution[a] - solution[b] }; processed[a] = 1; } // Priority queue for processing groups starting with currently smallest one. Doing it this way // should result in number of constraints within group doubling each time two groups are joined. // That way each constraint is processed no more than log(n) times. std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> queue; for (size_t i = 0; i < n; i++) { if (!processed[i]) { queue.push({ edgeCount[i], i }); } } while (!queue.empty()) { int g = queue.top().second; int size = queue.top().first; queue.pop(); if ((size_t)size != edgeCount[g] || processed[g]) { continue; } int direction = objectiveFunction[g]; if (direction == 0) { continue; } // Find the first constraint which will be hit by changing the variable in the desired // direction defined by objective function. int limitingGroup = -1; int smallestMove = 0; if (direction < 0) { smallestMove = INT_MAX; for (auto it = edgePool.head(edges[g]); it; ++it) { auto &inequality = inequalities[*it]; if (g == inequality.first.second) { continue; } int other = inequality.first.second; if (getGroup(other) == g) { continue; } int move = solution[other] + inequality.second - solution[g]; if (move < smallestMove) { smallestMove = move; limitingGroup = other; } } } else { smallestMove = -solution[g] - groupRelativeMin[g]; // keep all variables >= 0 for (auto it = edgePool.head(edges[g]); it; ++it) { auto &inequality = inequalities[*it]; if (g == inequality.first.first) { continue; } int other = inequality.first.first; if (getGroup(other) == g) { continue; } int move = solution[other] - inequality.second - solution[g]; if (move > smallestMove) { smallestMove = move; limitingGroup = other; } } } assert(smallestMove != INT_MAX); if (smallestMove == INT_MAX) { // Unbound variable, this means that linear program wasn't set up correctly. // Better don't change it instead of stretching the graph to infinity. smallestMove = 0; } solution[g] += smallestMove; if (smallestMove == 0 && stickWhenNotMoving == false) { continue; } processed[g] = 1; if (limitingGroup != -1) { joinSegmentGroups(limitingGroup, g); if (!processed[limitingGroup]) { queue.push({ edgeCount[limitingGroup], limitingGroup }); } equalities.push_back({ { g, limitingGroup }, solution[g] - solution[limitingGroup] }); } // else do nothing if limited by variable >= 0 } for (auto it = equalities.rbegin(), end = equalities.rend(); it != end; ++it) { solution[it->first.first] = solution[it->first.second] + it->second; } } /** * @brief Linear programming solver * Does not guarantee optimal solution. * @param n number of variables * @param objectiveFunction coefficients for function \f$\sum c_i x_i\f$ which needs to be minimized * @param inequalities inequality constraints \f$x_{e_i} - x_{f_i} \leq b_i\f$ * @param equalities equality constraints \f$x_{e_i} - x_{f_i} = b_i\f$ * @param solution input/output argument, returns results, needs to be initialized with a feasible * solution */ static void optimizeLinearProgram(size_t n, const std::vector<int> &objectiveFunction, std::vector<Constraint> inequalities, const std::vector<Constraint> &equalities, std::vector<int> &solution) { // Remove redundant inequalities std::sort(inequalities.begin(), inequalities.end()); auto uniqueEnd = std::unique( inequalities.begin(), inequalities.end(), [](const Constraint &a, const Constraint &b) { return a.first == b.first; }); inequalities.erase(uniqueEnd, inequalities.end()); static const int ITERATIONS = 1; for (int i = 0; i < ITERATIONS; i++) { optimizeLinearProgramPass(n, objectiveFunction, inequalities, equalities, solution, true); // optimizeLinearProgramPass(n, objectiveFunction, inequalities, equalities, solution, // false); } } namespace { struct Segment { int x; int variableId; int y0, y1; }; } static Constraint createInequality(size_t a, int posA, size_t b, int posB, int minSpacing, const std::vector<int> &positions) { minSpacing = std::min(minSpacing, posB - posA); return { { a, b }, posB - positions[b] - (posA - positions[a]) - minSpacing }; } /** * @brief Create inequality constraints from segments which preserves their relative order on single * axis. * * @param segments list of edge segments and block sides * @param positions initial element positions before optimization * @param blockCount number of variables representing blocks, it is assumed that segments with * variableId < \a blockCount represent one side of block. * @param variableGroup used to check if segments are part of the same edge and spacing can be * reduced * @param blockSpacing minimal spacing between blocks * @param segmentSpacing minimal spacing between two edge segments, spacing may be less if values in * \a positions are closer than this * @param inequalities output variable for resulting inequalities, values initially stored in it are * not removed */ static void createInequalitiesFromSegments(std::vector<Segment> segments, const std::vector<int> &positions, const std::vector<size_t> &variableGroup, int blockCount, int blockSpacing, int segmentSpacing, std::vector<Constraint> &inequalities) { // map used as binary search tree y_position -> segment{variableId, x_position} // It is used to maintain which segment was last seen in the range y_position.. std::map<int, std::pair<int, int>> lastSegments; lastSegments[-1] = { -1, -1 }; std::sort(segments.begin(), segments.end(), [](const Segment &a, const Segment &b) { return a.x < b.x; }); for (auto &segment : segments) { auto startPos = lastSegments.lower_bound(segment.y0); --startPos; // should never be lastSegment.begin() because map is initialized with segment // at pos -1 auto lastSegment = startPos->second; auto it = startPos; while (it != lastSegments.end() && it->first <= segment.y1) { int prevSegmentVariable = it->second.first; int prevSegmentPos = it->second.second; if (prevSegmentVariable != -1) { int minSpacing = segmentSpacing; if (prevSegmentVariable < blockCount && segment.variableId < blockCount) { // no need to add inequality between two sides of block if (prevSegmentVariable == segment.variableId) { ++it; continue; } minSpacing = blockSpacing; } else if (variableGroup[prevSegmentVariable] == variableGroup[segment.variableId]) { minSpacing = 0; } inequalities.push_back(createInequality(prevSegmentVariable, prevSegmentPos, segment.variableId, segment.x, minSpacing, positions)); } lastSegment = it->second; ++it; } if (startPos->first < segment.y0) { startPos++; } lastSegments.erase(startPos, it); // erase segments covered by current one lastSegments[segment.y0] = { segment.variableId, segment.x }; // current segment // either current segment splitting previous one into two parts or remaining part of // partially covered segment lastSegments[segment.y1] = lastSegment; } } void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const { std::unordered_map<uint64_t, int> blockMapping; size_t blockIndex = 0; for (auto &blockIt : *state.blocks) { blockMapping[blockIt.first] = blockIndex++; } std::vector<size_t> variableGroups(blockMapping.size()); std::iota(variableGroups.begin(), variableGroups.end(), 0); std::vector<int> objectiveFunction; std::vector<Constraint> inequalities; std::vector<Constraint> equalities; std::vector<int> solution; auto addObjective = [&](size_t a, int posA, size_t b, int posB) { objectiveFunction.resize(std::max(objectiveFunction.size(), std::max(a, b) + 1)); if (posA < posB) { objectiveFunction[b] += 1; objectiveFunction[a] -= 1; } else { objectiveFunction[a] += 1; objectiveFunction[b] -= 1; } }; auto addInequality = [&](size_t a, int posA, size_t b, int posB, int minSpacing) { inequalities.push_back(createInequality(a, posA, b, posB, minSpacing, solution)); }; auto addBlockSegmentEquality = [&](ut64 blockId, int edgeVariable, int edgeVariablePos) { int blockPos = (*state.blocks)[blockId].x; int blockVariable = blockMapping[blockId]; equalities.push_back({ { blockVariable, edgeVariable }, blockPos - edgeVariablePos }); }; auto setFeasibleSolution = [&](size_t variable, int value) { solution.resize(std::max(solution.size(), variable + 1)); solution[variable] = value; }; auto copyVariablesToPositions = [&](const std::vector<int> &solution, bool horizontal = false) { #ifndef NDEBUG for (auto v : solution) { assert(v >= 0); } #endif size_t variableIndex = blockMapping.size(); for (auto &blockIt : *state.blocks) { auto &block = blockIt.second; for (auto &edge : blockIt.second.edges) { for (int i = 1 + int(horizontal); i < edge.polyline.size(); i += 2) { int x = solution[variableIndex++]; if (horizontal) { edge.polyline[i].ry() = x; edge.polyline[i - 1].ry() = x; } else { edge.polyline[i].rx() = x; edge.polyline[i - 1].rx() = x; } } } int blockVariable = blockMapping[blockIt.first]; (horizontal ? block.y : block.x) = solution[blockVariable]; } }; std::vector<Segment> segments; segments.reserve(state.blocks->size() * 2 + state.blocks->size() * 2); size_t variableIndex = state.blocks->size(); size_t edgeIndex = 0; // horizontal segments objectiveFunction.assign(blockMapping.size(), 1); for (auto &blockIt : *state.blocks) { auto &block = blockIt.second; int blockVariable = blockMapping[blockIt.first]; for (auto &edge : block.edges) { auto &targetBlock = (*state.blocks)[edge.target]; if (block.y < targetBlock.y) { int spacing = block.height + layoutConfig.blockVerticalSpacing; inequalities.push_back({ { blockVariable, blockMapping[edge.target] }, -spacing }); } if (edge.polyline.size() < 3) { continue; } for (int i = 2; i < edge.polyline.size(); i += 2) { int y0 = edge.polyline[i - 1].x(); int y1 = edge.polyline[i].x(); if (y0 > y1) { std::swap(y0, y1); } int x = edge.polyline[i].y(); segments.push_back({ x, int(variableIndex), y0, y1 }); variableGroups.push_back(blockMapping.size() + edgeIndex); setFeasibleSolution(variableIndex, x); if (i > 2) { int prevX = edge.polyline[i - 2].y(); addObjective(variableIndex, x, variableIndex - 1, prevX); } variableIndex++; } edgeIndex++; } segments.push_back({ block.y, blockVariable, block.x, block.x + block.width }); segments.push_back( { block.y + block.height, blockVariable, block.x, block.x + block.width }); setFeasibleSolution(blockVariable, block.y); } createInequalitiesFromSegments(std::move(segments), solution, variableGroups, blockMapping.size(), layoutConfig.blockVerticalSpacing, layoutConfig.edgeVerticalSpacing, inequalities); objectiveFunction.resize(solution.size()); optimizeLinearProgram(solution.size(), objectiveFunction, inequalities, equalities, solution); copyVariablesToPositions(solution, true); connectEdgeEnds(*state.blocks); // vertical segments variableGroups.resize(blockMapping.size()); solution.clear(); equalities.clear(); inequalities.clear(); objectiveFunction.clear(); segments.clear(); variableIndex = blockMapping.size(); edgeIndex = 0; for (auto &blockIt : *state.blocks) { auto &block = blockIt.second; for (auto &edge : block.edges) { if (edge.polyline.size() < 2) { continue; } size_t firstEdgeVariable = variableIndex; for (int i = 1; i < edge.polyline.size(); i += 2) { int y0 = edge.polyline[i - 1].y(); int y1 = edge.polyline[i].y(); if (y0 > y1) { std::swap(y0, y1); } int x = edge.polyline[i].x(); segments.push_back({ x, int(variableIndex), y0, y1 }); variableGroups.push_back(blockMapping.size() + edgeIndex); setFeasibleSolution(variableIndex, x); if (i > 2) { int prevX = edge.polyline[i - 2].x(); addObjective(variableIndex, x, variableIndex - 1, prevX); } variableIndex++; } size_t lastEdgeVariableIndex = variableIndex - 1; addBlockSegmentEquality(blockIt.first, firstEdgeVariable, edge.polyline[1].x()); addBlockSegmentEquality(edge.target, lastEdgeVariableIndex, segments.back().x); edgeIndex++; } int blockVariable = blockMapping[blockIt.first]; segments.push_back({ block.x, blockVariable, block.y, block.y + block.height }); segments.push_back( { block.x + block.width, blockVariable, block.y, block.y + block.height }); setFeasibleSolution(blockVariable, block.x); } createInequalitiesFromSegments(std::move(segments), solution, variableGroups, blockMapping.size(), layoutConfig.blockHorizontalSpacing, layoutConfig.edgeHorizontalSpacing, inequalities); objectiveFunction.resize(solution.size()); // horizontal centering constraints for (auto &blockIt : *state.blocks) { auto &block = blockIt.second; int blockVariable = blockMapping[blockIt.first]; if (block.edges.size() == 2) { auto &blockLeft = (*state.blocks)[block.edges[0].target]; auto &blockRight = (*state.blocks)[block.edges[1].target]; auto middle = block.x + block.width / 2; if (blockLeft.x + blockLeft.width < middle && blockRight.x > middle) { addInequality(blockMapping[block.edges[0].target], blockLeft.x + blockLeft.width, blockVariable, middle, layoutConfig.blockHorizontalSpacing / 2); addInequality(blockVariable, middle, blockMapping[block.edges[1].target], blockRight.x, layoutConfig.blockHorizontalSpacing / 2); auto &gridBlock = state.grid_blocks[blockIt.first]; if (gridBlock.mergeBlock) { auto &mergeBlock = (*state.blocks)[gridBlock.mergeBlock]; if (mergeBlock.x + mergeBlock.width / 2 == middle) { equalities.push_back( { { blockVariable, blockMapping[gridBlock.mergeBlock] }, block.x - mergeBlock.x }); } } } } } optimizeLinearProgram(solution.size(), objectiveFunction, inequalities, equalities, solution); copyVariablesToPositions(solution); }
77,636
C++
.cpp
1,629
37.431553
100
0.612643
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,539
SegmentsWidget.cpp
rizinorg_cutter/src/widgets/SegmentsWidget.cpp
#include "SegmentsWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "ui_ListDockWidget.h" #include <QVBoxLayout> #include <QShortcut> SegmentsModel::SegmentsModel(QList<SegmentDescription> *segments, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), segments(segments) { } int SegmentsModel::rowCount(const QModelIndex &) const { return segments->count(); } int SegmentsModel::columnCount(const QModelIndex &) const { return SegmentsModel::ColumnCount; } QVariant SegmentsModel::data(const QModelIndex &index, int role) const { // TODO: create unique colors, e. g. use HSV color space and rotate in H for 360/size static const QList<QColor> colors = { QColor("#1ABC9C"), // TURQUOISE QColor("#2ECC71"), // EMERALD QColor("#3498DB"), // PETER RIVER QColor("#9B59B6"), // AMETHYST QColor("#34495E"), // WET ASPHALT QColor("#F1C40F"), // SUN FLOWER QColor("#E67E22"), // CARROT QColor("#E74C3C"), // ALIZARIN QColor("#ECF0F1"), // CLOUDS QColor("#BDC3C7"), // SILVER QColor("#95A5A6") // COBCRETE }; if (index.row() >= segments->count()) return QVariant(); const SegmentDescription &segment = segments->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case SegmentsModel::NameColumn: return segment.name; case SegmentsModel::SizeColumn: return QString::number(segment.size); case SegmentsModel::AddressColumn: return RzAddressString(segment.vaddr); case SegmentsModel::EndAddressColumn: return RzAddressString(segment.vaddr + segment.size); case SegmentsModel::PermColumn: return segment.perm; case SegmentsModel::CommentColumn: return Core()->getCommentAt(segment.vaddr); default: return QVariant(); } case Qt::DecorationRole: if (index.column() == 0) return colors[index.row() % colors.size()]; return QVariant(); case SegmentsModel::SegmentDescriptionRole: return QVariant::fromValue(segment); default: return QVariant(); } } QVariant SegmentsModel::headerData(int segment, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (segment) { case SegmentsModel::NameColumn: return tr("Name"); case SegmentsModel::SizeColumn: return tr("Size"); case SegmentsModel::AddressColumn: return tr("Address"); case SegmentsModel::EndAddressColumn: return tr("End Address"); case SegmentsModel::PermColumn: return tr("Permissions"); case SegmentsModel::CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA SegmentsModel::address(const QModelIndex &index) const { const SegmentDescription &segment = segments->at(index.row()); return segment.vaddr; } QString SegmentsModel::name(const QModelIndex &index) const { const SegmentDescription &segment = segments->at(index.row()); return segment.name; } SegmentsProxyModel::SegmentsProxyModel(SegmentsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool SegmentsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftSegment = left.data(SegmentsModel::SegmentDescriptionRole).value<SegmentDescription>(); auto rightSegment = right.data(SegmentsModel::SegmentDescriptionRole).value<SegmentDescription>(); switch (left.column()) { case SegmentsModel::NameColumn: return leftSegment.name < rightSegment.name; case SegmentsModel::SizeColumn: return leftSegment.size < rightSegment.size; case SegmentsModel::AddressColumn: case SegmentsModel::EndAddressColumn: return leftSegment.vaddr < rightSegment.vaddr; case SegmentsModel::CommentColumn: return Core()->getCommentAt(leftSegment.vaddr) < Core()->getCommentAt(rightSegment.vaddr); default: break; } return false; } SegmentsWidget::SegmentsWidget(MainWindow *main) : ListDockWidget(main) { setObjectName("SegmentsWidget"); setWindowTitle(QStringLiteral("Segments")); segmentsModel = new SegmentsModel(&segments, this); auto proxyModel = new SegmentsProxyModel(segmentsModel, this); setModels(proxyModel); ui->treeView->sortByColumn(SegmentsModel::NameColumn, Qt::AscendingOrder); ui->quickFilterView->closeFilter(); showCount(false); connect(Core(), &CutterCore::refreshAll, this, &SegmentsWidget::refreshSegments); connect(Core(), &CutterCore::codeRebased, this, &SegmentsWidget::refreshSegments); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(segmentsModel, SegmentsModel::CommentColumn); }); } SegmentsWidget::~SegmentsWidget() {} void SegmentsWidget::refreshSegments() { segmentsModel->beginResetModel(); segments = Core()->getAllSegments(); segmentsModel->endResetModel(); qhelpers::adjustColumns(ui->treeView, SegmentsModel::ColumnCount, 0); }
5,446
C++
.cpp
148
30.736486
100
0.69187
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,540
SectionsWidget.cpp
rizinorg_cutter/src/widgets/SectionsWidget.cpp
#include "SectionsWidget.h" #include "QuickFilterView.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "common/Configuration.h" #include "ui_ListDockWidget.h" #include <QGraphicsSceneMouseEvent> #include <QGraphicsTextItem> #include <QGraphicsView> #include <QHBoxLayout> #include <QVBoxLayout> #include <QShortcut> #include <QToolTip> SectionsModel::SectionsModel(QList<SectionDescription> *sections, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), sections(sections) { } int SectionsModel::rowCount(const QModelIndex &) const { return sections->count(); } int SectionsModel::columnCount(const QModelIndex &) const { return SectionsModel::ColumnCount; } QVariant SectionsModel::data(const QModelIndex &index, int role) const { // TODO: create unique colors, e. g. use HSV color space and rotate in H for 360/size static const QList<QColor> colors = { QColor("#1ABC9C"), // TURQUOISE QColor("#2ECC71"), // EMERALD QColor("#3498DB"), // PETER RIVER QColor("#9B59B6"), // AMETHYST QColor("#34495E"), // WET ASPHALT QColor("#F1C40F"), // SUN FLOWER QColor("#E67E22"), // CARROT QColor("#E74C3C"), // ALIZARIN QColor("#ECF0F1"), // CLOUDS QColor("#BDC3C7"), // SILVER QColor("#95A5A6") // COBCRETE }; if (index.row() >= sections->count()) { return QVariant(); } const SectionDescription &section = sections->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case SectionsModel::NameColumn: return section.name; case SectionsModel::SizeColumn: return RzSizeString(section.size); case SectionsModel::AddressColumn: return RzAddressString(section.vaddr); case SectionsModel::EndAddressColumn: return RzAddressString(section.vaddr + section.vsize); case SectionsModel::VirtualSizeColumn: return RzSizeString(section.vsize); case SectionsModel::PermissionsColumn: return section.perm; case SectionsModel::EntropyColumn: return section.entropy; case SectionsModel::CommentColumn: return Core()->getCommentAt(section.vaddr); default: return QVariant(); } case Qt::DecorationRole: if (index.column() == 0) return colors[index.row() % colors.size()]; return QVariant(); case SectionsModel::SectionDescriptionRole: return QVariant::fromValue(section); default: return QVariant(); } } QVariant SectionsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case SectionsModel::NameColumn: return tr("Name"); case SectionsModel::SizeColumn: return tr("Size"); case SectionsModel::AddressColumn: return tr("Address"); case SectionsModel::EndAddressColumn: return tr("End Address"); case SectionsModel::VirtualSizeColumn: return tr("Virtual Size"); case SectionsModel::PermissionsColumn: return tr("Permissions"); case SectionsModel::EntropyColumn: return tr("Entropy"); case SectionsModel::CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA SectionsModel::address(const QModelIndex &index) const { const SectionDescription &section = sections->at(index.row()); return section.vaddr; } QString SectionsModel::name(const QModelIndex &index) const { const SectionDescription &section = sections->at(index.row()); return section.name; } SectionsProxyModel::SectionsProxyModel(SectionsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool SectionsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftSection = left.data(SectionsModel::SectionDescriptionRole).value<SectionDescription>(); auto rightSection = right.data(SectionsModel::SectionDescriptionRole).value<SectionDescription>(); switch (left.column()) { default: case SectionsModel::NameColumn: return leftSection.name < rightSection.name; case SectionsModel::SizeColumn: return leftSection.size < rightSection.size; case SectionsModel::AddressColumn: case SectionsModel::EndAddressColumn: if (leftSection.vaddr != rightSection.vaddr) { return leftSection.vaddr < rightSection.vaddr; } return leftSection.vsize < rightSection.vsize; case SectionsModel::VirtualSizeColumn: return leftSection.vsize < rightSection.vsize; case SectionsModel::PermissionsColumn: return leftSection.perm < rightSection.perm; case SectionsModel::EntropyColumn: return leftSection.entropy < rightSection.entropy; case SectionsModel::CommentColumn: return Core()->getCommentAt(leftSection.vaddr) < Core()->getCommentAt(rightSection.vaddr); } } SectionsWidget::SectionsWidget(MainWindow *main) : ListDockWidget(main) { setObjectName("SectionsWidget"); setWindowTitle(tr("Sections")); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); sectionsRefreshDeferrer = createRefreshDeferrer([this]() { refreshSections(); }); dockRefreshDeferrer = createRefreshDeferrer([this]() { refreshDocks(); }); initSectionsTable(); initQuickFilter(); initAddrMapDocks(); initConnects(); } SectionsWidget::~SectionsWidget() = default; void SectionsWidget::initSectionsTable() { sectionsModel = new SectionsModel(&sections, this); proxyModel = new SectionsProxyModel(sectionsModel, this); setModels(proxyModel); ui->treeView->sortByColumn(SectionsModel::AddressColumn, Qt::AscendingOrder); } void SectionsWidget::initQuickFilter() { ui->quickFilterView->closeFilter(); } void SectionsWidget::initAddrMapDocks() { QVBoxLayout *layout = ui->verticalLayout; showCount(false); rawAddrDock = new RawAddrDock(sectionsModel, this); virtualAddrDock = new VirtualAddrDock(sectionsModel, this); addrDockWidget = new QWidget(); QHBoxLayout *addrDockLayout = new QHBoxLayout(); addrDockLayout->addWidget(rawAddrDock); addrDockLayout->addWidget(virtualAddrDock); addrDockWidget->setLayout(addrDockLayout); layout->addWidget(addrDockWidget); QPixmap map(":/img/icons/previous.svg"); QTransform transform; transform = transform.rotate(90); map = map.transformed(transform); QIcon icon; icon.addPixmap(map); toggleButton = new QToolButton; toggleButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); toggleButton->setFixedHeight(30); toggleButton->setIcon(icon); toggleButton->setIconSize(QSize(16, 12)); toggleButton->setAutoRaise(true); toggleButton->setArrowType(Qt::NoArrow); toggleButton->hide(); layout->addWidget(toggleButton); } void SectionsWidget::initConnects() { connect(Core(), &CutterCore::refreshAll, this, &SectionsWidget::refreshSections); connect(Core(), &CutterCore::codeRebased, this, &SectionsWidget::refreshSections); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visibility) { if (visibility) { refreshSections(); } }); connect(Core(), &CutterCore::seekChanged, this, &SectionsWidget::refreshDocks); connect(Config(), &Configuration::colorsUpdated, this, &SectionsWidget::refreshSections); connect(toggleButton, &QToolButton::clicked, this, [=] { toggleButton->hide(); addrDockWidget->show(); virtualAddrDock->show(); }); connect(virtualAddrDock, &QDockWidget::visibilityChanged, this, [=](bool visibility) { if (!visibility) { updateToggle(); } }); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(sectionsModel, SectionsModel::CommentColumn); }); } void SectionsWidget::refreshSections() { if (!sectionsRefreshDeferrer->attemptRefresh(nullptr) || Core()->isDebugTaskInProgress()) { return; } sectionsModel->beginResetModel(); sections = Core()->getAllSections(); sectionsModel->endResetModel(); qhelpers::adjustColumns(ui->treeView, SectionsModel::ColumnCount, 0); refreshDocks(); } void SectionsWidget::refreshDocks() { if (!dockRefreshDeferrer->attemptRefresh(nullptr)) { return; } rawAddrDock->updateDock(); virtualAddrDock->updateDock(); drawIndicatorOnAddrDocks(); } void SectionsWidget::drawIndicatorOnAddrDocks() { RVA offset = Core()->getOffset(); for (int i = 0; i != virtualAddrDock->proxyModel->rowCount(); i++) { QModelIndex idx = virtualAddrDock->proxyModel->index(i, 0); RVA vaddr = idx.data(SectionsModel::SectionDescriptionRole).value<SectionDescription>().vaddr; int vsize = idx.data(SectionsModel::SectionDescriptionRole).value<SectionDescription>().vsize; RVA end = vaddr + vsize; if (offset < end) { QString name = idx.data(SectionsModel::SectionDescriptionRole) .value<SectionDescription>() .name; float ratio = 0; if (vsize > 0 && offset > vaddr) { ratio = (float)(offset - vaddr) / (float)vsize; } rawAddrDock->drawIndicator(name, ratio); virtualAddrDock->drawIndicator(name, ratio); return; } } } void SectionsWidget::resizeEvent(QResizeEvent *event) { CutterDockWidget::resizeEvent(event); refreshDocks(); } void SectionsWidget::updateToggle() { if (!virtualAddrDock->isVisible()) { addrDockWidget->hide(); toggleButton->show(); } } AbstractAddrDock::AbstractAddrDock(SectionsModel *model, QWidget *parent) : QDockWidget(parent), addrDockScene(new AddrDockScene(this)), graphicsView(new QGraphicsView(this)) { graphicsView->setScene(addrDockScene); setWidget(graphicsView); setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); proxyModel = new SectionsProxyModel(model, this); setWidget(graphicsView); indicatorHeight = 5; indicatorParamPosY = 20; heightThreshold = 30; heightDivisor = 1000; rectOffset = 100; rectWidthMin = 80; rectWidthMax = 400; indicatorColor = ConfigColor("gui.navbar.seek"); textColor = ConfigColor("gui.dataoffset"); } AbstractAddrDock::~AbstractAddrDock() {} void AbstractAddrDock::updateDock() { addrDockScene->clear(); const QBrush bg = QBrush(ConfigColor("gui.background")); addrDockScene->setBackgroundBrush(bg); textColor = ConfigColor("gui.dataoffset"); int y = 0; int validMinSize = getValidMinSize(); int rectWidth = getRectWidth(); proxyModel->sort(SectionsModel::AddressColumn, Qt::AscendingOrder); for (int i = 0; i < proxyModel->rowCount(); ++i) { QModelIndex idx = proxyModel->index(i, 0); auto desc = idx.data(SectionsModel::SectionDescriptionRole).value<SectionDescription>(); QString name = desc.name; addrDockScene->seekAddrMap[name] = desc.vaddr; addrDockScene->seekAddrSizeMap[name] = desc.vsize; RVA addr = getAddressOfSection(desc); RVA size = getSizeOfSection(desc); addrDockScene->nameAddrMap[name] = addr; addrDockScene->nameAddrSizeMap[name] = size; int drawSize = getAdjustedSize(size, validMinSize); QGraphicsRectItem *rect = new QGraphicsRectItem(rectOffset, y, rectWidth, drawSize); rect->setBrush(QBrush(idx.data(Qt::DecorationRole).value<QColor>())); addrDockScene->addItem(rect); addTextItem(textColor, QPoint(0, y), RzAddressString(addr)); addTextItem(textColor, QPoint(rectOffset, y), RzSizeString(size)); addTextItem(textColor, QPoint(rectOffset + rectWidth, y), name); addrDockScene->namePosYMap[name] = y; addrDockScene->nameHeightMap[name] = drawSize; y += drawSize; } graphicsView->setSceneRect(addrDockScene->itemsBoundingRect()); } void AbstractAddrDock::addTextItem(QColor color, QPoint pos, QString string) { QGraphicsTextItem *text = new QGraphicsTextItem; text->setDefaultTextColor(color); text->setPos(pos); text->setPlainText(string); addrDockScene->addItem(text); } int AbstractAddrDock::getAdjustedSize(int size, int validMinSize) { if (size == 0) { return size; } if (size == validMinSize) { return heightThreshold; } float r = (float)size / (float)validMinSize; r /= heightDivisor; r += 1; return heightThreshold * r; } int AbstractAddrDock::getRectWidth() { return qBound(rectWidthMin, width() - 300, rectWidthMax); } int AbstractAddrDock::getIndicatorWidth() { return getRectWidth() + 200; } int AbstractAddrDock::getValidMinSize() { proxyModel->sort(SectionsModel::SizeColumn, Qt::AscendingOrder); for (int i = 0; i < proxyModel->rowCount(); i++) { QModelIndex idx = proxyModel->index(i, 0); int size = getSizeOfSection( idx.data(SectionsModel::SectionDescriptionRole).value<SectionDescription>()); if (size > 0) { return size; } } return 0; } void AbstractAddrDock::drawIndicator(QString name, float ratio) { RVA offset = Core()->getOffset(); float padding = addrDockScene->nameHeightMap[name] * ratio; int y = addrDockScene->namePosYMap[name] + (int)padding; QColor color = indicatorColor; QGraphicsRectItem *indicator = new QGraphicsRectItem(QRectF(0, y, getIndicatorWidth(), indicatorHeight)); indicator->setBrush(QBrush(color)); addrDockScene->addItem(indicator); if (!addrDockScene->disableCenterOn) { graphicsView->centerOn(indicator); } addTextItem(color, QPoint(rectOffset + getRectWidth(), y - indicatorParamPosY), name); addTextItem(color, QPoint(0, y - indicatorParamPosY), QString("0x%1").arg(offset, 0, 16)); } AddrDockScene::AddrDockScene(QWidget *parent) : QGraphicsScene(parent) { disableCenterOn = false; } AddrDockScene::~AddrDockScene() {} void AddrDockScene::mousePressEvent(QGraphicsSceneMouseEvent *event) { RVA addr = getAddrFromPos((int)event->scenePos().y(), false); if (addr != RVA_INVALID) { QToolTip::showText(event->screenPos(), RzAddressString(addr)); if (event->buttons() & Qt::LeftButton) { RVA seekAddr = getAddrFromPos((int)event->scenePos().y(), true); disableCenterOn = true; Core()->seekAndShow(seekAddr); disableCenterOn = false; return; } } else { QToolTip::hideText(); } } void AddrDockScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { mousePressEvent(event); } RVA AddrDockScene::getAddrFromPos(int posY, bool seek) { QHash<QString, int>::const_iterator it; QHash<QString, RVA> addrMap = seek ? seekAddrMap : nameAddrMap; QHash<QString, RVA> addrSizeMap = seek ? seekAddrSizeMap : nameAddrSizeMap; for (it = namePosYMap.constBegin(); it != namePosYMap.constEnd(); ++it) { QString name = it.key(); int y = it.value(); int h = nameHeightMap[name]; if (posY >= y && y + h >= posY) { if (h == 0) { return addrMap[name]; } return addrMap[name] + (float)addrSizeMap[name] * ((float)(posY - y) / (float)h); } } return RVA_INVALID; } RawAddrDock::RawAddrDock(SectionsModel *model, QWidget *parent) : AbstractAddrDock(model, parent) { setWindowTitle(tr("Raw")); connect(this, &QDockWidget::featuresChanged, this, [=]() { setFeatures(QDockWidget::NoDockWidgetFeatures); }); } VirtualAddrDock::VirtualAddrDock(SectionsModel *model, QWidget *parent) : AbstractAddrDock(model, parent) { setWindowTitle(tr("Virtual")); connect(this, &QDockWidget::featuresChanged, this, [=]() { setFeatures(QDockWidget::DockWidgetClosable); }); } void RawAddrDock::updateDock() { AbstractAddrDock::updateDock(); setFeatures(QDockWidget::DockWidgetClosable); } void VirtualAddrDock::updateDock() { AbstractAddrDock::updateDock(); setFeatures(QDockWidget::NoDockWidgetFeatures); }
16,738
C++
.cpp
458
30.561135
100
0.686648
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,541
CallGraph.cpp
rizinorg_cutter/src/widgets/CallGraph.cpp
#include "CallGraph.h" #include "MainWindow.h" #include <QJsonValue> #include <QJsonArray> #include <QJsonObject> CallGraphWidget::CallGraphWidget(MainWindow *main, bool global) : MemoryDockWidget(MemoryWidgetType::CallGraph, main), graphView(new CallGraphView(this, main, global)), global(global) { setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); this->setWindowTitle(getWindowTitle()); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &CallGraphWidget::onSeekChanged); setWidget(graphView); } CallGraphWidget::~CallGraphWidget() {} QString CallGraphWidget::getWindowTitle() const { return global ? tr("Global Callgraph") : tr("Callgraph"); } QString CallGraphWidget::getWidgetType() const { return global ? tr("GlobalCallgraph") : tr("Callgraph"); } void CallGraphWidget::onSeekChanged(RVA address) { if (auto function = Core()->functionIn(address)) { graphView->showAddress(function->addr); } } CallGraphView::CallGraphView(CutterDockWidget *parent, MainWindow *main, bool global) : SimpleTextGraphView(parent, main), global(global), refreshDeferrer(nullptr, this) { enableAddresses(true); refreshDeferrer.registerFor(parent); connect(&refreshDeferrer, &RefreshDeferrer::refreshNow, this, &CallGraphView::refreshView); connect(Core(), &CutterCore::refreshAll, this, &SimpleTextGraphView::refreshView); connect(Core(), &CutterCore::functionRenamed, this, &CallGraphView::refreshView); } void CallGraphView::showExportDialog() { QString defaultName; if (global) { defaultName = "global_callgraph"; } else { defaultName = QString("callgraph_%1").arg(RzAddressString(address)); } showExportGraphDialog(defaultName, RZ_CORE_GRAPH_TYPE_FUNCALL, global ? RVA_INVALID : address); } void CallGraphView::showAddress(RVA address) { if (global) { selectBlockWithId(address); showBlock(blocks[address]); } else if (address != this->address) { this->address = address; refreshView(); } } void CallGraphView::refreshView() { if (!refreshDeferrer.attemptRefresh(nullptr)) { return; } SimpleTextGraphView::refreshView(); } static inline bool isBetween(ut64 a, ut64 x, ut64 b) { return (a == UT64_MAX || a <= x) && (b == UT64_MAX || x <= b); } void CallGraphView::loadCurrentGraph() { blockContent.clear(); blocks.clear(); const ut64 from = Core()->getConfigi("graph.from"); const ut64 to = Core()->getConfigi("graph.to"); const bool usenames = Core()->getConfigb("graph.json.usenames"); auto edges = std::unordered_set<ut64> {}; auto addFunction = [&](RzAnalysisFunction *fcn) { GraphLayout::GraphBlock block; block.entry = fcn->addr; auto xrefs = fromOwned(rz_analysis_function_get_xrefs_from(fcn)); auto calls = std::unordered_set<ut64>(); for (const auto &xref : CutterRzList<RzAnalysisXRef>(xrefs.get())) { const auto x = xref->to; if (!(xref->type == RZ_ANALYSIS_XREF_TYPE_CALL && calls.find(x) == calls.end())) { continue; } calls.insert(x); block.edges.emplace_back(x); edges.insert(x); } QString name = usenames ? fcn->name : RzAddressString(fcn->addr); addBlock(std::move(block), name, fcn->addr); }; if (global) { for (const auto &fcn : CutterRzList<RzAnalysisFunction>(Core()->core()->analysis->fcns)) { if (!isBetween(from, fcn->addr, to)) { continue; } addFunction(fcn); } } else { const auto &fcn = Core()->functionIn(address); if (fcn) { addFunction(fcn); } } for (const auto &x : edges) { if (blockContent.find(x) != blockContent.end()) { continue; } GraphLayout::GraphBlock block; block.entry = x; QString flagName = Core()->flagAt(x); QString name = usenames ? (!flagName.isEmpty() ? flagName : QString("unk.%0").arg(RzAddressString(x))) : RzAddressString(x); addBlock(std::move(block), name, x); } if (blockContent.empty() && !global) { const auto name = RzAddressString(address); addBlock({}, name, address); } computeGraphPlacement(); } void CallGraphView::restoreCurrentBlock() { if (!global && lastLoadedAddress != address) { selectedBlock = NO_BLOCK_SELECTED; lastLoadedAddress = address; center(); } else { SimpleTextGraphView::restoreCurrentBlock(); } }
4,701
C++
.cpp
136
28.522059
99
0.649351
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,542
GraphWidget.cpp
rizinorg_cutter/src/widgets/GraphWidget.cpp
#include "core/MainWindow.h" #include "GraphWidget.h" #include "DisassemblerGraphView.h" #include "WidgetShortcuts.h" #include <QVBoxLayout> GraphWidget::GraphWidget(MainWindow *main) : MemoryDockWidget(MemoryWidgetType::Graph, main) { setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); setAllowedAreas(Qt::AllDockWidgetAreas); auto *layoutWidget = new QWidget(this); setWidget(layoutWidget); auto *layout = new QVBoxLayout(layoutWidget); layout->setContentsMargins(0, 0, 0, 0); layoutWidget->setLayout(layout); header = new QLineEdit(this); header->setReadOnly(true); layout->addWidget(header); graphView = new DisassemblerGraphView(layoutWidget, seekable, main, { &syncAction }); layout->addWidget(graphView); // Title needs to get set after graphView is defined updateWindowTitle(); // getting the name of the class is implementation defined, and cannot be // used reliably across different compilers. // QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts[typeid(this).name()], main); QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["GraphWidget"], main); connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(graphView, &DisassemblerGraphView::nameChanged, this, &MemoryDockWidget::updateWindowTitle); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visibility) { main->toggleOverview(visibility, this); if (visibility) { graphView->onSeekChanged(Core()->getOffset()); } }); QAction *switchAction = new QAction(this); switchAction->setShortcut(Qt::Key_Space); switchAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); addAction(switchAction); connect(switchAction, &QAction::triggered, this, [this] { mainWindow->showMemoryWidget(MemoryWidgetType::Disassembly); }); connect(graphView, &DisassemblerGraphView::graphMoved, this, [=]() { main->toggleOverview(true, this); }); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &GraphWidget::prepareHeader); connect(Core(), &CutterCore::functionRenamed, this, &GraphWidget::prepareHeader); graphView->installEventFilter(this); } QWidget *GraphWidget::widgetToFocusOnRaise() { return graphView; } void GraphWidget::closeEvent(QCloseEvent *event) { CutterDockWidget::closeEvent(event); emit graphClosed(); } QString GraphWidget::getWindowTitle() const { return graphView->windowTitle; } DisassemblerGraphView *GraphWidget::getGraphView() const { return graphView; } QString GraphWidget::getWidgetType() { return "Graph"; } void GraphWidget::prepareHeader() { RzAnalysisFunction *f = Core()->functionIn(seekable->getOffset()); char *str = f ? rz_analysis_function_get_signature(f) : nullptr; if (!str) { header->hide(); return; } header->show(); header->setText(str); free(str); }
3,038
C++
.cpp
79
33.898734
95
0.724337
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,543
FunctionsWidget.cpp
rizinorg_cutter/src/widgets/FunctionsWidget.cpp
#include "FunctionsWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/DisassemblyPreview.h" #include "common/Helpers.h" #include "common/FunctionsTask.h" #include "common/TempConfig.h" #include "menus/AddressableItemContextMenu.h" #include <algorithm> #include <QMenu> #include <QDebug> #include <QString> #include <QResource> #include <QShortcut> #include <QJsonArray> #include <QJsonObject> #include <QInputDialog> #include <QActionGroup> #include <QBitmap> #include <QPainter> namespace { static const int kMaxTooltipWidth = 400; static const int kMaxTooltipDisasmPreviewLines = 10; static const int kMaxTooltipHighlightsLines = 5; } FunctionModel::FunctionModel(QList<FunctionDescription> *functions, QSet<RVA> *importAddresses, ut64 *mainAdress, bool nested, QFont default_font, QFont highlight_font, QObject *parent) : AddressableItemModel<>(parent), functions(functions), importAddresses(importAddresses), mainAdress(mainAdress), highlightFont(highlight_font), defaultFont(default_font), nested(nested), currentIndex(-1), iconFuncImpDark(":/img/icons/function_import_dark.svg"), iconFuncImpLight(":/img/icons/function_import_light.svg"), iconFuncMainDark(":/img/icons/function_main_dark.svg"), iconFuncMainLight(":/img/icons/function_main_light.svg"), iconFuncDark(":/img/icons/function_dark.svg"), iconFuncLight(":/img/icons/function_light.svg") { connect(Core(), &CutterCore::seekChanged, this, &FunctionModel::seekChanged); connect(Core(), &CutterCore::functionRenamed, this, &FunctionModel::functionRenamed); } QModelIndex FunctionModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid()) return createIndex(row, column, (quintptr)0); // root function nodes have id = 0 return createIndex(row, column, (quintptr)(parent.row() + 1)); // sub-nodes have id = function index + 1 } QModelIndex FunctionModel::parent(const QModelIndex &index) const { if (!index.isValid() || index.column() != 0) return QModelIndex(); if (index.internalId() == 0) // root function node return QModelIndex(); else // sub-node return this->index((int)(index.internalId() - 1), 0); } int FunctionModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) return functions->count(); if (nested) { if (parent.internalId() == 0) return ColumnCount - 1; // sub-nodes for nested functions return 0; } else return 0; } int FunctionModel::columnCount(const QModelIndex & /*parent*/) const { if (nested) return 1; else return ColumnCount; } bool FunctionModel::functionIsImport(ut64 addr) const { return importAddresses->contains(addr); } bool FunctionModel::functionIsMain(ut64 addr) const { return *mainAdress == addr; } QVariant FunctionModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); int function_index; bool subnode; bool is_dark; if (index.internalId() != 0) { // sub-node function_index = index.parent().row(); subnode = true; } else { // root function node function_index = index.row(); subnode = false; } const FunctionDescription &function = functions->at(function_index); if (function_index >= functions->count()) return QVariant(); switch (role) { case Qt::DisplayRole: if (nested) { if (subnode) { switch (index.row()) { case 0: return tr("Offset: %1").arg(RzAddressString(function.offset)); case 1: return tr("Size: %1").arg(RzSizeString(function.linearSize)); case 2: return tr("Import: %1") .arg(functionIsImport(function.offset) ? tr("true") : tr("false")); case 3: return tr("Nargs: %1").arg(RzSizeString(function.nargs)); case 4: return tr("Nbbs: %1").arg(RzSizeString(function.nbbs)); case 5: return tr("Nlocals: %1").arg(RzSizeString(function.nlocals)); case 6: return tr("Call type: %1").arg(function.calltype); case 7: return tr("Edges: %1").arg(function.edges); case 8: return tr("StackFrame: %1").arg(function.stackframe); case 9: return tr("Comment: %1").arg(Core()->getCommentAt(function.offset)); default: return QVariant(); } } else return function.name; } else { switch (index.column()) { case NameColumn: return function.name; case SizeColumn: return QString::number(function.linearSize); case ImportColumn: return functionIsImport(function.offset) ? tr("true") : tr("false"); case OffsetColumn: return RzAddressString(function.offset); case NargsColumn: return QString::number(function.nargs); case NlocalsColumn: return QString::number(function.nlocals); case NbbsColumn: return QString::number(function.nbbs); case CalltypeColumn: return function.calltype; case EdgesColumn: return QString::number(function.edges); case FrameColumn: return QString::number(function.stackframe); case CommentColumn: return Core()->getCommentAt(function.offset); default: return QVariant(); } } case Qt::DecorationRole: { // Check if we aren't inside a tree view if (nested && subnode) { return QVariant(); } if (index.column() == NameColumn) { is_dark = Config()->windowColorIsDark(); if (functionIsImport(function.offset)) { if (is_dark) { return iconFuncImpDark; } return iconFuncImpLight; } else if (functionIsMain(function.offset)) { if (is_dark) { return iconFuncMainDark; } return iconFuncMainLight; } if (is_dark) { return iconFuncDark; } return iconFuncLight; } return QVariant(); } case Qt::FontRole: if (currentIndex == function_index) return highlightFont; return defaultFont; case Qt::TextAlignmentRole: if (index.column() == 1) return static_cast<int>(Qt::AlignRight | Qt::AlignVCenter); return static_cast<int>(Qt::AlignLeft | Qt::AlignVCenter); case Qt::ToolTipRole: { QStringList disasmPreview = Core()->getDisassemblyPreview(function.offset, kMaxTooltipDisasmPreviewLines); QStringList summary {}; { auto seeker = Core()->seekTemp(function.offset); auto strings = fromOwnedCharPtr(rz_core_print_disasm_strings( Core()->core(), RZ_CORE_DISASM_STRINGS_MODE_FUNCTION, 0, NULL)); summary = strings.split('\n', CUTTER_QT_SKIP_EMPTY_PARTS); } const QFont &fnt = Config()->getFont(); QFontMetrics fm { fnt }; // elide long strings using current disasm font metrics QStringList highlights; for (const QString &s : summary) { highlights << fm.elidedText(s, Qt::ElideRight, kMaxTooltipWidth); if (highlights.length() > kMaxTooltipHighlightsLines) { highlights << "..."; break; } } if (disasmPreview.isEmpty() && highlights.isEmpty()) return {}; QString toolTipContent = QString("<html><div style=\"font-family: %1; font-size: %2pt; white-space: " "nowrap;\">") .arg(fnt.family()) .arg(qMax(6, fnt.pointSize() - 1)); // slightly decrease font size, to // keep more text in the same box if (!disasmPreview.isEmpty()) toolTipContent += tr("<div style=\"margin-bottom: 10px;\"><strong>Disassembly " "preview</strong>:<br>%1</div>") .arg(disasmPreview.join("<br>")); if (!highlights.isEmpty()) { toolTipContent += tr("<div><strong>Highlights</strong>:<br>%1</div>") .arg(highlights.join(QLatin1Char('\n')) .toHtmlEscaped() .replace(QLatin1Char('\n'), "<br>")); } toolTipContent += "</div></html>"; return toolTipContent; } case Qt::ForegroundRole: if (functionIsImport(function.offset)) { return QVariant(ConfigColor("gui.imports")); } else if (functionIsMain(function.offset)) { return QVariant(ConfigColor("gui.main")); } else if (function.name.startsWith("flirt.")) { return QVariant(ConfigColor("gui.flirt")); } return QVariant(this->property("color")); case FunctionDescriptionRole: return QVariant::fromValue(function); case IsImportRole: return importAddresses->contains(function.offset); default: return {}; } } QVariant FunctionModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { if (nested) { return tr("Name"); } else { switch (section) { case NameColumn: return tr("Name"); case SizeColumn: return tr("Size"); case ImportColumn: return tr("Import"); case OffsetColumn: return tr("Offset"); case NargsColumn: return tr("Nargs"); case NlocalsColumn: return tr("Nlocals"); case NbbsColumn: return tr("Nbbs"); case CalltypeColumn: return tr("Call type"); case EdgesColumn: return tr("Edges"); case FrameColumn: return tr("StackFrame"); case CommentColumn: return tr("Comment"); default: return QVariant(); } } } return QVariant(); } void FunctionModel::setNested(bool nested) { beginResetModel(); this->nested = nested; updateCurrentIndex(); endResetModel(); } RVA FunctionModel::address(const QModelIndex &index) const { auto function = data(index, FunctionDescriptionRole).value<FunctionDescription>(); return function.offset; } QString FunctionModel::name(const QModelIndex &index) const { auto function = data(index, FunctionDescriptionRole).value<FunctionDescription>(); return function.name; } void FunctionModel::seekChanged(RVA) { int previousIndex = currentIndex; if (updateCurrentIndex()) { if (previousIndex >= 0) { emit dataChanged(index(previousIndex, 0), index(previousIndex, columnCount() - 1)); } if (currentIndex >= 0) { emit dataChanged(index(currentIndex, 0), index(currentIndex, columnCount() - 1)); } } } bool FunctionModel::updateCurrentIndex() { int index = -1; RVA offset = 0; RVA seek = Core()->getOffset(); for (int i = 0; i < functions->count(); i++) { const FunctionDescription &function = functions->at(i); if (function.contains(seek) && function.offset >= offset) { offset = function.offset; index = i; } } bool changed = currentIndex != index; currentIndex = index; return changed; } void FunctionModel::functionRenamed(const RVA offset, const QString &new_name) { for (int i = 0; i < functions->count(); i++) { FunctionDescription &function = (*functions)[i]; if (function.offset == offset) { function.name = new_name; emit dataChanged(index(i, 0), index(i, columnCount() - 1)); } } } FunctionSortFilterProxyModel::FunctionSortFilterProxyModel(FunctionModel *source_model, QObject *parent) : AddressableFilterProxyModel(source_model, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool FunctionSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); FunctionDescription function = index.data(FunctionModel::FunctionDescriptionRole).value<FunctionDescription>(); return qhelpers::filterStringContains(function.name, this); } bool FunctionSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { if (!left.isValid() || !right.isValid()) return false; if (left.parent().isValid() || right.parent().isValid()) return false; FunctionDescription left_function = left.data(FunctionModel::FunctionDescriptionRole).value<FunctionDescription>(); FunctionDescription right_function = right.data(FunctionModel::FunctionDescriptionRole).value<FunctionDescription>(); if (static_cast<FunctionModel *>(sourceModel())->isNested()) { return left_function.name < right_function.name; } else { switch (left.column()) { case FunctionModel::OffsetColumn: return left_function.offset < right_function.offset; case FunctionModel::SizeColumn: if (left_function.linearSize != right_function.linearSize) return left_function.linearSize < right_function.linearSize; break; case FunctionModel::ImportColumn: { bool left_is_import = left.data(FunctionModel::IsImportRole).toBool(); bool right_is_import = right.data(FunctionModel::IsImportRole).toBool(); if (!left_is_import && right_is_import) return true; break; } case FunctionModel::NameColumn: return left_function.name < right_function.name; case FunctionModel::NargsColumn: if (left_function.nargs != right_function.nargs) return left_function.nargs < right_function.nargs; break; case FunctionModel::NlocalsColumn: if (left_function.nlocals != right_function.nlocals) return left_function.nlocals < right_function.nlocals; break; case FunctionModel::NbbsColumn: if (left_function.nbbs != right_function.nbbs) return left_function.nbbs < right_function.nbbs; break; case FunctionModel::CalltypeColumn: return left_function.calltype < right_function.calltype; case FunctionModel::EdgesColumn: if (left_function.edges != right_function.edges) return left_function.edges < right_function.edges; break; case FunctionModel::FrameColumn: if (left_function.stackframe != right_function.stackframe) return left_function.stackframe < right_function.stackframe; break; case FunctionModel::CommentColumn: return Core()->getCommentAt(left_function.offset) < Core()->getCommentAt(right_function.offset); default: return false; } return left_function.offset < right_function.offset; } } FunctionsWidget::FunctionsWidget(MainWindow *main) : ListDockWidget(main), actionRename(tr("Rename"), this), actionUndefine(tr("Undefine"), this), actionHorizontal(tr("Horizontal"), this), actionVertical(tr("Vertical"), this) { setWindowTitle(tr("Functions")); setObjectName("FunctionsWidget"); setTooltipStylesheet(); connect(Config(), &Configuration::colorsUpdated, this, &FunctionsWidget::setTooltipStylesheet); QFontInfo font_info = ui->treeView->fontInfo(); QFont default_font = QFont(font_info.family(), font_info.pointSize()); QFont highlight_font = QFont(font_info.family(), font_info.pointSize(), QFont::Bold); functionModel = new FunctionModel(&functions, &importAddresses, &mainAdress, false, default_font, highlight_font, this); functionProxyModel = new FunctionSortFilterProxyModel(functionModel, this); setModels(functionProxyModel); ui->treeView->sortByColumn(FunctionModel::NameColumn, Qt::AscendingOrder); ui->treeView->setExpandsOnDoubleClick(false); titleContextMenu = new QMenu(this); auto viewTypeGroup = new QActionGroup(titleContextMenu); actionHorizontal.setCheckable(true); actionHorizontal.setActionGroup(viewTypeGroup); connect(&actionHorizontal, &QAction::toggled, this, &FunctionsWidget::onActionHorizontalToggled); actionVertical.setCheckable(true); actionVertical.setActionGroup(viewTypeGroup); connect(&actionVertical, &QAction::toggled, this, &FunctionsWidget::onActionVerticalToggled); titleContextMenu->addActions(viewTypeGroup->actions()); actionRename.setShortcut({ Qt::Key_N }); actionRename.setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); connect(&actionRename, &QAction::triggered, this, &FunctionsWidget::onActionFunctionsRenameTriggered); connect(&actionUndefine, &QAction::triggered, this, &FunctionsWidget::onActionFunctionsUndefineTriggered); auto itemConextMenu = ui->treeView->getItemContextMenu(); itemConextMenu->addSeparator(); itemConextMenu->addAction(&actionRename); itemConextMenu->addAction(&actionUndefine); itemConextMenu->setWholeFunction(true); ui->treeView->addActions(itemConextMenu->actions()); // Use a custom context menu on the dock title bar if (Config()->getFunctionsWidgetLayout() == "horizontal") { actionHorizontal.setChecked(true); } else { actionVertical.setChecked(true); } this->setContextMenuPolicy(Qt::CustomContextMenu); connect(this, &QWidget::customContextMenuRequested, this, &FunctionsWidget::showTitleContextMenu); connect(Core(), &CutterCore::functionsChanged, this, &FunctionsWidget::refreshTree); connect(Core(), &CutterCore::codeRebased, this, &FunctionsWidget::refreshTree); connect(Core(), &CutterCore::refreshAll, this, &FunctionsWidget::refreshTree); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(functionModel, FunctionModel::CommentColumn); }); } FunctionsWidget::~FunctionsWidget() {} void FunctionsWidget::refreshTree() { if (task) { task->wait(); } task = QSharedPointer<FunctionsTask>(new FunctionsTask()); connect(task.data(), &FunctionsTask::fetchFinished, this, [this](const QList<FunctionDescription> &functions) { functionModel->beginResetModel(); this->functions = functions; importAddresses.clear(); for (const ImportDescription &import : Core()->getAllImports()) { importAddresses.insert(import.plt); } mainAdress = RVA_INVALID; RzCoreLocked core(Core()); RzBinFile *bf = rz_bin_cur(core->bin); if (bf) { const RzBinAddr *binmain = rz_bin_object_get_special_symbol(bf->o, RZ_BIN_SPECIAL_SYMBOL_MAIN); if (binmain) { int va = core->io->va || core->bin->is_debugger; mainAdress = va ? rz_bin_object_addr_with_base(bf->o, binmain->vaddr) : binmain->paddr; } } functionModel->updateCurrentIndex(); functionModel->endResetModel(); // resize offset and size columns qhelpers::adjustColumns(ui->treeView, 3, 0); }); Core()->getAsyncTaskManager()->start(task); } void FunctionsWidget::changeSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver) { ui->dockWidgetContents->setSizePolicy(hor, ver); } void FunctionsWidget::onActionFunctionsRenameTriggered() { // Get selected item in functions tree view FunctionDescription function = ui->treeView->selectionModel() ->currentIndex() .data(FunctionModel::FunctionDescriptionRole) .value<FunctionDescription>(); bool ok; // Create dialog QString newName = QInputDialog::getText(this, tr("Rename function %1").arg(function.name), tr("Function name:"), QLineEdit::Normal, function.name, &ok); // If user accepted if (ok && !newName.isEmpty()) { // Rename function in rizin core Core()->renameFunction(function.offset, newName); // Seek to new renamed function Core()->seekAndShow(function.offset); } } void FunctionsWidget::onActionFunctionsUndefineTriggered() { const auto selection = ui->treeView->selectionModel()->selection().indexes(); QSet<RVA> offsets; for (const auto &index : selection) { offsets.insert(functionProxyModel->address(index)); } for (RVA offset : offsets) { Core()->delFunction(offset); } } void FunctionsWidget::showTitleContextMenu(const QPoint &pt) { titleContextMenu->exec(this->mapToGlobal(pt)); } void FunctionsWidget::onActionHorizontalToggled(bool enable) { if (enable) { Config()->setFunctionsWidgetLayout("horizontal"); functionModel->setNested(false); ui->treeView->setIndentation(8); } } void FunctionsWidget::onActionVerticalToggled(bool enable) { if (enable) { Config()->setFunctionsWidgetLayout("vertical"); functionModel->setNested(true); ui->treeView->setIndentation(20); } } /** * @brief a SLOT to set the stylesheet for a tooltip */ void FunctionsWidget::setTooltipStylesheet() { setStyleSheet(DisassemblyPreview::getToolTipStyleSheet()); }
23,034
C++
.cpp
574
30.41115
100
0.613466
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,544
RizinGraphWidget.cpp
rizinorg_cutter/src/widgets/RizinGraphWidget.cpp
#include "RizinGraphWidget.h" #include "ui_RizinGraphWidget.h" #include <QJsonValue> #include <QJsonArray> #include <QJsonObject> RizinGraphWidget::RizinGraphWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::RizinGraphWidget), graphView(new GenericRizinGraphView(this, main)) { ui->setupUi(this); ui->verticalLayout->addWidget(graphView); connect(ui->refreshButton, &QPushButton::pressed, this, [this]() { graphView->refreshView(); }); struct GraphType { QChar commandChar; QString label; } types[] = { { 'a', tr("Data reference graph (aga)") }, { 'A', tr("Global data references graph (agA)") }, // {'c', tr("c - Function callgraph")}, // {'C', tr("C - Global callgraph")}, // {'f', tr("f - Basic blocks function graph")}, { 'i', tr("Imports graph (agi)") }, { 'r', tr("References graph (agr)") }, { 'R', tr("Global references graph (agR)") }, { 'x', tr("Cross references graph (agx)") }, { 'I', tr("RzIL statement graph (agI)") }, { 'g', tr("Custom graph (agg)") }, { ' ', tr("User command") }, }; for (auto &graphType : types) { if (graphType.commandChar != ' ') { ui->graphType->addItem(graphType.label, graphType.commandChar); } else { ui->graphType->addItem(graphType.label, QVariant()); } } connect<void (QComboBox::*)(int)>(ui->graphType, &QComboBox::currentIndexChanged, this, &RizinGraphWidget::typeChanged); connect(ui->customCommand, &QLineEdit::textEdited, this, [this]() { graphView->setGraphCommand(ui->customCommand->text()); }); connect(ui->customCommand, &QLineEdit::returnPressed, this, [this]() { graphView->setGraphCommand(ui->customCommand->text()); graphView->refreshView(); }); ui->customCommand->hide(); typeChanged(); } RizinGraphWidget::~RizinGraphWidget() {} void RizinGraphWidget::typeChanged() { auto currentData = ui->graphType->currentData(); if (currentData.isNull()) { ui->customCommand->setVisible(true); graphView->setGraphCommand(ui->customCommand->text()); ui->customCommand->setFocus(); } else { ui->customCommand->setVisible(false); auto command = QString("ag%1").arg(currentData.toChar()); graphView->setGraphCommand(command); graphView->refreshView(); } } GenericRizinGraphView::GenericRizinGraphView(RizinGraphWidget *parent, MainWindow *main) : SimpleTextGraphView(parent, main), refreshDeferrer(nullptr, this) { refreshDeferrer.registerFor(parent); connect(&refreshDeferrer, &RefreshDeferrer::refreshNow, this, &GenericRizinGraphView::refreshView); } void GenericRizinGraphView::setGraphCommand(QString cmd) { graphCommand = cmd; } void GenericRizinGraphView::refreshView() { if (!refreshDeferrer.attemptRefresh(nullptr)) { return; } SimpleTextGraphView::refreshView(); } void GenericRizinGraphView::loadCurrentGraph() { blockContent.clear(); blocks.clear(); if (graphCommand.isEmpty()) { return; } CutterJson functionsDoc = Core()->cmdj(QString("%1 json").arg(graphCommand)); auto nodes = functionsDoc["nodes"]; for (CutterJson block : nodes) { uint64_t id = block["id"].toUt64(); QString content; QString title = block["title"].toString(); QString body = block["body"].toString(); if (!title.isEmpty() && !body.isEmpty()) { content = title + "/n" + body; } else { content = title + body; } auto edges = block["out_nodes"]; GraphLayout::GraphBlock layoutBlock; layoutBlock.entry = id; for (auto edge : edges) { auto targetId = edge.toUt64(); layoutBlock.edges.emplace_back(targetId); } addBlock(std::move(layoutBlock), content); } cleanupEdges(blocks); computeGraphPlacement(); if (graphCommand != lastShownCommand) { selectedBlock = NO_BLOCK_SELECTED; lastShownCommand = graphCommand; center(); } }
4,229
C++
.cpp
118
29.152542
100
0.626038
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,545
ThreadsWidget.cpp
rizinorg_cutter/src/widgets/ThreadsWidget.cpp
#include <QShortcut> #include "ThreadsWidget.h" #include "ui_ThreadsWidget.h" #include "common/JsonModel.h" #include "QuickFilterView.h" #include <rz_debug.h> #include "core/MainWindow.h" #define DEBUGGED_PID (-1) ThreadsWidget::ThreadsWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::ThreadsWidget) { ui->setupUi(this); // Setup threads model modelThreads = new QStandardItemModel(1, 3, this); modelThreads->setHorizontalHeaderItem(ThreadsWidget::COLUMN_PID, new QStandardItem(tr("PID"))); modelThreads->setHorizontalHeaderItem(ThreadsWidget::COLUMN_STATUS, new QStandardItem(tr("Status"))); modelThreads->setHorizontalHeaderItem(ThreadsWidget::COLUMN_PATH, new QStandardItem(tr("Path"))); ui->viewThreads->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); ui->viewThreads->verticalHeader()->setVisible(false); ui->viewThreads->setFont(Config()->getFont()); modelFilter = new ThreadsFilterModel(this); modelFilter->setSourceModel(modelThreads); ui->viewThreads->setModel(modelFilter); // CTRL+F switches to the filter view and opens it in case it's hidden QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // ESC switches back to the thread table and clears the buffer QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, this, [this]() { ui->quickFilterView->clearFilter(); ui->viewThreads->setFocus(); }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, modelFilter, &ThreadsFilterModel::setFilterWildcard); connect(Core(), &CutterCore::refreshAll, this, &ThreadsWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &ThreadsWidget::updateContents); connect(Core(), &CutterCore::debugTaskStateChanged, this, &ThreadsWidget::updateContents); // Seek doesn't necessarily change when switching threads/processes connect(Core(), &CutterCore::switchedThread, this, &ThreadsWidget::updateContents); connect(Core(), &CutterCore::switchedProcess, this, &ThreadsWidget::updateContents); connect(Config(), &Configuration::fontsUpdated, this, &ThreadsWidget::fontsUpdatedSlot); connect(ui->viewThreads, &QTableView::activated, this, &ThreadsWidget::onActivated); } ThreadsWidget::~ThreadsWidget() {} void ThreadsWidget::updateContents() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } if (!Core()->currentlyDebugging) { // Remove rows from the previous debugging session modelThreads->removeRows(0, modelThreads->rowCount()); return; } if (Core()->isDebugTaskInProgress()) { ui->viewThreads->setDisabled(true); } else { setThreadsGrid(); ui->viewThreads->setDisabled(false); } } QString ThreadsWidget::translateStatus(const char status) { switch (status) { case RZ_DBG_PROC_STOP: return "Stopped"; case RZ_DBG_PROC_RUN: return "Running"; case RZ_DBG_PROC_SLEEP: return "Sleeping"; case RZ_DBG_PROC_ZOMBIE: return "Zombie"; case RZ_DBG_PROC_DEAD: return "Dead"; case RZ_DBG_PROC_RAISED: return "Raised event"; default: return "Unknown status"; } } void ThreadsWidget::setThreadsGrid() { int i = 0; QFont font; for (const auto &threadsItem : Core()->getProcessThreads(DEBUGGED_PID)) { st64 pid = threadsItem.pid; QString status = translateStatus(threadsItem.status); QString path = threadsItem.path; bool current = threadsItem.current; // Use bold font to highlight active thread font.setBold(current); QStandardItem *rowPid = new QStandardItem(QString::number(pid)); rowPid->setFont(font); QStandardItem *rowStatus = new QStandardItem(status); rowStatus->setFont(font); QStandardItem *rowPath = new QStandardItem(path); rowPath->setFont(font); modelThreads->setItem(i, ThreadsWidget::COLUMN_PID, rowPid); modelThreads->setItem(i, ThreadsWidget::COLUMN_STATUS, rowStatus); modelThreads->setItem(i, ThreadsWidget::COLUMN_PATH, rowPath); i++; } // Remove irrelevant old rows if (modelThreads->rowCount() > i) { modelThreads->removeRows(i, modelThreads->rowCount() - i); } modelFilter->setSourceModel(modelThreads); ui->viewThreads->resizeColumnsToContents(); ; } void ThreadsWidget::fontsUpdatedSlot() { ui->viewThreads->setFont(Config()->getFont()); } void ThreadsWidget::onActivated(const QModelIndex &index) { if (!index.isValid()) return; int tid = modelFilter->data(index.sibling(index.row(), ThreadsWidget::COLUMN_PID)).toInt(); // Verify that the selected tid is still in the threads list since dpt= will // attach to any given id. If it isn't found simply update the UI. for (const auto &value : Core()->getProcessThreads(DEBUGGED_PID)) { if (tid == value.pid) { Core()->setCurrentDebugThread(tid); break; } } updateContents(); } ThreadsFilterModel::ThreadsFilterModel(QObject *parent) : QSortFilterProxyModel(parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool ThreadsFilterModel::filterAcceptsRow(int row, const QModelIndex &parent) const { // All columns are checked for a match for (int i = ThreadsWidget::COLUMN_PID; i <= ThreadsWidget::COLUMN_PATH; ++i) { QModelIndex index = sourceModel()->index(row, i, parent); if (qhelpers::filterStringContains(sourceModel()->data(index).toString(), this)) { return true; } } return false; }
6,229
C++
.cpp
150
35.42
99
0.695688
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,546
CutterGraphView.cpp
rizinorg_cutter/src/widgets/CutterGraphView.cpp
#include "CutterGraphView.h" #include "core/Cutter.h" #include "common/Configuration.h" #include "dialogs/MultitypeFileSaveDialog.h" #include "TempConfig.h" #include <cmath> #include <QStandardPaths> #include <QActionGroup> static const qhelpers::KeyComb KEY_ZOOM_IN = Qt::Key_Plus | Qt::ControlModifier; static const qhelpers::KeyComb KEY_ZOOM_IN2 = Qt::Key_Plus | (Qt::ControlModifier | Qt::ShiftModifier); static const qhelpers::KeyComb KEY_ZOOM_OUT = Qt::Key_Minus | Qt::ControlModifier; static const qhelpers::KeyComb KEY_ZOOM_RESET = Qt::Key_Equal | Qt::ControlModifier; static const uint64_t BITMPA_EXPORT_WARNING_SIZE = 32 * 1024 * 1024; #ifndef NDEBUG # define GRAPH_GRID_DEBUG_MODES true #else # define GRAPH_GRID_DEBUG_MODES false #endif CutterGraphView::CutterGraphView(QWidget *parent) : GraphView(parent), mFontMetrics(nullptr), actionExportGraph(tr("Export Graph"), this), graphLayout(GraphView::Layout::GridMedium) { connect(Core(), &CutterCore::graphOptionsChanged, this, &CutterGraphView::refreshView); connect(Config(), &Configuration::colorsUpdated, this, &CutterGraphView::colorsUpdatedSlot); connect(Config(), &Configuration::fontsUpdated, this, &CutterGraphView::fontsUpdatedSlot); initFont(); updateColors(); connect(&actionExportGraph, &QAction::triggered, this, &CutterGraphView::showExportDialog); layoutMenu = new QMenu(tr("Layout"), this); horizontalLayoutAction = layoutMenu->addAction(tr("Horizontal")); horizontalLayoutAction->setCheckable(true); static const std::pair<QString, GraphView::Layout> LAYOUT_CONFIG[] = { { tr("Grid narrow"), GraphView::Layout::GridNarrow }, { tr("Grid medium"), GraphView::Layout::GridMedium }, { tr("Grid wide"), GraphView::Layout::GridWide } #if GRAPH_GRID_DEBUG_MODES , { "GridAAA", GraphView::Layout::GridAAA }, { "GridAAB", GraphView::Layout::GridAAB }, { "GridABA", GraphView::Layout::GridABA }, { "GridABB", GraphView::Layout::GridABB }, { "GridBAA", GraphView::Layout::GridBAA }, { "GridBAB", GraphView::Layout::GridBAB }, { "GridBBA", GraphView::Layout::GridBBA }, { "GridBBB", GraphView::Layout::GridBBB } #endif #ifdef CUTTER_ENABLE_GRAPHVIZ , { tr("Graphviz polyline"), GraphView::Layout::GraphvizPolyline }, { tr("Graphviz ortho"), GraphView::Layout::GraphvizOrtho }, { tr("Graphviz sfdp"), GraphView::Layout::GraphvizSfdp }, { tr("Graphviz neato"), GraphView::Layout::GraphvizNeato }, { tr("Graphviz twopi"), GraphView::Layout::GraphvizTwoPi }, { tr("Graphviz circo"), GraphView::Layout::GraphvizCirco } #endif }; layoutMenu->addSeparator(); connect(horizontalLayoutAction, &QAction::toggled, this, &CutterGraphView::updateLayout); QActionGroup *layoutGroup = new QActionGroup(layoutMenu); for (auto &item : LAYOUT_CONFIG) { auto action = layoutGroup->addAction(item.first); action->setCheckable(true); GraphView::Layout layout = item.second; if (layout == this->graphLayout) { action->setChecked(true); } connect(action, &QAction::triggered, this, [this, layout]() { this->graphLayout = layout; updateLayout(); }); } layoutMenu->addActions(layoutGroup->actions()); grabGesture(Qt::PinchGesture); } QPoint CutterGraphView::getTextOffset(int line) const { return QPoint(padding, padding + line * charHeight); } void CutterGraphView::initFont() { setFont(Config()->getFont()); QFontMetricsF metrics(font()); baseline = int(metrics.ascent()); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) ACharWidth = metrics.width('A'); #else ACharWidth = metrics.horizontalAdvance('A'); #endif padding = ACharWidth; charHeight = static_cast<int>(metrics.height()); charOffset = 0; mFontMetrics.reset(new CachedFontMetrics<qreal>(font())); } void CutterGraphView::zoom(QPointF mouseRelativePos, double velocity) { qreal newScale = getViewScale() * std::pow(1.25, velocity); setZoom(mouseRelativePos, newScale); } void CutterGraphView::setZoom(QPointF mouseRelativePos, double scale) { mouseRelativePos.rx() *= size().width(); mouseRelativePos.ry() *= size().height(); mouseRelativePos /= getViewScale(); auto globalMouse = mouseRelativePos + getViewOffset(); mouseRelativePos *= getViewScale(); qreal newScale = scale; newScale = std::max(newScale, 0.05); mouseRelativePos /= newScale; setViewScale(newScale); // Adjusting offset, so that zooming will be approaching to the cursor. setViewOffset(globalMouse.toPoint() - mouseRelativePos.toPoint()); viewport()->update(); emit viewZoomed(); } void CutterGraphView::zoomIn() { zoom(QPointF(0.5, 0.5), 1); } void CutterGraphView::zoomOut() { zoom(QPointF(0.5, 0.5), -1); } void CutterGraphView::zoomReset() { setZoom(QPointF(0.5, 0.5), 1); } void CutterGraphView::showExportDialog() { showExportGraphDialog("global_funcall", RZ_CORE_GRAPH_TYPE_FUNCALL, RVA_INVALID); } void CutterGraphView::updateColors() { disassemblyBackgroundColor = ConfigColor("gui.alt_background"); disassemblySelectedBackgroundColor = ConfigColor("gui.disass_selected"); mDisabledBreakpointColor = disassemblyBackgroundColor; graphNodeColor = ConfigColor("gui.border"); backgroundColor = ConfigColor("gui.background"); disassemblySelectionColor = ConfigColor("lineHighlight"); PCSelectionColor = ConfigColor("highlightPC"); jmpColor = ConfigColor("graph.trufae"); brtrueColor = ConfigColor("graph.true"); brfalseColor = ConfigColor("graph.false"); mCommentColor = ConfigColor("comment"); } void CutterGraphView::colorsUpdatedSlot() { updateColors(); refreshView(); } GraphLayout::LayoutConfig CutterGraphView::getLayoutConfig() { auto blockSpacing = Config()->getGraphBlockSpacing(); auto edgeSpacing = Config()->getGraphEdgeSpacing(); GraphLayout::LayoutConfig layoutConfig; layoutConfig.blockHorizontalSpacing = blockSpacing.x(); layoutConfig.blockVerticalSpacing = blockSpacing.y(); layoutConfig.edgeHorizontalSpacing = edgeSpacing.x(); layoutConfig.edgeVerticalSpacing = edgeSpacing.y(); return layoutConfig; } void CutterGraphView::updateLayout() { setGraphLayout(GraphView::makeGraphLayout(graphLayout, horizontalLayoutAction->isChecked())); saveCurrentBlock(); setLayoutConfig(getLayoutConfig()); computeGraphPlacement(); restoreCurrentBlock(); emit viewRefreshed(); } void CutterGraphView::fontsUpdatedSlot() { initFont(); refreshView(); } bool CutterGraphView::event(QEvent *event) { switch (event->type()) { case QEvent::ShortcutOverride: { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); qhelpers::KeyComb key = Qt::Key(keyEvent->key()) | keyEvent->modifiers(); if (key == KEY_ZOOM_OUT || key == KEY_ZOOM_RESET || key == KEY_ZOOM_IN || key == KEY_ZOOM_IN2) { event->accept(); return true; } break; } case QEvent::KeyPress: { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); qhelpers::KeyComb key = Qt::Key(keyEvent->key()) | keyEvent->modifiers(); if (key == KEY_ZOOM_IN || key == KEY_ZOOM_IN2) { zoomIn(); return true; } else if (key == KEY_ZOOM_OUT) { zoomOut(); return true; } else if (key == KEY_ZOOM_RESET) { zoomReset(); return true; } break; } default: break; } return GraphView::event(event); } void CutterGraphView::refreshView() { initFont(); setLayoutConfig(getLayoutConfig()); } bool CutterGraphView::gestureEvent(QGestureEvent *event) { if (!event) { return false; } if (auto gesture = static_cast<QPinchGesture *>(event->gesture(Qt::PinchGesture))) { auto changeFlags = gesture->changeFlags(); if (changeFlags & QPinchGesture::ScaleFactorChanged) { auto cursorPos = gesture->centerPoint(); cursorPos.rx() /= size().width(); cursorPos.ry() /= size().height(); setZoom(cursorPos, getViewScale() * gesture->scaleFactor()); } event->accept(gesture); return true; } return false; } void CutterGraphView::wheelEvent(QWheelEvent *event) { // when CTRL is pressed, we zoom in/out with mouse wheel if (Qt::ControlModifier == event->modifiers()) { const QPoint numDegrees = event->angleDelta() / 8; if (!numDegrees.isNull()) { int numSteps = numDegrees.y() / 15; #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) QPointF relativeMousePos = event->pos(); #else QPointF relativeMousePos = event->position(); #endif relativeMousePos.rx() /= size().width(); relativeMousePos.ry() /= size().height(); zoom(relativeMousePos, numSteps); } event->accept(); } else { // use mouse wheel for scrolling when CTRL is not pressed GraphView::wheelEvent(event); } emit graphMoved(); } void CutterGraphView::resizeEvent(QResizeEvent *event) { GraphView::resizeEvent(event); emit resized(); } void CutterGraphView::saveCurrentBlock() {} void CutterGraphView::restoreCurrentBlock() {} void CutterGraphView::mousePressEvent(QMouseEvent *event) { GraphView::mousePressEvent(event); emit graphMoved(); } void CutterGraphView::mouseMoveEvent(QMouseEvent *event) { GraphView::mouseMoveEvent(event); emit graphMoved(); } void CutterGraphView::exportGraph(QString filePath, GraphExportType exportType, RzCoreGraphType graphType, RVA address) { bool graphTransparent = Config()->getBitmapTransparentState(); double graphScaleFactor = Config()->getBitmapExportScaleFactor(); switch (exportType) { case GraphExportType::Png: this->saveAsBitmap(filePath, "png", graphScaleFactor, graphTransparent); break; case GraphExportType::Jpeg: this->saveAsBitmap(filePath, "jpg", graphScaleFactor, false); break; case GraphExportType::Svg: this->saveAsSvg(filePath); break; case GraphExportType::GVDot: exportRzTextGraph(filePath, graphType, RZ_CORE_GRAPH_FORMAT_DOT, address); break; case GraphExportType::RzJson: exportRzTextGraph(filePath, graphType, RZ_CORE_GRAPH_FORMAT_JSON, address); break; case GraphExportType::RzGml: exportRzTextGraph(filePath, graphType, RZ_CORE_GRAPH_FORMAT_GML, address); break; case GraphExportType::GVJson: Core()->writeGraphvizGraphToFile(filePath, "json", graphType, address); break; case GraphExportType::GVGif: Core()->writeGraphvizGraphToFile(filePath, "gif", graphType, address); break; case GraphExportType::GVPng: Core()->writeGraphvizGraphToFile(filePath, "png", graphType, address); break; case GraphExportType::GVJpeg: Core()->writeGraphvizGraphToFile(filePath, "jpg", graphType, address); break; case GraphExportType::GVPostScript: Core()->writeGraphvizGraphToFile(filePath, "ps", graphType, address); break; case GraphExportType::GVSvg: Core()->writeGraphvizGraphToFile(filePath, "svg", graphType, address); break; case GraphExportType::GVPdf: Core()->writeGraphvizGraphToFile(filePath, "pdf", graphType, address); break; } } void CutterGraphView::exportRzTextGraph(QString filePath, RzCoreGraphType type, RzCoreGraphFormat format, RVA address) { char *string = Core()->getTextualGraphAt(type, format, address); if (!string) { return; } QFile file(filePath); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream fileOut(&file); fileOut << string; } else { qWarning() << "Can't open or create file: " << filePath; } free(string); } bool CutterGraphView::graphIsBitamp(CutterGraphView::GraphExportType type) { switch (type) { case GraphExportType::Png: case GraphExportType::Jpeg: case GraphExportType::GVGif: case GraphExportType::GVPng: case GraphExportType::GVJpeg: return true; default: return false; } } Q_DECLARE_METATYPE(CutterGraphView::GraphExportType); void CutterGraphView::showExportGraphDialog(QString defaultName, RzCoreGraphType type, RVA address) { qWarning() << defaultName << " - " << type << " addr " << RzAddressString(address); QVector<MultitypeFileSaveDialog::TypeDescription> types = { { tr("PNG (*.png)"), "png", QVariant::fromValue(GraphExportType::Png) }, { tr("JPEG (*.jpg)"), "jpg", QVariant::fromValue(GraphExportType::Jpeg) }, { tr("SVG (*.svg)"), "svg", QVariant::fromValue(GraphExportType::Svg) } }; types.append({ { tr("Graphviz dot (*.dot)"), "dot", QVariant::fromValue(GraphExportType::GVDot) }, { tr("Graph Modelling Language (*.gml)"), "gml", QVariant::fromValue(GraphExportType::RzGml) }, { tr("RZ JSON (*.json)"), "json", QVariant::fromValue(GraphExportType::RzJson) }, }); bool hasGraphviz = !QStandardPaths::findExecutable("dot").isEmpty() || !QStandardPaths::findExecutable("xdot").isEmpty(); if (hasGraphviz) { types.append({ { tr("Graphviz json (*.json)"), "json", QVariant::fromValue(GraphExportType::GVJson) }, { tr("Graphviz gif (*.gif)"), "gif", QVariant::fromValue(GraphExportType::GVGif) }, { tr("Graphviz png (*.png)"), "png", QVariant::fromValue(GraphExportType::GVPng) }, { tr("Graphviz jpg (*.jpg)"), "jpg", QVariant::fromValue(GraphExportType::GVJpeg) }, { tr("Graphviz PostScript (*.ps)"), "ps", QVariant::fromValue(GraphExportType::GVPostScript) }, { tr("Graphviz svg (*.svg)"), "svg", QVariant::fromValue(GraphExportType::GVSvg) }, { tr("Graphviz pdf (*.pdf)"), "pdf", QVariant::fromValue(GraphExportType::GVPdf) } }); } MultitypeFileSaveDialog dialog(this, tr("Export Graph")); dialog.setTypes(types); dialog.selectFile(defaultName); if (!dialog.exec()) { return; } auto selectedType = dialog.selectedType(); if (!selectedType.data.canConvert<GraphExportType>()) { qWarning() << "Bad selected type, should not happen."; return; } auto exportType = selectedType.data.value<GraphExportType>(); if (graphIsBitamp(exportType)) { uint64_t bitmapSize = uint64_t(width) * uint64_t(height); if (bitmapSize > BITMPA_EXPORT_WARNING_SIZE) { auto answer = QMessageBox::question(this, tr("Graph Export"), tr("Do you really want to export %1 x %2 = %3 pixel " "bitmap image? Consider using different format.") .arg(width) .arg(height) .arg(bitmapSize)); if (answer != QMessageBox::Yes) { return; } } } QString filePath = dialog.selectedFiles().first(); exportGraph(filePath, exportType, type, address); }
15,855
C++
.cpp
412
31.463592
99
0.650393
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,547
GraphView.cpp
rizinorg_cutter/src/widgets/GraphView.cpp
#include "GraphView.h" #include "GraphGridLayout.h" #ifdef CUTTER_ENABLE_GRAPHVIZ # include "GraphvizLayout.h" #endif #include "GraphHorizontalAdapter.h" #include "Helpers.h" #include <vector> #include <QPainter> #include <QMouseEvent> #include <QKeyEvent> #include <QPropertyAnimation> #include <QSvgGenerator> #ifndef CUTTER_NO_OPENGL_GRAPH # include <QOpenGLContext> # include <QOpenGLWidget> # include <QOpenGLPaintDevice> # include <QOpenGLExtraFunctions> #endif GraphView::GraphView(QWidget *parent) : QAbstractScrollArea(parent), useGL(false) #ifndef CUTTER_NO_OPENGL_GRAPH , cacheTexture(0), cacheFBO(0) #endif { #ifndef CUTTER_NO_OPENGL_GRAPH if (useGL) { glWidget = new QOpenGLWidget(this); setViewport(glWidget); } else { glWidget = nullptr; } #endif setGraphLayout(makeGraphLayout(Layout::GridMedium)); } GraphView::~GraphView() {} // Callbacks void GraphView::blockClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) { Q_UNUSED(block); Q_UNUSED(event); Q_UNUSED(pos); } void GraphView::blockDoubleClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) { Q_UNUSED(block); Q_UNUSED(event); Q_UNUSED(pos); } void GraphView::blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, QPoint pos) { Q_UNUSED(block); Q_UNUSED(event); Q_UNUSED(pos); } bool GraphView::helpEvent(QHelpEvent *event) { auto p = viewToLogicalCoordinates(event->pos()); if (auto block = getBlockContaining(p)) { blockHelpEvent(*block, event, p - QPoint(block->x, block->y)); return true; } return false; } void GraphView::blockTransitionedTo(GraphView::GraphBlock *to) { Q_UNUSED(to); } GraphView::EdgeConfiguration GraphView::edgeConfiguration(GraphView::GraphBlock &from, GraphView::GraphBlock *to, bool interactive) { Q_UNUSED(from) Q_UNUSED(to) Q_UNUSED(interactive) qWarning() << "Edge configuration not overridden!"; EdgeConfiguration ec; return ec; } void GraphView::blockContextMenuRequested(GraphView::GraphBlock &, QContextMenuEvent *, QPoint) {} bool GraphView::event(QEvent *event) { if (event->type() == QEvent::ToolTip) { if (helpEvent(static_cast<QHelpEvent *>(event))) { return true; } } else if (event->type() == QEvent::Gesture) { if (gestureEvent(static_cast<QGestureEvent *>(event))) { return true; } } return QAbstractScrollArea::event(event); } bool GraphView::gestureEvent(QGestureEvent *event) { Q_UNUSED(event) return false; } void GraphView::contextMenuEvent(QContextMenuEvent *event) { event->ignore(); if (event->reason() == QContextMenuEvent::Mouse) { QPoint p = viewToLogicalCoordinates(event->pos()); if (auto block = getBlockContaining(p)) { blockContextMenuRequested(*block, event, p); } } } void GraphView::computeGraphPlacement() { graphLayoutSystem->CalculateLayout(blocks, entry, width, height); setCacheDirty(); clampViewOffset(); viewport()->update(); } void GraphView::cleanupEdges(GraphLayout::Graph &graph) { for (auto &blockIt : graph) { auto &block = blockIt.second; auto outIt = block.edges.begin(); std::unordered_set<ut64> seenEdges; for (auto it = block.edges.begin(), end = block.edges.end(); it != end; ++it) { // remove edges going to different functions // and remove duplicate edges, common in switch statements if (graph.find(it->target) != graph.end() && seenEdges.find(it->target) == seenEdges.end()) { *outIt++ = *it; seenEdges.insert(it->target); } } block.edges.erase(outIt, block.edges.end()); } } void GraphView::beginMouseDrag(QMouseEvent *event) { scrollBase = event->pos(); scroll_mode = true; setCursor(Qt::ClosedHandCursor); } void GraphView::setViewOffset(QPoint offset) { setViewOffsetInternal(offset); } void GraphView::setViewScale(qreal scale) { this->current_scale = scale; emit viewScaleChanged(scale); } QSize GraphView::getCacheSize() { return #ifndef CUTTER_NO_OPENGL_GRAPH useGL ? cacheSize : #endif pixmap.size(); } qreal GraphView::getCacheDevicePixelRatioF() { return #ifndef CUTTER_NO_OPENGL_GRAPH useGL ? 1.0 : #endif qhelpers::devicePixelRatio(&pixmap); } QSize GraphView::getRequiredCacheSize() { return viewport()->size() * qhelpers::devicePixelRatio(this); } qreal GraphView::getRequiredCacheDevicePixelRatioF() { return #ifndef CUTTER_NO_OPENGL_GRAPH useGL ? 1.0f : #endif qhelpers::devicePixelRatio(this); } void GraphView::paintEvent(QPaintEvent *) { #ifndef CUTTER_NO_OPENGL_GRAPH if (useGL) { glWidget->makeCurrent(); } #endif if (!qFuzzyCompare(getCacheDevicePixelRatioF(), getRequiredCacheDevicePixelRatioF()) || getCacheSize() != getRequiredCacheSize()) { setCacheDirty(); } if (cacheDirty) { paintGraphCache(); cacheDirty = false; } if (useGL) { #ifndef CUTTER_NO_OPENGL_GRAPH auto gl = glWidget->context()->extraFunctions(); gl->glBindFramebuffer(GL_READ_FRAMEBUFFER, cacheFBO); gl->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glWidget->defaultFramebufferObject()); auto dpr = qhelpers::devicePixelRatio(this); gl->glBlitFramebuffer(0, 0, cacheSize.width(), cacheSize.height(), 0, 0, viewport()->width() * dpr, viewport()->height() * dpr, GL_COLOR_BUFFER_BIT, GL_NEAREST); glWidget->doneCurrent(); #endif } else { QPainter p(viewport()); p.drawPixmap(QPoint(0, 0), pixmap); } } void GraphView::clampViewOffset() { const qreal edgeFraction = 0.25; qreal edgeX = edgeFraction * (viewport()->width() / current_scale); qreal edgeY = edgeFraction * (viewport()->height() / current_scale); offset.rx() = std::max(std::min(qreal(offset.x()), width - edgeX), -viewport()->width() / current_scale + edgeX); offset.ry() = std::max(std::min(qreal(offset.y()), height - edgeY), -viewport()->height() / current_scale + edgeY); } void GraphView::setViewOffsetInternal(QPoint pos, bool emitSignal) { offset = pos; clampViewOffset(); if (emitSignal) emit viewOffsetChanged(offset); } void GraphView::addViewOffset(QPoint move, bool emitSignal) { setViewOffsetInternal(offset + move, emitSignal); } void GraphView::paintGraphCache() { #ifndef CUTTER_NO_OPENGL_GRAPH std::unique_ptr<QOpenGLPaintDevice> paintDevice; #endif QPainter p; if (useGL) { #ifndef CUTTER_NO_OPENGL_GRAPH auto gl = QOpenGLContext::currentContext()->functions(); bool resizeTex = false; QSize sizeNeed = getRequiredCacheSize(); if (!cacheTexture) { gl->glGenTextures(1, &cacheTexture); gl->glBindTexture(GL_TEXTURE_2D, cacheTexture); gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); resizeTex = true; } else if (cacheSize != sizeNeed) { gl->glBindTexture(GL_TEXTURE_2D, cacheTexture); resizeTex = true; } if (resizeTex) { cacheSize = sizeNeed; gl->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cacheSize.width(), cacheSize.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); gl->glGenFramebuffers(1, &cacheFBO); gl->glBindFramebuffer(GL_FRAMEBUFFER, cacheFBO); gl->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cacheTexture, 0); } else { gl->glBindFramebuffer(GL_FRAMEBUFFER, cacheFBO); } gl->glViewport(0, 0, viewport()->width(), viewport()->height()); gl->glClearColor(backgroundColor.redF(), backgroundColor.greenF(), backgroundColor.blueF(), 1.0f); gl->glClear(GL_COLOR_BUFFER_BIT); paintDevice.reset(new QOpenGLPaintDevice(cacheSize)); p.begin(paintDevice.get()); #endif } else { auto dpr = qhelpers::devicePixelRatio(this); pixmap = QPixmap(getRequiredCacheSize() * dpr); pixmap.setDevicePixelRatio(dpr); pixmap.fill(backgroundColor); p.begin(&pixmap); p.setRenderHint(QPainter::Antialiasing); p.setViewport(this->viewport()->rect()); } paint(p, offset, this->viewport()->rect(), current_scale); p.end(); } void GraphView::paint(QPainter &p, QPoint offset, QRect viewport, qreal scale, bool interactive) { QPointF offsetF(offset.x(), offset.y()); p.setBrush(Qt::black); int render_width = viewport.width(); int render_height = viewport.height(); // window - rectangle in logical coordinates QRect window = QRect(offset, QSize(qRound(render_width / scale), qRound(render_height / scale))); p.setWindow(window); QRectF windowF(window.x(), window.y(), window.width(), window.height()); for (auto &blockIt : blocks) { GraphBlock &block = blockIt.second; QRectF blockRect(block.x, block.y, block.width, block.height); // Check if block is visible by checking if block intersects with view area if (blockRect.intersects(windowF)) { drawBlock(p, block, interactive); } p.setBrush(Qt::gray); // Always draw edges // TODO: Only draw edges if they are actually visible ... // Draw edges for (GraphEdge &edge : block.edges) { if (edge.polyline.empty()) { continue; } QPolygonF polyline = edge.polyline; EdgeConfiguration ec = edgeConfiguration(block, &blocks[edge.target], interactive); QPen pen(ec.color); pen.setStyle(ec.lineStyle); pen.setWidthF(pen.width() * ec.width_scale); if (scale_thickness_multiplier && ec.width_scale > 1.01 && pen.widthF() * scale < 2) { pen.setWidthF(ec.width_scale / scale); } if (pen.widthF() * scale < 2) { pen.setWidth(0); } p.setPen(pen); p.setBrush(ec.color); p.drawPolyline(polyline); pen.setStyle(Qt::SolidLine); p.setPen(pen); auto drawArrow = [&](QPointF tip, QPointF dir) { pen.setWidth(0); p.setPen(pen); QPolygonF arrow; arrow << tip; QPointF dy(-dir.y(), dir.x()); QPointF base = tip - dir * 6; arrow << base + 3 * dy; arrow << base - 3 * dy; p.drawConvexPolygon(arrow); }; if (!polyline.empty()) { if (ec.start_arrow) { auto firstPt = edge.polyline.first(); drawArrow(firstPt, QPointF(0, 1)); } if (ec.end_arrow) { auto lastPt = edge.polyline.last(); QPointF dir(0, -1); switch (edge.arrow) { case GraphLayout::GraphEdge::Down: dir = QPointF(0, 1); break; case GraphLayout::GraphEdge::Up: dir = QPointF(0, -1); break; case GraphLayout::GraphEdge::Left: dir = QPointF(-1, 0); break; case GraphLayout::GraphEdge::Right: dir = QPointF(1, 0); break; default: break; } drawArrow(lastPt, dir); } } } } } void GraphView::saveAsBitmap(QString path, const char *format, double scaler, bool transparent) { QImage image(width * scaler, height * scaler, QImage::Format_ARGB32); if (transparent) { image.fill(qRgba(0, 0, 0, 0)); } else { image.fill(backgroundColor); } QPainter p; p.begin(&image); paint(p, QPoint(0, 0), image.rect(), scaler, false); p.end(); if (!image.save(path, format)) { qWarning() << "Could not save image"; } } void GraphView::saveAsSvg(QString path) { QSvgGenerator generator; generator.setFileName(path); generator.setSize(QSize(width, height)); generator.setViewBox(QRect(0, 0, width, height)); generator.setTitle(tr("Cutter graph export")); QPainter p; p.begin(&generator); paint(p, QPoint(0, 0), QRect(0, 0, width, height), 1.0, false); p.end(); } void GraphView::center() { centerX(false); centerY(false); emit viewOffsetChanged(offset); } void GraphView::centerX(bool emitSignal) { offset.rx() = -((viewport()->width() - width * current_scale) / 2); offset.rx() /= current_scale; clampViewOffset(); if (emitSignal) { emit viewOffsetChanged(offset); } } void GraphView::centerY(bool emitSignal) { offset.ry() = -((viewport()->height() - height * current_scale) / 2); offset.ry() /= current_scale; clampViewOffset(); if (emitSignal) { emit viewOffsetChanged(offset); } } void GraphView::showBlock(GraphBlock &block, bool anywhere) { showRectangle(QRect(block.x, block.y, block.width, block.height), anywhere); blockTransitionedTo(&block); } void GraphView::showRectangle(const QRect &block, bool anywhere) { QSizeF renderSize = QSizeF(viewport()->size()) / current_scale; if (width * current_scale <= viewport()->width()) { centerX(false); } else { if (!anywhere || block.x() < offset.x() || block.right() > offset.x() + renderSize.width()) { offset.rx() = block.x() - ((renderSize.width() - block.width()) / 2); } } if (height * current_scale <= viewport()->height()) { centerY(false); } else { if (!anywhere || block.y() < offset.y() || block.bottom() > offset.y() + renderSize.height()) { offset.ry() = block.y(); // Leave some space at top if possible const qreal topPadding = 10 / current_scale; if (block.height() + topPadding < renderSize.height()) { offset.ry() -= topPadding; } } } clampViewOffset(); emit viewOffsetChanged(offset); viewport()->update(); } GraphView::GraphBlock *GraphView::getBlockContaining(QPoint p) { // Check if a block was clicked for (auto &blockIt : blocks) { GraphBlock &block = blockIt.second; QRect rec(block.x, block.y, block.width, block.height); if (rec.contains(p)) { return &block; } } return nullptr; } QPoint GraphView::viewToLogicalCoordinates(QPoint p) { return p / current_scale + offset; } QPoint GraphView::logicalToViewCoordinates(QPoint p) { return (p - offset) * current_scale; } void GraphView::setGraphLayout(std::unique_ptr<GraphLayout> layout) { graphLayoutSystem = std::move(layout); if (!graphLayoutSystem) { graphLayoutSystem = makeGraphLayout(Layout::GridMedium); } } void GraphView::setLayoutConfig(const GraphLayout::LayoutConfig &config) { graphLayoutSystem->setLayoutConfig(config); } std::unique_ptr<GraphLayout> GraphView::makeGraphLayout(GraphView::Layout layout, bool horizontal) { std::unique_ptr<GraphLayout> result; bool needAdapter = true; #ifdef CUTTER_ENABLE_GRAPHVIZ auto makeGraphvizLayout = [&](GraphvizLayout::LayoutType type) { result.reset(new GraphvizLayout( type, horizontal ? GraphvizLayout::Direction::LR : GraphvizLayout::Direction::TB)); needAdapter = false; }; #endif switch (layout) { case Layout::GridNarrow: result.reset(new GraphGridLayout(GraphGridLayout::LayoutType::Narrow)); break; case Layout::GridMedium: result.reset(new GraphGridLayout(GraphGridLayout::LayoutType::Medium)); break; case Layout::GridWide: result.reset(new GraphGridLayout(GraphGridLayout::LayoutType::Wide)); break; case Layout::GridAAA: case Layout::GridAAB: case Layout::GridABA: case Layout::GridABB: case Layout::GridBAA: case Layout::GridBAB: case Layout::GridBBA: case Layout::GridBBB: { int options = static_cast<int>(layout) - static_cast<int>(Layout::GridAAA); std::unique_ptr<GraphGridLayout> gridLayout(new GraphGridLayout()); gridLayout->setTightSubtreePlacement((options & 1) == 0); gridLayout->setParentBetweenDirectChild((options & 2)); gridLayout->setLayoutOptimization((options & 4)); result = std::move(gridLayout); break; } #ifdef CUTTER_ENABLE_GRAPHVIZ case Layout::GraphvizOrtho: makeGraphvizLayout(GraphvizLayout::LayoutType::DotOrtho); break; case Layout::GraphvizPolyline: makeGraphvizLayout(GraphvizLayout::LayoutType::DotPolyline); break; case Layout::GraphvizSfdp: makeGraphvizLayout(GraphvizLayout::LayoutType::Sfdp); break; case Layout::GraphvizNeato: makeGraphvizLayout(GraphvizLayout::LayoutType::Neato); break; case Layout::GraphvizTwoPi: makeGraphvizLayout(GraphvizLayout::LayoutType::TwoPi); break; case Layout::GraphvizCirco: makeGraphvizLayout(GraphvizLayout::LayoutType::Circo); break; #endif } if (needAdapter && horizontal) { result.reset(new GraphHorizontalAdapter(std::move(result))); } return result; } void GraphView::addBlock(GraphView::GraphBlock block) { blocks[block.entry] = block; } void GraphView::setEntry(ut64 e) { entry = e; } bool GraphView::checkPointClicked(QPointF &point, int x, int y, bool above_y) { int half_target_size = 5; if ((point.x() - half_target_size < x) && (point.y() - (above_y ? (2 * half_target_size) : 0) < y) && (x < point.x() + half_target_size) && (y < point.y() + (above_y ? 0 : (3 * half_target_size)))) { return true; } return false; } // Mouse events void GraphView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::MiddleButton) { beginMouseDrag(event); return; } QPoint pos = viewToLogicalCoordinates(event->pos()); // Check if a block was clicked if (auto block = getBlockContaining(pos)) { blockClicked(*block, event, pos - QPoint(block->x, block->y)); // Don't do anything else here! blockClicked might seek and // all our data is invalid then. return; } // Check if a line beginning/end was clicked if (event->button() == Qt::LeftButton) { for (auto &blockIt : blocks) { GraphBlock &block = blockIt.second; for (GraphEdge &edge : block.edges) { if (edge.polyline.length() < 2) { continue; } QPointF start = edge.polyline.first(); QPointF end = edge.polyline.last(); if (checkPointClicked(start, pos.x(), pos.y())) { showBlock(blocks[edge.target]); // TODO: Callback to child return; } if (checkPointClicked(end, pos.x(), pos.y(), true)) { showBlock(block); // TODO: Callback to child return; } } } } // No block was clicked if (event->button() == Qt::LeftButton) { // Left click outside any block, enter scrolling mode beginMouseDrag(event); return; } QAbstractScrollArea::mousePressEvent(event); } void GraphView::mouseMoveEvent(QMouseEvent *event) { if (scroll_mode) { addViewOffset((scrollBase - event->pos()) / current_scale); scrollBase = event->pos(); viewport()->update(); } } void GraphView::mouseDoubleClickEvent(QMouseEvent *event) { auto p = viewToLogicalCoordinates(event->pos()); if (auto block = getBlockContaining(p)) { blockDoubleClicked(*block, event, p - QPoint(block->x, block->y)); } } void GraphView::keyPressEvent(QKeyEvent *event) { // for scrolling with arrow keys const int delta = static_cast<int>(30.0 / current_scale); // for scrolling with pgup/pgdown keys const int delta2 = static_cast<int>(100.0 / current_scale); int dx = 0, dy = 0; switch (event->key()) { case Qt::Key_Up: dy = -delta; break; case Qt::Key_Down: dy = delta; break; case Qt::Key_Left: dx = -delta; break; case Qt::Key_Right: dx = delta; break; case Qt::Key_PageUp: dy = -delta2; break; case Qt::Key_PageDown: dy = delta2; break; default: QAbstractScrollArea::keyPressEvent(event); return; } addViewOffset(QPoint(dx, dy)); viewport()->update(); event->accept(); } void GraphView::mouseReleaseEvent(QMouseEvent *event) { if (scroll_mode && (event->buttons() & (Qt::LeftButton | Qt::MiddleButton)) == 0) { scroll_mode = false; setCursor(Qt::ArrowCursor); } } void GraphView::wheelEvent(QWheelEvent *event) { if (scroll_mode) { // With some mice it's easy to hit sideway scroll button while holding middle mouse. // That would result in unwanted scrolling while panning. return; } QPoint delta = -event->angleDelta(); delta /= current_scale; addViewOffset(delta); viewport()->update(); event->accept(); }
22,532
C++
.cpp
681
25.787078
99
0.612611
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,548
SearchWidget.cpp
rizinorg_cutter/src/widgets/SearchWidget.cpp
#include "SearchWidget.h" #include "ui_SearchWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QDockWidget> #include <QTreeWidget> #include <QComboBox> #include <QShortcut> namespace { static const int kMaxTooltipWidth = 500; static const int kMaxTooltipDisasmPreviewLines = 10; static const int kMaxTooltipHexdumpBytes = 64; } static const QMap<QString, QString> searchBoundaries { { "io.maps", "All maps" }, { "io.map", "Current map" }, { "raw", "Raw" }, { "block", "Current block" }, { "bin.section", "Current mapped section" }, { "bin.sections", "All mapped sections" }, }; static const QMap<QString, QString> searchBoundariesDebug { { "dbg.maps", "All memory maps" }, { "dbg.map", "Memory map" }, { "block", "Current block" }, { "dbg.stack", "Stack" }, { "dbg.heap", "Heap" } }; SearchModel::SearchModel(QList<SearchDescription> *search, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), search(search) { } int SearchModel::rowCount(const QModelIndex &) const { return search->count(); } int SearchModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant SearchModel::data(const QModelIndex &index, int role) const { if (index.row() >= search->count()) return QVariant(); const SearchDescription &exp = search->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case OFFSET: return RzAddressString(exp.offset); case SIZE: return RzSizeString(exp.size); case CODE: return exp.code; case DATA: return exp.data; case COMMENT: return Core()->getCommentAt(exp.offset); default: return QVariant(); } case Qt::ToolTipRole: { QString previewContent = QString(); // if result is CODE, show disassembly if (!exp.code.isEmpty()) { previewContent = Core()->getDisassemblyPreview(exp.offset, kMaxTooltipDisasmPreviewLines) .join("<br>"); // if result is DATA or Disassembly is N/A } else if (!exp.data.isEmpty() || previewContent.isEmpty()) { previewContent = Core()->getHexdumpPreview(exp.offset, kMaxTooltipHexdumpBytes); } const QFont &fnt = Config()->getBaseFont(); QFontMetrics fm { fnt }; QString toolTipContent = QString("<html><div style=\"font-family: %1; font-size: %2pt; white-space: " "nowrap;\">") .arg(fnt.family()) .arg(qMax(6, fnt.pointSize() - 1)); // slightly decrease font size, to keep // more text in the same box toolTipContent += tr("<div style=\"margin-bottom: 10px;\"><strong>Preview</strong>:<br>%1</div>") .arg(previewContent); toolTipContent += "</div></html>"; return toolTipContent; } case SearchDescriptionRole: return QVariant::fromValue(exp); default: return QVariant(); } } QVariant SearchModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case SIZE: return tr("Size"); case OFFSET: return tr("Offset"); case CODE: return tr("Code"); case DATA: return tr("Data"); case COMMENT: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA SearchModel::address(const QModelIndex &index) const { const SearchDescription &exp = search->at(index.row()); return exp.offset; } SearchSortFilterProxyModel::SearchSortFilterProxyModel(SearchModel *source_model, QObject *parent) : AddressableFilterProxyModel(source_model, parent) { } bool SearchSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); SearchDescription search = index.data(SearchModel::SearchDescriptionRole).value<SearchDescription>(); return qhelpers::filterStringContains(search.code, this); } bool SearchSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { SearchDescription left_search = left.data(SearchModel::SearchDescriptionRole).value<SearchDescription>(); SearchDescription right_search = right.data(SearchModel::SearchDescriptionRole).value<SearchDescription>(); switch (left.column()) { case SearchModel::SIZE: return left_search.size < right_search.size; case SearchModel::OFFSET: return left_search.offset < right_search.offset; case SearchModel::CODE: return left_search.code < right_search.code; case SearchModel::DATA: return left_search.data < right_search.data; case SearchModel::COMMENT: return Core()->getCommentAt(left_search.offset) < Core()->getCommentAt(right_search.offset); default: break; } return left_search.offset < right_search.offset; } SearchWidget::SearchWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::SearchWidget) { ui->setupUi(this); setStyleSheet(QString("QToolTip { max-width: %1px; opacity: 230; }").arg(kMaxTooltipWidth)); updateSearchBoundaries(); search_model = new SearchModel(&search, this); search_proxy_model = new SearchSortFilterProxyModel(search_model, this); ui->searchTreeView->setModel(search_proxy_model); ui->searchTreeView->setMainWindow(main); ui->searchTreeView->sortByColumn(SearchModel::OFFSET, Qt::AscendingOrder); setScrollMode(); connect(Core(), &CutterCore::toggleDebugView, this, &SearchWidget::updateSearchBoundaries); connect(Core(), &CutterCore::refreshAll, this, &SearchWidget::refreshSearchspaces); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(search_model, SearchModel::COMMENT); }); QShortcut *enter_press = new QShortcut(QKeySequence(Qt::Key_Return), this); connect(enter_press, &QShortcut::activated, this, [this]() { disableSearch(); refreshSearch(); checkSearchResultEmpty(); enableSearch(); }); enter_press->setContext(Qt::WidgetWithChildrenShortcut); connect(ui->searchButton, &QAbstractButton::clicked, this, [this]() { disableSearch(); refreshSearch(); checkSearchResultEmpty(); enableSearch(); }); connect(ui->searchspaceCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int index) { updatePlaceholderText(index); }); } SearchWidget::~SearchWidget() {} void SearchWidget::updateSearchBoundaries() { QMap<QString, QString>::const_iterator mapIter; QMap<QString, QString> boundaries; if (Core()->currentlyDebugging && !Core()->currentlyEmulating) { boundaries = searchBoundariesDebug; } else { boundaries = searchBoundaries; } mapIter = boundaries.cbegin(); ui->searchInCombo->setCurrentIndex(ui->searchInCombo->findData(mapIter.key())); ui->searchInCombo->blockSignals(true); ui->searchInCombo->clear(); for (; mapIter != boundaries.cend(); ++mapIter) { ui->searchInCombo->addItem(mapIter.value(), mapIter.key()); } ui->searchInCombo->blockSignals(false); ui->filterLineEdit->clear(); } void SearchWidget::searchChanged() { refreshSearchspaces(); } void SearchWidget::refreshSearchspaces() { int cur_idx = ui->searchspaceCombo->currentIndex(); if (cur_idx < 0) cur_idx = 0; ui->searchspaceCombo->clear(); ui->searchspaceCombo->addItem(tr("asm code"), QVariant("/acj")); ui->searchspaceCombo->addItem(tr("string"), QVariant("/j")); ui->searchspaceCombo->addItem(tr("string (case insensitive)"), QVariant("/ij")); ui->searchspaceCombo->addItem(tr("hex string"), QVariant("/xj")); ui->searchspaceCombo->addItem(tr("ROP gadgets"), QVariant("/Rj")); ui->searchspaceCombo->addItem(tr("32bit value"), QVariant("/vj")); if (cur_idx > 0) ui->searchspaceCombo->setCurrentIndex(cur_idx); refreshSearch(); } void SearchWidget::refreshSearch() { QString searchFor = ui->filterLineEdit->text(); QString searchSpace = ui->searchspaceCombo->currentData().toString(); QString searchIn = ui->searchInCombo->currentData().toString(); search_model->beginResetModel(); search = Core()->getAllSearch(searchFor, searchSpace, searchIn); search_model->endResetModel(); qhelpers::adjustColumns(ui->searchTreeView, 3, 0); } // No Results Found information message when search returns empty // Called by &QShortcut::activated and &QAbstractButton::clicked signals void SearchWidget::checkSearchResultEmpty() { if (search.isEmpty()) { QString noResultsMessage = "<b>"; noResultsMessage.append(tr("No results found for:")); noResultsMessage.append("</b><br>"); noResultsMessage.append(ui->filterLineEdit->text().toHtmlEscaped()); QMessageBox::information(this, tr("No Results Found"), noResultsMessage); } } void SearchWidget::setScrollMode() { qhelpers::setVerticalScrollMode(ui->searchTreeView); } void SearchWidget::updatePlaceholderText(int index) { switch (index) { case 1: // string ui->filterLineEdit->setPlaceholderText("foobar"); break; case 2: // string (case insensitive) ui->filterLineEdit->setPlaceholderText("FooBar"); break; case 3: // hex string ui->filterLineEdit->setPlaceholderText("deadbeef"); break; case 4: // ROP gadgets ui->filterLineEdit->setPlaceholderText("pop,,pop"); break; case 5: // 32bit value ui->filterLineEdit->setPlaceholderText("0xdeadbeef"); break; default: ui->filterLineEdit->setPlaceholderText("jmp rax"); } } void SearchWidget::disableSearch() { ui->searchButton->setEnabled(false); ui->searchButton->setText(tr("Searching...")); qApp->processEvents(); } void SearchWidget::enableSearch() { ui->searchButton->setEnabled(true); ui->searchButton->setText(tr("Search")); }
10,704
C++
.cpp
282
30.819149
100
0.648636
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,549
CutterTreeWidget.cpp
rizinorg_cutter/src/widgets/CutterTreeWidget.cpp
#include "CutterTreeWidget.h" #include "core/MainWindow.h" CutterTreeWidget::CutterTreeWidget(QObject *parent) : QObject(parent), bar(nullptr) {} void CutterTreeWidget::addStatusBar(QVBoxLayout *pos) { if (!bar) { bar = new QStatusBar; QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); bar->setSizePolicy(sizePolicy); pos->addWidget(bar); } } void CutterTreeWidget::showItemsNumber(int count) { if (bar) { bar->showMessage(tr("%1 Items").arg(count)); } } void CutterTreeWidget::showStatusBar(bool show) { bar->setVisible(show); } CutterTreeWidget::~CutterTreeWidget() {}
656
C++
.cpp
23
24.695652
86
0.714968
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,550
BoolToggleDelegate.cpp
rizinorg_cutter/src/widgets/BoolToggleDelegate.cpp
#include "BoolToggleDelegate.h" #include <QEvent> BoolTogggleDelegate::BoolTogggleDelegate(QObject *parent) : QStyledItemDelegate(parent) {} QWidget *BoolTogggleDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.data(Qt::EditRole).type() == QVariant::Bool) { return nullptr; } return QStyledItemDelegate::createEditor(parent, option, index); } bool BoolTogggleDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { if (model->flags(index).testFlag(Qt::ItemFlag::ItemIsEditable)) { if (event->type() == QEvent::MouseButtonDblClick) { auto data = index.data(Qt::EditRole); if (data.type() == QVariant::Bool) { model->setData(index, !data.toBool()); return true; } } } return QStyledItemDelegate::editorEvent(event, model, option, index); }
1,080
C++
.cpp
25
34.2
99
0.641635
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,551
AddressableDockWidget.cpp
rizinorg_cutter/src/widgets/AddressableDockWidget.cpp
#include "AddressableDockWidget.h" #include "common/CutterSeekable.h" #include "MainWindow.h" #include <QAction> #include <QEvent> #include <QMenu> #include <QContextMenuEvent> AddressableDockWidget::AddressableDockWidget(MainWindow *parent) : CutterDockWidget(parent), seekable(new CutterSeekable(this)), syncAction(tr("Sync/unsync offset"), this) { connect(seekable, &CutterSeekable::syncChanged, this, &AddressableDockWidget::updateWindowTitle); connect(&syncAction, &QAction::triggered, seekable, &CutterSeekable::toggleSynchronization); dockMenu = new QMenu(this); dockMenu->addAction(&syncAction); setContextMenuPolicy(Qt::ContextMenuPolicy::DefaultContextMenu); } QVariantMap AddressableDockWidget::serializeViewProprties() { auto result = CutterDockWidget::serializeViewProprties(); result["synchronized"] = seekable->isSynchronized(); return result; } void AddressableDockWidget::deserializeViewProperties(const QVariantMap &properties) { QVariant synchronized = properties.value("synchronized", true); seekable->setSynchronization(synchronized.toBool()); } void AddressableDockWidget::updateWindowTitle() { QString name = getWindowTitle(); QString id = getDockNumber(); if (!id.isEmpty()) { name += " " + id; } if (!seekable->isSynchronized()) { name += CutterSeekable::tr(" (unsynced)"); } setWindowTitle(name); } void AddressableDockWidget::contextMenuEvent(QContextMenuEvent *event) { event->accept(); dockMenu->exec(mapToGlobal(event->pos())); } CutterSeekable *AddressableDockWidget::getSeekable() const { return seekable; }
1,672
C++
.cpp
51
29.196078
96
0.751395
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,552
CutterTreeView.cpp
rizinorg_cutter/src/widgets/CutterTreeView.cpp
#include "CutterTreeView.h" #include "ui_CutterTreeView.h" CutterTreeView::CutterTreeView(QWidget *parent) : QTreeView(parent), ui(new Ui::CutterTreeView()) { ui->setupUi(this); applyCutterStyle(this); } CutterTreeView::~CutterTreeView() {} void CutterTreeView::applyCutterStyle(QTreeView *view) { view->setSelectionMode(QAbstractItemView::ExtendedSelection); view->setUniformRowHeights(true); }
415
C++
.cpp
13
29.461538
97
0.784461
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,553
VTablesWidget.cpp
rizinorg_cutter/src/widgets/VTablesWidget.cpp
#include <QShortcut> #include <QModelIndex> #include "core/MainWindow.h" #include "common/Helpers.h" #include "VTablesWidget.h" #include "ui_VTablesWidget.h" VTableModel::VTableModel(QList<VTableDescription> *vtables, QObject *parent) : QAbstractItemModel(parent), vtables(vtables) { } QModelIndex VTableModel::index(int row, int column, const QModelIndex &parent) const { return createIndex(row, column, (quintptr)parent.isValid() ? parent.row() : -1); } QModelIndex VTableModel::parent(const QModelIndex &index) const { return index.isValid() && index.internalId() != (quintptr)-1 ? this->index(index.internalId(), index.column()) : QModelIndex(); } int VTableModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? (parent.parent().isValid() ? 0 : vtables->at(parent.row()).methods.count()) : vtables->count(); } int VTableModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant VTableModel::data(const QModelIndex &index, int role) const { QModelIndex parent = index.parent(); if (parent.isValid()) { const BinClassMethodDescription &res = vtables->at(parent.row()).methods.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return res.name; case ADDRESS: return RzAddressString(res.addr); } break; case VTableDescriptionRole: return QVariant::fromValue(res); default: break; } } else switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return tr("VTable") + " " + QString::number(index.row() + 1); case ADDRESS: return RzAddressString(vtables->at(index.row()).addr); } break; case VTableDescriptionRole: { const VTableDescription &res = vtables->at(index.row()); return QVariant::fromValue(res); } default: break; } return QVariant(); } QVariant VTableModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case NAME: return tr("Name"); case ADDRESS: return tr("Address"); default: break; } break; default: break; } return QVariant(); } VTableSortFilterProxyModel::VTableSortFilterProxyModel(VTableModel *model, QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(model); setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); setFilterKeyColumn(VTableModel::NAME); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) setRecursiveFilteringEnabled(true); #endif } bool VTableSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { if (QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent)) return true; if (source_parent.isValid()) return QSortFilterProxyModel::filterAcceptsRow(source_parent.row(), QModelIndex()); #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) else { QAbstractItemModel *const model = sourceModel(); const QModelIndex source = model->index(source_row, 0, QModelIndex()); const int rows = model->rowCount(source); for (int i = 0; i < rows; ++i) if (QSortFilterProxyModel::filterAcceptsRow(i, source)) return true; } #endif return false; } VTablesWidget::VTablesWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::VTablesWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); // Add Status Bar footer tree->addStatusBar(ui->verticalLayout); model = new VTableModel(&vtables, this); proxy = new VTableSortFilterProxyModel(model, this); ui->vTableTreeView->setModel(proxy); ui->vTableTreeView->sortByColumn(VTableModel::ADDRESS, Qt::AscendingOrder); // Esc to clear the filter entry QShortcut *clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clear_shortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::clearFilter); clear_shortcut->setContext(Qt::WidgetWithChildrenShortcut); // Ctrl-F to show/hide the filter entry QShortcut *search_shortcut = new QShortcut(QKeySequence::Find, this); connect(search_shortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); search_shortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, proxy, &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->vTableTreeView, [this]() { ui->vTableTreeView->setFocus(); }); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, [this] { tree->showItemsNumber(proxy->rowCount()); }); connect(Core(), &CutterCore::codeRebased, this, &VTablesWidget::refreshVTables); connect(Core(), &CutterCore::refreshAll, this, &VTablesWidget::refreshVTables); refreshDeferrer = createRefreshDeferrer([this]() { refreshVTables(); }); } VTablesWidget::~VTablesWidget() {} void VTablesWidget::refreshVTables() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } model->beginResetModel(); vtables = Core()->getAllVTables(); model->endResetModel(); qhelpers::adjustColumns(ui->vTableTreeView, 3, 0); ui->vTableTreeView->setColumnWidth(0, 200); tree->showItemsNumber(proxy->rowCount()); } void VTablesWidget::on_vTableTreeView_doubleClicked(const QModelIndex &index) { if (!index.isValid()) { return; } QModelIndex parent = index.parent(); if (parent.isValid()) { Core()->seekAndShow(index.data(VTableModel::VTableDescriptionRole) .value<BinClassMethodDescription>() .addr); } else { Core()->seekAndShow( index.data(VTableModel::VTableDescriptionRole).value<VTableDescription>().addr); } }
6,429
C++
.cpp
174
29.862069
97
0.657886
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,554
ListDockWidget.cpp
rizinorg_cutter/src/widgets/ListDockWidget.cpp
#include "ListDockWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QMenu> #include <QResizeEvent> #include <QShortcut> ListDockWidget::ListDockWidget(MainWindow *main, SearchBarPolicy searchBarPolicy) : CutterDockWidget(main), ui(new Ui::ListDockWidget), tree(new CutterTreeWidget(this)), searchBarPolicy(searchBarPolicy) { ui->setupUi(this); // Add Status Bar footer tree->addStatusBar(ui->verticalLayout); if (searchBarPolicy != SearchBarPolicy::Hide) { // Ctrl-F to show/hide the filter entry QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // Esc to clear the filter entry QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, [this]() { ui->quickFilterView->clearFilter(); ui->treeView->setFocus(); }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); } qhelpers::setVerticalScrollMode(ui->treeView); ui->treeView->setMainWindow(mainWindow); if (searchBarPolicy != SearchBarPolicy::ShowByDefault) { ui->quickFilterView->closeFilter(); } } ListDockWidget::~ListDockWidget() {} void ListDockWidget::showCount(bool show) { tree->showStatusBar(show); } void ListDockWidget::setModels(AddressableFilterProxyModel *objectFilterProxyModel) { this->objectFilterProxyModel = objectFilterProxyModel; ui->treeView->setModel(objectFilterProxyModel); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, objectFilterProxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->treeView, static_cast<void (QWidget::*)()>(&QWidget::setFocus)); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, [this] { tree->showItemsNumber(this->objectFilterProxyModel->rowCount()); }); }
2,230
C++
.cpp
52
37.038462
93
0.725046
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,555
Omnibar.cpp
rizinorg_cutter/src/widgets/Omnibar.cpp
#include "Omnibar.h" #include "core/MainWindow.h" #include "CutterSeekable.h" #include <QStringListModel> #include <QCompleter> #include <QShortcut> #include <QAbstractItemView> Omnibar::Omnibar(MainWindow *main, QWidget *parent) : QLineEdit(parent), main(main) { // QLineEdit basic features this->setMinimumHeight(16); this->setFrame(false); this->setPlaceholderText(tr("Type flag name or address here")); this->setStyleSheet("border-radius: 5px; padding: 0 8px; margin: 5px 0;"); this->setTextMargins(10, 0, 0, 0); this->setClearButtonEnabled(true); connect(this, &QLineEdit::returnPressed, this, &Omnibar::on_gotoEntry_returnPressed); // Esc clears omnibar QShortcut *clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clear_shortcut, &QShortcut::activated, this, &Omnibar::clear); clear_shortcut->setContext(Qt::WidgetWithChildrenShortcut); } void Omnibar::setupCompleter() { // Set gotoEntry completer for jump history QCompleter *completer = new QCompleter(flags, this); completer->setMaxVisibleItems(20); completer->setCompletionMode(QCompleter::PopupCompletion); completer->setModelSorting(QCompleter::CaseSensitivelySortedModel); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setFilterMode(Qt::MatchContains); this->setCompleter(completer); } void Omnibar::refresh(const QStringList &flagList) { flags = flagList; setupCompleter(); } void Omnibar::restoreCompleter() { QCompleter *completer = this->completer(); if (!completer) { return; } completer->setFilterMode(Qt::MatchContains); } void Omnibar::clear() { QLineEdit::clear(); // Close the potential shown completer popup clearFocus(); setFocus(); } void Omnibar::on_gotoEntry_returnPressed() { QString str = this->text(); if (!str.isEmpty()) { if (auto memoryWidget = main->getLastMemoryWidget()) { RVA offset = Core()->math(str); memoryWidget->getSeekable()->seek(offset); memoryWidget->raiseMemoryWidget(); } else { Core()->seekAndShow(str); } } this->setText(""); this->clearFocus(); this->restoreCompleter(); }
2,258
C++
.cpp
69
28.289855
89
0.705882
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,556
ColorThemeComboBox.cpp
rizinorg_cutter/src/widgets/ColorThemeComboBox.cpp
#include "ColorThemeComboBox.h" #include "core/Cutter.h" #include "common/ColorThemeWorker.h" #include "common/Configuration.h" ColorThemeComboBox::ColorThemeComboBox(QWidget *parent) : QComboBox(parent), showOnlyCustom(false) { connect(this, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ColorThemeComboBox::onCurrentIndexChanged); updateFromConfig(); } void ColorThemeComboBox::updateFromConfig(bool interfaceThemeChanged) { QSignalBlocker signalBlockerColorBox(this); const int curInterfaceThemeIndex = Config()->getInterfaceTheme(); const QList<QString> themes(showOnlyCustom ? ThemeWorker().customThemes() : Core()->getColorThemes()); clear(); for (const QString &theme : themes) { if (ThemeWorker().isCustomTheme(theme) || !Configuration::relevantThemes[theme] || (Configuration::cutterInterfaceThemesList()[curInterfaceThemeIndex].flag & Configuration::relevantThemes[theme])) { addItem(theme); } } QString curTheme = interfaceThemeChanged ? Config()->getLastThemeOf( Configuration::cutterInterfaceThemesList()[curInterfaceThemeIndex]) : Config()->getColorTheme(); const int index = findText(curTheme); setCurrentIndex(index == -1 ? 0 : index); if (interfaceThemeChanged || index == -1) { curTheme = currentText(); Config()->setColorTheme(curTheme); } int maxThemeLen = 0; for (const QString &str : themes) { int strLen = str.length(); if (strLen > maxThemeLen) { maxThemeLen = strLen; } } setMinimumContentsLength(maxThemeLen); setSizeAdjustPolicy(QComboBox::AdjustToContents); } void ColorThemeComboBox::onCurrentIndexChanged(int index) { QString theme = itemText(index); int curQtThemeIndex = Config()->getInterfaceTheme(); if (curQtThemeIndex >= Configuration::cutterInterfaceThemesList().size()) { curQtThemeIndex = 0; Config()->setInterfaceTheme(curQtThemeIndex); } Config()->setLastThemeOf(Configuration::cutterInterfaceThemesList()[curQtThemeIndex], theme); Config()->setColorTheme(theme); } void ColorThemeComboBox::setShowOnlyCustom(bool value) { showOnlyCustom = value; updateFromConfig(); }
2,418
C++
.cpp
59
33.627119
98
0.680017
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,557
DisassemblyWidget.cpp
rizinorg_cutter/src/widgets/DisassemblyWidget.cpp
#include "DisassemblyWidget.h" #include "menus/DisassemblyContextMenu.h" #include "common/Configuration.h" #include "common/DisassemblyPreview.h" #include "common/Helpers.h" #include "common/TempConfig.h" #include "common/SelectionHighlight.h" #include "common/BinaryTrees.h" #include "core/MainWindow.h" #include <QApplication> #include <QScrollBar> #include <QJsonArray> #include <QJsonObject> #include <QVBoxLayout> #include <QRegularExpression> #include <QToolTip> #include <QTextBlockUserData> #include <QPainter> #include <QPainterPath> #include <QSplitter> #include <algorithm> #include <cmath> DisassemblyWidget::DisassemblyWidget(MainWindow *main) : MemoryDockWidget(MemoryWidgetType::Disassembly, main), mCtxMenu(new DisassemblyContextMenu(this, main)), mDisasScrollArea(new DisassemblyScrollArea(this)), mDisasTextEdit(new DisassemblyTextEdit(this)) { setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); updateWindowTitle(); topOffset = bottomOffset = RVA_INVALID; cursorLineOffset = 0; cursorCharOffset = 0; seekFromCursor = false; // Instantiate the window layout auto *splitter = new QSplitter; // Setup the left frame that contains breakpoints and jumps leftPanel = new DisassemblyLeftPanel(this); splitter->addWidget(leftPanel); // Setup the disassembly content auto *layout = new QHBoxLayout; layout->addWidget(mDisasTextEdit); layout->setContentsMargins(0, 0, 0, 0); mDisasScrollArea->viewport()->setLayout(layout); splitter->addWidget(mDisasScrollArea); mDisasScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff); // Use stylesheet instead of QWidget::setFrameShape(QFrame::NoShape) to avoid // issues with dark and light interface themes mDisasScrollArea->setStyleSheet("QAbstractScrollArea { border: 0px transparent black; }"); mDisasTextEdit->setStyleSheet("QPlainTextEdit { border: 0px transparent black; }"); mDisasTextEdit->setFocusProxy(this); mDisasTextEdit->setFocusPolicy(Qt::ClickFocus); mDisasScrollArea->setFocusProxy(this); mDisasScrollArea->setFocusPolicy(Qt::ClickFocus); setFocusPolicy(Qt::ClickFocus); // Behave like all widgets: highlight on focus and hover connect(qApp, &QApplication::focusChanged, this, [this](QWidget *, QWidget *now) { QColor borderColor = this == now ? palette().color(QPalette::Highlight) : palette().color(QPalette::WindowText).darker(); widget()->setStyleSheet(QString("QSplitter { border: %1px solid %2 } \n" "QSplitter:hover { border: %1px solid %3 } \n") .arg(devicePixelRatio()) .arg(borderColor.name()) .arg(palette().color(QPalette::Highlight).name())); }); splitter->setFrameShape(QFrame::Box); // Set current widget to the splitted layout we just created setWidget(splitter); // Resize properly QList<int> sizes; sizes.append(3); sizes.append(1); splitter->setSizes(sizes); setAllowedAreas(Qt::AllDockWidgetAreas); setupFonts(); setupColors(); disasmRefresh = createReplacingRefreshDeferrer<RVA>( false, [this](const RVA *offset) { refreshDisasm(offset ? *offset : RVA_INVALID); }); maxLines = 0; updateMaxLines(); mDisasTextEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); mDisasTextEdit->setFont(Config()->getFont()); mDisasTextEdit->setReadOnly(true); mDisasTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); // wrapping breaks readCurrentDisassemblyOffset() at the moment :-( mDisasTextEdit->setWordWrapMode(QTextOption::NoWrap); // Increase asm text edit margin QTextDocument *asm_docu = mDisasTextEdit->document(); asm_docu->setDocumentMargin(10); // Event filter to intercept double clicks in the textbox // and showing tooltips when hovering above those offsets mDisasTextEdit->viewport()->installEventFilter(this); // Set Disas context menu mDisasTextEdit->setContextMenuPolicy(Qt::CustomContextMenu); connect(mDisasTextEdit, &QWidget::customContextMenuRequested, this, &DisassemblyWidget::showDisasContextMenu); connect(mDisasScrollArea, &DisassemblyScrollArea::scrollLines, this, &DisassemblyWidget::scrollInstructions); connect(mDisasScrollArea, &DisassemblyScrollArea::disassemblyResized, this, &DisassemblyWidget::updateMaxLines); connectCursorPositionChanged(false); connect(mDisasTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, [=](int value) { if (value != 0) { mDisasTextEdit->verticalScrollBar()->setValue(0); } }); connect(Core(), &CutterCore::commentsChanged, this, [this]() { refreshDisasm(); }); connect(Core(), SIGNAL(flagsChanged()), this, SLOT(refreshDisasm())); connect(Core(), SIGNAL(globalVarsChanged()), this, SLOT(refreshDisasm())); connect(Core(), SIGNAL(functionsChanged()), this, SLOT(refreshDisasm())); connect(Core(), &CutterCore::functionRenamed, this, [this]() { refreshDisasm(); }); connect(Core(), SIGNAL(varsChanged()), this, SLOT(refreshDisasm())); connect(Core(), SIGNAL(asmOptionsChanged()), this, SLOT(refreshDisasm())); connect(Core(), &CutterCore::instructionChanged, this, &DisassemblyWidget::instructionChanged); connect(Core(), &CutterCore::breakpointsChanged, this, &DisassemblyWidget::refreshIfInRange); connect(Core(), SIGNAL(refreshCodeViews()), this, SLOT(refreshDisasm())); connect(Config(), &Configuration::fontsUpdated, this, &DisassemblyWidget::fontsUpdatedSlot); connect(Config(), &Configuration::colorsUpdated, this, &DisassemblyWidget::colorsUpdatedSlot); connect(Core(), &CutterCore::refreshAll, this, [this]() { refreshDisasm(seekable->getOffset()); }); refreshDisasm(seekable->getOffset()); connect(mCtxMenu, &DisassemblyContextMenu::copy, mDisasTextEdit, &QPlainTextEdit::copy); mCtxMenu->addSeparator(); mCtxMenu->addAction(&syncAction); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &DisassemblyWidget::on_seekChanged); addActions(mCtxMenu->actions()); #define ADD_ACTION(ksq, ctx, slot) \ { \ QAction *a = new QAction(this); \ a->setShortcut(ksq); \ a->setShortcutContext(ctx); \ addAction(a); \ connect(a, &QAction::triggered, this, (slot)); \ } // Space to switch to graph ADD_ACTION(Qt::Key_Space, Qt::WidgetWithChildrenShortcut, [this] { mainWindow->showMemoryWidget(MemoryWidgetType::Graph); }) ADD_ACTION(Qt::Key_Escape, Qt::WidgetWithChildrenShortcut, &DisassemblyWidget::seekPrev) ADD_ACTION(Qt::Key_J, Qt::WidgetWithChildrenShortcut, [this]() { moveCursorRelative(false, false); }) ADD_ACTION(QKeySequence::MoveToNextLine, Qt::WidgetWithChildrenShortcut, [this]() { moveCursorRelative(false, false); }) ADD_ACTION(Qt::Key_K, Qt::WidgetWithChildrenShortcut, [this]() { moveCursorRelative(true, false); }) ADD_ACTION(QKeySequence::MoveToPreviousLine, Qt::WidgetWithChildrenShortcut, [this]() { moveCursorRelative(true, false); }) ADD_ACTION(QKeySequence::MoveToNextPage, Qt::WidgetWithChildrenShortcut, [this]() { moveCursorRelative(false, true); }) ADD_ACTION(QKeySequence::MoveToPreviousPage, Qt::WidgetWithChildrenShortcut, [this]() { moveCursorRelative(true, true); }) #undef ADD_ACTION } void DisassemblyWidget::setPreviewMode(bool previewMode) { mDisasTextEdit->setContextMenuPolicy(previewMode ? Qt::NoContextMenu : Qt::CustomContextMenu); mCtxMenu->setEnabled(!previewMode); for (auto action : mCtxMenu->actions()) { action->setEnabled(!previewMode); } for (auto action : actions()) { if (action->shortcut() == Qt::Key_Space || action->shortcut() == Qt::Key_Escape) { action->setEnabled(!previewMode); } } if (previewMode) { seekable->setSynchronization(false); } } QWidget *DisassemblyWidget::getTextWidget() { return mDisasTextEdit; } QString DisassemblyWidget::getWidgetType() { return "Disassembly"; } QFontMetrics DisassemblyWidget::getFontMetrics() { return QFontMetrics(mDisasTextEdit->font()); } QList<DisassemblyLine> DisassemblyWidget::getLines() { return lines; } void DisassemblyWidget::refreshIfInRange(RVA offset) { if (offset >= topOffset && offset <= bottomOffset) { refreshDisasm(); } } void DisassemblyWidget::instructionChanged(RVA offset) { leftPanel->clearArrowFrom(offset); refreshDisasm(); } void DisassemblyWidget::refreshDisasm(RVA offset) { if (!disasmRefresh->attemptRefresh(offset == RVA_INVALID ? nullptr : new RVA(offset))) { return; } if (offset != RVA_INVALID) { topOffset = offset; } if (topOffset == RVA_INVALID) { return; } if (maxLines <= 0) { connectCursorPositionChanged(true); mDisasTextEdit->clear(); connectCursorPositionChanged(false); return; } breakpoints = Core()->getBreakpointsAddresses(); int horizontalScrollValue = mDisasTextEdit->horizontalScrollBar()->value(); mDisasTextEdit->setLockScroll(true); // avoid flicker // Retrieve disassembly lines { TempConfig tempConfig; tempConfig.set("scr.color", COLOR_MODE_16M).set("asm.lines", false); lines = Core()->disassembleLines(topOffset, maxLines); } connectCursorPositionChanged(true); mDisasTextEdit->document()->clear(); QTextCursor cursor(mDisasTextEdit->document()); QTextBlockFormat regular = cursor.blockFormat(); for (const DisassemblyLine &line : lines) { if (line.offset < topOffset) { // overflow break; } cursor.insertHtml(line.text); if (Core()->isBreakpoint(breakpoints, line.offset)) { QTextBlockFormat f; f.setBackground(ConfigColor("gui.breakpoint_background")); cursor.setBlockFormat(f); } auto a = new DisassemblyTextBlockUserData(line); cursor.block().setUserData(a); cursor.insertBlock(); cursor.setBlockFormat(regular); } if (!lines.isEmpty()) { bottomOffset = lines[qMin(lines.size(), maxLines) - 1].offset; if (bottomOffset < topOffset) { bottomOffset = RVA_MAX; } } else { bottomOffset = topOffset; } connectCursorPositionChanged(false); updateCursorPosition(); // remove additional lines QTextCursor tc = mDisasTextEdit->textCursor(); tc.movePosition(QTextCursor::Start); tc.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, maxLines - 1); tc.movePosition(QTextCursor::EndOfLine); tc.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); tc.removeSelectedText(); mDisasTextEdit->setLockScroll(false); mDisasTextEdit->horizontalScrollBar()->setValue(horizontalScrollValue); // Refresh the left panel (trigger paintEvent) leftPanel->update(); } void DisassemblyWidget::scrollInstructions(int count) { if (count == 0) { return; } RVA offset; if (count > 0) { offset = Core()->nextOpAddr(topOffset, count); if (offset < topOffset) { offset = RVA_MAX; } } else { offset = Core()->prevOpAddr(topOffset, -count); if (offset > topOffset) { offset = 0; } } refreshDisasm(offset); topOffsetHistory[topOffsetHistoryPos] = offset; } bool DisassemblyWidget::updateMaxLines() { int currentMaxLines = qhelpers::getMaxFullyDisplayedLines(mDisasTextEdit); if (currentMaxLines != maxLines) { maxLines = currentMaxLines; refreshDisasm(); return true; } return false; } void DisassemblyWidget::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> extraSelections; QColor highlightColor = ConfigColor("lineHighlight"); // Highlight the current word QTextCursor cursor = mDisasTextEdit->textCursor(); auto clickedCharPos = cursor.positionInBlock(); // Select the line (BlockUnderCursor matches a line with current implementation) cursor.select(QTextCursor::BlockUnderCursor); // Remove any non-breakable space from the current line QString searchString = cursor.selectedText().replace("\xc2\xa0", " "); // Cut the line in "tokens" that can be highlighted static const QRegularExpression tokenRegExp(R"(\b(?<!\.)([^\s]+)\b(?!\.))"); QRegularExpressionMatchIterator i = tokenRegExp.globalMatch(searchString); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); // Current token is under our cursor, select this one if (match.capturedStart() <= clickedCharPos && match.capturedEnd() > clickedCharPos) { curHighlightedWord = match.captured(); break; } } // Highlight the current line QTextEdit::ExtraSelection highlightSelection; highlightSelection.cursor = cursor; highlightSelection.cursor.movePosition(QTextCursor::Start); while (true) { RVA lineOffset = DisassemblyPreview::readDisassemblyOffset(highlightSelection.cursor); if (lineOffset == seekable->getOffset()) { highlightSelection.format.setBackground(highlightColor); highlightSelection.format.setProperty(QTextFormat::FullWidthSelection, true); highlightSelection.cursor.clearSelection(); extraSelections.append(highlightSelection); } else if (lineOffset != RVA_INVALID && lineOffset > seekable->getOffset()) { break; } highlightSelection.cursor.movePosition(QTextCursor::EndOfLine); if (highlightSelection.cursor.atEnd()) { break; } highlightSelection.cursor.movePosition(QTextCursor::Down); } // Highlight all the words in the document same as the current one extraSelections.append(createSameWordsSelections(mDisasTextEdit, curHighlightedWord)); mDisasTextEdit->setExtraSelections(extraSelections); } void DisassemblyWidget::highlightPCLine() { RVA PCAddr = Core()->getProgramCounterValue(); QColor highlightPCColor = ConfigColor("highlightPC"); QList<QTextEdit::ExtraSelection> pcSelections; QTextEdit::ExtraSelection highlightSelection; highlightSelection.cursor = mDisasTextEdit->textCursor(); highlightSelection.cursor.movePosition(QTextCursor::Start); if (PCAddr != RVA_INVALID) { while (true) { RVA lineOffset = DisassemblyPreview::readDisassemblyOffset(highlightSelection.cursor); if (lineOffset == PCAddr) { highlightSelection.format.setBackground(highlightPCColor); highlightSelection.format.setProperty(QTextFormat::FullWidthSelection, true); highlightSelection.cursor.clearSelection(); pcSelections.append(highlightSelection); } else if (lineOffset != RVA_INVALID && lineOffset > PCAddr) { break; } highlightSelection.cursor.movePosition(QTextCursor::EndOfLine); if (highlightSelection.cursor.atEnd()) { break; } highlightSelection.cursor.movePosition(QTextCursor::Down); } } // Don't override any extraSelections already set QList<QTextEdit::ExtraSelection> currentSelections = mDisasTextEdit->extraSelections(); currentSelections.append(pcSelections); mDisasTextEdit->setExtraSelections(currentSelections); } void DisassemblyWidget::showDisasContextMenu(const QPoint &pt) { mCtxMenu->exec(mDisasTextEdit->mapToGlobal(pt)); } RVA DisassemblyWidget::readCurrentDisassemblyOffset() { QTextCursor tc = mDisasTextEdit->textCursor(); return DisassemblyPreview::readDisassemblyOffset(tc); } void DisassemblyWidget::updateCursorPosition() { RVA offset = seekable->getOffset(); // already fine where it is? RVA currentLineOffset = readCurrentDisassemblyOffset(); if (currentLineOffset == offset) { return; } connectCursorPositionChanged(true); if (offset < topOffset || (offset > bottomOffset && bottomOffset != RVA_INVALID)) { mDisasTextEdit->moveCursor(QTextCursor::Start); mDisasTextEdit->setExtraSelections( createSameWordsSelections(mDisasTextEdit, curHighlightedWord)); } else { RVA currentCursorOffset = readCurrentDisassemblyOffset(); QTextCursor originalCursor = mDisasTextEdit->textCursor(); QTextCursor cursor = originalCursor; cursor.movePosition(QTextCursor::Start); while (true) { RVA lineOffset = DisassemblyPreview::readDisassemblyOffset(cursor); if (lineOffset == offset) { if (cursorLineOffset > 0) { cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, cursorLineOffset); } if (cursorCharOffset > 0) { cursor.movePosition(QTextCursor::StartOfLine); cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, cursorCharOffset); } mDisasTextEdit->setTextCursor(cursor); highlightCurrentLine(); break; } else if (lineOffset != RVA_INVALID && lineOffset > offset) { mDisasTextEdit->moveCursor(QTextCursor::Start); mDisasTextEdit->setExtraSelections({}); break; } cursor.movePosition(QTextCursor::EndOfLine); if (cursor.atEnd()) { break; } cursor.movePosition(QTextCursor::Down); } // this is true if a seek came from the user clicking on a line. // then the cursor should be restored 1:1 to retain selection and cursor position. if (currentCursorOffset == offset) { mDisasTextEdit->setTextCursor(originalCursor); } } highlightPCLine(); connectCursorPositionChanged(false); } void DisassemblyWidget::connectCursorPositionChanged(bool disconnect) { if (disconnect) { QObject::disconnect(mDisasTextEdit, &QPlainTextEdit::cursorPositionChanged, this, &DisassemblyWidget::cursorPositionChanged); } else { connect(mDisasTextEdit, &QPlainTextEdit::cursorPositionChanged, this, &DisassemblyWidget::cursorPositionChanged); } } void DisassemblyWidget::cursorPositionChanged() { RVA offset = readCurrentDisassemblyOffset(); cursorLineOffset = 0; QTextCursor c = mDisasTextEdit->textCursor(); cursorCharOffset = c.positionInBlock(); while (c.blockNumber() > 0) { c.movePosition(QTextCursor::PreviousBlock); if (DisassemblyPreview::readDisassemblyOffset(c) != offset) { break; } cursorLineOffset++; } seekFromCursor = true; seekable->seek(offset); seekFromCursor = false; highlightCurrentLine(); highlightPCLine(); mCtxMenu->setCanCopy(mDisasTextEdit->textCursor().hasSelection()); if (mDisasTextEdit->textCursor().hasSelection()) { // A word is selected so use it mCtxMenu->setCurHighlightedWord(mDisasTextEdit->textCursor().selectedText()); } else { // No word is selected so use the word under the cursor mCtxMenu->setCurHighlightedWord(curHighlightedWord); } leftPanel->update(); } void DisassemblyWidget::moveCursorRelative(bool up, bool page) { if (page) { RVA offset; if (!up) { offset = Core()->nextOpAddr(bottomOffset, 1); if (offset < bottomOffset) { offset = RVA_MAX; } } else { offset = Core()->prevOpAddr(topOffset, maxLines); if (offset > topOffset) { offset = 0; } else { // disassembly from calculated offset may have more than maxLines lines // move some instructions down if necessary. auto lines = Core()->disassembleLines(offset, maxLines).toVector(); int oldTopLine; for (oldTopLine = lines.length(); oldTopLine > 0; oldTopLine--) { if (lines[oldTopLine - 1].offset < topOffset) { break; } } int overflowLines = oldTopLine - maxLines; if (overflowLines > 0) { while (lines[overflowLines - 1].offset == lines[overflowLines].offset && overflowLines < lines.length() - 1) { overflowLines++; } offset = lines[overflowLines].offset; } } } refreshDisasm(offset); } else { // normal arrow keys int blockCount = mDisasTextEdit->blockCount(); if (blockCount < 1) { return; } int blockNumber = mDisasTextEdit->textCursor().blockNumber(); if (blockNumber == blockCount - 1 && !up) { scrollInstructions(1); } else if (blockNumber == 0 && up) { scrollInstructions(-1); } mDisasTextEdit->moveCursor(up ? QTextCursor::Up : QTextCursor::Down); // handle cases where top instruction offsets change RVA offset = readCurrentDisassemblyOffset(); if (offset != seekable->getOffset()) { seekable->seek(offset); highlightCurrentLine(); highlightPCLine(); } } } void DisassemblyWidget::jumpToOffsetUnderCursor(const QTextCursor &cursor) { RVA offset = DisassemblyPreview::readDisassemblyOffset(cursor); seekable->seekToReference(offset); } bool DisassemblyWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::MouseButtonDblClick && (obj == mDisasTextEdit || obj == mDisasTextEdit->viewport())) { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); if (mouseEvent->button() == Qt::LeftButton) { const QTextCursor &cursor = mDisasTextEdit->cursorForPosition(mouseEvent->pos()); jumpToOffsetUnderCursor(cursor); return true; } } else if ((Config()->getPreviewValue() || Config()->getShowVarTooltips()) && event->type() == QEvent::ToolTip && obj == mDisasTextEdit->viewport()) { QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event); auto cursorForWord = mDisasTextEdit->cursorForPosition(helpEvent->pos()); cursorForWord.select(QTextCursor::WordUnderCursor); RVA offsetFrom = DisassemblyPreview::readDisassemblyOffset(cursorForWord); if (Config()->getPreviewValue() && DisassemblyPreview::showDisasPreview(this, helpEvent->globalPos(), offsetFrom)) { return true; } if (Config()->getShowVarTooltips() && DisassemblyPreview::showDebugValueTooltip( this, helpEvent->globalPos(), cursorForWord.selectedText(), offsetFrom)) { return true; } } return MemoryDockWidget::eventFilter(obj, event); } void DisassemblyWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return) { const QTextCursor cursor = mDisasTextEdit->textCursor(); jumpToOffsetUnderCursor(cursor); } MemoryDockWidget::keyPressEvent(event); } QString DisassemblyWidget::getWindowTitle() const { return tr("Disassembly"); } void DisassemblyWidget::on_seekChanged(RVA offset, CutterCore::SeekHistoryType type) { if (type == CutterCore::SeekHistoryType::New) { // Erase previous history past this point. if (topOffsetHistory.size() > topOffsetHistoryPos + 1) { topOffsetHistory.erase(topOffsetHistory.begin() + topOffsetHistoryPos + 1, topOffsetHistory.end()); } topOffsetHistory.push_back(offset); topOffsetHistoryPos = topOffsetHistory.size() - 1; } else if (type == CutterCore::SeekHistoryType::Undo) { --topOffsetHistoryPos; } else if (type == CutterCore::SeekHistoryType::Redo) { ++topOffsetHistoryPos; } if (!seekFromCursor) { cursorLineOffset = 0; cursorCharOffset = 0; } if (topOffset != RVA_INVALID && offset >= topOffset && offset <= bottomOffset && type == CutterCore::SeekHistoryType::New) { // if the line with the seek offset is currently visible, just move the cursor there updateCursorPosition(); topOffsetHistory[topOffsetHistoryPos] = topOffset; } else { // otherwise scroll there refreshDisasm(topOffsetHistory[topOffsetHistoryPos]); } mCtxMenu->setOffset(offset); } void DisassemblyWidget::fontsUpdatedSlot() { setupFonts(); if (!updateMaxLines()) { // updateMaxLines() returns true if it already refreshed. refreshDisasm(); } } void DisassemblyWidget::colorsUpdatedSlot() { setupColors(); refreshDisasm(); } void DisassemblyWidget::setupFonts() { mDisasTextEdit->setFont(Config()->getFont()); } void DisassemblyWidget::setupColors() { mDisasTextEdit->setStyleSheet(QString("QPlainTextEdit { background-color: %1; color: %2; }") .arg(ConfigColor("gui.background").name()) .arg(ConfigColor("btext").name())); // Read and set a stylesheet for the QToolTip too setStyleSheet(DisassemblyPreview::getToolTipStyleSheet()); } DisassemblyScrollArea::DisassemblyScrollArea(QWidget *parent) : QAbstractScrollArea(parent) {} bool DisassemblyScrollArea::viewportEvent(QEvent *event) { int dy = verticalScrollBar()->value() - 5; if (dy != 0) { emit scrollLines(dy); } if (event->type() == QEvent::Resize) { emit disassemblyResized(); } resetScrollBars(); return QAbstractScrollArea::viewportEvent(event); } void DisassemblyScrollArea::resetScrollBars() { verticalScrollBar()->blockSignals(true); verticalScrollBar()->setRange(0, 10); verticalScrollBar()->setValue(5); verticalScrollBar()->blockSignals(false); } qreal DisassemblyTextEdit::textOffset() const { return (blockBoundingGeometry(document()->begin()).topLeft() + contentOffset()).y(); } bool DisassemblyTextEdit::viewportEvent(QEvent *event) { switch (event->type()) { case QEvent::Type::Wheel: return false; default: return QAbstractScrollArea::viewportEvent(event); } } void DisassemblyTextEdit::scrollContentsBy(int dx, int dy) { if (!lockScroll) { QPlainTextEdit::scrollContentsBy(dx, dy); } } void DisassemblyTextEdit::keyPressEvent(QKeyEvent *event) { Q_UNUSED(event) // QPlainTextEdit::keyPressEvent(event); } void DisassemblyTextEdit::mousePressEvent(QMouseEvent *event) { QPlainTextEdit::mousePressEvent(event); if (event->button() == Qt::RightButton && !textCursor().hasSelection()) { setTextCursor(cursorForPosition(event->pos())); } } void DisassemblyWidget::seekPrev() { Core()->seekPrev(); } /********************* * Left panel *********************/ DisassemblyLeftPanel::DisassemblyLeftPanel(DisassemblyWidget *disas) { this->disas = disas; arrows.reserve((arrowsSize * 3) / 2); } void DisassemblyLeftPanel::wheelEvent(QWheelEvent *event) { int count = -(event->angleDelta() / 15).y(); count -= (count > 0 ? 5 : -5); this->disas->scrollInstructions(count); } void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) { Q_UNUSED(event) constexpr int penSizePix = 1; constexpr int distanceBetweenLines = 10; constexpr int arrowWidth = 5; int rightOffset = size().rwidth(); auto tEdit = qobject_cast<DisassemblyTextEdit *>(disas->getTextWidget()); int topOffset = int(tEdit->contentsMargins().top() + tEdit->textOffset()); int lineHeight = disas->getFontMetrics().height(); QColor arrowColorDown = ConfigColor("flow"); QColor arrowColorUp = ConfigColor("cflow"); QPainter p(this); QPen penDown(arrowColorDown, penSizePix, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin); QPen penUp(arrowColorUp, penSizePix, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin); // Fill background p.fillRect(event->rect(), Config()->getColor("gui.background").darker(115)); QList<DisassemblyLine> lines = disas->getLines(); if (lines.size() == 0) { // No line to print, abort early return; } using LineInfo = std::pair<RVA, int>; std::vector<LineInfo> lineOffsets; lineOffsets.reserve(lines.size() + arrows.size()); RVA minViewOffset = 0, maxViewOffset = 0; minViewOffset = maxViewOffset = lines[0].offset; for (int i = 0; i < lines.size(); i++) { lineOffsets.emplace_back(lines[i].offset, i); minViewOffset = std::min(minViewOffset, lines[i].offset); maxViewOffset = std::max(maxViewOffset, lines[i].offset); if (lines[i].arrow != RVA_INVALID) { Arrow a { lines[i].offset, lines[i].arrow }; bool contains = std::find_if(std::begin(arrows), std::end(arrows), [&](const Arrow &it) { return it.min == a.min && it.max == a.max; }) != std::end(arrows); if (!contains) { arrows.emplace_back(lines[i].offset, lines[i].arrow); } } } auto addOffsetOutsideScreen = [&](RVA offset) { if (offset < minViewOffset || offset > maxViewOffset) { lineOffsets.emplace_back(offset, -1); } }; // Assign sequential numbers to offsets outside screen while preserving their relative order. // Preserving relative order helps reducing reordering while scrolling. Using sequential numbers // allows using data structures designed for dense ranges. for (auto &arrow : arrows) { addOffsetOutsideScreen(arrow.min); addOffsetOutsideScreen(arrow.max); } std::sort(lineOffsets.begin(), lineOffsets.end()); lineOffsets.erase(std::unique(lineOffsets.begin(), lineOffsets.end()), lineOffsets.end()); size_t firstVisibleLine = std::find_if(lineOffsets.begin(), lineOffsets.end(), [](const LineInfo &line) { return line.second == 0; }) - lineOffsets.begin(); for (int i = int(firstVisibleLine) - 1; i >= 0; i--) { // -1 to ensure end of arrrow is drawn outside screen lineOffsets[i].second = i - firstVisibleLine - 1; } size_t firstLineAfter = std::find_if(lineOffsets.begin(), lineOffsets.end(), [&](const LineInfo &line) { return line.first > maxViewOffset; }) - lineOffsets.begin(); for (size_t i = firstLineAfter; i < lineOffsets.size(); i++) { lineOffsets[i].second = lines.size() + (i - firstLineAfter) + 1; // +1 to ensure end of arrrow is drawn outside screen } auto offsetToLine = [&](RVA offset) -> int { // binary search because linesPixPosition is sorted by offset if (lineOffsets.empty()) { return 0; } if (offset < lineOffsets[0].first) { return lineOffsets[0].second - 1; } auto res = lower_bound(std::begin(lineOffsets), std::end(lineOffsets), offset, [](const LineInfo &it, RVA offset) { return it.first < offset; }); if (res == std::end(lineOffsets)) { return lineOffsets.back().second + 1; } return res->second; }; auto fitsInScreen = [&](const Arrow &a) { return maxViewOffset - minViewOffset < a.length(); }; std::sort(std::begin(arrows), std::end(arrows), [&](const Arrow &l, const Arrow &r) { int lScreen = fitsInScreen(l), rScreen = fitsInScreen(r); if (lScreen != rScreen) { return lScreen < rScreen; } return l.max != r.max ? l.max < r.max : l.min > r.min; }); int minLine = 0, maxLine = 0; for (auto &it : arrows) { minLine = std::min(offsetToLine(it.min), minLine); maxLine = std::max(offsetToLine(it.max), maxLine); it.level = 0; } const int MAX_ARROW_LINES = 1 << 18; uint32_t maxLevel = 0; if (!arrows.empty() && maxLine - minLine < MAX_ARROW_LINES) { // Limit maximum tree range to MAX_ARROW_LINES as sanity check, since the tree is designed // for dense ranges. Under normal conditions due to amount lines fitting screen and number // of arrows remembered should be few hundreds at most. MinMaxAccumulateTree<uint32_t> maxLevelTree(maxLine - minLine + 2); for (Arrow &arrow : arrows) { int top = offsetToLine(arrow.min) - minLine; int bottom = offsetToLine(arrow.max) - minLine + 1; auto minMax = maxLevelTree.rangeMinMax(top, bottom); if (minMax.first > 1) { arrow.level = 1; // place bellow existing lines } else { arrow.level = minMax.second + 1; // place on top of existing lines maxLevel = std::max(maxLevel, arrow.level); } maxLevelTree.updateRange(top, bottom, arrow.level); } } const RVA currOffset = disas->getSeekable()->getOffset(); const qreal pixelRatio = qhelpers::devicePixelRatio(p.device()); const Arrow visibleRange { lines.first().offset, lines.last().offset }; // Draw the lines for (const auto &arrow : arrows) { if (!visibleRange.intersects(arrow)) { continue; } int lineOffset = int((distanceBetweenLines * arrow.level + distanceBetweenLines) * pixelRatio); p.setPen(arrow.up ? penUp : penDown); if (arrow.min == currOffset || arrow.max == currOffset) { QPen pen = p.pen(); pen.setWidthF((penSizePix * 3) / 2.0); p.setPen(pen); } auto lineToPixels = [&](int i) { int offset = int(arrow.up ? std::floor(pixelRatio) : -std::floor(pixelRatio)); return i * lineHeight + lineHeight / 2 + topOffset + offset; }; int lineStartNumber = offsetToLine(arrow.jmpFromOffset()); int currentLineYPos = lineToPixels(lineStartNumber); int arrowLineNumber = offsetToLine(arrow.jmpToffset()); int lineArrowY = lineToPixels(arrowLineNumber); // Draw the lines p.drawLine(rightOffset, currentLineYPos, rightOffset - lineOffset, currentLineYPos); // left p.drawLine(rightOffset - lineOffset, currentLineYPos, rightOffset - lineOffset, lineArrowY); // vertical p.drawLine(rightOffset - lineOffset, lineArrowY, rightOffset, lineArrowY); // right { // triangle QPainterPath arrow; arrow.moveTo(rightOffset - arrowWidth, lineArrowY + arrowWidth); arrow.lineTo(rightOffset - arrowWidth, lineArrowY - arrowWidth); arrow.lineTo(rightOffset, lineArrowY); p.fillPath(arrow, p.pen().brush()); } } if (maxLevel > maxLevelBeforeFlush) { arrows.clear(); } const size_t eraseN = arrows.size() > arrowsSize ? arrows.size() - arrowsSize : 0; if (eraseN > 0) { const bool scrolledDown = lastBeginOffset > lines.first().offset; std::sort(std::begin(arrows), std::end(arrows), [&](const Arrow &l, const Arrow &r) { if (scrolledDown) { return l.jmpFromOffset() < r.jmpFromOffset(); } else { return l.jmpFromOffset() > r.jmpFromOffset(); } }); arrows.erase(std::end(arrows) - eraseN, std::end(arrows)); } lastBeginOffset = lines.first().offset; } void DisassemblyLeftPanel::clearArrowFrom(RVA offset) { auto it = std::find_if(arrows.begin(), arrows.end(), [&](const Arrow &it) { return it.jmpFromOffset() == offset; }); if (it != arrows.end()) { arrows.erase(it); } }
37,157
C++
.cpp
876
34.552511
100
0.644698
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,558
GlibcHeapWidget.cpp
rizinorg_cutter/src/widgets/GlibcHeapWidget.cpp
#include <dialogs/GlibcHeapBinsDialog.h> #include <dialogs/ArenaInfoDialog.h> #include "GlibcHeapWidget.h" #include "ui_GlibcHeapWidget.h" #include "core/MainWindow.h" #include "QHeaderView" #include "dialogs/GlibcHeapInfoDialog.h" GlibcHeapWidget::GlibcHeapWidget(MainWindow *main, QWidget *parent) : QWidget(parent), ui(new Ui::GlibcHeapWidget), addressableItemContextMenu(this, main), main(main) { ui->setupUi(this); viewHeap = ui->tableView; arenaSelectorView = ui->arenaSelector; viewHeap->setFont(Config()->getFont()); viewHeap->setModel(modelHeap); viewHeap->verticalHeader()->hide(); // change the scroll mode to ScrollPerPixel viewHeap->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); viewHeap->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); viewHeap->setContextMenuPolicy(Qt::CustomContextMenu); chunkInfoAction = new QAction(tr("Detailed Chunk Info"), this); binInfoAction = new QAction(tr("Bins Info"), this); connect(Core(), &CutterCore::refreshAll, this, &GlibcHeapWidget::updateContents); connect(Core(), &CutterCore::debugTaskStateChanged, this, &GlibcHeapWidget::updateContents); connect(viewHeap, &QAbstractItemView::doubleClicked, this, &GlibcHeapWidget::onDoubleClicked); connect<void (QComboBox::*)(int)>(arenaSelectorView, &QComboBox::currentIndexChanged, this, &GlibcHeapWidget::onArenaSelected); connect(viewHeap, &QWidget::customContextMenuRequested, this, &GlibcHeapWidget::customMenuRequested); connect(viewHeap->selectionModel(), &QItemSelectionModel::currentChanged, this, &GlibcHeapWidget::onCurrentChanged); connect(chunkInfoAction, &QAction::triggered, this, &GlibcHeapWidget::viewChunkInfo); connect(binInfoAction, &QAction::triggered, this, &GlibcHeapWidget::viewBinInfo); connect(ui->binsButton, &QPushButton::clicked, this, &GlibcHeapWidget::viewBinInfo); connect(ui->arenaButton, &QPushButton::clicked, this, &GlibcHeapWidget::viewArenaInfo); addressableItemContextMenu.addAction(chunkInfoAction); addressableItemContextMenu.addAction(binInfoAction); addActions(addressableItemContextMenu.actions()); refreshDeferrer = dynamic_cast<CutterDockWidget *>(parent)->createRefreshDeferrer( [this]() { updateContents(); }); } GlibcHeapWidget::~GlibcHeapWidget() { delete ui; } GlibcHeapModel::GlibcHeapModel(QObject *parent) : QAbstractTableModel(parent) {} void GlibcHeapWidget::updateArenas() { arenas = Core()->getArenas(); // store the currently selected arena's index int currentIndex = arenaSelectorView->currentIndex(); arenaSelectorView->clear(); // add the new arenas to the arena selector for (auto &arena : arenas) { arenaSelectorView->addItem(RzAddressString(arena.offset) + QString(" (" + arena.type + " Arena)")); } // check if arenas reduced or invalid index and restore the previously selected arena if (arenaSelectorView->count() <= currentIndex || currentIndex == -1) { currentIndex = 0; } arenaSelectorView->setCurrentIndex(currentIndex); } void GlibcHeapWidget::onArenaSelected(int index) { if (index == -1) { modelHeap->arena_addr = 0; } else { modelHeap->arena_addr = arenas[index].offset; } updateChunks(); } void GlibcHeapWidget::updateContents() { if (!refreshDeferrer->attemptRefresh(nullptr) || Core()->isDebugTaskInProgress()) { return; } updateArenas(); updateChunks(); } void GlibcHeapWidget::updateChunks() { modelHeap->reload(); viewHeap->resizeColumnsToContents(); } void GlibcHeapWidget::customMenuRequested(QPoint pos) { addressableItemContextMenu.exec(viewHeap->viewport()->mapToGlobal(pos)); } void GlibcHeapModel::reload() { beginResetModel(); values.clear(); values = Core()->getHeapChunks(arena_addr); endResetModel(); } int GlibcHeapModel::columnCount(const QModelIndex &) const { return ColumnCount; } int GlibcHeapModel::rowCount(const QModelIndex &) const { return this->values.size(); } QVariant GlibcHeapModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= values.count()) return QVariant(); const auto &item = values.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case OffsetColumn: return RzAddressString(item.offset); case SizeColumn: return RzHexString(item.size); case StatusColumn: return item.status; default: return QVariant(); } default: return QVariant(); } } QVariant GlibcHeapModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); switch (role) { case Qt::DisplayRole: switch (section) { case OffsetColumn: return tr("Offset"); case SizeColumn: return tr("Size"); case StatusColumn: return tr("Status"); default: return QVariant(); } default: return QVariant(); } } void GlibcHeapWidget::onDoubleClicked(const QModelIndex &index) { if (!index.isValid()) { return; } int column = index.column(); if (column == GlibcHeapModel::OffsetColumn) { QString item = index.data().toString(); Core()->seek(item); main->showMemoryWidget(MemoryWidgetType::Hexdump); } } void GlibcHeapWidget::onCurrentChanged(const QModelIndex &current, const QModelIndex &prev) { Q_UNUSED(current) Q_UNUSED(prev) auto currentIndex = viewHeap->selectionModel()->currentIndex(); QString offsetString = currentIndex.sibling(currentIndex.row(), GlibcHeapModel::OffsetColumn) .data() .toString(); addressableItemContextMenu.setTarget(Core()->math(offsetString)); } void GlibcHeapWidget::viewChunkInfo() { auto currentIndex = viewHeap->selectionModel()->currentIndex(); QString offsetString = currentIndex.sibling(currentIndex.row(), GlibcHeapModel::OffsetColumn) .data() .toString(); QString status = currentIndex.sibling(currentIndex.row(), GlibcHeapModel::StatusColumn) .data() .toString(); GlibcHeapInfoDialog heapInfoDialog(Core()->math(offsetString), status, this); heapInfoDialog.exec(); } void GlibcHeapWidget::viewBinInfo() { GlibcHeapBinsDialog heapBinsDialog(modelHeap->arena_addr, main, this); heapBinsDialog.exec(); } void GlibcHeapWidget::viewArenaInfo() { // find the active arena Arena currentArena; for (auto &arena : arenas) { if (arena.offset == modelHeap->arena_addr) { currentArena = arena; break; } } ArenaInfoDialog arenaInfoDialog(currentArena, this); arenaInfoDialog.exec(); }
7,145
C++
.cpp
199
29.648241
98
0.684218
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,559
GraphvizLayout.cpp
rizinorg_cutter/src/widgets/GraphvizLayout.cpp
#include "GraphvizLayout.h" #include <unordered_set> #include <unordered_map> #include <queue> #include <stack> #include <cassert> #include <sstream> #include <iomanip> #include <set> #include <gvc.h> GraphvizLayout::GraphvizLayout(LayoutType lineType, Direction direction) : GraphLayout({}), direction(direction), layoutType(lineType) { } static GraphLayout::GraphEdge::ArrowDirection getArrowDirection(QPointF direction, bool preferVertical) { if (abs(direction.x()) > abs(direction.y()) * (preferVertical ? 3.0 : 1.0)) { if (direction.x() > 0) { return GraphLayout::GraphEdge::Right; } else { return GraphLayout::GraphEdge::Left; } } else { if (direction.y() > 0) { return GraphLayout::GraphEdge::Down; } else { return GraphLayout::GraphEdge::Up; } } } static std::set<std::pair<ut64, ut64>> SelectLoopEdges(const GraphLayout::Graph &graph, ut64 entry) { std::set<std::pair<ut64, ut64>> result; // Run DFS to select backwards/loop edges // 0 - not visited // 1 - in stack // 2 - visited std::unordered_map<ut64, uint8_t> visited; visited.reserve(graph.size()); std::stack<std::pair<ut64, size_t>> stack; auto dfsFragment = [&visited, &graph, &stack, &result](ut64 first) { visited[first] = 1; stack.push({ first, 0 }); while (!stack.empty()) { auto v = stack.top().first; auto edge_index = stack.top().second; auto blockIt = graph.find(v); if (blockIt == graph.end()) { continue; } const auto &block = blockIt->second; if (edge_index < block.edges.size()) { ++stack.top().second; auto target = block.edges[edge_index].target; auto &targetState = visited[target]; if (targetState == 0) { targetState = 1; stack.push({ target, 0 }); } else if (targetState == 1) { result.insert({ v, target }); } } else { stack.pop(); visited[v] = 2; } } }; dfsFragment(entry); for (auto &blockIt : graph) { if (!visited[blockIt.first]) { dfsFragment(blockIt.first); } } return result; } void GraphvizLayout::CalculateLayout(std::unordered_map<ut64, GraphBlock> &blocks, ut64 entry, int &width, int &height) const { // https://gitlab.com/graphviz/graphviz/issues/1441 #define STR(v) const_cast<char *>(v) width = height = 10; GVC_t *gvc = gvContext(); Agraph_t *g = agopen(STR("G"), Agdirected, nullptr); std::unordered_map<ut64, Agnode_t *> nodes; for (const auto &block : blocks) { nodes[block.first] = agnode(g, nullptr, true); } std::vector<std::string> strc; strc.reserve(2 * blocks.size()); std::map<std::pair<ut64, ut64>, Agedge_t *> edges; agsafeset(g, STR("splines"), layoutType == LayoutType::DotOrtho ? STR("ortho") : STR("polyline"), STR("")); switch (direction) { case Direction::LR: agsafeset(g, STR("rankdir"), STR("LR"), STR("")); break; case Direction::TB: agsafeset(g, STR("rankdir"), STR("BT"), STR("")); break; } agsafeset(g, STR("newrank"), STR("true"), STR("")); // graphviz has builtin 72 dpi setting for input that differs from output // it's easier to use 72 everywhere const double dpi = 72.0; agsafeset(g, STR("dpi"), STR("72"), STR("")); auto widhAttr = agattr(g, AGNODE, STR("width"), STR("1")); auto heightAatr = agattr(g, AGNODE, STR("height"), STR("1")); agattr(g, AGNODE, STR("shape"), STR("box")); agattr(g, AGNODE, STR("fixedsize"), STR("true")); auto constraintAttr = agattr(g, AGEDGE, STR("constraint"), STR("1")); std::ostringstream stream; stream.imbue(std::locale::classic()); auto setFloatingPointAttr = [&stream](void *obj, Agsym_t *sym, double value) { stream.str({}); stream << std::fixed << std::setw(4) << value; auto str = stream.str(); agxset(obj, sym, STR(str.c_str())); }; std::set<std::pair<ut64, ut64>> loopEdges = SelectLoopEdges(blocks, entry); for (const auto &blockIt : blocks) { auto u = nodes[blockIt.first]; auto &block = blockIt.second; for (auto &edge : block.edges) { auto v = nodes.find(edge.target); if (v == nodes.end()) { continue; } auto e = agedge(g, u, v->second, nullptr, true); edges[{ blockIt.first, edge.target }] = e; if (loopEdges.find({ blockIt.first, edge.target }) != loopEdges.end()) { agxset(e, constraintAttr, STR("0")); } } setFloatingPointAttr(u, widhAttr, block.width / dpi); setFloatingPointAttr(u, heightAatr, block.height / dpi); } const char *layoutEngine = "dot"; switch (layoutType) { case LayoutType::DotOrtho: case LayoutType::DotPolyline: layoutEngine = "dot"; break; case LayoutType::Sfdp: layoutEngine = "sfdp"; break; case LayoutType::Neato: layoutEngine = "neato"; break; case LayoutType::TwoPi: layoutEngine = "twopi"; break; case LayoutType::Circo: layoutEngine = "circo"; break; } gvLayout(gvc, g, layoutEngine); for (auto &blockIt : blocks) { auto &block = blockIt.second; auto u = nodes[blockIt.first]; auto pos = ND_coord(u); auto w = ND_width(u) * dpi; auto h = ND_height(u) * dpi; block.x = pos.x - w / 2.0; block.y = pos.y - h / 2.0; width = std::max(width, block.x + block.width); height = std::max(height, block.y + block.height); for (auto &edge : block.edges) { auto it = edges.find({ blockIt.first, edge.target }); if (it != edges.end()) { auto e = it->second; if (auto spl = ED_spl(e)) { for (size_t i = 0; i < 1 && i < spl->size; i++) { auto bz = spl->list[i]; edge.polyline.clear(); edge.polyline.reserve(bz.size + 1); for (size_t j = 0; j < bz.size; j++) { edge.polyline.push_back(QPointF(bz.list[j].x, bz.list[j].y)); } QPointF last(0, 0); if (!edge.polyline.empty()) { last = edge.polyline.back(); } if (bz.eflag) { QPointF tip = QPointF(bz.ep.x, bz.ep.y); edge.polyline.push_back(tip); } if (edge.polyline.size() >= 2) { // make sure self loops go from bottom to top if (edge.target == block.entry && edge.polyline.first().y() < edge.polyline.last().y()) { std::reverse(edge.polyline.begin(), edge.polyline.end()); } auto it = std::prev(edge.polyline.end()); QPointF direction = *it; direction -= *(--it); edge.arrow = getArrowDirection(direction, layoutType == LayoutType::DotPolyline); } else { edge.arrow = GraphEdge::Down; } } } } } } gvFreeLayout(gvc, g); agclose(g); gvFreeContext(gvc); #undef STR }
8,076
C++
.cpp
211
27
99
0.509759
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,560
StackWidget.cpp
rizinorg_cutter/src/widgets/StackWidget.cpp
#include "StackWidget.h" #include "ui_StackWidget.h" #include "common/JsonModel.h" #include "common/Helpers.h" #include "dialogs/EditInstructionDialog.h" #include "core/MainWindow.h" #include "QHeaderView" #include "QMenu" StackWidget::StackWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::StackWidget), menuText(this), addressableItemContextMenu(this, main) { ui->setupUi(this); // Setup stack model viewStack->setFont(Config()->getFont()); viewStack->setModel(modelStack); viewStack->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); viewStack->verticalHeader()->hide(); viewStack->setShowGrid(false); viewStack->setSortingEnabled(true); viewStack->setAutoScroll(false); viewStack->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); ui->verticalLayout->addWidget(viewStack); viewStack->setEditTriggers( viewStack->editTriggers() & ~(QAbstractItemView::DoubleClicked | QAbstractItemView::AnyKeyPressed)); editAction = new QAction(tr("Edit stack value..."), this); viewStack->setContextMenuPolicy(Qt::CustomContextMenu); refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(Core(), &CutterCore::refreshAll, this, &StackWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &StackWidget::updateContents); connect(Core(), &CutterCore::stackChanged, this, &StackWidget::updateContents); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(modelStack, StackModel::CommentColumn); }); connect(Config(), &Configuration::fontsUpdated, this, &StackWidget::fontsUpdatedSlot); connect(viewStack, &QAbstractItemView::doubleClicked, this, &StackWidget::onDoubleClicked); connect(viewStack, &QWidget::customContextMenuRequested, this, &StackWidget::customMenuRequested); connect(editAction, &QAction::triggered, this, &StackWidget::editStack); connect(viewStack->selectionModel(), &QItemSelectionModel::currentChanged, this, &StackWidget::onCurrentChanged); addressableItemContextMenu.addAction(editAction); addActions(addressableItemContextMenu.actions()); menuText.setSeparator(true); qhelpers::prependQAction(&menuText, &addressableItemContextMenu); } StackWidget::~StackWidget() = default; void StackWidget::updateContents() { if (!refreshDeferrer->attemptRefresh(nullptr) || Core()->isDebugTaskInProgress()) { return; } setStackGrid(); } void StackWidget::setStackGrid() { modelStack->reload(); viewStack->resizeColumnsToContents(); } void StackWidget::fontsUpdatedSlot() { viewStack->setFont(Config()->getFont()); } void StackWidget::onDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; // Check if we are clicking on the offset or value columns and seek if it is the case int column = index.column(); if (column <= StackModel::ValueColumn) { QString item = index.data().toString(); Core()->seek(item); if (column == StackModel::OffsetColumn) { mainWindow->showMemoryWidget(MemoryWidgetType::Hexdump); } else { Core()->showMemoryWidget(); } } } void StackWidget::customMenuRequested(QPoint pos) { addressableItemContextMenu.exec(viewStack->viewport()->mapToGlobal(pos)); } void StackWidget::editStack() { bool ok; int row = viewStack->selectionModel()->currentIndex().row(); auto model = viewStack->model(); QString offset = model->index(row, StackModel::OffsetColumn).data().toString(); EditInstructionDialog e(EDIT_NONE, this); e.setWindowTitle(tr("Edit stack at %1").arg(offset)); QString oldBytes = model->index(row, StackModel::ValueColumn).data().toString(); e.setInstruction(oldBytes); if (e.exec()) { QString bytes = e.getInstruction(); if (bytes != oldBytes) { Core()->editBytesEndian(offset.toULongLong(&ok, 16), bytes); } } } void StackWidget::onCurrentChanged(const QModelIndex &current, const QModelIndex &previous) { Q_UNUSED(current) Q_UNUSED(previous) auto currentIndex = viewStack->selectionModel()->currentIndex(); QString offsetString; if (currentIndex.column() != StackModel::DescriptionColumn) { offsetString = currentIndex.data().toString(); } else { offsetString = currentIndex.sibling(currentIndex.row(), StackModel::ValueColumn).data().toString(); } RVA offset = Core()->math(offsetString); addressableItemContextMenu.setTarget(offset); if (currentIndex.column() == StackModel::OffsetColumn) { menuText.setText(tr("Stack position")); } else { menuText.setText(tr("Pointed memory")); } } StackModel::StackModel(QObject *parent) : QAbstractTableModel(parent) {} void StackModel::reload() { QList<AddrRefs> stackItems = Core()->getStack(); beginResetModel(); values.clear(); for (const AddrRefs &stackItem : stackItems) { Item item; item.offset = stackItem.addr; item.value = RzAddressString(stackItem.value); if (!stackItem.ref.isNull()) { item.refDesc = Core()->formatRefDesc(stackItem.ref); } values.push_back(item); } endResetModel(); } int StackModel::rowCount(const QModelIndex &) const { return this->values.size(); } int StackModel::columnCount(const QModelIndex &) const { return ColumnCount; } QVariant StackModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= values.count()) return QVariant(); const auto &item = values.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case OffsetColumn: return RzAddressString(item.offset); case ValueColumn: return item.value; case DescriptionColumn: return item.refDesc.ref; case CommentColumn: return Core()->getCommentAt(item.offset); default: return QVariant(); } case Qt::ForegroundRole: switch (index.column()) { case DescriptionColumn: return item.refDesc.refColor; default: return QVariant(); } case StackDescriptionRole: return QVariant::fromValue(item); default: return QVariant(); } } QVariant StackModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); switch (role) { case Qt::DisplayRole: switch (section) { case OffsetColumn: return tr("Offset"); case ValueColumn: return tr("Value"); case DescriptionColumn: return tr("Reference"); case CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } bool StackModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole || index.column() != ValueColumn) { return false; } auto currentData = data(index, StackDescriptionRole); if (!currentData.canConvert<StackModel::Item>()) { return false; } auto currentItem = currentData.value<StackModel::Item>(); Core()->editBytesEndian(currentItem.offset, value.toString()); return true; } Qt::ItemFlags StackModel::flags(const QModelIndex &index) const { switch (index.column()) { case ValueColumn: return QAbstractTableModel::flags(index) | Qt::ItemIsEditable; default: return QAbstractTableModel::flags(index); } }
7,801
C++
.cpp
222
29.306306
100
0.682264
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,561
Dashboard.cpp
rizinorg_cutter/src/widgets/Dashboard.cpp
#include "Dashboard.h" #include "ui_Dashboard.h" #include "common/Helpers.h" #include "common/JsonModel.h" #include "common/TempConfig.h" #include "dialogs/VersionInfoDialog.h" #include "core/MainWindow.h" #include "CutterTreeView.h" #include <QDebug> #include <QJsonArray> #include <QStringList> #include <QJsonObject> #include <QJsonDocument> #include <QFile> #include <QLayoutItem> #include <QString> #include <QMessageBox> #include <QDialog> #include <QTreeWidget> Dashboard::Dashboard(MainWindow *main) : CutterDockWidget(main), ui(new Ui::Dashboard) { ui->setupUi(this); connect(Core(), &CutterCore::refreshAll, this, &Dashboard::updateContents); } Dashboard::~Dashboard() {} void Dashboard::updateContents() { RzCoreLocked core(Core()); int fd = rz_io_fd_get_current(core->io); RzIODesc *desc = rz_io_desc_get(core->io, fd); setPlainText(this->ui->modeEdit, desc ? rz_str_rwx_i(desc->perm & RZ_PERM_RWX) : ""); RzBinFile *bf = rz_bin_cur(core->bin); if (bf) { setPlainText(this->ui->compilationDateEdit, rz_core_bin_get_compile_time(bf)); if (bf->o) { char *relco_buf = sdb_get(bf->o->kv, "elf.relro"); if (RZ_STR_ISNOTEMPTY(relco_buf)) { QString relro = QString(relco_buf).section(QLatin1Char(' '), 0, 0); relro[0] = relro[0].toUpper(); setPlainText(this->ui->relroEdit, relro); } else { setPlainText(this->ui->relroEdit, "N/A"); } } } // Add file hashes, analysis info and libraries RzBinObject *bobj = rz_bin_cur_object(core->bin); const RzBinInfo *binInfo = bobj ? rz_bin_object_get_info(bobj) : nullptr; setPlainText(ui->fileEdit, binInfo ? binInfo->file : ""); setPlainText(ui->formatEdit, binInfo ? binInfo->rclass : ""); setPlainText(ui->typeEdit, binInfo ? binInfo->type : ""); setPlainText(ui->archEdit, binInfo ? binInfo->arch : ""); setPlainText(ui->langEdit, binInfo ? binInfo->lang : ""); setPlainText(ui->classEdit, binInfo ? binInfo->bclass : ""); setPlainText(ui->machineEdit, binInfo ? binInfo->machine : ""); setPlainText(ui->osEdit, binInfo ? binInfo->os : ""); setPlainText(ui->subsysEdit, binInfo ? binInfo->subsystem : ""); setPlainText(ui->compilerEdit, binInfo ? binInfo->compiler : ""); setPlainText(ui->bitsEdit, binInfo ? QString::number(binInfo->bits) : ""); setPlainText(ui->baddrEdit, bf ? RzAddressString(rz_bin_file_get_baddr(bf)) : ""); setPlainText(ui->sizeEdit, bf ? qhelpers::formatBytecount(bf->size) : ""); setPlainText(ui->fdEdit, bf ? QString::number(bf->fd) : ""); // Setting the value of "Endianness" const char *endian = binInfo ? (binInfo->big_endian ? "BE" : "LE") : ""; setPlainText(this->ui->endianEdit, endian); // Setting boolean values setRzBinInfo(binInfo); // Setting the value of "static" int static_value = rz_bin_is_static(core->bin); setPlainText(ui->staticEdit, tr(setBoolText(static_value))); const RzPVector *hashes = bf ? rz_bin_file_compute_hashes(core->bin, bf, UT64_MAX) : nullptr; // Delete hashesWidget if it isn't null to avoid duplicate components if (hashesWidget) { hashesWidget->deleteLater(); } // Define dynamic components to hold the hashes hashesWidget = new QWidget(); QFormLayout *hashesLayout = new QFormLayout; hashesWidget->setLayout(hashesLayout); ui->hashesVerticalLayout->addWidget(hashesWidget); // Add hashes as a pair of Hash Name : Hash Value. if (hashes != nullptr) { for (const auto &hash : CutterPVector<RzBinFileHash>(hashes)) { // Create a bold QString with the hash name uppercased QString label = QString("<b>%1:</b>").arg(QString(hash->type).toUpper()); // Define a Read-Only line edit to display the hash value QLineEdit *hashLineEdit = new QLineEdit(); hashLineEdit->setReadOnly(true); hashLineEdit->setText(hash->hex); // Set cursor position to begining to avoid long hashes (e.g sha256) // to look truncated at the begining hashLineEdit->setCursorPosition(0); // Add both controls to a form layout in a single row hashesLayout->addRow(new QLabel(label), hashLineEdit); } } st64 fcns = rz_list_length(core->analysis->fcns); st64 strs = rz_flag_count(core->flags, "str.*"); st64 syms = rz_flag_count(core->flags, "sym.*"); st64 imps = rz_flag_count(core->flags, "sym.imp.*"); st64 code = rz_core_analysis_code_count(core); st64 covr = rz_core_analysis_coverage_count(core); st64 call = rz_core_analysis_calls_count(core); ut64 xrfs = rz_analysis_xrefs_count(core->analysis); double precentage = (code > 0) ? (covr * 100.0 / code) : 0; setPlainText(ui->functionsLineEdit, QString::number(fcns)); setPlainText(ui->xRefsLineEdit, QString::number(xrfs)); setPlainText(ui->callsLineEdit, QString::number(call)); setPlainText(ui->stringsLineEdit, QString::number(strs)); setPlainText(ui->symbolsLineEdit, QString::number(syms)); setPlainText(ui->importsLineEdit, QString::number(imps)); setPlainText(ui->coverageLineEdit, QString::number(covr) + " bytes"); setPlainText(ui->codeSizeLineEdit, QString::number(code) + " bytes"); setPlainText(ui->percentageLineEdit, QString::number(precentage) + "%"); ui->libraryList->setPlainText(""); const RzPVector *libs = bf ? rz_bin_object_get_libs(bf->o) : nullptr; if (libs) { QString libText; bool first = true; for (const auto &lib : CutterPVector<char>(libs)) { if (!first) { libText.append("\n"); } libText.append(lib); first = false; } ui->libraryList->setPlainText(libText); } // Check if signature info and version info available if (!Core()->getSignatureInfo().size()) { ui->certificateButton->setEnabled(false); } ui->versioninfoButton->setEnabled(Core()->existsFileInfo()); } void Dashboard::on_certificateButton_clicked() { QDialog dialog(this); auto view = new QTreeWidget(&dialog); view->setHeaderLabels({ tr("Key"), tr("Value") }); view->addTopLevelItem(Cutter::jsonTreeWidgetItem(QString("<%1>").arg(tr("root")), Core()->getSignatureInfo())); CutterTreeView::applyCutterStyle(view); view->expandAll(); view->resize(900, 600); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(view->sizePolicy().hasHeightForWidth()); dialog.setSizePolicy(sizePolicy); dialog.setMinimumSize(QSize(900, 600)); dialog.setMaximumSize(QSize(900, 600)); dialog.setSizeGripEnabled(false); dialog.setWindowTitle(tr("Certificates")); dialog.exec(); } void Dashboard::on_versioninfoButton_clicked() { static QDialog *infoDialog = nullptr; if (!infoDialog) { infoDialog = new VersionInfoDialog(this); } if (!infoDialog->isVisible()) { infoDialog->show(); } } /** * @brief Set the text of a QLineEdit. If no text, then "N/A" is set. * @param textBox * @param text */ void Dashboard::setPlainText(QLineEdit *textBox, const QString &text) { if (!text.isEmpty()) { textBox->setText(text); } else { textBox->setText(tr("N/A")); } textBox->setCursorPosition(0); } /** * @brief Setting boolean values of binary information in dashboard * @param RzBinInfo */ void Dashboard::setRzBinInfo(const RzBinInfo *binInfo) { setPlainText(ui->vaEdit, binInfo ? setBoolText(binInfo->has_va) : ""); setPlainText(ui->canaryEdit, binInfo ? setBoolText(binInfo->has_canary) : ""); setPlainText(ui->cryptoEdit, binInfo ? setBoolText(binInfo->has_crypto) : ""); setPlainText(ui->nxEdit, binInfo ? setBoolText(binInfo->has_nx) : ""); setPlainText(ui->picEdit, binInfo ? setBoolText(binInfo->has_pi) : ""); setPlainText(ui->strippedEdit, binInfo ? setBoolText(RZ_BIN_DBG_STRIPPED & binInfo->dbg_info) : ""); setPlainText(ui->relocsEdit, binInfo ? setBoolText(RZ_BIN_DBG_RELOCS & binInfo->dbg_info) : ""); } /** * @brief Set the text of a QLineEdit as True, False * @param boolean value */ const char *Dashboard::setBoolText(bool value) { return value ? "True" : "False"; }
8,556
C++
.cpp
202
36.544554
100
0.662461
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,562
BacktraceWidget.cpp
rizinorg_cutter/src/widgets/BacktraceWidget.cpp
#include "BacktraceWidget.h" #include "ui_BacktraceWidget.h" #include "common/JsonModel.h" #include "QHeaderView" #include "core/MainWindow.h" BacktraceWidget::BacktraceWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::BacktraceWidget) { ui->setupUi(this); // setup backtrace model QString PC = Core()->getRegisterName("PC"); QString SP = Core()->getRegisterName("SP"); modelBacktrace->setHorizontalHeaderItem(0, new QStandardItem(tr("Function"))); modelBacktrace->setHorizontalHeaderItem(1, new QStandardItem(SP)); modelBacktrace->setHorizontalHeaderItem(2, new QStandardItem(PC)); modelBacktrace->setHorizontalHeaderItem(3, new QStandardItem(tr("Description"))); modelBacktrace->setHorizontalHeaderItem(4, new QStandardItem(tr("Frame Size"))); viewBacktrace->setFont(Config()->getFont()); viewBacktrace->setModel(modelBacktrace); viewBacktrace->verticalHeader()->setVisible(false); viewBacktrace->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); ui->verticalLayout->addWidget(viewBacktrace); refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(Core(), &CutterCore::refreshAll, this, &BacktraceWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &BacktraceWidget::updateContents); connect(Config(), &Configuration::fontsUpdated, this, &BacktraceWidget::fontsUpdatedSlot); } BacktraceWidget::~BacktraceWidget() {} void BacktraceWidget::updateContents() { if (!refreshDeferrer->attemptRefresh(nullptr) || Core()->isDebugTaskInProgress()) { return; } setBacktraceGrid(); } void BacktraceWidget::setBacktraceGrid() { RzList *list = rz_core_debug_backtraces(Core()->core()); int i = 0; RzListIter *iter; RzBacktrace *bt; CutterRzListForeach (list, iter, RzBacktrace, bt) { QString funcName = bt->fcn ? bt->fcn->name : ""; QString pc = RzAddressString(bt->frame ? bt->frame->addr : 0); QString sp = RzAddressString(bt->frame ? bt->frame->sp : 0); QString frameSize = QString::number(bt->frame ? bt->frame->size : 0); QString desc = bt->desc; modelBacktrace->setItem(i, 0, new QStandardItem(funcName)); modelBacktrace->setItem(i, 1, new QStandardItem(sp)); modelBacktrace->setItem(i, 2, new QStandardItem(pc)); modelBacktrace->setItem(i, 3, new QStandardItem(desc)); modelBacktrace->setItem(i, 4, new QStandardItem(frameSize)); ++i; } rz_list_free(list); // Remove irrelevant old rows if (modelBacktrace->rowCount() > i) { modelBacktrace->removeRows(i, modelBacktrace->rowCount() - i); } viewBacktrace->setModel(modelBacktrace); viewBacktrace->resizeColumnsToContents(); } void BacktraceWidget::fontsUpdatedSlot() { viewBacktrace->setFont(Config()->getFont()); }
2,892
C++
.cpp
66
38.924242
94
0.716317
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,563
HexdumpWidget.cpp
rizinorg_cutter/src/widgets/HexdumpWidget.cpp
#include "HexdumpWidget.h" #include "ui_HexdumpWidget.h" #include "common/Helpers.h" #include "common/Configuration.h" #include "common/TempConfig.h" #include "common/SyntaxHighlighter.h" #include "core/MainWindow.h" #include <QJsonObject> #include <QJsonArray> #include <QElapsedTimer> #include <QTextDocumentFragment> #include <QMenu> #include <QClipboard> #include <QScrollBar> #include <QInputDialog> #include <QShortcut> HexdumpWidget::HexdumpWidget(MainWindow *main) : MemoryDockWidget(MemoryWidgetType::Hexdump, main), ui(new Ui::HexdumpWidget) { ui->setupUi(this); setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); updateWindowTitle(); ui->copyMD5->setIcon(QIcon(":/img/icons/copy.svg")); ui->copySHA1->setIcon(QIcon(":/img/icons/copy.svg")); ui->copySHA256->setIcon(QIcon(":/img/icons/copy.svg")); ui->copyCRC32->setIcon(QIcon(":/img/icons/copy.svg")); ui->splitter->setChildrenCollapsible(false); QToolButton *closeButton = new QToolButton; QIcon closeIcon = QIcon(":/img/icons/delete.svg"); closeButton->setIcon(closeIcon); closeButton->setAutoRaise(true); ui->hexSideTab_2->setCornerWidget(closeButton); syntaxHighLighter = Config()->createSyntaxHighlighter(ui->hexDisasTextEdit->document()); ui->openSideViewB->hide(); // hide button at startup since side view is visible connect(closeButton, &QToolButton::clicked, this, [this] { showSidePanel(false); }); connect(ui->openSideViewB, &QToolButton::clicked, this, [this] { showSidePanel(true); }); // Set placeholders for the line-edit components QString placeholder = tr("Select bytes to display information"); ui->bytesMD5->setPlaceholderText(placeholder); ui->bytesEntropy->setPlaceholderText(placeholder); ui->bytesSHA1->setPlaceholderText(placeholder); ui->bytesSHA256->setPlaceholderText(placeholder); ui->bytesCRC32->setPlaceholderText(placeholder); ui->hexDisasTextEdit->setPlaceholderText(placeholder); setupFonts(); ui->openSideViewB->setStyleSheet("" "QToolButton {" " border : 0px;" " padding : 0px;" " margin : 0px;" "}" "QToolButton:hover {" " border : 1px solid;" " border-width : 1px;" " border-color : #3daee9" "}"); refreshDeferrer = createReplacingRefreshDeferrer<RVA>( false, [this](const RVA *offset) { refresh(offset ? *offset : RVA_INVALID); }); this->ui->hexTextView->addAction(&syncAction); connect(Config(), &Configuration::fontsUpdated, this, &HexdumpWidget::fontsUpdated); connect(Core(), &CutterCore::refreshAll, this, [this]() { refresh(); }); connect(Core(), &CutterCore::refreshCodeViews, this, [this]() { refresh(); }); connect(Core(), &CutterCore::instructionChanged, this, [this]() { refresh(); }); connect(Core(), &CutterCore::stackChanged, this, [this]() { refresh(); }); connect(Core(), &CutterCore::registersChanged, this, [this]() { refresh(); }); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &HexdumpWidget::onSeekChanged); connect(ui->hexTextView, &HexWidget::positionChanged, this, [this](RVA addr) { if (!sent_seek) { sent_seek = true; seekable->seek(addr); sent_seek = false; } }); connect(ui->hexTextView, &HexWidget::selectionChanged, this, &HexdumpWidget::selectionChanged); connect(ui->hexSideTab_2, &QTabWidget::currentChanged, this, &HexdumpWidget::refreshSelectionInfo); ui->hexTextView->installEventFilter(this); initParsing(); selectHexPreview(); // apply initial offset refresh(seekable->getOffset()); } void HexdumpWidget::onSeekChanged(RVA addr) { if (sent_seek) { sent_seek = false; return; } refresh(addr); } HexdumpWidget::~HexdumpWidget() {} QString HexdumpWidget::getWidgetType() { return "Hexdump"; } void HexdumpWidget::refresh() { refresh(RVA_INVALID); } void HexdumpWidget::refresh(RVA addr) { if (!refreshDeferrer->attemptRefresh(addr == RVA_INVALID ? nullptr : new RVA(addr))) { return; } sent_seek = true; if (addr != RVA_INVALID) { ui->hexTextView->seek(addr); } else { ui->hexTextView->refresh(); refreshSelectionInfo(); } sent_seek = false; } void HexdumpWidget::initParsing() { // Fill the plugins combo for the hexdump sidebar ui->parseTypeComboBox->addItem(tr("Disassembly"), "pda"); ui->parseTypeComboBox->addItem(tr("String"), "pcs"); ui->parseTypeComboBox->addItem(tr("Assembler"), "pca"); ui->parseTypeComboBox->addItem(tr("C bytes"), "pc"); ui->parseTypeComboBox->addItem(tr("C half-words (2 byte)"), "pch"); ui->parseTypeComboBox->addItem(tr("C words (4 byte)"), "pcw"); ui->parseTypeComboBox->addItem(tr("C dwords (8 byte)"), "pcd"); ui->parseTypeComboBox->addItem(tr("Python"), "pcp"); ui->parseTypeComboBox->addItem(tr("JSON"), "pcj"); ui->parseTypeComboBox->addItem(tr("JavaScript"), "pcJ"); ui->parseTypeComboBox->addItem(tr("Yara"), "pcy"); ui->parseArchComboBox->insertItems(0, Core()->getAsmPluginNames()); ui->parseEndianComboBox->setCurrentIndex(Core()->getConfigb("cfg.bigendian") ? 1 : 0); } void HexdumpWidget::selectionChanged(HexWidget::Selection selection) { if (selection.empty) { clearParseWindow(); } else { updateParseWindow(selection.startAddress, selection.endAddress - selection.startAddress + 1); } } void HexdumpWidget::on_parseArchComboBox_currentTextChanged(const QString & /*arg1*/) { refreshSelectionInfo(); } void HexdumpWidget::on_parseBitsComboBox_currentTextChanged(const QString & /*arg1*/) { refreshSelectionInfo(); } void HexdumpWidget::setupFonts() { QFont font = Config()->getFont(); ui->hexDisasTextEdit->setFont(font); ui->hexTextView->setMonospaceFont(font); } void HexdumpWidget::refreshSelectionInfo() { selectionChanged(ui->hexTextView->getSelection()); } void HexdumpWidget::fontsUpdated() { setupFonts(); } void HexdumpWidget::clearParseWindow() { ui->hexDisasTextEdit->setPlainText(""); ui->bytesEntropy->setText(""); ui->bytesMD5->setText(""); ui->bytesSHA1->setText(""); ui->bytesSHA256->setText(""); ui->bytesCRC32->setText(""); } void HexdumpWidget::showSidePanel(bool show) { ui->hexSideTab_2->setVisible(show); ui->openSideViewB->setHidden(show); if (show) { refreshSelectionInfo(); } } QString HexdumpWidget::getWindowTitle() const { return tr("Hexdump"); } void HexdumpWidget::updateParseWindow(RVA start_address, int size) { if (!ui->hexSideTab_2->isVisible()) { return; } if (ui->hexSideTab_2->currentIndex() == 0) { // scope for TempConfig // Get selected combos QString arch = ui->parseArchComboBox->currentText(); QString bits = ui->parseBitsComboBox->currentText(); QString selectedCommand = ui->parseTypeComboBox->currentData().toString(); QString commandResult = ""; bool bigEndian = ui->parseEndianComboBox->currentIndex() == 1; TempConfig tempConfig; tempConfig.set("asm.arch", arch).set("asm.bits", bits).set("cfg.bigendian", bigEndian); ui->hexDisasTextEdit->setPlainText( selectedCommand != "" ? Core()->cmdRawAt( QString("%1 @! %2").arg(selectedCommand).arg(size), start_address) : ""); } else { // Fill the information tab hashes and entropy RzHashSize digest_size = 0; RzCoreLocked core(Core()); ut64 old_offset = core->offset; rz_core_seek(core, start_address, true); ut8 *block = core->block; char *digest = rz_hash_cfg_calculate_small_block_string(core->hash, "md5", block, size, &digest_size, false); ui->bytesMD5->setText(QString(digest)); free(digest); digest = rz_hash_cfg_calculate_small_block_string(core->hash, "sha1", block, size, &digest_size, false); ui->bytesSHA1->setText(QString(digest)); free(digest); digest = rz_hash_cfg_calculate_small_block_string(core->hash, "sha256", block, size, &digest_size, false); ui->bytesSHA256->setText(QString(digest)); free(digest); digest = rz_hash_cfg_calculate_small_block_string(core->hash, "crc32", block, size, &digest_size, false); ui->bytesCRC32->setText(QString(digest)); free(digest); digest = rz_hash_cfg_calculate_small_block_string(core->hash, "entropy", block, size, &digest_size, false); ui->bytesEntropy->setText(QString(digest)); free(digest); rz_core_seek(core, old_offset, true); ui->bytesMD5->setCursorPosition(0); ui->bytesSHA1->setCursorPosition(0); ui->bytesSHA256->setCursorPosition(0); ui->bytesCRC32->setCursorPosition(0); } } void HexdumpWidget::on_parseTypeComboBox_currentTextChanged(const QString &) { QString currentParseTypeText = ui->parseTypeComboBox->currentData().toString(); if (currentParseTypeText == "pda" || currentParseTypeText == "pci") { ui->hexSideFrame_2->show(); } else { ui->hexSideFrame_2->hide(); } refreshSelectionInfo(); } void HexdumpWidget::on_parseEndianComboBox_currentTextChanged(const QString &) { refreshSelectionInfo(); } void HexdumpWidget::on_hexSideTab_2_currentChanged(int /*index*/) { /* if (index == 2) { // Add data to HTML Polar functions graph QFile html(":/html/bar.html"); if(!html.open(QIODevice::ReadOnly)) { QMessageBox::information(0,"error",html.errorString()); } QString code = html.readAll(); html.close(); this->histoWebView->setHtml(code); this->histoWebView->show(); } else { this->histoWebView->hide(); } */ } void HexdumpWidget::resizeEvent(QResizeEvent *event) { // Heuristics to hide sidebar when it hides the content of the hexdump. 600px looks just "okay" // Only applied when widget width is decreased to avoid unwanted behavior if (event->oldSize().width() > event->size().width() && event->size().width() < 600) { showSidePanel(false); } QDockWidget::resizeEvent(event); refresh(); } QWidget *HexdumpWidget::widgetToFocusOnRaise() { return ui->hexTextView; } void HexdumpWidget::on_copyMD5_clicked() { QString md5 = ui->bytesMD5->text(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(md5); Core()->message("MD5 copied to clipboard: " + md5); } void HexdumpWidget::on_copySHA1_clicked() { QString sha1 = ui->bytesSHA1->text(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(sha1); Core()->message("SHA1 copied to clipboard: " + sha1); } void HexdumpWidget::on_copySHA256_clicked() { QString sha256 = ui->bytesSHA256->text(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(sha256); Core()->message("SHA256 copied to clipboard: " + sha256); } void HexdumpWidget::on_copyCRC32_clicked() { QString crc32 = ui->bytesCRC32->text(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(crc32); Core()->message("CRC32 copied to clipboard: " + crc32); } void HexdumpWidget::selectHexPreview() { // Pre-select arch and bits in the hexdump sidebar QString arch = Core()->getConfig("asm.arch"); QString bits = Core()->getConfig("asm.bits"); if (ui->parseArchComboBox->findText(arch) != -1) { ui->parseArchComboBox->setCurrentIndex(ui->parseArchComboBox->findText(arch)); } if (ui->parseBitsComboBox->findText(bits) != -1) { ui->parseBitsComboBox->setCurrentIndex(ui->parseBitsComboBox->findText(bits)); } }
12,543
C++
.cpp
321
32.006231
99
0.642258
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,564
OverviewWidget.cpp
rizinorg_cutter/src/widgets/OverviewWidget.cpp
#include "core/MainWindow.h" #include "OverviewWidget.h" #include "GraphWidget.h" #include "OverviewView.h" OverviewWidget::OverviewWidget(MainWindow *main) : CutterDockWidget(main) { setWindowTitle("Graph Overview"); setObjectName("Graph Overview"); setAllowedAreas(Qt::AllDockWidgetAreas); graphView = new OverviewView(this); setWidget(graphView); targetGraphWidget = nullptr; connect(graphView, &OverviewView::mouseMoved, this, &OverviewWidget::updateTargetView); graphDataRefreshDeferrer = createRefreshDeferrer([this]() { updateGraphData(); }); // Zoom shortcuts QShortcut *shortcut_zoom_in = new QShortcut(QKeySequence(Qt::Key_Plus), this); shortcut_zoom_in->setContext(Qt::WidgetWithChildrenShortcut); connect(shortcut_zoom_in, &QShortcut::activated, this, [this]() { zoomTarget(1); }); QShortcut *shortcut_zoom_out = new QShortcut(QKeySequence(Qt::Key_Minus), this); shortcut_zoom_out->setContext(Qt::WidgetWithChildrenShortcut); connect(shortcut_zoom_out, &QShortcut::activated, this, [this]() { zoomTarget(-1); }); } OverviewWidget::~OverviewWidget() {} void OverviewWidget::resizeEvent(QResizeEvent *event) { graphView->refreshView(); updateRangeRect(); QDockWidget::resizeEvent(event); emit resized(); } void OverviewWidget::showEvent(QShowEvent *event) { CutterDockWidget::showEvent(event); setUserOpened(true); } void OverviewWidget::closeEvent(QCloseEvent *event) { CutterDockWidget::closeEvent(event); setUserOpened(false); } void OverviewWidget::setIsAvailable(bool isAvailable) { if (this->isAvailable == isAvailable) { return; } this->isAvailable = isAvailable; if (!isAvailable) { hide(); } else if (userOpened) { show(); } emit isAvailableChanged(isAvailable); } void OverviewWidget::setUserOpened(bool userOpened) { if (this->userOpened == userOpened) { return; } this->userOpened = userOpened; emit userOpenedChanged(userOpened); } void OverviewWidget::zoomTarget(int d) { if (!targetGraphWidget) { return; } targetGraphWidget->getGraphView()->zoom(QPointF(0.5, 0.5), d); } void OverviewWidget::setTargetGraphWidget(GraphWidget *widget) { if (widget == targetGraphWidget) { return; } if (targetGraphWidget) { disconnect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::viewRefreshed, this, &OverviewWidget::updateGraphData); disconnect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::resized, this, &OverviewWidget::updateRangeRect); disconnect(targetGraphWidget->getGraphView(), &GraphView::viewOffsetChanged, this, &OverviewWidget::updateRangeRect); disconnect(targetGraphWidget->getGraphView(), &GraphView::viewScaleChanged, this, &OverviewWidget::updateRangeRect); disconnect(targetGraphWidget, &GraphWidget::graphClosed, this, &OverviewWidget::targetClosed); } targetGraphWidget = widget; if (targetGraphWidget) { connect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::viewRefreshed, this, &OverviewWidget::updateGraphData); connect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::resized, this, &OverviewWidget::updateRangeRect); connect(targetGraphWidget->getGraphView(), &GraphView::viewOffsetChanged, this, &OverviewWidget::updateRangeRect); connect(targetGraphWidget->getGraphView(), &GraphView::viewScaleChanged, this, &OverviewWidget::updateRangeRect); connect(targetGraphWidget, &GraphWidget::graphClosed, this, &OverviewWidget::targetClosed); } updateGraphData(); updateRangeRect(); setIsAvailable(targetGraphWidget != nullptr); } void OverviewWidget::wheelEvent(QWheelEvent *event) { zoomTarget(event->angleDelta().y() / 90); graphView->centreRect(); } void OverviewWidget::targetClosed() { setTargetGraphWidget(nullptr); } void OverviewWidget::updateTargetView() { if (!targetGraphWidget) { return; } qreal curScale = graphView->getViewScale(); int rectx = graphView->getRangeRect().x(); int recty = graphView->getRangeRect().y(); int overview_offset_x = graphView->getViewOffset().x(); int overview_offset_y = graphView->getViewOffset().y(); QPoint newOffset; newOffset.rx() = rectx / curScale + overview_offset_x; newOffset.ry() = recty / curScale + overview_offset_y; targetGraphWidget->getGraphView()->setViewOffset(newOffset); targetGraphWidget->getGraphView()->viewport()->update(); } void OverviewWidget::updateGraphData() { if (!graphDataRefreshDeferrer->attemptRefresh(nullptr)) { return; } if (targetGraphWidget && !targetGraphWidget->getGraphView()->isGraphEmpty()) { graphView->currentFcnAddr = targetGraphWidget->getGraphView()->currentFcnAddr; auto &mainGraphView = *targetGraphWidget->getGraphView(); graphView->setData(mainGraphView.getWidth(), mainGraphView.getHeight(), mainGraphView.getBlocks(), mainGraphView.getEdgeConfigurations()); } else { graphView->currentFcnAddr = RVA_INVALID; graphView->setData(0, 0, {}, {}); graphView->setRangeRect(QRectF(0, 0, 0, 0)); } } void OverviewWidget::updateRangeRect() { if (targetGraphWidget) { qreal curScale = graphView->getViewScale(); qreal baseScale = targetGraphWidget->getGraphView()->getViewScale(); qreal w = targetGraphWidget->getGraphView()->viewport()->width() * curScale / baseScale; qreal h = targetGraphWidget->getGraphView()->viewport()->height() * curScale / baseScale; int graph_offset_x = targetGraphWidget->getGraphView()->getViewOffset().x(); int graph_offset_y = targetGraphWidget->getGraphView()->getViewOffset().y(); int overview_offset_x = graphView->getViewOffset().x(); int overview_offset_y = graphView->getViewOffset().y(); int rangeRectX = graph_offset_x * curScale - overview_offset_x * curScale; int rangeRectY = graph_offset_y * curScale - overview_offset_y * curScale; graphView->setRangeRect(QRectF(rangeRectX, rangeRectY, w, h)); } else { graphView->setRangeRect(QRectF(0, 0, 0, 0)); } }
6,437
C++
.cpp
160
34.4125
99
0.701438
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,565
DebugActions.cpp
rizinorg_cutter/src/widgets/DebugActions.cpp
#include "DebugActions.h" #include "core/MainWindow.h" #include "dialogs/AttachProcDialog.h" #include "dialogs/NativeDebugDialog.h" #include "common/Configuration.h" #include "common/Helpers.h" #include <QPainter> #include <QMenu> #include <QList> #include <QFileInfo> #include <QToolBar> #include <QToolButton> #include <QSettings> DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : QObject(main), main(main) { setObjectName("DebugActions"); // setIconSize(QSize(16, 16)); // define icons QIcon startEmulIcon = QIcon(":/img/icons/play_light_emul.svg"); QIcon startAttachIcon = QIcon(":/img/icons/play_light_attach.svg"); QIcon startRemoteIcon = QIcon(":/img/icons/play_light_remote.svg"); QIcon continueBackIcon = QIcon(":/img/icons/reverse_continue.svg"); QIcon stepBackIcon = QIcon(":/img/icons/reverse_step.svg"); startTraceIcon = QIcon(":/img/icons/start_trace.svg"); stopTraceIcon = QIcon(":/img/icons/stop_trace.svg"); stopIcon = QIcon(":/img/icons/media-stop_light.svg"); restartIcon = QIcon(":/img/icons/spin_light.svg"); detachIcon = QIcon(":/img/icons/detach_debugger.svg"); startDebugIcon = QIcon(":/img/icons/play_light_debug.svg"); continueIcon = QIcon(":/img/icons/media-skip-forward_light.svg"); suspendIcon = QIcon(":/img/icons/media-suspend_light.svg"); // define action labels QString startEmulLabel = tr("Start emulation"); QString startAttachLabel = tr("Attach to process"); QString startRemoteLabel = tr("Connect to a remote debugger"); QString stopDebugLabel = tr("Stop debug"); QString stopEmulLabel = tr("Stop emulation"); QString restartEmulLabel = tr("Restart emulation"); QString continueUMLabel = tr("Continue until main"); QString continueUCLabel = tr("Continue until call"); QString continueUSLabel = tr("Continue until syscall"); QString continueBackLabel = tr("Continue backwards"); QString stepLabel = tr("Step"); QString stepOverLabel = tr("Step over"); QString stepOutLabel = tr("Step out"); QString stepBackLabel = tr("Step backwards"); startTraceLabel = tr("Start trace session"); stopTraceLabel = tr("Stop trace session"); suspendLabel = tr("Suspend the process"); continueLabel = tr("Continue"); restartDebugLabel = tr("Restart program"); startDebugLabel = tr("Start debug"); // define actions actionStart = new QAction(startDebugIcon, startDebugLabel, this); actionStart->setShortcut(QKeySequence(Qt::Key_F9)); actionStartEmul = new QAction(startEmulIcon, startEmulLabel, this); actionAttach = new QAction(startAttachIcon, startAttachLabel, this); actionStartRemote = new QAction(startRemoteIcon, startRemoteLabel, this); actionStop = new QAction(stopIcon, stopDebugLabel, this); actionContinue = new QAction(continueIcon, continueLabel, this); actionContinue->setShortcut(QKeySequence(Qt::Key_F5)); actionContinueUntilMain = new QAction(continueUMLabel, this); actionContinueUntilCall = new QAction(continueUCLabel, this); actionContinueUntilSyscall = new QAction(continueUSLabel, this); actionContinueBack = new QAction(continueBackIcon, continueBackLabel, this); actionContinueBack->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F5)); actionStep = new QAction(stepLabel, this); actionStep->setShortcut(QKeySequence(Qt::Key_F7)); actionStepOver = new QAction(stepOverLabel, this); actionStepOver->setShortcut(QKeySequence(Qt::Key_F8)); actionStepOut = new QAction(stepOutLabel, this); actionStepOut->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F8)); actionStepBack = new QAction(stepBackIcon, stepBackLabel, this); actionStepBack->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F7)); actionTrace = new QAction(startTraceIcon, startTraceLabel, this); QToolButton *startButton = new QToolButton; startButton->setPopupMode(QToolButton::MenuButtonPopup); connect(startButton, &QToolButton::triggered, startButton, &QToolButton::setDefaultAction); QMenu *startMenu = new QMenu(startButton); startMenu->addAction(actionStart); startMenu->addAction(actionStartEmul); startMenu->addAction(actionAttach); startMenu->addAction(actionStartRemote); startButton->setDefaultAction(actionStart); startButton->setMenu(startMenu); continueUntilButton = new QToolButton; continueUntilButton->setPopupMode(QToolButton::MenuButtonPopup); connect(continueUntilButton, &QToolButton::triggered, continueUntilButton, &QToolButton::setDefaultAction); QMenu *continueUntilMenu = new QMenu(continueUntilButton); continueUntilMenu->addAction(actionContinueUntilMain); continueUntilMenu->addAction(actionContinueUntilCall); continueUntilMenu->addAction(actionContinueUntilSyscall); continueUntilButton->setMenu(continueUntilMenu); continueUntilButton->setDefaultAction(actionContinueUntilMain); // define toolbar widgets and actions toolBar->addWidget(startButton); toolBar->addAction(actionContinue); toolBar->addAction(actionStop); actionAllContinues = toolBar->addWidget(continueUntilButton); toolBar->addAction(actionStepOver); toolBar->addAction(actionStep); toolBar->addAction(actionStepOut); toolBar->addAction(actionStepBack); toolBar->addAction(actionContinueBack); toolBar->addAction(actionTrace); allActions = { actionStop, actionAllContinues, actionContinue, actionContinueUntilCall, actionContinueUntilMain, actionContinueUntilSyscall, actionStep, actionStepOut, actionStepOver, actionContinueBack, actionStepBack, actionTrace }; // Hide all actions setAllActionsVisible(false); // Toggle all buttons except reverse step/continue which are handled separately and // restart, suspend(=continue) and stop since those are necessary to avoid freezing toggleActions = { actionStepOver, actionStep, actionStepOut, actionContinueUntilMain, actionContinueUntilCall, actionContinueUntilSyscall, actionTrace }; toggleConnectionActions = { actionAttach, actionStartRemote }; reverseActions = { actionStepBack, actionContinueBack }; connect(Core(), &CutterCore::debugProcessFinished, this, [=](int pid) { QMessageBox msgBox; msgBox.setText(tr("Debugged process exited (") + QString::number(pid) + ")"); msgBox.exec(); }); connect(Core(), &CutterCore::debugTaskStateChanged, this, [=]() { bool disableToolbar = Core()->isDebugTaskInProgress(); if (Core()->currentlyDebugging) { for (QAction *a : toggleActions) { a->setDisabled(disableToolbar); } // Suspend should only be available when other icons are disabled if (disableToolbar) { actionContinue->setText(suspendLabel); actionContinue->setIcon(suspendIcon); } else { actionContinue->setText(continueLabel); actionContinue->setIcon(continueIcon); } for (QAction *a : reverseActions) { a->setVisible(Core()->currentlyTracing); a->setDisabled(disableToolbar); } } else { for (QAction *a : toggleConnectionActions) { a->setDisabled(disableToolbar); } } }); connect(actionStop, &QAction::triggered, Core(), &CutterCore::stopDebug); connect(actionStop, &QAction::triggered, [=]() { actionStart->setVisible(true); actionStartEmul->setVisible(true); actionAttach->setVisible(true); actionStartRemote->setVisible(true); actionStop->setText(stopDebugLabel); actionStop->setIcon(stopIcon); actionStart->setText(startDebugLabel); actionStart->setIcon(startDebugIcon); actionStartEmul->setText(startEmulLabel); actionStartEmul->setIcon(startEmulIcon); continueUntilButton->setDefaultAction(actionContinueUntilMain); setAllActionsVisible(false); }); connect(actionStep, &QAction::triggered, Core(), &CutterCore::stepDebug); connect(actionStepBack, &QAction::triggered, Core(), &CutterCore::stepBackDebug); connect(actionStart, &QAction::triggered, this, &DebugActions::startDebug); connect(actionAttach, &QAction::triggered, this, &DebugActions::attachProcessDialog); connect(actionStartRemote, &QAction::triggered, this, &DebugActions::attachRemoteDialog); connect(Core(), &CutterCore::attachedRemote, this, &DebugActions::onAttachedRemoteDebugger); connect(actionStartEmul, &QAction::triggered, Core(), &CutterCore::startEmulation); connect(actionStartEmul, &QAction::triggered, [=]() { setAllActionsVisible(true); actionStart->setVisible(false); actionAttach->setVisible(false); actionStartRemote->setVisible(false); actionContinueUntilMain->setVisible(false); actionStepOut->setVisible(false); continueUntilButton->setDefaultAction(actionContinueUntilSyscall); actionStartEmul->setText(restartEmulLabel); actionStartEmul->setIcon(restartIcon); actionStop->setText(stopEmulLabel); // Reverse debug actions aren't visible until we start tracing for (QAction *a : reverseActions) { a->setVisible(false); } }); connect(actionStepOver, &QAction::triggered, Core(), &CutterCore::stepOverDebug); connect(actionStepOut, &QAction::triggered, Core(), &CutterCore::stepOutDebug); connect(actionContinueUntilMain, &QAction::triggered, this, &DebugActions::continueUntilMain); connect(actionContinueUntilCall, &QAction::triggered, Core(), &CutterCore::continueUntilCall); connect(actionContinueUntilSyscall, &QAction::triggered, Core(), &CutterCore::continueUntilSyscall); connect(actionContinueBack, &QAction::triggered, Core(), &CutterCore::continueBackDebug); connect(actionContinue, &QAction::triggered, Core(), [=]() { // Switch between continue and suspend depending on the debugger's state if (Core()->isDebugTaskInProgress()) { Core()->suspendDebug(); } else { Core()->continueDebug(); } }); connect(actionTrace, &QAction::triggered, Core(), [=]() { // Check if a debug session was created to switch between start and stop if (!Core()->currentlyTracing) { Core()->startTraceSession(); actionTrace->setText(stopTraceLabel); actionTrace->setIcon(stopTraceIcon); } else { Core()->stopTraceSession(); actionTrace->setText(startTraceLabel); actionTrace->setIcon(startTraceIcon); } }); connect(Config(), &Configuration::interfaceThemeChanged, this, &DebugActions::chooseThemeIcons); chooseThemeIcons(); } void DebugActions::setButtonVisibleIfMainExists() { RzCoreLocked core(Core()->core()); // if main is not a flag we hide the continue until main button if (!rz_flag_get(Core()->core()->flags, "sym.main") && !rz_flag_get(Core()->core()->flags, "main")) { actionContinueUntilMain->setVisible(false); continueUntilButton->setDefaultAction(actionContinueUntilCall); } } void DebugActions::showDebugWarning() { if (!acceptedDebugWarning) { acceptedDebugWarning = true; QMessageBox msgBox; msgBox.setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); msgBox.setText(tr("Debug is currently in beta.\n") + tr("If you encounter any problems or have suggestions, please submit an " "issue to https://github.com/rizinorg/cutter/issues")); msgBox.exec(); } } void DebugActions::continueUntilMain() { RzCoreLocked core(Core()->core()); RzFlagItem *main_flag = rz_flag_get(Core()->core()->flags, "sym.main"); if (!main_flag) { main_flag = rz_flag_get(Core()->core()->flags, "main"); if (!main_flag) { return; } } Core()->continueUntilDebug(main_flag->offset); } void DebugActions::attachRemoteDebugger() { QString stopAttachLabel = tr("Detach from process"); // Hide unwanted buttons setAllActionsVisible(true); actionStart->setVisible(false); actionStartRemote->setVisible(false); actionStartEmul->setVisible(false); actionStop->setText(stopAttachLabel); } void DebugActions::onAttachedRemoteDebugger(bool successfully) { // TODO(#2829): Investigate why this is happening if (remoteDialog == nullptr) return; if (!successfully) { QMessageBox msgBox; msgBox.setText(tr("Error connecting.")); msgBox.exec(); attachRemoteDialog(); } else { QSettings settings; QStringList ips = settings.value("recentIpList").toStringList(); ips.removeAll(remoteDialog->getUri()); ips.prepend(remoteDialog->getUri()); settings.setValue("recentIpList", ips); delete remoteDialog; remoteDialog = nullptr; attachRemoteDebugger(); } } void DebugActions::attachRemoteDialog() { showDebugWarning(); if (!remoteDialog) { remoteDialog = new RemoteDebugDialog(main); } QMessageBox msgBox; bool success = false; while (!success) { success = true; if (remoteDialog->exec()) { if (!remoteDialog->validate()) { success = false; continue; } Core()->attachRemote(remoteDialog->getUri()); } } } void DebugActions::attachProcessDialog() { showDebugWarning(); AttachProcDialog dialog(main); bool success = false; while (!success) { success = true; if (dialog.exec()) { int pid = dialog.getPID(); if (pid >= 0) { attachProcess(pid); } else { success = false; QMessageBox msgBox; msgBox.setText(tr("Error attaching. No process selected!")); msgBox.exec(); } } } } void DebugActions::attachProcess(int pid) { QString stopAttachLabel = tr("Detach from process"); // hide unwanted buttons setAllActionsVisible(true); actionStart->setVisible(false); actionStartRemote->setVisible(false); actionStartEmul->setVisible(false); actionStop->setText(stopAttachLabel); actionStop->setIcon(detachIcon); // attach Core()->attachDebug(pid); } void DebugActions::startDebug() { // check if file is executable before starting debug QString filename = Core()->getConfig("file.path"); QFileInfo info(filename); if (!Core()->currentlyDebugging && !info.isExecutable()) { QMessageBox msgBox; msgBox.setText(tr("File '%1' does not have executable permissions.").arg(filename)); msgBox.exec(); return; } showDebugWarning(); NativeDebugDialog dialog(main); dialog.setArgs(Core()->getConfig("dbg.args")); QString args; if (dialog.exec()) { args = dialog.getArgs(); } else { return; } // Update dbg.args with the new args Core()->setConfig("dbg.args", args); setAllActionsVisible(true); actionAttach->setVisible(false); actionStartRemote->setVisible(false); actionStartEmul->setVisible(false); actionStart->setText(restartDebugLabel); actionStart->setIcon(restartIcon); setButtonVisibleIfMainExists(); // Reverse debug actions aren't visible until we start tracing for (QAction *a : reverseActions) { a->setVisible(false); } actionTrace->setText(startTraceLabel); actionTrace->setIcon(startTraceIcon); Core()->startDebug(); } void DebugActions::setAllActionsVisible(bool visible) { for (QAction *action : allActions) { action->setVisible(visible); } } /** * @brief When theme changed, change icons which have a special version for the theme. */ void DebugActions::chooseThemeIcons() { // List of QActions which have alternative icons in different themes const QList<QPair<void *, QString>> kSupportedIconsNames { { actionStep, QStringLiteral("step_into.svg") }, { actionStepOver, QStringLiteral("step_over.svg") }, { actionStepOut, QStringLiteral("step_out.svg") }, { actionContinueUntilMain, QStringLiteral("continue_until_main.svg") }, { actionContinueUntilCall, QStringLiteral("continue_until_call.svg") }, { actionContinueUntilSyscall, QStringLiteral("continue_until_syscall.svg") }, }; // Set the correct icon for the QAction qhelpers::setThemeIcons(kSupportedIconsNames, [](void *obj, const QIcon &icon) { static_cast<QAction *>(obj)->setIcon(icon); }); }
17,210
C++
.cpp
407
35.04914
100
0.680769
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,566
DecompilerWidget.cpp
rizinorg_cutter/src/widgets/DecompilerWidget.cpp
#include "DecompilerWidget.h" #include "ui_DecompilerWidget.h" #include "menus/DecompilerContextMenu.h" #include "common/Configuration.h" #include "common/Helpers.h" #include "common/TempConfig.h" #include "common/SelectionHighlight.h" #include "common/Decompiler.h" #include "common/CutterSeekable.h" #include "core/MainWindow.h" #include "common/DecompilerHighlighter.h" #include <QTextEdit> #include <QPlainTextEdit> #include <QTextBlock> #include <QClipboard> #include <QObject> #include <QTextBlockUserData> #include <QScrollBar> #include <QAbstractSlider> DecompilerWidget::DecompilerWidget(MainWindow *main) : MemoryDockWidget(MemoryWidgetType::Decompiler, main), mCtxMenu(new DecompilerContextMenu(this, main)), ui(new Ui::DecompilerWidget), decompilerBusy(false), seekFromCursor(false), historyPos(0), previousFunctionAddr(RVA_INVALID), decompiledFunctionAddr(RVA_INVALID), code(Decompiler::makeWarning(tr("Choose an offset and refresh to get decompiled code")), &rz_annotated_code_free) { ui->setupUi(this); setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); updateWindowTitle(); setHighlighter(Config()->isDecompilerAnnotationHighlighterEnabled()); // Event filter to intercept double click and right click in the textbox ui->textEdit->viewport()->installEventFilter(this); setupFonts(); colorsUpdatedSlot(); connect(Config(), &Configuration::fontsUpdated, this, &DecompilerWidget::fontsUpdatedSlot); connect(Config(), &Configuration::colorsUpdated, this, &DecompilerWidget::colorsUpdatedSlot); connect(Core(), &CutterCore::registersChanged, this, &DecompilerWidget::highlightPC); connect(mCtxMenu, &DecompilerContextMenu::copy, this, &DecompilerWidget::copy); refreshDeferrer = createRefreshDeferrer([this]() { doRefresh(); }); auto decompilers = Core()->getDecompilers(); QString selectedDecompilerId = Config()->getSelectedDecompiler(); if (selectedDecompilerId.isEmpty()) { // If no decompiler was previously chosen. set rz-ghidra as default decompiler selectedDecompilerId = "ghidra"; } for (Decompiler *dec : decompilers) { ui->decompilerComboBox->addItem(dec->getName(), dec->getId()); if (dec->getId() == selectedDecompilerId) { ui->decompilerComboBox->setCurrentIndex(ui->decompilerComboBox->count() - 1); } } decompilerSelectionEnabled = decompilers.size() > 1; ui->decompilerComboBox->setEnabled(decompilerSelectionEnabled); if (decompilers.isEmpty()) { ui->textEdit->setPlainText(tr("No Decompiler available.")); } connect(ui->decompilerComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &DecompilerWidget::decompilerSelected); connectCursorPositionChanged(true); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &DecompilerWidget::seekChanged); ui->textEdit->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->textEdit, &QWidget::customContextMenuRequested, this, &DecompilerWidget::showDecompilerContextMenu); connect(Core(), &CutterCore::breakpointsChanged, this, &DecompilerWidget::updateBreakpoints); mCtxMenu->addSeparator(); mCtxMenu->addAction(&syncAction); addActions(mCtxMenu->actions()); ui->progressLabel->setVisible(false); doRefresh(); connect(Core(), &CutterCore::refreshAll, this, &DecompilerWidget::doRefresh); connect(Core(), &CutterCore::functionRenamed, this, &DecompilerWidget::doRefresh); connect(Core(), &CutterCore::varsChanged, this, &DecompilerWidget::doRefresh); connect(Core(), &CutterCore::functionsChanged, this, &DecompilerWidget::doRefresh); connect(Core(), &CutterCore::flagsChanged, this, &DecompilerWidget::doRefresh); connect(Core(), &CutterCore::globalVarsChanged, this, &DecompilerWidget::doRefresh); connect(Core(), &CutterCore::commentsChanged, this, &DecompilerWidget::refreshIfChanged); connect(Core(), &CutterCore::instructionChanged, this, &DecompilerWidget::refreshIfChanged); connect(Core(), &CutterCore::refreshCodeViews, this, &DecompilerWidget::doRefresh); // Esc to seek backward QAction *seekPrevAction = new QAction(this); seekPrevAction->setShortcut(Qt::Key_Escape); seekPrevAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); addAction(seekPrevAction); connect(seekPrevAction, &QAction::triggered, seekable, &CutterSeekable::seekPrev); } DecompilerWidget::~DecompilerWidget() = default; QString DecompilerWidget::getWidgetType() { return "DecompilerWidget"; } Decompiler *DecompilerWidget::getCurrentDecompiler() { return Core()->getDecompilerById(ui->decompilerComboBox->currentData().toString()); } ut64 DecompilerWidget::findReference(size_t pos) { size_t closestPos = SIZE_MAX; ut64 closestOffset = RVA_INVALID; void *iter; rz_vector_foreach(&code->annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (!(annotation->type == RZ_CODE_ANNOTATION_TYPE_GLOBAL_VARIABLE) || annotation->start > pos || annotation->end <= pos) { continue; } if (closestPos != SIZE_MAX && closestPos >= annotation->start) { continue; } closestPos = annotation->start; closestOffset = annotation->reference.offset; } return closestOffset; } ut64 DecompilerWidget::offsetForPosition(size_t pos) { size_t closestPos = SIZE_MAX; ut64 closestOffset = mCtxMenu->getFirstOffsetInLine(); void *iter; rz_vector_foreach(&code->annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (!(annotation->type == RZ_CODE_ANNOTATION_TYPE_OFFSET) || annotation->start > pos || annotation->end <= pos) { continue; } if (closestPos != SIZE_MAX && closestPos >= annotation->start) { continue; } closestPos = annotation->start; closestOffset = annotation->offset.offset; } return closestOffset; } size_t DecompilerWidget::positionForOffset(ut64 offset) { size_t closestPos = SIZE_MAX; ut64 closestOffset = UT64_MAX; void *iter; rz_vector_foreach(&code->annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type != RZ_CODE_ANNOTATION_TYPE_OFFSET || annotation->offset.offset > offset) { continue; } if (closestOffset != UT64_MAX && closestOffset >= annotation->offset.offset) { continue; } closestPos = annotation->start; closestOffset = annotation->offset.offset; } return closestPos; } void DecompilerWidget::updateBreakpoints(RVA addr) { if (!addressInRange(addr)) { return; } setInfoForBreakpoints(); QTextCursor cursor = ui->textEdit->textCursor(); cursor.select(QTextCursor::Document); cursor.setCharFormat(QTextCharFormat()); cursor.setBlockFormat(QTextBlockFormat()); ui->textEdit->setExtraSelections({}); highlightPC(); highlightBreakpoints(); updateSelection(); } void DecompilerWidget::setInfoForBreakpoints() { if (mCtxMenu->getIsTogglingBreakpoints()) { return; } // Get the range of the line QTextCursor cursorForLine = ui->textEdit->textCursor(); cursorForLine.movePosition(QTextCursor::StartOfLine); size_t startPos = cursorForLine.position(); cursorForLine.movePosition(QTextCursor::EndOfLine); size_t endPos = cursorForLine.position(); gatherBreakpointInfo(*code, startPos, endPos); } void DecompilerWidget::gatherBreakpointInfo(RzAnnotatedCode &codeDecompiled, size_t startPos, size_t endPos) { RVA firstOffset = RVA_MAX; void *iter; rz_vector_foreach(&codeDecompiled.annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type != RZ_CODE_ANNOTATION_TYPE_OFFSET) { continue; } if ((startPos <= annotation->start && annotation->start < endPos) || (startPos < annotation->end && annotation->end < endPos)) { firstOffset = (annotation->offset.offset < firstOffset) ? annotation->offset.offset : firstOffset; } } mCtxMenu->setFirstOffsetInLine(firstOffset); QList<RVA> functionBreakpoints = Core()->getBreakpointsInFunction(decompiledFunctionAddr); QVector<RVA> offsetList; for (RVA bpOffset : functionBreakpoints) { size_t pos = positionForOffset(bpOffset); if (startPos <= pos && pos <= endPos) { offsetList.push_back(bpOffset); } } std::sort(offsetList.begin(), offsetList.end()); mCtxMenu->setAvailableBreakpoints(offsetList); } void DecompilerWidget::refreshIfChanged(RVA addr) { if (addressInRange(addr)) { doRefresh(); } } void DecompilerWidget::doRefresh() { RVA addr = seekable->getOffset(); if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } if (ui->decompilerComboBox->currentIndex() < 0) { return; } Decompiler *dec = getCurrentDecompiler(); if (!dec) { return; } // Disabling decompiler selection combo box and making progress label visible ahead of // decompilation. ui->progressLabel->setVisible(true); ui->decompilerComboBox->setEnabled(false); if (dec->isRunning()) { if (!decompilerBusy) { connect(dec, &Decompiler::finished, this, &DecompilerWidget::doRefresh); } return; } disconnect(dec, &Decompiler::finished, this, &DecompilerWidget::doRefresh); // Clear all selections since we just refreshed ui->textEdit->setExtraSelections({}); previousFunctionAddr = decompiledFunctionAddr; decompiledFunctionAddr = Core()->getFunctionStart(addr); updateWindowTitle(); if (decompiledFunctionAddr == RVA_INVALID) { // No function was found, so making the progress label invisible and enabling // the decompiler selection combo box as we are not waiting for any decompilation to finish. ui->progressLabel->setVisible(false); ui->decompilerComboBox->setEnabled(true); setCode(Decompiler::makeWarning( tr("No function found at this offset. " "Seek to a function or define one in order to decompile it."))); return; } mCtxMenu->setDecompiledFunctionAddress(decompiledFunctionAddr); connect(dec, &Decompiler::finished, this, &DecompilerWidget::decompilationFinished); decompilerBusy = true; dec->decompileAt(addr); } void DecompilerWidget::refreshDecompiler() { doRefresh(); setInfoForBreakpoints(); } QTextCursor DecompilerWidget::getCursorForAddress(RVA addr) { size_t pos = positionForOffset(addr); if (pos == SIZE_MAX || pos == 0) { return QTextCursor(); } QTextCursor cursor = ui->textEdit->textCursor(); cursor.setPosition(pos); return cursor; } void DecompilerWidget::decompilationFinished(RzAnnotatedCode *codeDecompiled) { ui->progressLabel->setVisible(false); ui->decompilerComboBox->setEnabled(decompilerSelectionEnabled); mCtxMenu->setAnnotationHere(nullptr); setCode(codeDecompiled); Decompiler *dec = getCurrentDecompiler(); QObject::disconnect(dec, &Decompiler::finished, this, &DecompilerWidget::decompilationFinished); decompilerBusy = false; if (ui->textEdit->toPlainText().isEmpty()) { setCode(Decompiler::makeWarning(tr("Cannot decompile at this address (Not a function?)"))); lowestOffsetInCode = RVA_MAX; highestOffsetInCode = 0; return; } else { updateCursorPosition(); highlightPC(); highlightBreakpoints(); lowestOffsetInCode = RVA_MAX; highestOffsetInCode = 0; void *iter; rz_vector_foreach(&code->annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type == RZ_CODE_ANNOTATION_TYPE_OFFSET) { if (lowestOffsetInCode > annotation->offset.offset) { lowestOffsetInCode = annotation->offset.offset; } if (highestOffsetInCode < annotation->offset.offset) { highestOffsetInCode = annotation->offset.offset; } } } } if (!scrollHistory.empty()) { ui->textEdit->horizontalScrollBar()->setSliderPosition(scrollHistory[historyPos].first); ui->textEdit->verticalScrollBar()->setSliderPosition(scrollHistory[historyPos].second); } } void DecompilerWidget::setAnnotationsAtCursor(size_t pos) { RzCodeAnnotation *annotationAtPos = nullptr; void *iter; rz_vector_foreach(&this->code->annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type == RZ_CODE_ANNOTATION_TYPE_OFFSET || annotation->type == RZ_CODE_ANNOTATION_TYPE_SYNTAX_HIGHLIGHT || annotation->start > pos || annotation->end <= pos) { continue; } annotationAtPos = annotation; break; } mCtxMenu->setAnnotationHere(annotationAtPos); } void DecompilerWidget::decompilerSelected() { Config()->setSelectedDecompiler(ui->decompilerComboBox->currentData().toString()); doRefresh(); } void DecompilerWidget::connectCursorPositionChanged(bool connectPositionChange) { if (!connectPositionChange) { disconnect(ui->textEdit, &QPlainTextEdit::cursorPositionChanged, this, &DecompilerWidget::cursorPositionChanged); } else { connect(ui->textEdit, &QPlainTextEdit::cursorPositionChanged, this, &DecompilerWidget::cursorPositionChanged); } } void DecompilerWidget::cursorPositionChanged() { // Do not perform seeks along with the cursor while selecting multiple lines if (!ui->textEdit->textCursor().selectedText().isEmpty()) { return; } size_t pos = ui->textEdit->textCursor().position(); setAnnotationsAtCursor(pos); setInfoForBreakpoints(); RVA offset = offsetForPosition(pos); if (offset != RVA_INVALID && offset != seekable->getOffset()) { seekFromCursor = true; seekable->seek(offset); mCtxMenu->setOffset(offset); seekFromCursor = false; } updateSelection(); } void DecompilerWidget::seekChanged(RVA /* addr */, CutterCore::SeekHistoryType type) { if (seekFromCursor) { return; } if (!scrollHistory.empty()) { // History is empty upon init. scrollHistory[historyPos] = { ui->textEdit->horizontalScrollBar()->sliderPosition(), ui->textEdit->verticalScrollBar()->sliderPosition() }; } if (type == CutterCore::SeekHistoryType::New) { // Erase previous history past this point. if (scrollHistory.size() > historyPos + 1) { scrollHistory.erase(scrollHistory.begin() + historyPos + 1, scrollHistory.end()); } scrollHistory.push_back({ 0, 0 }); historyPos = scrollHistory.size() - 1; } else if (type == CutterCore::SeekHistoryType::Undo) { --historyPos; } else if (type == CutterCore::SeekHistoryType::Redo) { ++historyPos; } RVA fcnAddr = Core()->getFunctionStart(seekable->getOffset()); if (fcnAddr == RVA_INVALID || fcnAddr != decompiledFunctionAddr) { doRefresh(); return; } updateCursorPosition(); } void DecompilerWidget::updateCursorPosition() { RVA offset = seekable->getOffset(); size_t pos = positionForOffset(offset); if (pos == SIZE_MAX) { return; } mCtxMenu->setOffset(offset); connectCursorPositionChanged(false); QTextCursor cursor = ui->textEdit->textCursor(); cursor.setPosition(pos); ui->textEdit->setTextCursor(cursor); updateSelection(); connectCursorPositionChanged(true); } void DecompilerWidget::setupFonts() { ui->textEdit->setFont(Config()->getFont()); } void DecompilerWidget::updateSelection() { QList<QTextEdit::ExtraSelection> extraSelections; // Highlight the current line QTextCursor cursor = ui->textEdit->textCursor(); extraSelections.append(createLineHighlightSelection(cursor)); // Highlight all the words in the document same as the current one cursor.select(QTextCursor::WordUnderCursor); QString searchString = cursor.selectedText(); mCtxMenu->setCurHighlightedWord(searchString); extraSelections.append(createSameWordsSelections(ui->textEdit, searchString)); ui->textEdit->setExtraSelections(extraSelections); // Highlight PC after updating the selected line highlightPC(); } QString DecompilerWidget::getWindowTitle() const { RzAnalysisFunction *fcn = Core()->functionAt(decompiledFunctionAddr); QString windowTitle = tr("Decompiler"); if (fcn != NULL) { windowTitle += " (" + QString(fcn->name) + ")"; } else { windowTitle += " (Empty)"; } return windowTitle; } void DecompilerWidget::fontsUpdatedSlot() { setupFonts(); } void DecompilerWidget::colorsUpdatedSlot() { bool useAnotationHiglighter = Config()->isDecompilerAnnotationHighlighterEnabled(); if (useAnotationHiglighter != usingAnnotationBasedHighlighting) { setHighlighter(useAnotationHiglighter); } } void DecompilerWidget::showDecompilerContextMenu(const QPoint &pt) { mCtxMenu->exec(ui->textEdit->mapToGlobal(pt)); } void DecompilerWidget::seekToReference() { size_t pos = ui->textEdit->textCursor().position(); RVA offset = findReference(pos); if (offset != RVA_INVALID) { seekable->seek(offset); } seekable->seekToReference(offsetForPosition(pos)); } bool DecompilerWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::MouseButtonDblClick && (obj == ui->textEdit || obj == ui->textEdit->viewport())) { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); ui->textEdit->setTextCursor(ui->textEdit->cursorForPosition(mouseEvent->pos())); seekToReference(); return true; } if (event->type() == QEvent::MouseButtonPress && (obj == ui->textEdit || obj == ui->textEdit->viewport())) { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); if (mouseEvent->button() == Qt::RightButton && !ui->textEdit->textCursor().hasSelection()) { ui->textEdit->setTextCursor(ui->textEdit->cursorForPosition(mouseEvent->pos())); return true; } } return MemoryDockWidget::eventFilter(obj, event); } void DecompilerWidget::highlightPC() { RVA PCAddress = Core()->getProgramCounterValue(); if (PCAddress == RVA_INVALID || (Core()->getFunctionStart(PCAddress) != decompiledFunctionAddr)) { return; } QTextCursor cursor = getCursorForAddress(PCAddress); if (!cursor.isNull()) { colorLine(createLineHighlightPC(cursor)); } } void DecompilerWidget::highlightBreakpoints() { QList<RVA> functionBreakpoints = Core()->getBreakpointsInFunction(decompiledFunctionAddr); QTextCursor cursor; for (RVA &bp : functionBreakpoints) { if (bp == RVA_INVALID) { continue; } cursor = getCursorForAddress(bp); if (!cursor.isNull()) { // Use a Block formatting since these lines are not updated frequently as selections and // PC QTextBlockFormat f; f.setBackground(ConfigColor("gui.breakpoint_background")); cursor.setBlockFormat(f); } } } bool DecompilerWidget::colorLine(QTextEdit::ExtraSelection extraSelection) { QList<QTextEdit::ExtraSelection> extraSelections = ui->textEdit->extraSelections(); extraSelections.append(extraSelection); ui->textEdit->setExtraSelections(extraSelections); return true; } void DecompilerWidget::copy() { if (ui->textEdit->textCursor().hasSelection()) { ui->textEdit->copy(); } else { QTextCursor cursor = ui->textEdit->textCursor(); QClipboard *clipboard = QApplication::clipboard(); cursor.select(QTextCursor::WordUnderCursor); if (!cursor.selectedText().isEmpty()) { clipboard->setText(cursor.selectedText()); } else { cursor.select(QTextCursor::LineUnderCursor); clipboard->setText(cursor.selectedText()); } } } bool DecompilerWidget::addressInRange(RVA addr) { if (lowestOffsetInCode <= addr && addr <= highestOffsetInCode) { return true; } return false; } /** * Convert annotation ranges from byte offsets in utf8 used by RzAnnotated code to QString QChars * used by QString and Qt text editor. * @param code - RzAnnotated code with annotations that need to be modified * @return Decompiled code */ static QString remapAnnotationOffsetsToQString(RzAnnotatedCode &code) { QByteArray bytes(code.code); std::vector<size_t> offsets; offsets.reserve(bytes.size()); char c; for (size_t off = 0; c = code.code[off], c; off++) { if ((c & 0xc0) == 0x80) { continue; } offsets.push_back(off); } auto mapPos = [&](size_t pos) { auto it = std::upper_bound(offsets.begin(), offsets.end(), pos); if (it != offsets.begin()) { --it; } return it - offsets.begin(); }; void *iter; rz_vector_foreach(&code.annotations, iter) { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; annotation->start = mapPos(annotation->start); annotation->end = mapPos(annotation->end); } return QString::fromUtf8(code.code); } void DecompilerWidget::setCode(RzAnnotatedCode *code) { connectCursorPositionChanged(false); if (auto highlighter = qobject_cast<DecompilerHighlighter *>(syntaxHighlighter.get())) { highlighter->setAnnotations(code); } this->code.reset(code); QString text = remapAnnotationOffsetsToQString(*this->code); this->ui->textEdit->setPlainText(text); connectCursorPositionChanged(true); syntaxHighlighter->rehighlight(); } void DecompilerWidget::setHighlighter(bool annotationBasedHighlighter) { usingAnnotationBasedHighlighting = annotationBasedHighlighter; if (usingAnnotationBasedHighlighting) { syntaxHighlighter.reset(new DecompilerHighlighter()); static_cast<DecompilerHighlighter *>(syntaxHighlighter.get())->setAnnotations(code.get()); } else { syntaxHighlighter.reset(Config()->createSyntaxHighlighter(nullptr)); } syntaxHighlighter->setDocument(ui->textEdit->document()); }
23,024
C++
.cpp
604
32.019868
100
0.687735
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,567
RegistersWidget.cpp
rizinorg_cutter/src/widgets/RegistersWidget.cpp
#include "RegistersWidget.h" #include "ui_RegistersWidget.h" #include "common/JsonModel.h" #include "core/MainWindow.h" #include <QCollator> #include <QLabel> #include <QLineEdit> RegistersWidget::RegistersWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::RegistersWidget), addressContextMenu(this, main) { ui->setupUi(this); // setup register layout registerLayout->setVerticalSpacing(0); registerLayout->setAlignment(Qt::AlignLeft | Qt::AlignTop); ui->verticalLayout->addLayout(registerLayout); refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(Core(), &CutterCore::refreshAll, this, &RegistersWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &RegistersWidget::updateContents); // Hide shortcuts because there is no way of selecting an item and triger them for (auto &action : addressContextMenu.actions()) { action->setShortcut(QKeySequence()); // setShortcutVisibleInContextMenu(false) doesn't work } } RegistersWidget::~RegistersWidget() = default; void RegistersWidget::updateContents() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } setRegisterGrid(); } void RegistersWidget::setRegisterGrid() { int i = 0; int col = 0; QString regValue; QLabel *registerLabel; QLineEdit *registerEditValue; const auto registerRefs = Core()->getRegisterRefValues(); registerLen = registerRefs.size(); for (auto &reg : registerRefs) { regValue = reg.value; // check if we already filled this grid space with label/value if (!registerLayout->itemAtPosition(i, col)) { registerLabel = new QLabel; registerLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); registerLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); registerLabel->setMaximumWidth(60); registerLabel->setStyleSheet("font-weight: bold; font-family: mono;"); registerEditValue = new QLineEdit; registerEditValue->setMaximumWidth(140); registerEditValue->setFont(Config()->getFont()); registerLabel->setContextMenuPolicy(Qt::CustomContextMenu); connect(registerLabel, &QWidget::customContextMenuRequested, this, [this, registerEditValue, registerLabel](QPoint p) { openContextMenu(registerLabel->mapToGlobal(p), registerEditValue->text()); }); registerEditValue->setContextMenuPolicy(Qt::CustomContextMenu); connect(registerEditValue, &QWidget::customContextMenuRequested, this, [this, registerEditValue](QPoint p) { openContextMenu(registerEditValue->mapToGlobal(p), registerEditValue->text()); }); // add label and register value to grid registerLayout->addWidget(registerLabel, i, col); registerLayout->addWidget(registerEditValue, i, col + 1); connect(registerEditValue, &QLineEdit::editingFinished, [=]() { QString regNameString = registerLabel->text(); QString regValueString = registerEditValue->text(); Core()->setRegister(regNameString, regValueString); }); } else { QWidget *regNameWidget = registerLayout->itemAtPosition(i, col)->widget(); QWidget *regValueWidget = registerLayout->itemAtPosition(i, col + 1)->widget(); registerLabel = qobject_cast<QLabel *>(regNameWidget); registerEditValue = qobject_cast<QLineEdit *>(regValueWidget); } // decide to highlight QLine Box in case of change of register value if (regValue != registerEditValue->text() && !registerEditValue->text().isEmpty()) { registerEditValue->setStyleSheet("border: 1px solid green;"); } else { // reset stylesheet registerEditValue->setStyleSheet(""); } // define register label and value registerLabel->setText(reg.name); registerLabel->setToolTip(reg.ref); registerEditValue->setToolTip(reg.ref); registerEditValue->setPlaceholderText(regValue); registerEditValue->setText(regValue); i++; // decide if we should change column if (i >= (registerLen + numCols - 1) / numCols) { i = 0; col += 2; } } } void RegistersWidget::openContextMenu(QPoint point, QString address) { addressContextMenu.setTarget(address.toULongLong(nullptr, 16)); addressContextMenu.exec(point); }
4,722
C++
.cpp
104
36.5
98
0.659427
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,568
HeadersWidget.cpp
rizinorg_cutter/src/widgets/HeadersWidget.cpp
#include "HeadersWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" HeadersModel::HeadersModel(QList<HeaderDescription> *headers, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), headers(headers) { } int HeadersModel::rowCount(const QModelIndex &) const { return headers->count(); } int HeadersModel::columnCount(const QModelIndex &) const { return HeadersModel::ColumnCount; } QVariant HeadersModel::data(const QModelIndex &index, int role) const { if (index.row() >= headers->count()) return QVariant(); const HeaderDescription &header = headers->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case OffsetColumn: return RzAddressString(header.vaddr); case NameColumn: return header.name; case ValueColumn: return header.value; case CommentColumn: return Core()->getCommentAt(header.vaddr); default: return QVariant(); } case HeaderDescriptionRole: return QVariant::fromValue(header); default: return QVariant(); } } QVariant HeadersModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case OffsetColumn: return tr("Offset"); case NameColumn: return tr("Name"); case ValueColumn: return tr("Value"); case CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA HeadersModel::address(const QModelIndex &index) const { const HeaderDescription &header = headers->at(index.row()); return header.vaddr; } QString HeadersModel::name(const QModelIndex &index) const { const HeaderDescription &header = headers->at(index.row()); return header.name; } HeadersProxyModel::HeadersProxyModel(HeadersModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { } bool HeadersProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); HeaderDescription item = index.data(HeadersModel::HeaderDescriptionRole).value<HeaderDescription>(); return qhelpers::filterStringContains(item.name, this); } bool HeadersProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { HeaderDescription leftHeader = left.data(HeadersModel::HeaderDescriptionRole).value<HeaderDescription>(); HeaderDescription rightHeader = right.data(HeadersModel::HeaderDescriptionRole).value<HeaderDescription>(); switch (left.column()) { case HeadersModel::OffsetColumn: return leftHeader.vaddr < rightHeader.vaddr; case HeadersModel::NameColumn: return leftHeader.name < rightHeader.name; case HeadersModel::ValueColumn: return leftHeader.value < rightHeader.value; case HeadersModel::CommentColumn: return Core()->getCommentAt(leftHeader.vaddr) < Core()->getCommentAt(rightHeader.vaddr); default: break; } return leftHeader.vaddr < rightHeader.vaddr; } HeadersWidget::HeadersWidget(MainWindow *main) : ListDockWidget(main) { setWindowTitle(tr("Headers")); setObjectName("HeadersWidget"); headersModel = new HeadersModel(&headers, this); headersProxyModel = new HeadersProxyModel(headersModel, this); setModels(headersProxyModel); ui->treeView->sortByColumn(HeadersModel::OffsetColumn, Qt::AscendingOrder); ui->quickFilterView->closeFilter(); showCount(false); connect(Core(), &CutterCore::codeRebased, this, &HeadersWidget::refreshHeaders); connect(Core(), &CutterCore::refreshAll, this, &HeadersWidget::refreshHeaders); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(headersModel, HeadersModel::CommentColumn); }); } HeadersWidget::~HeadersWidget() {} void HeadersWidget::refreshHeaders() { headersModel->beginResetModel(); headers = Core()->getAllHeaders(); headersModel->endResetModel(); ui->treeView->resizeColumnToContents(0); ui->treeView->resizeColumnToContents(1); }
4,379
C++
.cpp
126
29.269841
98
0.70794
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,569
CutterDockWidget.cpp
rizinorg_cutter/src/widgets/CutterDockWidget.cpp
#include "CutterDockWidget.h" #include "core/MainWindow.h" #include <QEvent> #include <QShortcut> CutterDockWidget::CutterDockWidget(MainWindow *parent, QAction *) : CutterDockWidget(parent) {} CutterDockWidget::CutterDockWidget(MainWindow *parent) : QDockWidget(parent), mainWindow(parent) { // Install event filter to catch redraw widgets when needed installEventFilter(this); updateIsVisibleToUser(); connect(toggleViewAction(), &QAction::triggered, this, &QWidget::raise); } CutterDockWidget::~CutterDockWidget() = default; bool CutterDockWidget::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn || event->type() == QEvent::ZOrderChange || event->type() == QEvent::Paint || event->type() == QEvent::Close || event->type() == QEvent::Show || event->type() == QEvent::Hide) { updateIsVisibleToUser(); } return QDockWidget::eventFilter(object, event); } QVariantMap CutterDockWidget::serializeViewProprties() { return {}; } void CutterDockWidget::deserializeViewProperties(const QVariantMap &) {} void CutterDockWidget::ignoreVisibilityStatus(bool ignore) { this->ignoreVisibility = ignore; updateIsVisibleToUser(); } void CutterDockWidget::raiseMemoryWidget() { show(); raise(); widgetToFocusOnRaise()->setFocus(Qt::FocusReason::TabFocusReason); } void CutterDockWidget::toggleDockWidget(bool show) { if (!show) { this->hide(); } else { this->show(); this->raise(); } } QWidget *CutterDockWidget::widgetToFocusOnRaise() { return this; } void CutterDockWidget::updateIsVisibleToUser() { // Check if the user can actually see the widget. bool visibleToUser = isVisible() && !visibleRegion().isEmpty() && !ignoreVisibility; if (visibleToUser == isVisibleToUserCurrent) { return; } isVisibleToUserCurrent = visibleToUser; if (isVisibleToUserCurrent) { emit becameVisibleToUser(); } } void CutterDockWidget::closeEvent(QCloseEvent *event) { QDockWidget::closeEvent(event); if (isTransient) { if (mainWindow) { mainWindow->removeWidget(this); } // remove parent, otherwise dock layout may still decide to use this widget which is about // to be deleted setParent(nullptr); deleteLater(); } emit closed(); } QString CutterDockWidget::getDockNumber() { auto name = this->objectName(); if (name.contains(';')) { auto parts = name.split(';'); if (parts.size() >= 2) { return parts[1]; } } return QString(); }
2,640
C++
.cpp
88
25.534091
98
0.688363
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,570
QuickFilterView.cpp
rizinorg_cutter/src/widgets/QuickFilterView.cpp
#include "QuickFilterView.h" #include "ui_QuickFilterView.h" QuickFilterView::QuickFilterView(QWidget *parent, bool defaultOn) : QWidget(parent), ui(new Ui::QuickFilterView()) { ui->setupUi(this); debounceTimer = new QTimer(this); debounceTimer->setSingleShot(true); connect(ui->closeFilterButton, &QAbstractButton::clicked, this, &QuickFilterView::closeFilter); connect(debounceTimer, &QTimer::timeout, this, [this]() { emit filterTextChanged(ui->filterLineEdit->text()); }); connect(ui->filterLineEdit, &QLineEdit::textChanged, this, [this]() { debounceTimer->start(150); }); if (!defaultOn) { closeFilter(); } } QuickFilterView::~QuickFilterView() {} void QuickFilterView::showFilter() { show(); ui->filterLineEdit->setFocus(); } void QuickFilterView::clearFilter() { if (ui->filterLineEdit->text().isEmpty()) { closeFilter(); } else { ui->filterLineEdit->setText(""); } } void QuickFilterView::closeFilter() { ui->filterLineEdit->setText(""); hide(); emit filterClosed(); }
1,105
C++
.cpp
37
25.432432
99
0.680227
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,571
StringsWidget.cpp
rizinorg_cutter/src/widgets/StringsWidget.cpp
#include "StringsWidget.h" #include "ui_StringsWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "WidgetShortcuts.h" #include <QClipboard> #include <QMenu> #include <QModelIndex> #include <QShortcut> StringsModel::StringsModel(QList<StringDescription> *strings, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), strings(strings) { } int StringsModel::rowCount(const QModelIndex &) const { return strings->count(); } int StringsModel::columnCount(const QModelIndex &) const { return StringsModel::ColumnCount; } QVariant StringsModel::data(const QModelIndex &index, int role) const { if (index.row() >= strings->count()) return QVariant(); const StringDescription &str = strings->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case StringsModel::OffsetColumn: return RzAddressString(str.vaddr); case StringsModel::StringColumn: return str.string; case StringsModel::TypeColumn: return str.type.toUpper(); case StringsModel::LengthColumn: return QString::number(str.length); case StringsModel::SizeColumn: return QString::number(str.size); case StringsModel::SectionColumn: return str.section; case StringsModel::CommentColumn: return Core()->getCommentAt(str.vaddr); default: return QVariant(); } case StringDescriptionRole: return QVariant::fromValue(str); default: return QVariant(); } } QVariant StringsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case StringsModel::OffsetColumn: return tr("Address"); case StringsModel::StringColumn: return tr("String"); case StringsModel::TypeColumn: return tr("Type"); case StringsModel::LengthColumn: return tr("Length"); case StringsModel::SizeColumn: return tr("Size"); case StringsModel::SectionColumn: return tr("Section"); case StringsModel::CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA StringsModel::address(const QModelIndex &index) const { const StringDescription &str = strings->at(index.row()); return str.vaddr; } const StringDescription *StringsModel::description(const QModelIndex &index) const { return &strings->at(index.row()); } StringsProxyModel::StringsProxyModel(StringsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } void StringsProxyModel::setSelectedSection(QString section) { selectedSection = section; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) invalidateFilter(); #else invalidateRowsFilter(); #endif } bool StringsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); StringDescription str = index.data(StringsModel::StringDescriptionRole).value<StringDescription>(); if (selectedSection.isEmpty()) { return qhelpers::filterStringContains(str.string, this); } else { return selectedSection == str.section && qhelpers::filterStringContains(str.string, this); } } bool StringsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto model = static_cast<StringsModel *>(sourceModel()); auto leftStr = model->description(left); auto rightStr = model->description(right); switch (left.column()) { case StringsModel::OffsetColumn: return leftStr->vaddr < rightStr->vaddr; case StringsModel::StringColumn: // sort by string return leftStr->string < rightStr->string; case StringsModel::TypeColumn: // sort by type return leftStr->type < rightStr->type; case StringsModel::SizeColumn: // sort by size return leftStr->size < rightStr->size; case StringsModel::LengthColumn: // sort by length return leftStr->length < rightStr->length; case StringsModel::SectionColumn: return leftStr->section < rightStr->section; case StringsModel::CommentColumn: return Core()->getCommentAt(leftStr->vaddr) < Core()->getCommentAt(rightStr->vaddr); default: break; } // fallback return leftStr->vaddr < rightStr->vaddr; } StringsWidget::StringsWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::StringsWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); ui->quickFilterView->setLabelText(tr("Section:")); // Add Status Bar footer tree->addStatusBar(ui->verticalLayout); qhelpers::setVerticalScrollMode(ui->stringsTreeView); // Shift-F12 to toggle strings window QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["StringsWidget"], main); connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(ui->actionCopy_String, &QAction::triggered, this, &StringsWidget::on_actionCopy); ui->actionFilter->setShortcut(QKeySequence::Find); ui->stringsTreeView->setContextMenuPolicy(Qt::CustomContextMenu); model = new StringsModel(&strings, this); proxyModel = new StringsProxyModel(model, this); ui->stringsTreeView->setMainWindow(main); ui->stringsTreeView->setModel(proxyModel); ui->stringsTreeView->sortByColumn(-1, Qt::AscendingOrder); // auto menu = ui->stringsTreeView->getItemContextMenu(); menu->addAction(ui->actionCopy_String); connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, proxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, [this] { tree->showItemsNumber(proxyModel->rowCount()); }); QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, this, [this]() { ui->quickFilterView->clearFilter(); ui->stringsTreeView->setFocus(); }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(Core(), &CutterCore::refreshAll, this, &StringsWidget::refreshStrings); connect(Core(), &CutterCore::codeRebased, this, &StringsWidget::refreshStrings); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(model, StringsModel::CommentColumn); }); connect(ui->quickFilterView->comboBox(), &QComboBox::currentTextChanged, this, [this]() { proxyModel->setSelectedSection(ui->quickFilterView->comboBox()->currentData().toString()); tree->showItemsNumber(proxyModel->rowCount()); }); auto header = ui->stringsTreeView->header(); header->setSectionResizeMode(QHeaderView::ResizeMode::ResizeToContents); header->setSectionResizeMode(StringsModel::StringColumn, QHeaderView::ResizeMode::Stretch); header->setStretchLastSection(false); header->setResizeContentsPrecision(256); } StringsWidget::~StringsWidget() {} void StringsWidget::refreshStrings() { if (task) { task->wait(); } task = QSharedPointer<StringsTask>(new StringsTask()); connect(task.data(), &StringsTask::stringSearchFinished, this, &StringsWidget::stringSearchFinished); Core()->getAsyncTaskManager()->start(task); refreshSectionCombo(); } void StringsWidget::refreshSectionCombo() { QComboBox *combo = ui->quickFilterView->comboBox(); combo->clear(); combo->addItem(tr("(all)")); for (const QString &section : Core()->getSectionList()) { combo->addItem(section, section); } proxyModel->setSelectedSection(QString()); } void StringsWidget::stringSearchFinished(const QList<StringDescription> &strings) { model->beginResetModel(); this->strings = strings; model->endResetModel(); tree->showItemsNumber(proxyModel->rowCount()); task.clear(); } void StringsWidget::on_actionCopy() { QModelIndex current_item = ui->stringsTreeView->currentIndex(); int row = current_item.row(); QModelIndex index; index = ui->stringsTreeView->model()->index(row, 1); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(index.data().toString()); }
8,866
C++
.cpp
228
33.276316
98
0.706903
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,572
ClassesWidget.cpp
rizinorg_cutter/src/widgets/ClassesWidget.cpp
#include "ClassesWidget.h" #include "core/MainWindow.h" #include "ui_ListDockWidget.h" #include "common/Helpers.h" #include "common/SvgIconEngine.h" #include "dialogs/EditMethodDialog.h" #include <QList> #include <QMenu> #include <QMouseEvent> #include <QInputDialog> #include <QShortcut> #include <QComboBox> QVariant ClassesModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case NAME: return tr("Name"); case REAL_NAME: return tr("Real Name"); case TYPE: return tr("Type"); case OFFSET: return tr("Offset"); case VTABLE: return tr("VTable"); default: return QVariant(); } default: return QVariant(); } } RVA ClassesModel::address(const QModelIndex &index) const { QVariant v = data(index, OffsetRole); return v.isValid() ? v.toULongLong() : RVA_INVALID; } QString ClassesModel::name(const QModelIndex &index) const { return data(index, NameRole).toString(); } BinClassesModel::BinClassesModel(QObject *parent) : ClassesModel(parent) {} void BinClassesModel::setClasses(const QList<BinClassDescription> &classes) { beginResetModel(); this->classes = classes; endResetModel(); } QModelIndex BinClassesModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid()) { return createIndex(row, column, (quintptr)0); // root function nodes have id = 0 } return createIndex(row, column, (quintptr)parent.row() + 1); // sub-nodes have id = class index + 1 } QModelIndex BinClassesModel::parent(const QModelIndex &index) const { if (!index.isValid()) { return {}; } if (index.internalId() == 0) { // root function node return {}; } else { // sub-node return this->index((int)(index.internalId() - 1), 0); } } int BinClassesModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { // root return classes.count(); } if (parent.internalId() == 0) { // methods/fields const BinClassDescription *cls = &classes.at(parent.row()); return cls->baseClasses.length() + cls->methods.length() + cls->fields.length(); } return 0; // below methods/fields } int BinClassesModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant BinClassesModel::data(const QModelIndex &index, int role) const { const BinClassDescription *cls; const BinClassMethodDescription *meth = nullptr; const BinClassFieldDescription *field = nullptr; const BinClassBaseClassDescription *base = nullptr; if (index.internalId() == 0) { // class row if (index.row() >= classes.count()) { return QVariant(); } cls = &classes.at(index.row()); } else { // method/field/base row cls = &classes.at(static_cast<int>(index.internalId() - 1)); if (index.row() >= cls->baseClasses.length() + cls->methods.length() + cls->fields.length()) { return QVariant(); } if (index.row() < cls->baseClasses.length()) { base = &cls->baseClasses[index.row()]; } else if (index.row() - cls->baseClasses.length() < cls->methods.length()) { meth = &cls->methods[index.row() - cls->baseClasses.length()]; } else { field = &cls->fields[index.row() - cls->baseClasses.length() - cls->methods.length()]; } } if (meth) { switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return meth->name; case TYPE: return tr("method"); case OFFSET: return meth->addr == RVA_INVALID ? QString() : RzAddressString(meth->addr); case VTABLE: return meth->vtableOffset < 0 ? QString() : QString("+%1").arg(meth->vtableOffset); default: return QVariant(); } case OffsetRole: return QVariant::fromValue(meth->addr); case NameRole: return meth->name; case TypeRole: return QVariant::fromValue(RowType::Method); default: return QVariant(); } } else if (field) { switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return field->name; case TYPE: return tr("field"); case OFFSET: return field->addr == RVA_INVALID ? QString() : RzAddressString(field->addr); default: return QVariant(); } case OffsetRole: return QVariant::fromValue(field->addr); case NameRole: return field->name; case TypeRole: return QVariant::fromValue(RowType::Field); default: return QVariant(); } } else if (base) { switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return base->name; case TYPE: return tr("base class"); case OFFSET: return QString("+%1").arg(base->offset); default: return QVariant(); } case NameRole: return base->name; case TypeRole: return QVariant::fromValue(RowType::Base); default: return QVariant(); } } else { switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return cls->name; case TYPE: return tr("class"); case OFFSET: return cls->addr == RVA_INVALID ? QString() : RzAddressString(cls->addr); case VTABLE: return cls->vtableAddr == RVA_INVALID ? QString() : RzAddressString(cls->vtableAddr); default: return QVariant(); } case OffsetRole: return QVariant::fromValue(cls->addr); case NameRole: return cls->name; case TypeRole: return QVariant::fromValue(RowType::Class); default: return QVariant(); } } } AnalysisClassesModel::AnalysisClassesModel(CutterDockWidget *parent) : ClassesModel(parent), attrs(new QMap<QString, QVector<Attribute>>) { // Just use a simple refresh deferrer. If an event was triggered in the background, simply // refresh everything later. refreshDeferrer = parent->createRefreshDeferrer([this]() { this->refreshAll(); }); connect(Core(), &CutterCore::refreshAll, this, &AnalysisClassesModel::refreshAll); connect(Core(), &CutterCore::codeRebased, this, &AnalysisClassesModel::refreshAll); connect(Core(), &CutterCore::classNew, this, &AnalysisClassesModel::classNew); connect(Core(), &CutterCore::classDeleted, this, &AnalysisClassesModel::classDeleted); connect(Core(), &CutterCore::classRenamed, this, &AnalysisClassesModel::classRenamed); connect(Core(), &CutterCore::classAttrsChanged, this, &AnalysisClassesModel::classAttrsChanged); refreshAll(); } void AnalysisClassesModel::refreshAll() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } beginResetModel(); attrs->clear(); classes = Core()->getAllAnalysisClasses(true); // must be sorted endResetModel(); } void AnalysisClassesModel::classNew(const QString &cls) { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } // find the destination position using binary search and add the row auto it = std::lower_bound(classes.begin(), classes.end(), cls); int index = it - classes.begin(); beginInsertRows(QModelIndex(), index, index); classes.insert(it, cls); endInsertRows(); } void AnalysisClassesModel::classDeleted(const QString &cls) { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } // find the position using binary search and remove the row auto it = std::lower_bound(classes.begin(), classes.end(), cls); if (it == classes.end() || *it != cls) { return; } int index = it - classes.begin(); beginRemoveRows(QModelIndex(), index, index); classes.erase(it); endRemoveRows(); } void AnalysisClassesModel::classRenamed(const QString &oldName, const QString &newName) { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } auto oldIt = std::lower_bound(classes.begin(), classes.end(), oldName); if (oldIt == classes.end() || *oldIt != oldName) { return; } auto newIt = std::lower_bound(classes.begin(), classes.end(), newName); int oldRow = oldIt - classes.begin(); int newRow = newIt - classes.begin(); // oldRow == newRow means the name stayed the same. // oldRow == newRow - 1 means the name changed, but the row stays the same. if (oldRow != newRow && oldRow != newRow - 1) { beginMoveRows(QModelIndex(), oldRow, oldRow, QModelIndex(), newRow); classes.erase(oldIt); // iterators are invalid now, so we calculate the new position from the rows. if (oldRow < newRow) { // if we move down, we need to account for the removed old element above. newRow--; } classes.insert(newRow, newName); endMoveRows(); } else if (oldRow == newRow - 1) { // class name changed, but not the row newRow--; classes[newRow] = newName; } emit dataChanged(index(newRow, 0), index(newRow, 0)); } void AnalysisClassesModel::classAttrsChanged(const QString &cls) { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } auto it = std::lower_bound(classes.begin(), classes.end(), cls); if (it == classes.end() || *it != cls) { return; } QPersistentModelIndex persistentIndex = QPersistentModelIndex(index(it - classes.begin(), 0)); layoutAboutToBeChanged({ persistentIndex }); attrs->remove(cls); layoutChanged({ persistentIndex }); } const QVector<AnalysisClassesModel::Attribute> & AnalysisClassesModel::getAttrs(const QString &cls) const { auto it = attrs->find(cls); if (it != attrs->end()) { return it.value(); } QVector<AnalysisClassesModel::Attribute> clsAttrs; QList<AnalysisBaseClassDescription> bases = Core()->getAnalysisClassBaseClasses(cls); QList<AnalysisMethodDescription> meths = Core()->getAnalysisClassMethods(cls); QList<AnalysisVTableDescription> vtables = Core()->getAnalysisClassVTables(cls); clsAttrs.reserve(bases.size() + meths.size() + vtables.size()); for (const AnalysisBaseClassDescription &base : bases) { clsAttrs.push_back(Attribute(Attribute::Type::Base, QVariant::fromValue(base))); } for (const AnalysisVTableDescription &vtable : vtables) { clsAttrs.push_back(Attribute(Attribute::Type::VTable, QVariant::fromValue(vtable))); } for (const AnalysisMethodDescription &meth : meths) { clsAttrs.push_back(Attribute(Attribute::Type::Method, QVariant::fromValue(meth))); } return attrs->insert(cls, clsAttrs).value(); } QModelIndex AnalysisClassesModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid()) { return createIndex(row, column, (quintptr)0); // root function nodes have id = 0 } return createIndex(row, column, (quintptr)parent.row() + 1); // sub-nodes have id = class index + 1 } QModelIndex AnalysisClassesModel::parent(const QModelIndex &index) const { if (!index.isValid()) { return {}; } if (index.internalId() == 0) { // root function node return {}; } else { // sub-node return this->index((int)(index.internalId() - 1), 0); } } int AnalysisClassesModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { // root return classes.count(); } if (parent.internalId() == 0) { // methods/fields return getAttrs(classes[parent.row()]).size(); } return 0; // below methods/fields } bool AnalysisClassesModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid() || !parent.parent().isValid(); } int AnalysisClassesModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant AnalysisClassesModel::data(const QModelIndex &index, int role) const { if (index.internalId() == 0) { // class row if (index.row() >= classes.count()) { return QVariant(); } QString cls = classes.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return cls; case TYPE: return tr("class"); default: return QVariant(); } case TypeRole: return QVariant::fromValue(RowType::Class); case NameRole: return cls; default: return QVariant(); } } else { // method/field/base row QString cls = classes.at(static_cast<int>(index.internalId() - 1)); const Attribute &attr = getAttrs(cls)[index.row()]; switch (attr.type) { case Attribute::Type::Base: { AnalysisBaseClassDescription base = attr.data.value<AnalysisBaseClassDescription>(); switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return base.className; case TYPE: return tr("base"); case OFFSET: return QString("+%1").arg(base.offset); default: return QVariant(); } case Qt::DecorationRole: if (index.column() == NAME) { return QIcon(new SvgIconEngine(QString(":/img/icons/home.svg"), QPalette::WindowText)); } return QVariant(); case VTableRole: return -1; case NameRole: return base.className; case TypeRole: return QVariant::fromValue(RowType::Base); default: return QVariant(); } break; } case Attribute::Type::Method: { AnalysisMethodDescription meth = attr.data.value<AnalysisMethodDescription>(); switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return meth.name; case REAL_NAME: return meth.realName; case TYPE: return tr("method"); case OFFSET: return meth.addr == RVA_INVALID ? QString() : RzAddressString(meth.addr); case VTABLE: return meth.vtableOffset < 0 ? QString() : QString("+%1").arg(meth.vtableOffset); default: return QVariant(); } case Qt::DecorationRole: if (index.column() == NAME) { return QIcon(new SvgIconEngine(QString(":/img/icons/fork.svg"), QPalette::WindowText)); } return QVariant(); case VTableRole: return QVariant::fromValue(meth.vtableOffset); case OffsetRole: return QVariant::fromValue(meth.addr); case NameRole: return meth.name; case RealNameRole: return meth.realName; case TypeRole: return QVariant::fromValue(RowType::Method); default: return QVariant(); } break; } case Attribute::Type::VTable: { AnalysisVTableDescription vtable = attr.data.value<AnalysisVTableDescription>(); switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return "vtable"; case TYPE: return tr("vtable"); case OFFSET: return RzAddressString(vtable.addr); default: return QVariant(); } case Qt::DecorationRole: if (index.column() == NAME) { return QIcon(new SvgIconEngine(QString(":/img/icons/list.svg"), QPalette::WindowText)); } return QVariant(); case OffsetRole: return QVariant::fromValue(vtable.addr); case TypeRole: return QVariant::fromValue(RowType::VTable); default: return QVariant(); } break; } } } return QVariant(); } ClassesSortFilterProxyModel::ClassesSortFilterProxyModel(QObject *parent) : AddressableFilterProxyModel(nullptr, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool ClassesSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { if (parent.isValid()) return true; QModelIndex index = sourceModel()->index(row, 0, parent); return qhelpers::filterStringContains(index.data(ClassesModel::NameRole).toString(), this); } bool ClassesSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { switch (left.column()) { case ClassesModel::OFFSET: { RVA left_offset = left.data(ClassesModel::OffsetRole).toULongLong(); RVA right_offset = right.data(ClassesModel::OffsetRole).toULongLong(); if (left_offset != right_offset) { return left_offset < right_offset; } } // fallthrough case ClassesModel::TYPE: { auto left_type = left.data(ClassesModel::TypeRole).value<ClassesModel::RowType>(); auto right_type = right.data(ClassesModel::TypeRole).value<ClassesModel::RowType>(); if (left_type != right_type) { return left_type < right_type; } } // fallthrough case ClassesModel::VTABLE: { auto left_vtable = left.data(ClassesModel::VTableRole).toLongLong(); auto right_vtable = right.data(ClassesModel::VTableRole).toLongLong(); if (left_vtable != right_vtable) { return left_vtable < right_vtable; } } // fallthrough case ClassesModel::NAME: default: QString left_name = left.data(ClassesModel::NameRole).toString(); QString right_name = right.data(ClassesModel::NameRole).toString(); return QString::compare(left_name, right_name, Qt::CaseInsensitive) < 0; } } bool ClassesSortFilterProxyModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid() || !parent.parent().isValid(); } ClassesWidget::ClassesWidget(MainWindow *main) : ListDockWidget(main), seekToVTableAction(tr("Seek to VTable"), this), editMethodAction(tr("Edit Method"), this), addMethodAction(tr("Add Method"), this), newClassAction(tr("Create new Class"), this), renameClassAction(tr("Rename Class"), this), deleteClassAction(tr("Delete Class"), this) { setWindowTitle(tr("Classes")); setObjectName("ClassesWidget"); ui->treeView->setIconSize(QSize(10, 10)); proxy_model = new ClassesSortFilterProxyModel(this); setModels(proxy_model); classSourceCombo = new QComboBox(this); // User an intermediate single-child layout to contain the combo box, otherwise // when the combo box is inserted directly, the entire vertical layout gets a // weird horizontal padding on macOS. QBoxLayout *comboLayout = new QBoxLayout(QBoxLayout::Direction::LeftToRight, nullptr); comboLayout->addWidget(classSourceCombo); ui->verticalLayout->insertLayout(ui->verticalLayout->indexOf(ui->quickFilterView), comboLayout); classSourceCombo->addItem(tr("Binary Info (Fixed)")); classSourceCombo->addItem(tr("Analysis (Editable)")); classSourceCombo->setCurrentIndex(1); connect<void (QComboBox::*)(int)>(classSourceCombo, &QComboBox::currentIndexChanged, this, &ClassesWidget::refreshClasses); connect(&seekToVTableAction, &QAction::triggered, this, &ClassesWidget::seekToVTableActionTriggered); connect(&editMethodAction, &QAction::triggered, this, &ClassesWidget::editMethodActionTriggered); connect(&addMethodAction, &QAction::triggered, this, &ClassesWidget::addMethodActionTriggered); connect(&newClassAction, &QAction::triggered, this, &ClassesWidget::newClassActionTriggered); connect(&renameClassAction, &QAction::triggered, this, &ClassesWidget::renameClassActionTriggered); connect(&deleteClassAction, &QAction::triggered, this, &ClassesWidget::deleteClassActionTriggered); // Build context menu like this: // class-related actions // -- classesMethodsSeparator // method-related actions // -- separator // default actions from AddressableItemList auto contextMenu = ui->treeView->getItemContextMenu(); contextMenu->insertSeparator(contextMenu->actions().first()); contextMenu->insertActions(contextMenu->actions().first(), { &addMethodAction, &editMethodAction, &seekToVTableAction }); classesMethodsSeparator = contextMenu->insertSeparator(contextMenu->actions().first()); contextMenu->insertActions(classesMethodsSeparator, { &newClassAction, &renameClassAction, &deleteClassAction }); connect(contextMenu, &QMenu::aboutToShow, this, &ClassesWidget::updateActions); ui->treeView->setShowItemContextMenuWithoutAddress(true); refreshClasses(); } ClassesWidget::~ClassesWidget() {} ClassesWidget::Source ClassesWidget::getSource() { switch (classSourceCombo->currentIndex()) { case 0: return Source::BIN; default: return Source::ANALYSIS; } } void ClassesWidget::refreshClasses() { switch (getSource()) { case Source::BIN: if (!bin_model) { proxy_model->setSourceModel(static_cast<AddressableItemModelI *>(nullptr)); delete analysis_model; analysis_model = nullptr; bin_model = new BinClassesModel(this); proxy_model->setSourceModel(static_cast<AddressableItemModelI *>(bin_model)); } bin_model->setClasses(Core()->getAllClassesFromBin()); break; case Source::ANALYSIS: if (!analysis_model) { proxy_model->setSourceModel(static_cast<AddressableItemModelI *>(nullptr)); delete bin_model; bin_model = nullptr; analysis_model = new AnalysisClassesModel(this); proxy_model->setSourceModel(static_cast<AddressableItemModelI *>(analysis_model)); } break; } qhelpers::adjustColumns(ui->treeView, 3, 0); ui->treeView->setColumnWidth(0, 200); } void ClassesWidget::updateActions() { bool isAnalysis = !!analysis_model; newClassAction.setVisible(isAnalysis); addMethodAction.setVisible(isAnalysis); bool rowIsAnalysisClass = false; bool rowIsAnalysisMethod = false; QModelIndex index = ui->treeView->selectionModel()->currentIndex(); if (isAnalysis && index.isValid()) { auto type = static_cast<ClassesModel::RowType>(index.data(ClassesModel::TypeRole).toInt()); rowIsAnalysisClass = type == ClassesModel::RowType::Class; rowIsAnalysisMethod = type == ClassesModel::RowType::Method; } renameClassAction.setVisible(rowIsAnalysisClass); deleteClassAction.setVisible(rowIsAnalysisClass); classesMethodsSeparator->setVisible(rowIsAnalysisClass || rowIsAnalysisMethod); editMethodAction.setVisible(rowIsAnalysisMethod); bool rowHasVTable = false; if (rowIsAnalysisMethod) { QString className = index.parent().data(ClassesModel::NameRole).toString(); QString methodName = index.data(ClassesModel::NameRole).toString(); AnalysisMethodDescription desc; if (Core()->getAnalysisMethod(className, methodName, &desc)) { if (desc.vtableOffset >= 0) { rowHasVTable = true; } } } seekToVTableAction.setVisible(rowHasVTable); } void ClassesWidget::seekToVTableActionTriggered() { QModelIndex index = ui->treeView->selectionModel()->currentIndex(); QString className = index.parent().data(ClassesModel::NameRole).toString(); QList<AnalysisVTableDescription> vtables = Core()->getAnalysisClassVTables(className); if (vtables.isEmpty()) { QMessageBox::warning(this, tr("Missing VTable in class"), tr("The class %1 does not have any VTable!").arg(className)); return; } QString methodName = index.data(ClassesModel::NameRole).toString(); AnalysisMethodDescription desc; if (!Core()->getAnalysisMethod(className, methodName, &desc) || desc.vtableOffset < 0) { return; } Core()->seekAndShow(vtables[0].addr + desc.vtableOffset); } void ClassesWidget::addMethodActionTriggered() { QModelIndex index = ui->treeView->selectionModel()->currentIndex(); if (!index.isValid()) { return; } QString className; if (index.data(ClassesModel::TypeRole).toInt() == static_cast<int>(ClassesModel::RowType::Class)) { className = index.data(ClassesModel::NameRole).toString(); } else { className = index.parent().data(ClassesModel::NameRole).toString(); } EditMethodDialog::newMethod(className, QString(), this); } void ClassesWidget::editMethodActionTriggered() { QModelIndex index = ui->treeView->selectionModel()->currentIndex(); if (!index.isValid() || index.data(ClassesModel::TypeRole).toInt() != static_cast<int>(ClassesModel::RowType::Method)) { return; } QString className = index.parent().data(ClassesModel::NameRole).toString(); QString methName = index.data(ClassesModel::NameRole).toString(); EditMethodDialog::editMethod(className, methName, this); } void ClassesWidget::newClassActionTriggered() { bool ok; QString name = QInputDialog::getText(this, tr("Create new Class"), tr("Class Name:"), QLineEdit::Normal, QString(), &ok); if (ok && !name.isEmpty()) { Core()->createNewClass(name); } } void ClassesWidget::deleteClassActionTriggered() { QModelIndex index = ui->treeView->selectionModel()->currentIndex(); if (!index.isValid() || index.data(ClassesModel::TypeRole).toInt() != static_cast<int>(ClassesModel::RowType::Class)) { return; } QString className = index.data(ClassesModel::NameRole).toString(); if (QMessageBox::question(this, tr("Delete Class"), tr("Are you sure you want to delete the class %1?").arg(className)) != QMessageBox::StandardButton::Yes) { return; } Core()->deleteClass(className); } void ClassesWidget::renameClassActionTriggered() { QModelIndex index = ui->treeView->selectionModel()->currentIndex(); if (!index.isValid() || index.data(ClassesModel::TypeRole).toInt() != static_cast<int>(ClassesModel::RowType::Class)) { return; } QString oldName = index.data(ClassesModel::NameRole).toString(); bool ok; QString newName = QInputDialog::getText(this, tr("Rename Class %1").arg(oldName), tr("Class name:"), QLineEdit::Normal, oldName, &ok); if (ok && !newName.isEmpty()) { Core()->renameClass(oldName, newName); } }
28,500
C++
.cpp
744
29.706989
100
0.617989
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,573
MemoryDockWidget.cpp
rizinorg_cutter/src/widgets/MemoryDockWidget.cpp
#include "MemoryDockWidget.h" #include "common/CutterSeekable.h" #include "MainWindow.h" #include <QAction> #include <QEvent> #include <QMenu> #include <QContextMenuEvent> MemoryDockWidget::MemoryDockWidget(MemoryWidgetType type, MainWindow *parent) : AddressableDockWidget(parent), mType(type) { if (parent) { parent->addMemoryDockWidget(this); } } bool MemoryDockWidget::tryRaiseMemoryWidget() { if (!seekable->isSynchronized()) { return false; } if (mType == MemoryWidgetType::Graph && Core()->isGraphEmpty()) { return false; } raiseMemoryWidget(); return true; } bool MemoryDockWidget::eventFilter(QObject *object, QEvent *event) { if (mainWindow && event->type() == QEvent::FocusIn) { mainWindow->setCurrentMemoryWidget(this); } return CutterDockWidget::eventFilter(object, event); }
874
C++
.cpp
32
23.65625
77
0.716846
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,574
ComboQuickFilterView.cpp
rizinorg_cutter/src/widgets/ComboQuickFilterView.cpp
#include "ComboQuickFilterView.h" #include "ui_ComboQuickFilterView.h" ComboQuickFilterView::ComboQuickFilterView(QWidget *parent) : QWidget(parent), ui(new Ui::ComboQuickFilterView) { ui->setupUi(this); debounceTimer = new QTimer(this); debounceTimer->setSingleShot(true); connect(debounceTimer, &QTimer::timeout, this, [this]() { emit filterTextChanged(ui->lineEdit->text()); }); connect(ui->lineEdit, &QLineEdit::textChanged, this, [this]() { debounceTimer->start(150); }); } ComboQuickFilterView::~ComboQuickFilterView() { delete ui; } void ComboQuickFilterView::setLabelText(const QString &text) { ui->label->setText(text); } QComboBox *ComboQuickFilterView::comboBox() { return ui->comboBox; } void ComboQuickFilterView::showFilter() { show(); ui->lineEdit->setFocus(); } void ComboQuickFilterView::clearFilter() { ui->lineEdit->setText(""); } void ComboQuickFilterView::closeFilter() { ui->lineEdit->setText(""); hide(); emit filterClosed(); }
1,033
C++
.cpp
39
23.384615
98
0.724593
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,575
FlirtWidget.cpp
rizinorg_cutter/src/widgets/FlirtWidget.cpp
#include "FlirtWidget.h" #include "ui_FlirtWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" FlirtModel::FlirtModel(QList<FlirtDescription> *sigdb, QObject *parent) : QAbstractListModel(parent), sigdb(sigdb) { } int FlirtModel::rowCount(const QModelIndex &) const { return sigdb->count(); } int FlirtModel::columnCount(const QModelIndex &) const { return FlirtModel::ColumnCount; } QVariant FlirtModel::data(const QModelIndex &index, int role) const { if (index.row() >= sigdb->count()) return QVariant(); const FlirtDescription &entry = sigdb->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case BinTypeColumn: return entry.bin_name; case ArchNameColumn: return entry.arch_name; case ArchBitsColumn: return entry.arch_bits; case NumModulesColumn: return entry.n_modules; case NameColumn: return entry.base_name; case DetailsColumn: return entry.details; default: return QVariant(); } case FlirtDescriptionRole: return QVariant::fromValue(entry); case Qt::ToolTipRole: { return entry.short_path; } default: return QVariant(); } } QVariant FlirtModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case BinTypeColumn: return tr("Bin"); case ArchNameColumn: return tr("Arch"); case ArchBitsColumn: return tr("Bits"); case NumModulesColumn: return tr("# Funcs"); case NameColumn: return tr("Name"); case DetailsColumn: return tr("Details"); default: return QVariant(); } default: return QVariant(); } } FlirtProxyModel::FlirtProxyModel(FlirtModel *sourceModel, QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(sourceModel); } bool FlirtProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); FlirtDescription entry = index.data(FlirtModel::FlirtDescriptionRole).value<FlirtDescription>(); return qhelpers::filterStringContains(entry.base_name, this); } bool FlirtProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { FlirtDescription leftEntry = left.data(FlirtModel::FlirtDescriptionRole).value<FlirtDescription>(); FlirtDescription rightEntry = right.data(FlirtModel::FlirtDescriptionRole).value<FlirtDescription>(); switch (left.column()) { case FlirtModel::BinTypeColumn: return leftEntry.bin_name < rightEntry.bin_name; case FlirtModel::ArchNameColumn: return leftEntry.arch_name < rightEntry.arch_name; case FlirtModel::ArchBitsColumn: return leftEntry.arch_bits.toULongLong() < rightEntry.arch_bits.toULongLong(); case FlirtModel::NumModulesColumn: return leftEntry.n_modules.toULongLong() < rightEntry.n_modules.toULongLong(); case FlirtModel::NameColumn: return leftEntry.base_name < rightEntry.base_name; case FlirtModel::DetailsColumn: return leftEntry.details < rightEntry.details; default: break; } return leftEntry.bin_name < rightEntry.bin_name; } FlirtWidget::FlirtWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::FlirtWidget), blockMenu(new FlirtContextMenu(this, mainWindow)) { ui->setupUi(this); model = new FlirtModel(&sigdb, this); proxyModel = new FlirtProxyModel(model, this); ui->flirtTreeView->setModel(proxyModel); ui->flirtTreeView->sortByColumn(FlirtModel::BinTypeColumn, Qt::AscendingOrder); setScrollMode(); this->connect(this, &QWidget::customContextMenuRequested, this, &FlirtWidget::showItemContextMenu); this->setContextMenuPolicy(Qt::CustomContextMenu); this->connect(ui->flirtTreeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlirtWidget::onSelectedItemChanged); connect(Core(), &CutterCore::refreshAll, this, &FlirtWidget::refreshFlirt); this->addActions(this->blockMenu->actions()); } FlirtWidget::~FlirtWidget() {} void FlirtWidget::refreshFlirt() { model->beginResetModel(); sigdb = Core()->getSignaturesDB(); model->endResetModel(); ui->flirtTreeView->resizeColumnToContents(0); ui->flirtTreeView->resizeColumnToContents(1); ui->flirtTreeView->resizeColumnToContents(2); ui->flirtTreeView->resizeColumnToContents(3); ui->flirtTreeView->resizeColumnToContents(4); ui->flirtTreeView->resizeColumnToContents(5); } void FlirtWidget::setScrollMode() { qhelpers::setVerticalScrollMode(ui->flirtTreeView); } void FlirtWidget::onSelectedItemChanged(const QModelIndex &index) { if (index.isValid()) { const FlirtDescription &entry = sigdb.at(index.row()); blockMenu->setTarget(entry); } else { blockMenu->clearTarget(); } } void FlirtWidget::showItemContextMenu(const QPoint &pt) { auto index = ui->flirtTreeView->currentIndex(); if (index.isValid()) { const FlirtDescription &entry = sigdb.at(index.row()); blockMenu->setTarget(entry); blockMenu->exec(this->mapToGlobal(pt)); } }
5,483
C++
.cpp
161
28.099379
100
0.691276
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,576
ConsoleWidget.cpp
rizinorg_cutter/src/widgets/ConsoleWidget.cpp
#include <QScrollBar> #include <QMenu> #include <QCompleter> #include <QAction> #include <QShortcut> #include <QStringListModel> #include <QTimer> #include <QSettings> #include <QDir> #include <QUuid> #include <iostream> #include "core/Cutter.h" #include "ConsoleWidget.h" #include "ui_ConsoleWidget.h" #include "common/Helpers.h" #include "common/SvgIconEngine.h" #include "WidgetShortcuts.h" #ifdef Q_OS_WIN # include <windows.h> # include <io.h> # define dup2 _dup2 # define dup _dup # define fileno _fileno # define fdopen _fdopen # define PIPE_SIZE 65536 // Match Linux size # define PIPE_NAME "\\\\.\\pipe\\cutteroutput-%1" #else # include <unistd.h> # define PIPE_READ (0) # define PIPE_WRITE (1) # define STDIN_PIPE_NAME "%1/cutter-stdin-%2" #endif #define CONSOLE_RIZIN_INPUT ("Rizin Console") #define CONSOLE_DEBUGEE_INPUT ("Debugee Input") static const int invalidHistoryPos = -1; static const char *consoleWrapSettingsKey = "console.wrap"; ConsoleWidget::ConsoleWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::ConsoleWidget), debugOutputEnabled(true), maxHistoryEntries(100), lastHistoryPosition(invalidHistoryPos), completer(nullptr), historyUpShortcut(nullptr), historyDownShortcut(nullptr) { ui->setupUi(this); // Adjust console lineedit ui->rzInputLineEdit->setTextMargins(10, 0, 0, 0); ui->debugeeInputLineEdit->setTextMargins(10, 0, 0, 0); setupFont(); // Adjust text margins of consoleOutputTextEdit QTextDocument *console_docu = ui->outputTextEdit->document(); console_docu->setDocumentMargin(10); // Ctrl+` and ';' to toggle console widget QAction *toggleConsole = toggleViewAction(); QList<QKeySequence> toggleShortcuts; toggleShortcuts << widgetShortcuts["ConsoleWidget"] << widgetShortcuts["ConsoleWidgetAlternative"]; toggleConsole->setShortcuts(toggleShortcuts); connect(toggleConsole, &QAction::triggered, this, [this, toggleConsole]() { if (toggleConsole->isChecked()) { widgetToFocusOnRaise()->setFocus(); } }); QAction *actionClear = new QAction(tr("Clear Output"), this); connect(actionClear, &QAction::triggered, ui->outputTextEdit, &QPlainTextEdit::clear); addAction(actionClear); // Ctrl+l to clear the output actionClear->setShortcut(Qt::CTRL | Qt::Key_L); actionClear->setShortcutContext(Qt::WidgetWithChildrenShortcut); actions.append(actionClear); actionWrapLines = new QAction(tr("Wrap Lines"), ui->outputTextEdit); actionWrapLines->setCheckable(true); setWrap(QSettings().value(consoleWrapSettingsKey, true).toBool()); connect(actionWrapLines, &QAction::triggered, this, [this](bool checked) { setWrap(checked); }); actions.append(actionWrapLines); // Completion completionActive = false; completer = new QCompleter(&completionModel, this); completer->setMaxVisibleItems(20); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setFilterMode(Qt::MatchStartsWith); ui->rzInputLineEdit->setCompleter(completer); connect(ui->rzInputLineEdit, &QLineEdit::textEdited, this, &ConsoleWidget::updateCompletion); updateCompletion(); // Set console output context menu ui->outputTextEdit->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->outputTextEdit, &QWidget::customContextMenuRequested, this, &ConsoleWidget::showCustomContextMenu); // Esc clears rzInputLineEdit and debugeeInputLineEdit (like OmniBar) QShortcut *rizin_clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), ui->rzInputLineEdit); connect(rizin_clear_shortcut, &QShortcut::activated, this, &ConsoleWidget::clear); rizin_clear_shortcut->setContext(Qt::WidgetShortcut); QShortcut *debugee_clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), ui->debugeeInputLineEdit); connect(debugee_clear_shortcut, &QShortcut::activated, this, &ConsoleWidget::clear); debugee_clear_shortcut->setContext(Qt::WidgetShortcut); // Up and down arrows show history historyUpShortcut = new QShortcut(QKeySequence(Qt::Key_Up), ui->rzInputLineEdit); connect(historyUpShortcut, &QShortcut::activated, this, &ConsoleWidget::historyPrev); historyUpShortcut->setContext(Qt::WidgetShortcut); historyDownShortcut = new QShortcut(QKeySequence(Qt::Key_Down), ui->rzInputLineEdit); connect(historyDownShortcut, &QShortcut::activated, this, &ConsoleWidget::historyNext); historyDownShortcut->setContext(Qt::WidgetShortcut); QShortcut *completionShortcut = new QShortcut(QKeySequence(Qt::Key_Tab), ui->rzInputLineEdit); connect(completionShortcut, &QShortcut::activated, this, &ConsoleWidget::triggerCompletion); connect(ui->rzInputLineEdit, &QLineEdit::editingFinished, this, &ConsoleWidget::disableCompletion); connect(Config(), &Configuration::fontsUpdated, this, &ConsoleWidget::setupFont); connect(ui->inputCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ConsoleWidget::onIndexChange); connect(Core(), &CutterCore::debugTaskStateChanged, this, [=]() { if (Core()->isRedirectableDebugee()) { ui->inputCombo->setVisible(true); } else { ui->inputCombo->setVisible(false); // Return to the rizin console ui->inputCombo->setCurrentIndex(ui->inputCombo->findText(CONSOLE_RIZIN_INPUT)); } }); completer->popup()->installEventFilter(this); if (Config()->getOutputRedirectionEnabled()) { redirectOutput(); } } ConsoleWidget::~ConsoleWidget() { #ifndef Q_OS_WIN ::close(stdinFile); remove(stdinFifoPath.toStdString().c_str()); #endif } bool ConsoleWidget::eventFilter(QObject *obj, QEvent *event) { if (completer && obj == completer->popup() && // disable up/down shortcuts if completer is shown (event->type() == QEvent::Type::Show || event->type() == QEvent::Type::Hide)) { bool enabled = !completer->popup()->isVisible(); if (historyUpShortcut) { historyUpShortcut->setEnabled(enabled); } if (historyDownShortcut) { historyDownShortcut->setEnabled(enabled); } } return false; } QWidget *ConsoleWidget::widgetToFocusOnRaise() { return ui->rzInputLineEdit; } void ConsoleWidget::setupFont() { ui->outputTextEdit->setFont(Config()->getFont()); } void ConsoleWidget::addOutput(const QString &msg) { ui->outputTextEdit->appendPlainText(msg); scrollOutputToEnd(); } void ConsoleWidget::addDebugOutput(const QString &msg) { if (debugOutputEnabled) { ui->outputTextEdit->appendHtml("<font color=\"red\"> [DEBUG]:\t" + msg + "</font>"); scrollOutputToEnd(); } } void ConsoleWidget::focusInputLineEdit() { ui->rzInputLineEdit->setFocus(); } void ConsoleWidget::removeLastLine() { ui->outputTextEdit->setFocus(); QTextCursor cur = ui->outputTextEdit->textCursor(); ui->outputTextEdit->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); ui->outputTextEdit->moveCursor(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); ui->outputTextEdit->moveCursor(QTextCursor::End, QTextCursor::KeepAnchor); ui->outputTextEdit->textCursor().removeSelectedText(); ui->outputTextEdit->textCursor().deletePreviousChar(); ui->outputTextEdit->setTextCursor(cur); } void ConsoleWidget::executeCommand(const QString &command) { if (!commandTask.isNull()) { return; } ui->rzInputLineEdit->setEnabled(false); QString cmd_line = "[" + RzAddressString(Core()->getOffset()) + "]> " + command; addOutput(cmd_line); RVA oldOffset = Core()->getOffset(); commandTask = QSharedPointer<CommandTask>(new CommandTask(command, CommandTask::ColorMode::MODE_16M)); connect(commandTask.data(), &CommandTask::finished, this, [this, cmd_line, command, oldOffset](const QString &result) { ui->outputTextEdit->appendHtml(CutterCore::ansiEscapeToHtml(result)); scrollOutputToEnd(); historyAdd(command); commandTask.clear(); ui->rzInputLineEdit->setEnabled(true); ui->rzInputLineEdit->setFocus(); if (oldOffset != Core()->getOffset()) { Core()->updateSeek(); } }); Core()->getAsyncTaskManager()->start(commandTask); } void ConsoleWidget::sendToStdin(const QString &input) { #ifndef Q_OS_WIN write(stdinFile, (input + "\n").toStdString().c_str(), input.size() + 1); fsync(stdinFile); addOutput("Sent input: '" + input + "'"); #else // Stdin redirection isn't currently available in windows because console applications // with stdin already get their own console window with stdin when they are launched // that the user can type into. addOutput("Unsupported feature"); #endif } void ConsoleWidget::onIndexChange() { QString console = ui->inputCombo->currentText(); if (console == CONSOLE_DEBUGEE_INPUT) { ui->rzInputLineEdit->setVisible(false); ui->debugeeInputLineEdit->setVisible(true); } else if (console == CONSOLE_RIZIN_INPUT) { ui->rzInputLineEdit->setVisible(true); ui->debugeeInputLineEdit->setVisible(false); } } void ConsoleWidget::setWrap(bool wrap) { QSettings().setValue(consoleWrapSettingsKey, wrap); actionWrapLines->setChecked(wrap); ui->outputTextEdit->setLineWrapMode(wrap ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap); } void ConsoleWidget::on_rzInputLineEdit_returnPressed() { QString input = ui->rzInputLineEdit->text(); if (input.isEmpty()) { return; } executeCommand(input); ui->rzInputLineEdit->clear(); } void ConsoleWidget::on_debugeeInputLineEdit_returnPressed() { QString input = ui->debugeeInputLineEdit->text(); if (input.isEmpty()) { return; } sendToStdin(input); ui->debugeeInputLineEdit->clear(); } void ConsoleWidget::on_execButton_clicked() { on_rzInputLineEdit_returnPressed(); } void ConsoleWidget::showCustomContextMenu(const QPoint &pt) { actionWrapLines->setChecked(ui->outputTextEdit->lineWrapMode() == QPlainTextEdit::WidgetWidth); QMenu *menu = new QMenu(ui->outputTextEdit); menu->addActions(actions); menu->exec(ui->outputTextEdit->mapToGlobal(pt)); menu->deleteLater(); } void ConsoleWidget::historyNext() { if (!history.isEmpty()) { if (lastHistoryPosition > invalidHistoryPos) { if (lastHistoryPosition >= history.size()) { lastHistoryPosition = history.size() - 1; } --lastHistoryPosition; if (lastHistoryPosition >= 0) { ui->rzInputLineEdit->setText(history.at(lastHistoryPosition)); } else { ui->rzInputLineEdit->clear(); } } } } void ConsoleWidget::historyPrev() { if (!history.isEmpty()) { if (lastHistoryPosition >= history.size() - 1) { lastHistoryPosition = history.size() - 2; } ui->rzInputLineEdit->setText(history.at(++lastHistoryPosition)); } } void ConsoleWidget::triggerCompletion() { if (completionActive) { return; } completionActive = true; updateCompletion(); completer->complete(); } void ConsoleWidget::disableCompletion() { if (!completionActive) { return; } completionActive = false; updateCompletion(); completer->popup()->hide(); } void ConsoleWidget::updateCompletion() { if (!completionActive) { completionModel.setStringList({}); return; } auto current = ui->rzInputLineEdit->text(); auto completions = Core()->autocomplete(current, RZ_LINE_PROMPT_DEFAULT); int lastSpace = current.lastIndexOf(' '); if (lastSpace >= 0) { current = current.left(lastSpace + 1); for (auto &s : completions) { s = current + s; } } completionModel.setStringList(completions); } void ConsoleWidget::clear() { disableCompletion(); ui->rzInputLineEdit->clear(); ui->debugeeInputLineEdit->clear(); invalidateHistoryPosition(); // Close the potential shown completer popup ui->rzInputLineEdit->clearFocus(); ui->rzInputLineEdit->setFocus(); } void ConsoleWidget::scrollOutputToEnd() { const int maxValue = ui->outputTextEdit->verticalScrollBar()->maximum(); ui->outputTextEdit->verticalScrollBar()->setValue(maxValue); } void ConsoleWidget::historyAdd(const QString &input) { if (history.size() + 1 > maxHistoryEntries) { history.removeLast(); } history.prepend(input); invalidateHistoryPosition(); } void ConsoleWidget::invalidateHistoryPosition() { lastHistoryPosition = invalidHistoryPos; } void ConsoleWidget::processQueuedOutput() { // Partial lines are ignored since carriage return is currently unsupported while (pipeSocket->canReadLine()) { QString output = QString(pipeSocket->readLine()); if (origStderr) { fprintf(origStderr, "%s", output.toStdString().c_str()); } // Get the last segment that wasn't overwritten by carriage return output = output.trimmed(); output = output.remove(0, output.lastIndexOf('\r')).trimmed(); ui->outputTextEdit->appendHtml(CutterCore::ansiEscapeToHtml(output)); scrollOutputToEnd(); } } // Haiku doesn't have O_ASYNC #ifdef Q_OS_HAIKU # define O_ASYNC O_NONBLOCK #endif void ConsoleWidget::redirectOutput() { // Make sure that we are running in a valid console with initialized output handles if (0 > fileno(stderr) && 0 > fileno(stdout)) { addOutput("Run cutter in a console to enable rizin output redirection into this widget."); return; } pipeSocket = new QLocalSocket(this); origStdin = fdopen(dup(fileno(stdin)), "r"); origStderr = fdopen(dup(fileno(stderr)), "a"); origStdout = fdopen(dup(fileno(stdout)), "a"); #ifdef Q_OS_WIN QString pipeName = QString::fromLatin1(PIPE_NAME).arg(QUuid::createUuid().toString()); SECURITY_ATTRIBUTES attributes = { sizeof(SECURITY_ATTRIBUTES), 0, false }; hWrite = CreateNamedPipeW((wchar_t *)pipeName.utf16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_WAIT, 1, PIPE_SIZE, PIPE_SIZE, 0, &attributes); int writeFd = _open_osfhandle((intptr_t)hWrite, _O_WRONLY | _O_TEXT); dup2(writeFd, fileno(stdout)); dup2(writeFd, fileno(stderr)); pipeSocket->connectToServer(pipeName, QIODevice::ReadOnly); #else pipe(redirectPipeFds); stdinFifoPath = QString(STDIN_PIPE_NAME).arg(QDir::tempPath(), QUuid::createUuid().toString()); mkfifo(stdinFifoPath.toStdString().c_str(), (mode_t)0777); stdinFile = open(stdinFifoPath.toStdString().c_str(), O_RDWR | O_ASYNC); dup2(stdinFile, fileno(stdin)); dup2(redirectPipeFds[PIPE_WRITE], fileno(stderr)); dup2(redirectPipeFds[PIPE_WRITE], fileno(stdout)); // Attempt to force line buffering to avoid calling processQueuedOutput // for partial lines setlinebuf(stderr); setlinebuf(stdout); // Configure the pipe to work in async mode fcntl(redirectPipeFds[PIPE_READ], F_SETFL, O_ASYNC | O_NONBLOCK); pipeSocket->setSocketDescriptor(redirectPipeFds[PIPE_READ]); pipeSocket->connectToServer(QIODevice::ReadOnly); #endif connect(pipeSocket, &QIODevice::readyRead, this, &ConsoleWidget::processQueuedOutput); }
15,774
C++
.cpp
416
32.5
100
0.693521
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,577
ColorThemeListView.cpp
rizinorg_cutter/src/widgets/ColorThemeListView.cpp
#include <QDebug> #include <QJsonObject> #include <QJsonArray> #include <QMap> #include <QPainter> #include <QPainterPath> #include <QFontMetrics> #include <QScreen> #include <QJsonArray> #include <QScrollBar> #include <QApplication> #include <QSvgRenderer> #include <QMouseEvent> #include <QSortFilterProxyModel> #include "common/Configuration.h" #include "common/ColorThemeWorker.h" #include "common/Helpers.h" #include "widgets/ColorThemeListView.h" constexpr int allFieldsRole = Qt::UserRole + 2; struct OptionInfo { QString info; QString displayingtext; }; extern const QMap<QString, OptionInfo> optionInfoMap__; ColorOptionDelegate::ColorOptionDelegate(QObject *parent) : QStyledItemDelegate(parent) { resetButtonPixmap = getPixmapFromSvg(":/img/icons/reset.svg", qApp->palette().text().color()); connect(qApp, &QGuiApplication::paletteChanged, this, [this]() { resetButtonPixmap = getPixmapFromSvg(":/img/icons/reset.svg", qApp->palette().text().color()); }); } void ColorOptionDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { int margin = this->margin; painter->save(); painter->setFont(option.font); painter->setRenderHint(QPainter::Antialiasing); ColorOption currCO = index.data(Qt::UserRole).value<ColorOption>(); QFontMetrics fm = QFontMetrics(painter->font()); int penWidth = painter->pen().width(); int fontHeight = fm.height(); QPoint tl = option.rect.topLeft(); QRect optionNameRect; optionNameRect.setTopLeft(tl + QPoint(margin, penWidth)); optionNameRect.setWidth(option.rect.width() - margin * 2); optionNameRect.setHeight(fontHeight); QRect optionRect; optionRect.setTopLeft(optionNameRect.bottomLeft() + QPoint(margin / 2, margin / 2)); optionRect.setWidth(option.rect.width() - (optionRect.topLeft() - tl).x() * 2); optionRect.setHeight(option.rect.height() - (optionRect.topLeft() - tl).y() - margin); QRect colorRect; colorRect.setTopLeft(optionRect.topLeft() + QPoint(margin / 4, margin / 4)); colorRect.setBottom(optionRect.bottom() - margin / 4); colorRect.setWidth(colorRect.height()); QRect descTextRect; descTextRect.setTopLeft(colorRect.topRight() + QPoint(margin, colorRect.height() / 2 - fontHeight / 2)); descTextRect.setWidth(optionRect.width() - (descTextRect.left() - optionRect.left()) - margin); descTextRect.setHeight(fontHeight); bool paintResetButton = false; QRect resetButtonRect; if (option.state & (QStyle::State_Selected | QStyle::State_MouseOver)) { QBrush br; QPen pen; if (option.state.testFlag(QStyle::State_Selected)) { QColor c = qApp->palette().highlight().color(); c.setAlphaF(0.4); br = c; pen = QPen(qApp->palette().highlight().color(), margin / 2); if (currCO.changed) { paintResetButton = true; descTextRect.setWidth(descTextRect.width() - descTextRect.height() - margin / 2); resetButtonRect.setTopLeft(descTextRect.topRight() + QPoint(margin, 0)); resetButtonRect.setWidth(descTextRect.height()); resetButtonRect.setHeight(descTextRect.height()); resetButtonRect.setSize(resetButtonRect.size() * 1.0); } } else { #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) QColor placeholderColor = qApp->palette().placeholderText().color(); #else QColor placeholderColor = qApp->palette().text().color(); placeholderColor.setAlphaF(0.5); #endif QColor c = placeholderColor; c.setAlphaF(0.2); br = c; pen = QPen(placeholderColor.darker(), margin / 2); } painter->fillRect(option.rect, br); painter->setPen(pen); int pw = painter->pen().width() / 2; QPoint top = option.rect.topLeft() + QPoint(pw, pw); QPoint bottom = option.rect.bottomLeft() - QPoint(-pw, pw - 1); painter->drawLine(top, bottom); } if (paintResetButton) { painter->drawPixmap(resetButtonRect, resetButtonPixmap); auto self = const_cast<ColorOptionDelegate *>(this); self->resetButtonRect = resetButtonRect; } if (option.rect.contains(this->resetButtonRect) && this->resetButtonRect != resetButtonRect) { auto self = const_cast<ColorOptionDelegate *>(this); self->resetButtonRect = QRect(0, 0, 0, 0); } painter->setPen(qApp->palette().text().color()); QFontMetrics fm2 = QFontMetrics(painter->font()); QString name = fm2.elidedText(optionInfoMap__[currCO.optionName].displayingtext, Qt::ElideRight, optionNameRect.width()); painter->drawText(optionNameRect, name); QPainterPath roundedOptionRect; roundedOptionRect.addRoundedRect(optionRect, fontHeight / 4, fontHeight / 4); painter->setPen(qApp->palette().text().color()); painter->drawPath(roundedOptionRect); QPainterPath roundedColorRect; roundedColorRect.addRoundedRect(colorRect, fontHeight / 4, fontHeight / 4); // Create chess-like pattern of black and white squares // and fill background of roundedColorRect with it if (currCO.color.alpha() < 255) { const int c1 = static_cast<int>(8); const int c2 = c1 / 2; QPixmap p(c1, c1); QPainter paint(&p); paint.fillRect(0, 0, c1, c1, Qt::white); paint.fillRect(0, 0, c2, c2, Qt::black); paint.fillRect(c2, c2, c2, c2, Qt::black); QBrush b; b.setTexture(p); painter->fillPath(roundedColorRect, b); } painter->setPen(currCO.color); painter->fillPath(roundedColorRect, currCO.color); QFontMetrics fm3 = QFontMetrics(painter->font()); QString desc = fm3.elidedText(currCO.optionName + ": " + optionInfoMap__[currCO.optionName].info, Qt::ElideRight, descTextRect.width()); painter->setPen(qApp->palette().text().color()); painter->setBrush(qApp->palette().text()); painter->drawText(descTextRect, desc); painter->restore(); } QSize ColorOptionDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { qreal margin = this->margin; qreal fontHeight = option.fontMetrics.height(); qreal h = QPen().width(); h += fontHeight; // option name h += margin / 2; // margin between option rect and option name h += margin / 4; // margin betveen option rect and color rect h += fontHeight; // color rect h += margin / 4; // margin betveen option rect and color rect h += margin; // last margin Q_UNUSED(index) return QSize(-1, qRound(h)); } QRect ColorOptionDelegate::getResetButtonRect() const { return resetButtonRect; } QPixmap ColorOptionDelegate::getPixmapFromSvg(const QString &fileName, const QColor &after) const { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { return QPixmap(); } QString data = file.readAll(); data.replace(QRegularExpression("#[0-9a-fA-F]{6}"), QString("%1").arg(after.name())); QSvgRenderer svgRenderer(data.toUtf8()); QFontMetrics fm = QFontMetrics(qApp->font()); QPixmap pix(QSize(fm.height(), fm.height())); pix.fill(Qt::transparent); QPainter pixPainter(&pix); svgRenderer.render(&pixPainter); return pix; } ColorThemeListView::ColorThemeListView(QWidget *parent) : QListView(parent) { QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this); ColorSettingsModel *model = new ColorSettingsModel(this); proxy->setSourceModel(model); model->updateTheme(); setModel(proxy); proxy->setFilterRole(allFieldsRole); proxy->setFilterCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive); proxy->setSortRole(Qt::DisplayRole); proxy->setSortCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive); setItemDelegate(new ColorOptionDelegate(this)); setResizeMode(ResizeMode::Adjust); backgroundColor = colorSettingsModel()->getTheme().find("gui.background").value(); connect(&blinkTimer, &QTimer::timeout, this, &ColorThemeListView::blinkTimeout); blinkTimer.setInterval(400); blinkTimer.start(); setMouseTracking(true); } void ColorThemeListView::currentChanged(const QModelIndex &current, const QModelIndex &previous) { ColorOption prev = previous.data(Qt::UserRole).value<ColorOption>(); Config()->setColor(prev.optionName, prev.color); if (ThemeWorker().getRizinSpecificOptions().contains(prev.optionName)) { Core()->setColor(prev.optionName, prev.color.name()); } QListView::currentChanged(current, previous); emit itemChanged(current.data(Qt::UserRole).value<ColorOption>().color); } void ColorThemeListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) { ColorOption curr = topLeft.data(Qt::UserRole).value<ColorOption>(); if (curr.optionName == "gui.background") { backgroundColor = curr.color; } QListView::dataChanged(topLeft, bottomRight, roles); emit itemChanged(curr.color); emit dataChanged(curr); } void ColorThemeListView::mouseReleaseEvent(QMouseEvent *e) { if (qobject_cast<ColorOptionDelegate *>(itemDelegate()) ->getResetButtonRect() .contains(e->pos())) { ColorOption co = currentIndex().data(Qt::UserRole).value<ColorOption>(); co.changed = false; co.color = ThemeWorker().getTheme(Config()->getColorTheme())[co.optionName]; model()->setData(currentIndex(), QVariant::fromValue(co)); QCursor c; c.setShape(Qt::CursorShape::ArrowCursor); setCursor(c); } } void ColorThemeListView::mouseMoveEvent(QMouseEvent *e) { if (qobject_cast<ColorOptionDelegate *>(itemDelegate()) ->getResetButtonRect() .contains(e->pos())) { QCursor c; c.setShape(Qt::CursorShape::PointingHandCursor); setCursor(c); } else if (cursor().shape() == Qt::CursorShape::PointingHandCursor) { QCursor c; c.setShape(Qt::CursorShape::ArrowCursor); setCursor(c); } } ColorSettingsModel *ColorThemeListView::colorSettingsModel() const { return static_cast<ColorSettingsModel *>( static_cast<QSortFilterProxyModel *>(model())->sourceModel()); } void ColorThemeListView::blinkTimeout() { static enum { Normal, Invisible } state = Normal; state = state == Normal ? Invisible : Normal; backgroundColor.setAlphaF(1); auto updateColor = [](const QString &name, const QColor &color) { Config()->setColor(name, color); if (ThemeWorker().getRizinSpecificOptions().contains(name)) { Core()->setColor(name, color.name()); } }; ColorOption curr = currentIndex().data(Qt::UserRole).value<ColorOption>(); switch (state) { case Normal: updateColor(curr.optionName, curr.color); break; case Invisible: updateColor(curr.optionName, backgroundColor); break; } emit blink(); } ColorSettingsModel::ColorSettingsModel(QObject *parent) : QAbstractListModel(parent) {} QVariant ColorSettingsModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } if (index.row() < 0 || index.row() >= theme.size()) { return QVariant(); } if (role == Qt::DisplayRole) { return QVariant::fromValue( optionInfoMap__[theme.at(index.row()).optionName].displayingtext); } if (role == Qt::UserRole) { return QVariant::fromValue(theme.at(index.row())); } if (role == Qt::ToolTipRole) { return QVariant::fromValue(optionInfoMap__[theme.at(index.row()).optionName].info); } if (role == allFieldsRole) { const QString name = theme.at(index.row()).optionName; return QVariant::fromValue(optionInfoMap__[name].displayingtext + " " + optionInfoMap__[theme.at(index.row()).optionName].info + " " + name); } return QVariant(); } bool ColorSettingsModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) { return false; } ColorOption currOpt = value.value<ColorOption>(); theme[index.row()] = currOpt; emit dataChanged(index, index); return true; } void ColorSettingsModel::updateTheme() { beginResetModel(); theme.clear(); ColorThemeWorker::Theme obj = ThemeWorker().getTheme(Config()->getColorTheme()); for (auto it = obj.constBegin(); it != obj.constEnd(); it++) { theme.push_back({ it.key(), it.value(), false }); } std::sort(theme.begin(), theme.end(), [](const ColorOption &f, const ColorOption &s) { QString s1 = optionInfoMap__[f.optionName].displayingtext; QString s2 = optionInfoMap__[s.optionName].displayingtext; int r = s1.compare(s2, Qt::CaseSensitivity::CaseInsensitive); return r < 0; }); endResetModel(); } ColorThemeWorker::Theme ColorSettingsModel::getTheme() const { ColorThemeWorker::Theme th; for (auto &it : theme) { th.insert(it.optionName, it.color); } return th; } const QMap<QString, OptionInfo> optionInfoMap__ = { { "comment", { QObject::tr("Color of comment generated by Rizin"), QObject::tr("Comment") } }, { "usrcmt", { QObject::tr("Comment created by user"), QObject::tr("Color of user Comment") } }, { "args", { "", "args" } }, { "fname", { QObject::tr("Color of names of functions"), QObject::tr("Function name") } }, { "floc", { QObject::tr("Color of function location"), QObject::tr("Function location") } }, { "fline", { QObject::tr("Color of the line which shows which opcodes belongs to a function"), QObject::tr("Function line") } }, { "flag", { QObject::tr("Color of flags (similar to bookmarks for offset)"), QObject::tr("Flag") } }, { "label", { "", QObject::tr("Label") } }, { "help", { "", QObject::tr("Help") } }, { "flow", { QObject::tr("Color of lines showing jump destination"), QObject::tr("Flow") } }, { "flow2", { "", QObject::tr("flow2") } }, { "prompt", { QObject::tr("Info"), QObject::tr("prompt") } }, { "offset", { QObject::tr("Color of offsets"), QObject::tr("Offset") } }, { "input", { QObject::tr("Info"), QObject::tr("input") } }, { "invalid", { QObject::tr("Invalid opcode color"), QObject::tr("invalid") } }, { "other", { "", QObject::tr("other") } }, { "b0x00", { QObject::tr("0x00 opcode color"), "b0x00" } }, { "b0x7f", { QObject::tr("0x7f opcode color"), "b0x7f" } }, { "b0xff", { QObject::tr("0xff opcode color"), "b0xff" } }, { "math", { QObject::tr("Color of arithmetic opcodes (add, div, mul etc)"), QObject::tr("Arithmetic") } }, { "bin", { QObject::tr("Color of binary operations (and, or, xor etc)."), QObject::tr("Binary") } }, { "btext", { QObject::tr( "Color of object names, commas between operators, squared brackets and operators " "inside them."), QObject::tr("Text") } }, { "push", { QObject::tr("push opcode color"), "push" } }, { "pop", { QObject::tr("pop opcode color"), "pop" } }, { "crypto", { QObject::tr("Cryptographic color"), "crypto" } }, { "jmp", { QObject::tr("jmp instructions color"), "jmp" } }, { "cjmp", { QObject::tr("Color of conditional jump opcodes such as je, jg, jne etc"), QObject::tr("Conditional jump") } }, { "call", { QObject::tr("call instructions color (ccall, rcall, call etc)"), "call" } }, { "nop", { QObject::tr("nop opcode color"), "nop" } }, { "ret", { QObject::tr("ret opcode color"), "ret" } }, { "trap", { QObject::tr("Color of interrupts"), QObject::tr("Interrupts") } }, { "swi", { QObject::tr("swi opcode color"), "swi" } }, { "cmp", { QObject::tr("Color of compare instructions such as test and cmp"), QObject::tr("Compare instructions") } }, { "reg", { QObject::tr("Registers color"), QObject::tr("Register") } }, { "creg", { "", "creg" } }, { "num", { QObject::tr("Color of numeric constants and object pointers"), QObject::tr("Constants") } }, { "mov", { QObject::tr("Color of move instructions such as mov, movd, lea etc"), QObject::tr("Move instructions") } }, { "func_var", { QObject::tr("Function variable color"), QObject::tr("Function variable") } }, { "func_var_type", { QObject::tr("Function variable (local or argument) type color"), QObject::tr("Variable type") } }, { "func_var_addr", { QObject::tr("Function variable address color"), QObject::tr("Variable address") } }, { "widget_bg", { "", "widget_bg" } }, { "widget_sel", { "", "widget_sel" } }, { "ai.read", { "", "ai.read" } }, { "ai.write", { "", "ai.write" } }, { "ai.exec", { "", "ai.exec" } }, { "ai.seq", { "", "ai.seq" } }, { "ai.ascii", { "", "ai.ascii" } }, { "graph.box", { "", "graph.box" } }, { "graph.box2", { "", "graph.box2" } }, { "graph.box3", { "", "graph.box3" } }, { "graph.box4", { "", "graph.box4" } }, { "graph.true", { QObject::tr("In graph view jump arrow true"), QObject::tr("Arrow true") } }, { "graph.false", { QObject::tr("In graph view jump arrow false"), QObject::tr("Arrow false") } }, { "graph.trufae", { QObject::tr("In graph view jump arrow (no condition)"), QObject::tr("Arrow") } }, { "graph.current", { "", "graph.current" } }, { "graph.traced", { "", "graph.traced" } }, { "gui.overview.node", { QObject::tr("Background color of Graph Overview's node"), QObject::tr("Graph Overview node") } }, { "gui.overview.fill", { QObject::tr("Fill color of Graph Overview's selection"), QObject::tr("Graph Overview fill") } }, { "gui.overview.border", { QObject::tr("Border color of Graph Overview's selection"), QObject::tr("Graph Overview border") } }, { "gui.cflow", { "", "gui.cflow" } }, { "gui.dataoffset", { "", "gui.dataoffset" } }, { "gui.background", { QObject::tr("General background color"), QObject::tr("Background") } }, { "gui.alt_background", { QObject::tr("Background color of non-focused graph node"), QObject::tr("Node background") } }, { "gui.disass_selected", { QObject::tr("Background of current graph node"), QObject::tr("Current graph node") } }, { "gui.border", { QObject::tr("Color of node border in graph view"), QObject::tr("Node border") } }, { "lineHighlight", { QObject::tr("Selected line background color"), QObject::tr("Line highlight") } }, { "wordHighlight", { QObject::tr("Background color of selected word"), QObject::tr("Word higlight") } }, { "gui.main", { QObject::tr("Main function color"), QObject::tr("Main") } }, { "gui.imports", { "", "gui.imports" } }, { "highlightPC", { "", "highlightPC" } }, { "gui.navbar.err", { "", "gui.navbar.err" } }, { "gui.navbar.seek", { "", "gui.navbar.seek" } }, { "angui.navbar.str", { "", "angui.navbar.str" } }, { "gui.navbar.pc", { "", "gui.navbar.pc" } }, { "gui.navbar.sym", { "", "gui.navbar.sym" } }, { "gui.navbar.code", { QObject::tr("Code section color in navigation bar"), QObject::tr("Navbar code") } }, { "gui.navbar.empty", { QObject::tr("Empty section color in navigation bar"), QObject::tr("Navbar empty") } }, { "ucall", { "", QObject::tr("ucall") } }, { "ujmp", { "", QObject::tr("ujmp") } }, { "gui.breakpoint_background", { "", QObject::tr("Breakpoint background") } } };
20,047
C++
.cpp
453
37.871965
100
0.631258
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,578
FlagsWidget.cpp
rizinorg_cutter/src/widgets/FlagsWidget.cpp
#include "FlagsWidget.h" #include "ui_FlagsWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QComboBox> #include <QMenu> #include <QShortcut> #include <QTreeWidget> #include <QStandardItemModel> #include <QInputDialog> FlagsModel::FlagsModel(QList<FlagDescription> *flags, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), flags(flags) { } int FlagsModel::rowCount(const QModelIndex &) const { return flags->count(); } int FlagsModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant FlagsModel::data(const QModelIndex &index, int role) const { if (index.row() >= flags->count()) return QVariant(); const FlagDescription &flag = flags->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case SIZE: return RzSizeString(flag.size); case OFFSET: return RzAddressString(flag.offset); case NAME: return flag.name; case REALNAME: return flag.realname; case COMMENT: return Core()->getCommentAt(flag.offset); default: return QVariant(); } case FlagDescriptionRole: return QVariant::fromValue(flag); default: return QVariant(); } } QVariant FlagsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case SIZE: return tr("Size"); case OFFSET: return tr("Offset"); case NAME: return tr("Name"); case REALNAME: return tr("Real Name"); case COMMENT: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA FlagsModel::address(const QModelIndex &index) const { const FlagDescription &flag = flags->at(index.row()); return flag.offset; } QString FlagsModel::name(const QModelIndex &index) const { const FlagDescription &flag = flags->at(index.row()); return flag.name; } const FlagDescription *FlagsModel::description(QModelIndex index) const { if (index.row() < flags->size()) { return &flags->at(index.row()); } return nullptr; } FlagsSortFilterProxyModel::FlagsSortFilterProxyModel(FlagsModel *source_model, QObject *parent) : AddressableFilterProxyModel(source_model, parent) { } bool FlagsSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); FlagDescription flag = index.data(FlagsModel::FlagDescriptionRole).value<FlagDescription>(); return qhelpers::filterStringContains(flag.name, this); } bool FlagsSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto source = static_cast<FlagsModel *>(sourceModel()); auto left_flag = source->description(left); auto right_flag = source->description(right); switch (left.column()) { case FlagsModel::SIZE: if (left_flag->size != right_flag->size) return left_flag->size < right_flag->size; // fallthrough case FlagsModel::OFFSET: if (left_flag->offset != right_flag->offset) return left_flag->offset < right_flag->offset; // fallthrough case FlagsModel::NAME: return left_flag->name < right_flag->name; case FlagsModel::REALNAME: return left_flag->realname < right_flag->realname; case FlagsModel::COMMENT: return Core()->getCommentAt(left_flag->offset) < Core()->getCommentAt(right_flag->offset); default: break; } // fallback return left_flag->offset < right_flag->offset; } FlagsWidget::FlagsWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::FlagsWidget), main(main), tree(new CutterTreeWidget(this)) { ui->setupUi(this); // Add Status Bar footer tree->addStatusBar(ui->verticalLayout); flags_model = new FlagsModel(&flags, this); flags_proxy_model = new FlagsSortFilterProxyModel(flags_model, this); connect(ui->filterLineEdit, &QLineEdit::textChanged, flags_proxy_model, &QSortFilterProxyModel::setFilterWildcard); ui->flagsTreeView->setMainWindow(mainWindow); ui->flagsTreeView->setModel(flags_proxy_model); ui->flagsTreeView->sortByColumn(FlagsModel::OFFSET, Qt::AscendingOrder); // Ctrl-F to move the focus to the Filter search box QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->filterLineEdit, [this]() { ui->filterLineEdit->setFocus(); }); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // Esc to clear the filter entry QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, [this] { if (ui->filterLineEdit->text().isEmpty()) { ui->flagsTreeView->setFocus(); } else { ui->filterLineEdit->setText(""); } }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(ui->filterLineEdit, &QLineEdit::textChanged, this, [this] { tree->showItemsNumber(flags_proxy_model->rowCount()); }); setScrollMode(); connect(Core(), &CutterCore::flagsChanged, this, &FlagsWidget::flagsChanged); connect(Core(), &CutterCore::codeRebased, this, &FlagsWidget::flagsChanged); connect(Core(), &CutterCore::refreshAll, this, &FlagsWidget::refreshFlagspaces); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(flags_model, FlagsModel::COMMENT); }); auto menu = ui->flagsTreeView->getItemContextMenu(); menu->addSeparator(); menu->addAction(ui->actionRename); menu->addAction(ui->actionDelete); addAction(ui->actionRename); addAction(ui->actionDelete); } FlagsWidget::~FlagsWidget() {} void FlagsWidget::on_flagspaceCombo_currentTextChanged(const QString &arg1) { Q_UNUSED(arg1); refreshFlags(); } void FlagsWidget::on_actionRename_triggered() { FlagDescription flag = ui->flagsTreeView->selectionModel() ->currentIndex() .data(FlagsModel::FlagDescriptionRole) .value<FlagDescription>(); bool ok; QString newName = QInputDialog::getText(this, tr("Rename flag %1").arg(flag.name), tr("Flag name:"), QLineEdit::Normal, flag.name, &ok); if (ok && !newName.isEmpty()) { Core()->renameFlag(flag.name, newName); } } void FlagsWidget::on_actionDelete_triggered() { FlagDescription flag = ui->flagsTreeView->selectionModel() ->currentIndex() .data(FlagsModel::FlagDescriptionRole) .value<FlagDescription>(); Core()->delFlag(flag.name); } void FlagsWidget::flagsChanged() { refreshFlagspaces(); } void FlagsWidget::refreshFlagspaces() { int cur_idx = ui->flagspaceCombo->currentIndex(); if (cur_idx < 0) cur_idx = 0; disableFlagRefresh = true; // prevent duplicate flag refresh caused by flagspaceCombo modifications ui->flagspaceCombo->clear(); ui->flagspaceCombo->addItem(tr("(all)")); for (const FlagspaceDescription &i : Core()->getAllFlagspaces()) { ui->flagspaceCombo->addItem(i.name, QVariant::fromValue(i)); } if (cur_idx > 0) ui->flagspaceCombo->setCurrentIndex(cur_idx); disableFlagRefresh = false; refreshFlags(); } void FlagsWidget::refreshFlags() { if (disableFlagRefresh) { return; } QString flagspace; QVariant flagspace_data = ui->flagspaceCombo->currentData(); if (flagspace_data.isValid()) flagspace = flagspace_data.value<FlagspaceDescription>().name; flags_model->beginResetModel(); flags = Core()->getAllFlags(flagspace); flags_model->endResetModel(); tree->showItemsNumber(flags_proxy_model->rowCount()); // TODO: this is not a very good place for the following: QStringList flagNames; for (const FlagDescription &i : flags) flagNames.append(i.name); main->refreshOmniBar(flagNames); } void FlagsWidget::setScrollMode() { qhelpers::setVerticalScrollMode(ui->flagsTreeView); }
8,523
C++
.cpp
238
29.483193
99
0.668406
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,579
GlobalsWidget.cpp
rizinorg_cutter/src/widgets/GlobalsWidget.cpp
#include "GlobalsWidget.h" #include "ui_GlobalsWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "dialogs/GlobalVariableDialog.h" #include <QMenu> #include <QShortcut> GlobalsModel::GlobalsModel(QList<GlobalDescription> *globals, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), globals(globals) { } int GlobalsModel::rowCount(const QModelIndex &) const { return globals->count(); } int GlobalsModel::columnCount(const QModelIndex &) const { return GlobalsModel::ColumnCount; } QVariant GlobalsModel::data(const QModelIndex &index, int role) const { if (index.row() >= globals->count()) { return QVariant(); } const GlobalDescription &global = globals->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case GlobalsModel::AddressColumn: return RzAddressString(global.addr); case GlobalsModel::TypeColumn: return QString(global.type).trimmed(); case GlobalsModel::NameColumn: return global.name; case GlobalsModel::CommentColumn: return Core()->getCommentAt(global.addr); default: return QVariant(); } case GlobalsModel::GlobalDescriptionRole: return QVariant::fromValue(global); default: return QVariant(); } } QVariant GlobalsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case GlobalsModel::AddressColumn: return tr("Address"); case GlobalsModel::TypeColumn: return tr("Type"); case GlobalsModel::NameColumn: return tr("Name"); case GlobalsModel::CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA GlobalsModel::address(const QModelIndex &index) const { const GlobalDescription &global = globals->at(index.row()); return global.addr; } QString GlobalsModel::name(const QModelIndex &index) const { const GlobalDescription &global = globals->at(index.row()); return global.name; } GlobalsProxyModel::GlobalsProxyModel(GlobalsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool GlobalsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); auto global = index.data(GlobalsModel::GlobalDescriptionRole).value<GlobalDescription>(); return qhelpers::filterStringContains(global.name, this); } bool GlobalsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftGlobal = left.data(GlobalsModel::GlobalDescriptionRole).value<GlobalDescription>(); auto rightGlobal = right.data(GlobalsModel::GlobalDescriptionRole).value<GlobalDescription>(); switch (left.column()) { case GlobalsModel::AddressColumn: return leftGlobal.addr < rightGlobal.addr; case GlobalsModel::TypeColumn: return leftGlobal.type < rightGlobal.type; case GlobalsModel::NameColumn: return leftGlobal.name < rightGlobal.name; case GlobalsModel::CommentColumn: return Core()->getCommentAt(leftGlobal.addr) < Core()->getCommentAt(rightGlobal.addr); default: break; } return false; } void GlobalsWidget::editGlobal() { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) { return; } RVA globalVariableAddress = globalsProxyModel->address(index); GlobalVariableDialog dialog(globalVariableAddress, parentWidget()); dialog.exec(); } void GlobalsWidget::deleteGlobal() { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) { return; } RVA globalVariableAddress = globalsProxyModel->address(index); Core()->delGlobalVariable(globalVariableAddress); } GlobalsWidget::GlobalsWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::GlobalsWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); ui->quickFilterView->setLabelText(tr("Category")); setWindowTitle(tr("Globals")); setObjectName("GlobalsWidget"); // Add status bar which displays the count tree->addStatusBar(ui->verticalLayout); // Set single select mode ui->treeView->setSelectionMode(QAbstractItemView::SingleSelection); ui->treeView->setMainWindow(mainWindow); // Setup up the model and the proxy model globalsModel = new GlobalsModel(&globals, this); globalsProxyModel = new GlobalsProxyModel(globalsModel, this); ui->treeView->setModel(globalsProxyModel); ui->treeView->sortByColumn(GlobalsModel::AddressColumn, Qt::AscendingOrder); // Setup custom context menu ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, globalsProxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, [this] { tree->showItemsNumber(globalsProxyModel->rowCount()); }); QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::clearFilter); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); actionEditGlobal = new QAction(tr("Edit Global Variable"), this); actionDeleteGlobal = new QAction(tr("Delete Global Variable"), this); auto menu = ui->treeView->getItemContextMenu(); menu->addAction(actionEditGlobal); menu->addAction(actionDeleteGlobal); connect(actionEditGlobal, &QAction::triggered, this, [this]() { editGlobal(); }); connect(actionDeleteGlobal, &QAction::triggered, this, [this]() { deleteGlobal(); }); connect(Core(), &CutterCore::globalVarsChanged, this, &GlobalsWidget::refreshGlobals); connect(Core(), &CutterCore::codeRebased, this, &GlobalsWidget::refreshGlobals); connect(Core(), &CutterCore::refreshAll, this, &GlobalsWidget::refreshGlobals); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(globalsModel, GlobalsModel::CommentColumn); }); } GlobalsWidget::~GlobalsWidget() {} void GlobalsWidget::refreshGlobals() { globalsModel->beginResetModel(); globals = Core()->getAllGlobals(); globalsModel->endResetModel(); qhelpers::adjustColumns(ui->treeView, GlobalsModel::ColumnCount, 0); }
7,017
C++
.cpp
176
34.522727
98
0.723529
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,580
MemoryMapWidget.cpp
rizinorg_cutter/src/widgets/MemoryMapWidget.cpp
#include "MemoryMapWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QShortcut> MemoryMapModel::MemoryMapModel(QList<MemoryMapDescription> *memoryMaps, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), memoryMaps(memoryMaps) { } int MemoryMapModel::rowCount(const QModelIndex &) const { return memoryMaps->count(); } int MemoryMapModel::columnCount(const QModelIndex &) const { return MemoryMapModel::ColumnCount; } QVariant MemoryMapModel::data(const QModelIndex &index, int role) const { if (index.row() >= memoryMaps->count()) return QVariant(); const MemoryMapDescription &memoryMap = memoryMaps->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case AddrStartColumn: return RzAddressString(memoryMap.addrStart); case AddrEndColumn: return RzAddressString(memoryMap.addrEnd); case NameColumn: return memoryMap.name; case PermColumn: return memoryMap.permission; case CommentColumn: return Core()->getCommentAt(memoryMap.addrStart); default: return QVariant(); } case MemoryDescriptionRole: return QVariant::fromValue(memoryMap); default: return QVariant(); } } QVariant MemoryMapModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case AddrStartColumn: return tr("Offset start"); case AddrEndColumn: return tr("Offset end"); case NameColumn: return tr("Name"); case PermColumn: return tr("Permissions"); case CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA MemoryMapModel::address(const QModelIndex &index) const { const MemoryMapDescription &memoryMap = memoryMaps->at(index.row()); return memoryMap.addrStart; } MemoryProxyModel::MemoryProxyModel(MemoryMapModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { } bool MemoryProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); MemoryMapDescription item = index.data(MemoryMapModel::MemoryDescriptionRole).value<MemoryMapDescription>(); return qhelpers::filterStringContains(item.name, this); } bool MemoryProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { MemoryMapDescription leftMemMap = left.data(MemoryMapModel::MemoryDescriptionRole).value<MemoryMapDescription>(); MemoryMapDescription rightMemMap = right.data(MemoryMapModel::MemoryDescriptionRole).value<MemoryMapDescription>(); switch (left.column()) { case MemoryMapModel::AddrStartColumn: return leftMemMap.addrStart < rightMemMap.addrStart; case MemoryMapModel::AddrEndColumn: return leftMemMap.addrEnd < rightMemMap.addrEnd; case MemoryMapModel::NameColumn: return leftMemMap.name < rightMemMap.name; case MemoryMapModel::PermColumn: return leftMemMap.permission < rightMemMap.permission; case MemoryMapModel::CommentColumn: return Core()->getCommentAt(leftMemMap.addrStart) < Core()->getCommentAt(rightMemMap.addrStart); default: break; } return leftMemMap.addrStart < rightMemMap.addrStart; } MemoryMapWidget::MemoryMapWidget(MainWindow *main) : ListDockWidget(main, ListDockWidget::SearchBarPolicy::HideByDefault) { setWindowTitle(tr("Memory Map")); setObjectName("MemoryMapWidget"); memoryModel = new MemoryMapModel(&memoryMaps, this); memoryProxyModel = new MemoryProxyModel(memoryModel, this); setModels(memoryProxyModel); ui->treeView->sortByColumn(MemoryMapModel::AddrStartColumn, Qt::AscendingOrder); refreshDeferrer = createRefreshDeferrer([this]() { refreshMemoryMap(); }); connect(Core(), &CutterCore::refreshAll, this, &MemoryMapWidget::refreshMemoryMap); connect(Core(), &CutterCore::registersChanged, this, &MemoryMapWidget::refreshMemoryMap); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(memoryModel, MemoryMapModel::CommentColumn); }); showCount(false); } MemoryMapWidget::~MemoryMapWidget() = default; void MemoryMapWidget::refreshMemoryMap() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } if (Core()->currentlyEmulating) { return; } memoryModel->beginResetModel(); memoryMaps = Core()->getMemoryMap(); memoryModel->endResetModel(); ui->treeView->resizeColumnToContents(0); ui->treeView->resizeColumnToContents(1); ui->treeView->resizeColumnToContents(2); }
4,997
C++
.cpp
137
30.613139
99
0.713311
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,581
VisualNavbar.cpp
rizinorg_cutter/src/widgets/VisualNavbar.cpp
#include "VisualNavbar.h" #include "core/MainWindow.h" #include "common/TempConfig.h" #include <QGraphicsView> #include <QComboBox> #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QJsonParseError> #include <QToolTip> #include <QMouseEvent> #include <array> #include <cmath> VisualNavbar::VisualNavbar(MainWindow *main, QWidget *parent) : QToolBar(main), graphicsView(new QGraphicsView), seekGraphicsItem(nullptr), PCGraphicsItem(nullptr), main(main) { Q_UNUSED(parent); blockTooltip = false; setObjectName("visualNavbar"); setWindowTitle(tr("Visual navigation bar")); // setMovable(false); setContentsMargins(0, 0, 0, 0); // If line below is used, with the dark theme the paintEvent is not called // and the result is wrong. Something to do with overwriting the style sheet :/ // setStyleSheet("QToolBar { border: 0px; border-bottom: 0px; border-top: 0px; border-width: // 0px;}"); /* QComboBox *addsCombo = new QComboBox(); addsCombo->addItem(""); addsCombo->addItem("Entry points"); addsCombo->addItem("Marks"); */ addWidget(this->graphicsView); // addWidget(addsCombo); connect(Core(), &CutterCore::seekChanged, this, &VisualNavbar::on_seekChanged); connect(Core(), &CutterCore::registersChanged, this, &VisualNavbar::drawPCCursor); connect(Core(), &CutterCore::refreshAll, this, &VisualNavbar::fetchAndPaintData); connect(Core(), &CutterCore::functionsChanged, this, &VisualNavbar::fetchAndPaintData); connect(Core(), &CutterCore::flagsChanged, this, &VisualNavbar::fetchAndPaintData); connect(Core(), &CutterCore::globalVarsChanged, this, &VisualNavbar::fetchAndPaintData); graphicsScene = new QGraphicsScene(this); const QBrush bg = QBrush(QColor(74, 74, 74)); graphicsScene->setBackgroundBrush(bg); this->graphicsView->setAlignment(Qt::AlignLeft); this->graphicsView->setMinimumHeight(15); this->graphicsView->setMaximumHeight(15); this->graphicsView->setFrameShape(QFrame::NoFrame); this->graphicsView->setRenderHints({}); this->graphicsView->setScene(graphicsScene); this->graphicsView->setRenderHints(QPainter::Antialiasing); this->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // So the graphicsView doesn't intercept mouse events. this->graphicsView->setEnabled(false); this->graphicsView->setMouseTracking(true); setMouseTracking(true); } unsigned int nextPow2(unsigned int n) { unsigned int b = 0; while (n) { n >>= 1; b++; } return (1u << b); } void VisualNavbar::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); auto w = static_cast<unsigned int>(width()); bool fetch = false; if (statsWidth < w) { statsWidth = nextPow2(w); fetch = true; } else if (statsWidth > w * 4) { statsWidth = statsWidth > 0 ? statsWidth / 2 : 0; fetch = true; } if (fetch) { fetchAndPaintData(); } else if (previousWidth != w) { this->previousWidth = w; updateGraphicsScene(); } } void VisualNavbar::fetchAndPaintData() { fetchStats(); updateGraphicsScene(); } void VisualNavbar::fetchStats() { static const ut64 blocksCount = 2048; RzCoreLocked core(Core()); stats.reset(nullptr); auto list = fromOwned(rz_core_get_boundaries_prot(core, -1, NULL, "search")); if (!list) { return; } RzListIter *iter; RzIOMap *map; ut64 from = UT64_MAX; ut64 to = 0; CutterRzListForeach (list.get(), iter, RzIOMap, map) { ut64 f = rz_itv_begin(map->itv); ut64 t = rz_itv_end(map->itv); if (f < from) { from = f; } if (t > to) { to = t; } } to--; // rz_core_analysis_get_stats takes inclusive ranges if (to < from) { return; } stats.reset( rz_core_analysis_get_stats(core, from, to, RZ_MAX(1, (to + 1 - from) / blocksCount))); } enum class DataType : int { Empty, Code, String, Symbol, Count }; void VisualNavbar::updateGraphicsScene() { graphicsScene->clear(); xToAddress.clear(); seekGraphicsItem = nullptr; PCGraphicsItem = nullptr; graphicsScene->setBackgroundBrush(QBrush(Config()->getColor("gui.navbar.empty"))); if (!stats) { return; } int w = graphicsView->width(); int h = graphicsView->height(); RVA totalSize = stats->to - stats->from + 1; RVA beginAddr = stats->from; double widthPerByte = (double)w / (double)(totalSize ? totalSize : pow(2.0, 64.0)); // account for overflow on 2^64 auto xFromAddr = [widthPerByte, beginAddr](RVA addr) -> double { return (addr - beginAddr) * widthPerByte; }; std::array<QBrush, static_cast<int>(DataType::Count)> dataTypeBrushes; dataTypeBrushes[static_cast<int>(DataType::Code)] = QBrush(Config()->getColor("gui.navbar.code")); dataTypeBrushes[static_cast<int>(DataType::String)] = QBrush(Config()->getColor("gui.navbar.str")); dataTypeBrushes[static_cast<int>(DataType::Symbol)] = QBrush(Config()->getColor("gui.navbar.sym")); DataType lastDataType = DataType::Empty; QGraphicsRectItem *dataItem = nullptr; QRectF dataItemRect(0.0, 0.0, 0.0, h); for (size_t i = 0; i < rz_vector_len(&stats->blocks); i++) { RzCoreAnalysisStatsItem *block = reinterpret_cast<RzCoreAnalysisStatsItem *>(rz_vector_index_ptr(&stats->blocks, i)); ut64 from = rz_core_analysis_stats_get_block_from(stats.get(), i); ut64 to = rz_core_analysis_stats_get_block_to(stats.get(), i) + 1; // Keep track of where which memory segment is mapped so we are able to convert from // address to X coordinate and vice versa. XToAddress x2a; x2a.x_start = xFromAddr(from); x2a.x_end = xFromAddr(to); x2a.address_from = from; x2a.address_to = to; xToAddress.append(x2a); DataType dataType; if (block->functions) { dataType = DataType::Code; } else if (block->strings) { dataType = DataType::String; } else if (block->symbols) { dataType = DataType::Symbol; } else if (block->in_functions) { dataType = DataType::Code; } else { lastDataType = DataType::Empty; continue; } if (dataType == lastDataType) { double r = xFromAddr(to); if (r > dataItemRect.right()) { dataItemRect.setRight(r); dataItem->setRect(dataItemRect); } dataItem->setRect(dataItemRect); continue; } dataItemRect.setX(xFromAddr(from)); dataItemRect.setRight(xFromAddr(to)); dataItem = new QGraphicsRectItem(); dataItem->setPen(Qt::NoPen); dataItem->setBrush(dataTypeBrushes[static_cast<int>(dataType)]); graphicsScene->addItem(dataItem); lastDataType = dataType; } // Update scene width graphicsScene->setSceneRect(0, 0, w, h); drawSeekCursor(); } void VisualNavbar::drawCursor(RVA addr, QColor color, QGraphicsRectItem *&graphicsItem) { double cursor_x = addressToLocalX(addr); if (graphicsItem != nullptr) { graphicsScene->removeItem(graphicsItem); delete graphicsItem; graphicsItem = nullptr; } if (std::isnan(cursor_x)) { return; } int h = this->graphicsView->height(); graphicsItem = new QGraphicsRectItem(cursor_x, 0, 2, h); graphicsItem->setPen(Qt::NoPen); graphicsItem->setBrush(QBrush(color)); graphicsScene->addItem(graphicsItem); } void VisualNavbar::drawPCCursor() { drawCursor(Core()->getProgramCounterValue(), Config()->getColor("gui.navbar.pc"), PCGraphicsItem); } void VisualNavbar::drawSeekCursor() { drawCursor(Core()->getOffset(), Config()->getColor("gui.navbar.seek"), seekGraphicsItem); } void VisualNavbar::on_seekChanged(RVA addr) { Q_UNUSED(addr); // Update cursor this->drawSeekCursor(); } void VisualNavbar::mousePressEvent(QMouseEvent *event) { if (blockTooltip) { return; } qreal x = qhelpers::mouseEventPos(event).x(); RVA address = localXToAddress(x); if (address != RVA_INVALID) { auto tooltipPos = qhelpers::mouseEventGlobalPos(event); blockTooltip = true; // on Haiku, the below call sometimes triggers another mouseMoveEvent, // causing infinite recursion QToolTip::showText(tooltipPos, toolTipForAddress(address), this, this->rect()); blockTooltip = false; if (event->buttons() & Qt::LeftButton) { event->accept(); Core()->seek(address); } } } void VisualNavbar::mouseMoveEvent(QMouseEvent *event) { event->accept(); mousePressEvent(event); } RVA VisualNavbar::localXToAddress(double x) { for (const XToAddress &x2a : xToAddress) { if ((x2a.x_start <= x) && (x <= x2a.x_end)) { double offset = (x - x2a.x_start) / (x2a.x_end - x2a.x_start); double size = x2a.address_to - x2a.address_from; return x2a.address_from + (offset * size); } } return RVA_INVALID; } double VisualNavbar::addressToLocalX(RVA address) { for (const XToAddress &x2a : xToAddress) { if ((x2a.address_from <= address) && (address < x2a.address_to)) { double offset = (double)(address - x2a.address_from) / (double)(x2a.address_to - x2a.address_from); double size = x2a.x_end - x2a.x_start; return x2a.x_start + (offset * size); } } return nan(""); } QList<QString> VisualNavbar::sectionsForAddress(RVA address) { QList<QString> ret; QList<SectionDescription> sections = Core()->getAllSections(); for (const SectionDescription &section : sections) { if (address >= section.vaddr && address < section.vaddr + section.vsize) { ret << section.name; } } return ret; } QString VisualNavbar::toolTipForAddress(RVA address) { QString ret = "Address: " + RzAddressString(address); // Don't append sections when a debug task is in progress to avoid freezing the interface if (Core()->isDebugTaskInProgress()) { return ret; } auto sections = sectionsForAddress(address); if (sections.count()) { ret += "\nSections: \n"; bool first = true; for (const QString &section : sections) { if (!first) { ret.append(QLatin1Char('\n')); } else { first = false; } ret += " " + section; } } return ret; }
11,040
C++
.cpp
316
28.575949
100
0.640757
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,582
DisassemblerGraphView.cpp
rizinorg_cutter/src/widgets/DisassemblerGraphView.cpp
#include "DisassemblerGraphView.h" #include "common/CutterSeekable.h" #include "core/Cutter.h" #include "core/MainWindow.h" #include "common/Colors.h" #include "common/Configuration.h" #include "common/DisassemblyPreview.h" #include "common/TempConfig.h" #include "common/SyntaxHighlighter.h" #include "common/BasicBlockHighlighter.h" #include "common/BasicInstructionHighlighter.h" #include "common/Helpers.h" #include <QColorDialog> #include <QPainter> #include <QJsonObject> #include <QJsonArray> #include <QMouseEvent> #include <QPropertyAnimation> #include <QShortcut> #include <QToolTip> #include <QTextDocument> #include <QTextEdit> #include <QVBoxLayout> #include <QRegularExpression> #include <QClipboard> #include <QApplication> #include <QAction> #include <cmath> DisassemblerGraphView::DisassemblerGraphView(QWidget *parent, CutterSeekable *seekable, MainWindow *mainWindow, QList<QAction *> additionalMenuActions) : CutterGraphView(parent), blockMenu(new DisassemblyContextMenu(this, mainWindow)), contextMenu(new QMenu(this)), seekable(seekable), actionUnhighlight(this), actionUnhighlightInstruction(this) { highlight_token = nullptr; auto *layout = new QVBoxLayout(this); setTooltipStylesheet(); // Signals that require a refresh all connect(Config(), &Configuration::colorsUpdated, this, &DisassemblerGraphView::setTooltipStylesheet); connect(Core(), &CutterCore::refreshAll, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::commentsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::functionRenamed, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::flagsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::globalVarsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::varsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::instructionChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::breakpointsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::functionsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::asmOptionsChanged, this, &DisassemblerGraphView::refreshView); connect(Core(), &CutterCore::refreshCodeViews, this, &DisassemblerGraphView::refreshView); connectSeekChanged(false); // ESC for previous QShortcut *shortcut_escape = new QShortcut(QKeySequence(Qt::Key_Escape), this); shortcut_escape->setContext(Qt::WidgetShortcut); connect(shortcut_escape, &QShortcut::activated, seekable, &CutterSeekable::seekPrev); // Branch shortcuts QShortcut *shortcut_take_true = new QShortcut(QKeySequence(Qt::Key_T), this); shortcut_take_true->setContext(Qt::WidgetShortcut); connect(shortcut_take_true, &QShortcut::activated, this, &DisassemblerGraphView::takeTrue); QShortcut *shortcut_take_false = new QShortcut(QKeySequence(Qt::Key_F), this); shortcut_take_false->setContext(Qt::WidgetShortcut); connect(shortcut_take_false, &QShortcut::activated, this, &DisassemblerGraphView::takeFalse); // Navigation shortcuts QShortcut *shortcut_next_instr = new QShortcut(QKeySequence(Qt::Key_J), this); shortcut_next_instr->setContext(Qt::WidgetShortcut); connect(shortcut_next_instr, &QShortcut::activated, this, &DisassemblerGraphView::nextInstr); QShortcut *shortcut_prev_instr = new QShortcut(QKeySequence(Qt::Key_K), this); shortcut_prev_instr->setContext(Qt::WidgetShortcut); connect(shortcut_prev_instr, &QShortcut::activated, this, &DisassemblerGraphView::prevInstr); shortcuts.append(shortcut_escape); shortcuts.append(shortcut_next_instr); shortcuts.append(shortcut_prev_instr); // Context menu that applies to everything contextMenu->addAction(&actionExportGraph); contextMenu->addMenu(layoutMenu); contextMenu->addSeparator(); contextMenu->addActions(additionalMenuActions); QAction *highlightBB = new QAction(this); actionUnhighlight.setVisible(false); highlightBB->setText(tr("Highlight block")); connect(highlightBB, &QAction::triggered, this, [this]() { auto bbh = Core()->getBBHighlighter(); RVA currBlockEntry = blockForAddress(this->seekable->getOffset())->entry; QColor background = disassemblyBackgroundColor; if (auto block = bbh->getBasicBlock(currBlockEntry)) { background = block->color; } QColor c = QColorDialog::getColor(background, this, QString(), QColorDialog::DontUseNativeDialog); if (c.isValid()) { bbh->highlight(currBlockEntry, c); } emit Config()->colorsUpdated(); }); actionUnhighlight.setText(tr("Unhighlight block")); connect(&actionUnhighlight, &QAction::triggered, this, [this]() { auto bbh = Core()->getBBHighlighter(); bbh->clear(blockForAddress(this->seekable->getOffset())->entry); emit Config()->colorsUpdated(); }); QAction *highlightBI = new QAction(this); actionUnhighlightInstruction.setVisible(false); highlightBI->setText(tr("Highlight instruction")); connect(highlightBI, &QAction::triggered, this, &DisassemblerGraphView::onActionHighlightBITriggered); actionUnhighlightInstruction.setText(tr("Unhighlight instruction")); connect(&actionUnhighlightInstruction, &QAction::triggered, this, &DisassemblerGraphView::onActionUnhighlightBITriggered); blockMenu->addAction(highlightBB); blockMenu->addAction(&actionUnhighlight); blockMenu->addAction(highlightBI); blockMenu->addAction(&actionUnhighlightInstruction); // Include all actions from generic context menu in block specific menu blockMenu->addSeparator(); blockMenu->addActions(contextMenu->actions()); connect(blockMenu, &DisassemblyContextMenu::copy, this, &DisassemblerGraphView::copySelection); // Add header as widget to layout so it stretches to the layout width layout->setContentsMargins(0, 0, 0, 0); layout->setAlignment(Qt::AlignTop); this->scale_thickness_multiplier = true; installEventFilter(this); } void DisassemblerGraphView::connectSeekChanged(bool disconn) { if (disconn) { disconnect(seekable, &CutterSeekable::seekableSeekChanged, this, &DisassemblerGraphView::onSeekChanged); } else { connect(seekable, &CutterSeekable::seekableSeekChanged, this, &DisassemblerGraphView::onSeekChanged); } } DisassemblerGraphView::~DisassemblerGraphView() { qDeleteAll(shortcuts); shortcuts.clear(); } void DisassemblerGraphView::refreshView() { CutterGraphView::refreshView(); loadCurrentGraph(); breakpoints = Core()->getBreakpointsAddresses(); emit viewRefreshed(); } void DisassemblerGraphView::loadCurrentGraph() { TempConfig tempConfig; tempConfig.set("scr.color", COLOR_MODE_16M) .set("asm.bb.line", false) .set("asm.lines", false) .set("asm.lines.fcn", false); disassembly_blocks.clear(); blocks.clear(); if (highlight_token) { delete highlight_token; highlight_token = nullptr; } RzAnalysisFunction *fcn = Core()->functionIn(seekable->getOffset()); windowTitle = tr("Graph"); if (fcn && RZ_STR_ISNOTEMPTY(fcn->name)) { currentFcnAddr = fcn->addr; auto fcnName = fromOwned(rz_str_escape_utf8_for_json(fcn->name, -1)); windowTitle += QString("(%0)").arg(fcnName.get()); } else { windowTitle += "(Empty)"; } emit nameChanged(windowTitle); emptyGraph = !fcn; if (emptyGraph) { // If there's no function to print, just add a message if (!emptyText) { emptyText = new QLabel(this); emptyText->setText(tr("No function detected. Cannot display graph.")); emptyText->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); layout()->addWidget(emptyText); layout()->setAlignment(emptyText, Qt::AlignHCenter); } emptyText->setVisible(true); } else if (emptyText) { emptyText->setVisible(false); } // Refresh global "empty graph" variable so other widget know there is nothing to show here Core()->setGraphEmpty(emptyGraph); setEntry(fcn ? fcn->addr : RVA_INVALID); if (!fcn) { return; } for (const auto &bbi : CutterPVector<RzAnalysisBlock>(fcn->bbs)) { RVA bbiFail = bbi->fail; RVA bbiJump = bbi->jump; DisassemblyBlock db; GraphBlock gb; gb.entry = bbi->addr; db.entry = bbi->addr; if (Config()->getGraphBlockEntryOffset()) { // QColor(0,0,0,0) is transparent db.header_text = Text("[" + RzAddressString(db.entry) + "]", ConfigColor("offset"), QColor(0, 0, 0, 0)); } db.true_path = RVA_INVALID; db.false_path = RVA_INVALID; if (bbiFail) { db.false_path = bbiFail; gb.edges.emplace_back(bbiFail); } if (bbiJump) { if (bbiFail) { db.true_path = bbiJump; } gb.edges.emplace_back(bbiJump); } RzAnalysisSwitchOp *switchOp = bbi->switch_op; if (switchOp) { for (const auto &caseOp : CutterRzList<RzAnalysisCaseOp>(switchOp->cases)) { if (caseOp->jump == RVA_INVALID) { continue; } gb.edges.emplace_back(caseOp->jump); } } RzCoreLocked core(Core()); std::unique_ptr<ut8[]> buf { new ut8[bbi->size] }; if (!buf) { break; } rz_io_read_at(core->io, bbi->addr, buf.get(), (int)bbi->size); auto vec = fromOwned( rz_pvector_new(reinterpret_cast<RzPVectorFree>(rz_analysis_disasm_text_free))); if (!vec) { break; } RzCoreDisasmOptions options = {}; options.vec = vec.get(); options.cbytes = 1; rz_core_print_disasm(core, bbi->addr, buf.get(), (int)bbi->size, (int)bbi->size, NULL, &options); auto vecVisitor = CutterPVector<RzAnalysisDisasmText>(vec.get()); auto iter = vecVisitor.begin(); while (iter != vecVisitor.end()) { RzAnalysisDisasmText *op = *iter; Instr instr; instr.addr = op->offset; ++iter; if (iter != vecVisitor.end()) { // get instruction size from distance to next instruction ... RVA nextOffset = (*iter)->offset; instr.size = nextOffset - instr.addr; } else { // or to the end of the block. instr.size = (bbi->addr + bbi->size) - instr.addr; } QTextDocument textDoc; textDoc.setHtml(CutterCore::ansiEscapeToHtml(op->text)); instr.plainText = textDoc.toPlainText(); RichTextPainter::List richText = RichTextPainter::fromTextDocument(textDoc); // Colors::colorizeAssembly(richText, textDoc.toPlainText(), 0); bool cropped; int blockLength = Config()->getGraphBlockMaxChars() + Core()->getConfigb("asm.bytes") * 24 + Core()->getConfigb("asm.emu") * 10; instr.text = Text(RichTextPainter::cropped(richText, blockLength, "...", &cropped)); if (cropped) instr.fullText = richText; else instr.fullText = Text(); db.instrs.push_back(instr); } disassembly_blocks[db.entry] = db; prepareGraphNode(gb); addBlock(gb); } cleanupEdges(blocks); computeGraphPlacement(); } DisassemblerGraphView::EdgeConfigurationMapping DisassemblerGraphView::getEdgeConfigurations() { EdgeConfigurationMapping result; for (auto &block : blocks) { for (const auto &edge : block.second.edges) { result[{ block.first, edge.target }] = edgeConfiguration(block.second, &blocks[edge.target], false); } } return result; } void DisassemblerGraphView::prepareGraphNode(GraphBlock &block) { DisassemblyBlock &db = disassembly_blocks[block.entry]; int width = 0; int height = 0; for (auto &line : db.header_text.lines) { int lw = 0; for (auto &part : line) lw += mFontMetrics->width(part.text); if (lw > width) width = lw; height += 1; } for (Instr &instr : db.instrs) { for (auto &line : instr.text.lines) { int lw = 0; for (auto &part : line) lw += mFontMetrics->width(part.text); if (lw > width) width = lw; height += 1; } } int extra = static_cast<int>(2 * padding + 4); qreal indent = ACharWidth; block.width = static_cast<int>(width + extra + indent); block.height = (height * charHeight) + extra; } void DisassemblerGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, bool interactive) { QRectF blockRect(block.x, block.y, block.width, block.height); p.setPen(Qt::black); p.setBrush(Qt::gray); p.setFont(Config()->getFont()); p.drawRect(blockRect); // Render node DisassemblyBlock &db = disassembly_blocks[block.entry]; bool block_selected = false; RVA selected_instruction = RVA_INVALID; // Figure out if the current block is selected RVA addr = seekable->getOffset(); RVA PCAddr = Core()->getProgramCounterValue(); for (const Instr &instr : db.instrs) { if (instr.contains(addr) && interactive) { block_selected = true; selected_instruction = instr.addr; } // TODO: L219 } p.setPen(QColor(0, 0, 0, 0)); if (db.terminal) { p.setBrush(retShadowColor); } else if (db.indirectcall) { p.setBrush(indirectcallShadowColor); } else { p.setBrush(QColor(0, 0, 0, 100)); } p.setPen(QPen(graphNodeColor, 1)); if (block_selected) { p.setBrush(disassemblySelectedBackgroundColor); } else { p.setBrush(disassemblyBackgroundColor); } // Draw basic block background p.drawRect(blockRect); auto bb = Core()->getBBHighlighter()->getBasicBlock(block.entry); if (bb) { QColor color(bb->color); p.setBrush(color); p.drawRect(blockRect); } const int firstInstructionY = block.y + getInstructionOffset(db, 0).y(); // Stop rendering text when it's too small auto transform = p.combinedTransform(); QRect screenChar = transform.mapRect(QRect(0, 0, ACharWidth, charHeight)); if (screenChar.width() < Config()->getGraphMinFontSize()) { return; } qreal indent = ACharWidth; // Highlight selected tokens if (interactive && highlight_token != nullptr) { int y = firstInstructionY; qreal tokenWidth = mFontMetrics->width(highlight_token->content); for (const Instr &instr : db.instrs) { int pos = -1; while ((pos = instr.plainText.indexOf(highlight_token->content, pos + 1)) != -1) { int tokenEnd = pos + highlight_token->content.length(); if ((pos > 0 && instr.plainText[pos - 1].isLetterOrNumber()) || (tokenEnd < instr.plainText.length() && instr.plainText[tokenEnd].isLetterOrNumber())) { continue; } qreal widthBefore = mFontMetrics->width(instr.plainText.left(pos)); qreal textOffset = padding + indent; if (textOffset + widthBefore > block.width - (10 + padding)) { continue; } qreal highlightWidth = tokenWidth; if (textOffset + widthBefore + tokenWidth >= block.width - (10 + padding)) { highlightWidth = block.width - widthBefore - (10 + 2 * padding); } QColor selectionColor = ConfigColor("wordHighlight"); p.fillRect( QRectF(block.x + textOffset + widthBefore, y, highlightWidth, charHeight), selectionColor); } y += int(instr.text.lines.size()) * charHeight; } } // Render node text auto x = block.x + padding; int y = block.y + getTextOffset(0).y(); for (auto &line : db.header_text.lines) { RichTextPainter::paintRichText<qreal>(&p, x, y, block.width, charHeight, 0, line, mFontMetrics.get()); y += charHeight; } auto bih = Core()->getBIHighlighter(); for (const Instr &instr : db.instrs) { const QRect instrRect = QRect(static_cast<int>(block.x + indent), y, static_cast<int>(block.width - (10 + padding)), int(instr.text.lines.size()) * charHeight); QColor instrColor; if (Core()->isBreakpoint(breakpoints, instr.addr)) { instrColor = ConfigColor("gui.breakpoint_background"); } else if (instr.addr == PCAddr) { instrColor = PCSelectionColor; } else if (auto background = bih->getBasicInstruction(instr.addr)) { instrColor = background->color; } if (instrColor.isValid()) { p.fillRect(instrRect, instrColor); } if (selected_instruction != RVA_INVALID && selected_instruction == instr.addr) { p.fillRect(instrRect, disassemblySelectionColor); } for (auto &line : instr.text.lines) { RichTextPainter::paintRichText<qreal>(&p, x + indent, y, block.width - padding, charHeight, 0, line, mFontMetrics.get()); y += charHeight; } } } GraphView::EdgeConfiguration DisassemblerGraphView::edgeConfiguration(GraphView::GraphBlock &from, GraphView::GraphBlock *to, bool interactive) { EdgeConfiguration ec; DisassemblyBlock &db = disassembly_blocks[from.entry]; if (to->entry == db.true_path) { ec.color = brtrueColor; } else if (to->entry == db.false_path) { ec.color = brfalseColor; } else { ec.color = jmpColor; } ec.start_arrow = false; ec.end_arrow = true; if (interactive) { if (from.entry == currentBlockAddress) { ec.width_scale = 2.0; } else if (to->entry == currentBlockAddress) { ec.width_scale = 2.0; } } return ec; } bool DisassemblerGraphView::eventFilter(QObject *obj, QEvent *event) { if ((Config()->getGraphPreview() || Config()->getShowVarTooltips()) && event->type() == QEvent::Type::ToolTip) { QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event); QPoint pointOfEvent = helpEvent->globalPos(); QPoint point = viewToLogicalCoordinates(helpEvent->pos()); if (auto block = getBlockContaining(point)) { // Get pos relative to start of block QPoint pos = point - QPoint(block->x, block->y); // offsetFrom is the address which on top the cursor triggered this RVA offsetFrom = RVA_INVALID; /* * getAddrForMouseEvent() doesn't work for jmps, like * getInstrForMouseEvent() with false as a 3rd argument. */ Instr *inst = getInstrForMouseEvent(*block, &pos, true); if (inst != nullptr) { offsetFrom = inst->addr; } // Don't preview anything for a small scale if (getViewScale() >= 0.8) { if (Config()->getGraphPreview() && DisassemblyPreview::showDisasPreview(this, pointOfEvent, offsetFrom)) { return true; } if (Config()->getShowVarTooltips() && inst) { auto token = getToken(inst, pos.x()); if (token && DisassemblyPreview::showDebugValueTooltip(this, pointOfEvent, token->content, offsetFrom)) { return true; } } } } } return CutterGraphView::eventFilter(obj, event); } RVA DisassemblerGraphView::getAddrForMouseEvent(GraphBlock &block, QPoint *point) { DisassemblyBlock &db = disassembly_blocks[block.entry]; // Remove header and margin int off_y = getInstructionOffset(db, 0).y(); // Get mouse coordinate over the actual text int text_point_y = point->y() - off_y; int mouse_row = text_point_y / charHeight; // If mouse coordinate is in header region or margin above if (mouse_row < 0) { return db.entry; } Instr *instr = getInstrForMouseEvent(block, point); if (instr) { return instr->addr; } return RVA_INVALID; } DisassemblerGraphView::Instr * DisassemblerGraphView::getInstrForMouseEvent(GraphView::GraphBlock &block, QPoint *point, bool force) { DisassemblyBlock &db = disassembly_blocks[block.entry]; // Remove header and margin int off_y = getInstructionOffset(db, 0).y(); // Get mouse coordinate over the actual text int text_point_y = point->y() - off_y; int mouse_row = text_point_y / charHeight; // Row in actual text int cur_row = 0; for (Instr &instr : db.instrs) { if (mouse_row < cur_row + (int)instr.text.lines.size()) { return &instr; } cur_row += instr.text.lines.size(); } if (force && !db.instrs.empty()) { if (mouse_row <= 0) { return &db.instrs.front(); } else { return &db.instrs.back(); } } return nullptr; } QRectF DisassemblerGraphView::getInstrRect(GraphView::GraphBlock &block, RVA addr) const { auto blockIt = disassembly_blocks.find(block.entry); if (blockIt == disassembly_blocks.end()) { return QRectF(); } auto &db = blockIt->second; if (db.instrs.empty()) { return QRectF(); } size_t sequenceAddr = db.instrs[0].addr; size_t firstLineWithAddr = 0; size_t currentLine = 0; for (size_t i = 0; i < db.instrs.size(); i++) { auto &instr = db.instrs[i]; if (instr.addr != sequenceAddr) { sequenceAddr = instr.addr; firstLineWithAddr = currentLine; } if (instr.contains(addr)) { while (i < db.instrs.size() && db.instrs[i].addr == sequenceAddr) { currentLine += db.instrs[i].text.lines.size(); i++; } QPointF topLeft = getInstructionOffset(db, static_cast<int>(firstLineWithAddr)); return QRectF(topLeft, QSizeF(block.width - 2 * padding, charHeight * int(currentLine - firstLineWithAddr))); } currentLine += instr.text.lines.size(); } return QRectF(); } void DisassemblerGraphView::showInstruction(GraphView::GraphBlock &block, RVA addr) { QRectF rect = getInstrRect(block, addr); rect.translate(block.x, block.y); showRectangle(QRect(rect.x(), rect.y(), rect.width(), rect.height()), true); } DisassemblerGraphView::DisassemblyBlock *DisassemblerGraphView::blockForAddress(RVA addr) { for (auto &blockIt : disassembly_blocks) { DisassemblyBlock &db = blockIt.second; for (const Instr &i : db.instrs) { if (i.addr == RVA_INVALID || i.size == RVA_INVALID) { continue; } if (i.contains(addr)) { return &db; } } } return nullptr; } const DisassemblerGraphView::Instr *DisassemblerGraphView::instrForAddress(RVA addr) { DisassemblyBlock *block = blockForAddress(addr); for (const Instr &i : block->instrs) { if (i.addr == RVA_INVALID || i.size == RVA_INVALID) { continue; } if (i.contains(addr)) { return &i; } } return nullptr; } void DisassemblerGraphView::onSeekChanged(RVA addr) { blockMenu->setOffset(addr); DisassemblyBlock *db = blockForAddress(addr); bool switchFunction = false; if (!db) { // not in this function, try refreshing refreshView(); db = blockForAddress(addr); switchFunction = true; } if (db) { // This is a local address! We animated to it. transition_dont_seek = true; showBlock(blocks[db->entry], !switchFunction); showInstruction(blocks[db->entry], addr); } } void DisassemblerGraphView::takeTrue() { DisassemblyBlock *db = blockForAddress(seekable->getOffset()); if (!db) { return; } if (db->true_path != RVA_INVALID) { seekable->seek(db->true_path); } else if (!blocks[db->entry].edges.empty()) { seekable->seek(blocks[db->entry].edges[0].target); } } void DisassemblerGraphView::takeFalse() { DisassemblyBlock *db = blockForAddress(seekable->getOffset()); if (!db) { return; } if (db->false_path != RVA_INVALID) { seekable->seek(db->false_path); } else if (!blocks[db->entry].edges.empty()) { seekable->seek(blocks[db->entry].edges[0].target); } } void DisassemblerGraphView::setTooltipStylesheet() { setStyleSheet(DisassemblyPreview::getToolTipStyleSheet()); } void DisassemblerGraphView::seekInstruction(bool previous_instr) { RVA addr = seekable->getOffset(); DisassemblyBlock *db = blockForAddress(addr); if (!db) { return; } for (size_t i = 0; i < db->instrs.size(); i++) { Instr &instr = db->instrs[i]; if (!instr.contains(addr)) { continue; } // Found the instruction. Check if a next one exists if (!previous_instr && (i < db->instrs.size() - 1)) { seekable->seek(db->instrs[i + 1].addr); } else if (previous_instr && (i > 0)) { while (i > 0 && db->instrs[i].addr == addr) { // jump over 0 size instructions i--; } seekable->seek(db->instrs[i].addr); break; } } } void DisassemblerGraphView::nextInstr() { seekInstruction(false); } void DisassemblerGraphView::prevInstr() { seekInstruction(true); } void DisassemblerGraphView::seekLocal(RVA addr, bool update_viewport) { RVA curAddr = seekable->getOffset(); if (addr == curAddr) { return; } connectSeekChanged(true); seekable->seek(addr); connectSeekChanged(false); if (update_viewport) { viewport()->update(); } } void DisassemblerGraphView::copySelection() { if (!highlight_token) return; QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(highlight_token->content); } DisassemblerGraphView::Token *DisassemblerGraphView::getToken(Instr *instr, int x) { x -= (int)(padding + ACharWidth); // Ignore left margin if (x < 0) { return nullptr; } int clickedCharPos = mFontMetrics->position(instr->plainText, x); if (clickedCharPos > instr->plainText.length()) { return nullptr; } static const QRegularExpression tokenRegExp(R"(\b(?<!\.)([^\s]+)\b(?!\.))"); QRegularExpressionMatchIterator i = tokenRegExp.globalMatch(instr->plainText); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); if (match.capturedStart() <= clickedCharPos && match.capturedEnd() > clickedCharPos) { auto t = new Token; t->start = match.capturedStart(); t->length = match.capturedLength(); t->content = match.captured(); t->instr = instr; return t; } } return nullptr; } QPoint DisassemblerGraphView::getInstructionOffset(const DisassemblyBlock &block, int line) const { return getTextOffset(line + static_cast<int>(block.header_text.lines.size())); } void DisassemblerGraphView::blockClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) { Instr *instr = getInstrForMouseEvent(block, &pos, event->button() == Qt::RightButton); if (!instr) { return; } currentBlockAddress = block.entry; highlight_token = getToken(instr, pos.x()); RVA addr = instr->addr; seekLocal(addr); blockMenu->setOffset(addr); blockMenu->setCanCopy(highlight_token); if (highlight_token) { blockMenu->setCurHighlightedWord(highlight_token->content); } viewport()->update(); } void DisassemblerGraphView::blockContextMenuRequested(GraphView::GraphBlock &block, QContextMenuEvent *event, QPoint /*pos*/) { const RVA offset = this->seekable->getOffset(); actionUnhighlight.setVisible(Core()->getBBHighlighter()->getBasicBlock(block.entry)); actionUnhighlightInstruction.setVisible( Core()->getBIHighlighter()->getBasicInstruction(offset)); event->accept(); blockMenu->exec(event->globalPos()); } void DisassemblerGraphView::contextMenuEvent(QContextMenuEvent *event) { GraphView::contextMenuEvent(event); if (!event->isAccepted()) { // TODO: handle opening block menu using keyboard contextMenu->exec(event->globalPos()); event->accept(); } } void DisassemblerGraphView::showExportDialog() { if (currentFcnAddr == RVA_INVALID) { qWarning() << "Cannot find current function."; return; } QString defaultName = "graph"; if (auto f = Core()->functionIn(currentFcnAddr)) { QString functionName = f->name; // don't confuse image type guessing and make c++ names somewhat usable functionName.replace(QRegularExpression("[.:]"), "_"); functionName.remove(QRegularExpression("[^a-zA-Z0-9_].*")); if (!functionName.isEmpty()) { defaultName = functionName; } } showExportGraphDialog(defaultName, RZ_CORE_GRAPH_TYPE_BLOCK_FUN, currentFcnAddr); } void DisassemblerGraphView::blockDoubleClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) { Q_UNUSED(event); seekable->seekToReference(getAddrForMouseEvent(block, &pos)); } void DisassemblerGraphView::blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, QPoint pos) { Instr *instr = getInstrForMouseEvent(block, &pos); if (!instr || instr->fullText.lines.empty()) { QToolTip::hideText(); event->ignore(); return; } QToolTip::showText(event->globalPos(), instr->fullText.ToQString()); } bool DisassemblerGraphView::helpEvent(QHelpEvent *event) { if (!GraphView::helpEvent(event)) { QToolTip::hideText(); event->ignore(); } return true; } void DisassemblerGraphView::blockTransitionedTo(GraphView::GraphBlock *to) { currentBlockAddress = to->entry; if (transition_dont_seek) { transition_dont_seek = false; return; } seekLocal(to->entry); } void DisassemblerGraphView::onActionHighlightBITriggered() { const RVA offset = this->seekable->getOffset(); const Instr *instr = instrForAddress(offset); if (!instr) { return; } auto bih = Core()->getBIHighlighter(); QColor background = ConfigColor("linehl"); if (auto currentColor = bih->getBasicInstruction(offset)) { background = currentColor->color; } QColor c = QColorDialog::getColor(background, this, QString(), QColorDialog::DontUseNativeDialog); if (c.isValid()) { bih->highlight(instr->addr, instr->size, c); } Config()->colorsUpdated(); } void DisassemblerGraphView::onActionUnhighlightBITriggered() { const RVA offset = this->seekable->getOffset(); const Instr *instr = instrForAddress(offset); if (!instr) { return; } auto bih = Core()->getBIHighlighter(); bih->clear(instr->addr, instr->size); Config()->colorsUpdated(); } void DisassemblerGraphView::restoreCurrentBlock() { onSeekChanged(this->seekable->getOffset()); // try to keep the view on current block } void DisassemblerGraphView::paintEvent(QPaintEvent *event) { // DisassemblerGraphView is always dirty setCacheDirty(); GraphView::paintEvent(event); } bool DisassemblerGraphView::Instr::contains(ut64 addr) const { return this->addr <= addr && (addr - this->addr) < size; }
33,314
C++
.cpp
867
30.279123
99
0.623494
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,583
ExportsWidget.cpp
rizinorg_cutter/src/widgets/ExportsWidget.cpp
#include "ExportsWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "WidgetShortcuts.h" #include <QShortcut> ExportsModel::ExportsModel(QList<ExportDescription> *exports, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), exports(exports) { } int ExportsModel::rowCount(const QModelIndex &) const { return exports->count(); } int ExportsModel::columnCount(const QModelIndex &) const { return ExportsModel::ColumnCount; } QVariant ExportsModel::data(const QModelIndex &index, int role) const { if (index.row() >= exports->count()) return QVariant(); const ExportDescription &exp = exports->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case ExportsModel::OffsetColumn: return RzAddressString(exp.vaddr); case ExportsModel::SizeColumn: return RzSizeString(exp.size); case ExportsModel::TypeColumn: return exp.type; case ExportsModel::NameColumn: return exp.name; case ExportsModel::CommentColumn: return Core()->getCommentAt(exp.vaddr); default: return QVariant(); } case ExportsModel::ExportDescriptionRole: return QVariant::fromValue(exp); default: return QVariant(); } } QVariant ExportsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case ExportsModel::OffsetColumn: return tr("Address"); case ExportsModel::SizeColumn: return tr("Size"); case ExportsModel::TypeColumn: return tr("Type"); case ExportsModel::NameColumn: return tr("Name"); case ExportsModel::CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA ExportsModel::address(const QModelIndex &index) const { const ExportDescription &exp = exports->at(index.row()); return exp.vaddr; } QString ExportsModel::name(const QModelIndex &index) const { const ExportDescription &exp = exports->at(index.row()); return exp.name; } ExportsProxyModel::ExportsProxyModel(ExportsModel *source_model, QObject *parent) : AddressableFilterProxyModel(source_model, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool ExportsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); auto exp = index.data(ExportsModel::ExportDescriptionRole).value<ExportDescription>(); return qhelpers::filterStringContains(exp.name, this); } bool ExportsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftExp = left.data(ExportsModel::ExportDescriptionRole).value<ExportDescription>(); auto rightExp = right.data(ExportsModel::ExportDescriptionRole).value<ExportDescription>(); switch (left.column()) { case ExportsModel::SizeColumn: if (leftExp.size != rightExp.size) return leftExp.size < rightExp.size; // fallthrough case ExportsModel::OffsetColumn: if (leftExp.vaddr != rightExp.vaddr) return leftExp.vaddr < rightExp.vaddr; // fallthrough case ExportsModel::NameColumn: if (leftExp.name != rightExp.name) return leftExp.name < rightExp.name; // fallthrough case ExportsModel::TypeColumn: if (leftExp.type != rightExp.type) return leftExp.type < rightExp.type; // fallthrough case ExportsModel::CommentColumn: return Core()->getCommentAt(leftExp.vaddr) < Core()->getCommentAt(rightExp.vaddr); default: break; } // fallback return leftExp.vaddr < rightExp.vaddr; } ExportsWidget::ExportsWidget(MainWindow *main) : ListDockWidget(main) { setWindowTitle(tr("Exports")); setObjectName("ExportsWidget"); exportsModel = new ExportsModel(&exports, this); exportsProxyModel = new ExportsProxyModel(exportsModel, this); setModels(exportsProxyModel); ui->treeView->sortByColumn(ExportsModel::OffsetColumn, Qt::AscendingOrder); QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["ExportsWidget"], main); connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(Core(), &CutterCore::codeRebased, this, &ExportsWidget::refreshExports); connect(Core(), &CutterCore::refreshAll, this, &ExportsWidget::refreshExports); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(exportsModel, ExportsModel::CommentColumn); }); } ExportsWidget::~ExportsWidget() {} void ExportsWidget::refreshExports() { exportsModel->beginResetModel(); exports = Core()->getAllExports(); exportsModel->endResetModel(); qhelpers::adjustColumns(ui->treeView, 3, 0); }
5,103
C++
.cpp
141
30.546099
98
0.701154
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,584
OverviewView.cpp
rizinorg_cutter/src/widgets/OverviewView.cpp
#include "OverviewView.h" #include <QPainter> #include <QMouseEvent> #include "core/Cutter.h" #include "common/Colors.h" #include "common/Configuration.h" #include "common/TempConfig.h" OverviewView::OverviewView(QWidget *parent) : GraphView(parent) { connect(Config(), &Configuration::colorsUpdated, this, &OverviewView::colorsUpdatedSlot); colorsUpdatedSlot(); } void OverviewView::setData(int baseWidth, int baseHeight, std::unordered_map<ut64, GraphBlock> baseBlocks, DisassemblerGraphView::EdgeConfigurationMapping baseEdgeConfigurations) { width = baseWidth; height = baseHeight; blocks = baseBlocks; edgeConfigurations = baseEdgeConfigurations; scaleAndCenter(); setCacheDirty(); viewport()->update(); } void OverviewView::centreRect() { qreal w = rangeRect.width(); qreal h = rangeRect.height(); initialDiff = QPointF(w / 2, h / 2); } OverviewView::~OverviewView() {} void OverviewView::scaleAndCenter() { qreal wScale = (qreal)viewport()->width() / width; qreal hScale = (qreal)viewport()->height() / height; setViewScale(std::min(wScale, hScale)); center(); } void OverviewView::refreshView() { scaleAndCenter(); viewport()->update(); } void OverviewView::drawBlock(QPainter &p, GraphView::GraphBlock &block, bool interactive) { Q_UNUSED(interactive) QRectF blockRect(block.x, block.y, block.width, block.height); p.setPen(Qt::black); p.setBrush(Qt::gray); p.drawRect(blockRect); p.setBrush(QColor(0, 0, 0, 100)); p.drawRect(blockRect.translated(2, 2)); // Draw basic block highlighting/tracing auto bb = Core()->getBBHighlighter()->getBasicBlock(block.entry); if (bb) { QColor color(bb->color); color.setAlphaF(0.5); p.setBrush(color); } else { p.setBrush(disassemblyBackgroundColor); } p.setPen(QPen(graphNodeColor, 1)); p.drawRect(blockRect); } void OverviewView::paintEvent(QPaintEvent *event) { GraphView::paintEvent(event); if (rangeRect.width() == 0 && rangeRect.height() == 0) { return; } QPainter p(viewport()); p.setPen(graphSelectionBorder); p.setBrush(graphSelectionFill); p.drawRect(rangeRect); } void OverviewView::mousePressEvent(QMouseEvent *event) { mouseActive = true; auto pos = qhelpers::mouseEventPos(event); if (rangeRect.contains(pos)) { initialDiff = pos - rangeRect.topLeft(); } else { QPointF size(rangeRect.width(), rangeRect.height()); initialDiff = size * 0.5; rangeRect.moveCenter(pos); viewport()->update(); emit mouseMoved(); } } void OverviewView::mouseReleaseEvent(QMouseEvent *event) { mouseActive = false; GraphView::mouseReleaseEvent(event); } void OverviewView::mouseMoveEvent(QMouseEvent *event) { if (!mouseActive) { return; } QPointF topLeft = qhelpers::mouseEventPos(event) - initialDiff; rangeRect.setTopLeft(topLeft); viewport()->update(); emit mouseMoved(); } void OverviewView::wheelEvent(QWheelEvent *event) { event->ignore(); } GraphView::EdgeConfiguration OverviewView::edgeConfiguration(GraphView::GraphBlock &from, GraphView::GraphBlock *to, bool interactive) { Q_UNUSED(interactive) EdgeConfiguration ec; auto baseEcIt = edgeConfigurations.find({ from.entry, to->entry }); if (baseEcIt != edgeConfigurations.end()) ec = baseEcIt->second; ec.width_scale = 1.0 / getViewScale(); return ec; } void OverviewView::colorsUpdatedSlot() { disassemblyBackgroundColor = ConfigColor("gui.overview.node"); graphNodeColor = ConfigColor("gui.border"); backgroundColor = ConfigColor("gui.background"); graphSelectionFill = ConfigColor("gui.overview.fill"); graphSelectionBorder = ConfigColor("gui.overview.border"); setCacheDirty(); refreshView(); } void OverviewView::setRangeRect(QRectF rect) { rangeRect = rect; viewport()->update(); }
4,156
C++
.cpp
135
25.562963
98
0.677992
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,585
HexWidget.cpp
rizinorg_cutter/src/widgets/HexWidget.cpp
#include "HexWidget.h" #include "Cutter.h" #include "Configuration.h" #include "dialogs/WriteCommandsDialogs.h" #include "dialogs/CommentsDialog.h" #include <QPainter> #include <QPaintEvent> #include <QResizeEvent> #include <QMouseEvent> #include <QKeyEvent> #include <QWheelEvent> #include <QtEndian> #include <QScrollBar> #include <QMenu> #include <QClipboard> #include <QApplication> #include <QInputDialog> #include <QPushButton> #include <QJsonObject> #include <QJsonArray> #include <QRegularExpression> #include <QToolTip> #include <QActionGroup> static constexpr uint64_t MAX_COPY_SIZE = 128 * 1024 * 1024; static constexpr int MAX_LINE_WIDTH_PRESET = 32; static constexpr int MAX_LINE_WIDTH_BYTES = 128 * 1024; static constexpr int WARNING_TIME_MS = 500; HexWidget::HexWidget(QWidget *parent) : QScrollArea(parent), cursorEnabled(true), cursorOnAscii(false), updatingSelection(false), itemByteLen(1), itemGroupSize(1), rowSizeBytes(16), columnMode(ColumnMode::PowerOf2), itemFormat(ItemFormatHex), itemBigEndian(false), addrCharLen(AddrWidth64), showHeader(true), showAscii(true), showExHex(true), showExAddr(true), warningTimer(this) { setMouseTracking(true); setFocusPolicy(Qt::FocusPolicy::StrongFocus); connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, [this]() { viewport()->update(); }); connect(Config(), &Configuration::colorsUpdated, this, &HexWidget::updateColors); connect(Config(), &Configuration::fontsUpdated, this, [this]() { setMonospaceFont(Config()->getFont()); }); auto sizeActionGroup = new QActionGroup(this); for (int i = 1; i <= 8; i *= 2) { QAction *action = new QAction(QString::number(i), this); action->setCheckable(true); action->setActionGroup(sizeActionGroup); connect(action, &QAction::triggered, this, [=]() { setItemSize(i); }); actionsItemSize.append(action); } actionsItemSize.at(0)->setChecked(true); /* Follow the order in ItemFormat enum */ QStringList names; names << tr("Hexadecimal"); names << tr("Octal"); names << tr("Decimal"); names << tr("Signed decimal"); names << tr("Float"); auto formatActionGroup = new QActionGroup(this); for (int i = 0; i < names.length(); ++i) { QAction *action = new QAction(names.at(i), this); action->setCheckable(true); action->setActionGroup(formatActionGroup); connect(action, &QAction::triggered, this, [=]() { setItemFormat(static_cast<ItemFormat>(i)); }); actionsItemFormat.append(action); } actionsItemFormat.at(0)->setChecked(true); actionsItemFormat.at(ItemFormatFloat)->setEnabled(false); rowSizeMenu = new QMenu(tr("Bytes per row"), this); auto columnsActionGroup = new QActionGroup(this); for (int i = 1; i <= MAX_LINE_WIDTH_PRESET; i *= 2) { QAction *action = new QAction(QString::number(i), rowSizeMenu); action->setCheckable(true); action->setActionGroup(columnsActionGroup); connect(action, &QAction::triggered, this, [=]() { setFixedLineSize(i); }); rowSizeMenu->addAction(action); } rowSizeMenu->addSeparator(); actionRowSizePowerOf2 = new QAction(tr("Power of 2"), this); actionRowSizePowerOf2->setCheckable(true); actionRowSizePowerOf2->setActionGroup(columnsActionGroup); connect(actionRowSizePowerOf2, &QAction::triggered, this, [=]() { setColumnMode(ColumnMode::PowerOf2); }); rowSizeMenu->addAction(actionRowSizePowerOf2); actionItemBigEndian = new QAction(tr("Big Endian"), this); actionItemBigEndian->setCheckable(true); actionItemBigEndian->setEnabled(false); connect(actionItemBigEndian, &QAction::triggered, this, &HexWidget::setItemEndianness); actionHexPairs = new QAction(tr("Bytes as pairs"), this); actionHexPairs->setCheckable(true); connect(actionHexPairs, &QAction::triggered, this, &HexWidget::onHexPairsModeEnabled); actionCopy = new QAction(tr("Copy"), this); addAction(actionCopy); actionCopy->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); actionCopy->setShortcut(QKeySequence::Copy); connect(actionCopy, &QAction::triggered, this, &HexWidget::copy); actionCopyAddress = new QAction(tr("Copy address"), this); actionCopyAddress->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); actionCopyAddress->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_C); connect(actionCopyAddress, &QAction::triggered, this, &HexWidget::copyAddress); addAction(actionCopyAddress); // Add comment option actionComment = new QAction(tr("Add Comment"), this); actionComment->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); actionComment->setShortcut(Qt::Key_Semicolon); connect(actionComment, &QAction::triggered, this, &HexWidget::onActionAddCommentTriggered); addAction(actionComment); // delete comment option actionDeleteComment = new QAction(tr("Delete Comment"), this); actionDeleteComment->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); connect(actionDeleteComment, &QAction::triggered, this, &HexWidget::onActionDeleteCommentTriggered); addAction(actionDeleteComment); actionSelectRange = new QAction(tr("Select range"), this); connect(actionSelectRange, &QAction::triggered, this, [this]() { rangeDialog.open(cursor.address); }); addAction(actionSelectRange); connect(&rangeDialog, &QDialog::accepted, this, &HexWidget::onRangeDialogAccepted); actionsWriteString.reserve(5); QAction *actionWriteString = new QAction(tr("Write string"), this); connect(actionWriteString, &QAction::triggered, this, &HexWidget::w_writeString); actionsWriteString.append(actionWriteString); QAction *actionWriteLenString = new QAction(tr("Write length and string"), this); connect(actionWriteLenString, &QAction::triggered, this, &HexWidget::w_writePascalString); actionsWriteString.append(actionWriteLenString); QAction *actionWriteWideString = new QAction(tr("Write wide string"), this); connect(actionWriteWideString, &QAction::triggered, this, &HexWidget::w_writeWideString); actionsWriteString.append(actionWriteWideString); QAction *actionWriteCString = new QAction(tr("Write zero terminated string"), this); connect(actionWriteCString, &QAction::triggered, this, &HexWidget::w_writeCString); actionsWriteString.append(actionWriteCString); QAction *actionWrite64 = new QAction(tr("Write a decoded or encoded Base64 string"), this); connect(actionWrite64, &QAction::triggered, this, &HexWidget::w_write64); actionsWriteString.append(actionWrite64); actionsWriteOther.reserve(5); QAction *actionWriteBytes = new QAction(tr("Write hex bytes"), this); connect(actionWriteBytes, &QAction::triggered, this, &HexWidget::w_writeBytes); actionsWriteOther.append(actionWriteBytes); QAction *actionWriteZeros = new QAction(tr("Write zeros"), this); connect(actionWriteZeros, &QAction::triggered, this, &HexWidget::w_writeZeros); actionsWriteOther.append(actionWriteZeros); QAction *actionWriteRandom = new QAction(tr("Write random bytes"), this); connect(actionWriteRandom, &QAction::triggered, this, &HexWidget::w_writeRandom); actionsWriteOther.append(actionWriteRandom); QAction *actionDuplicateFromOffset = new QAction(tr("Duplicate from offset"), this); connect(actionDuplicateFromOffset, &QAction::triggered, this, &HexWidget::w_duplFromOffset); actionsWriteOther.append(actionDuplicateFromOffset); QAction *actionIncDec = new QAction(tr("Increment/Decrement"), this); connect(actionIncDec, &QAction::triggered, this, &HexWidget::w_increaseDecrease); actionsWriteOther.append(actionIncDec); actionKeyboardEdit = new QAction(tr("Edit with keyboard"), this); actionKeyboardEdit->setCheckable(true); connect(actionKeyboardEdit, &QAction::triggered, this, &HexWidget::onKeyboardEditTriggered); connect(actionKeyboardEdit, &QAction::toggled, this, &HexWidget::onKeyboardEditChanged); connect(this, &HexWidget::selectionChanged, this, [this](Selection newSelection) { actionCopy->setEnabled(!newSelection.empty); }); updateMetrics(); updateItemLength(); startAddress = 0ULL; cursor.address = 0ULL; data.reset(new MemoryData()); oldData.reset(new MemoryData()); fetchData(); updateCursorMeta(); connect(&cursor.blinkTimer, &QTimer::timeout, this, &HexWidget::onCursorBlinked); cursor.setBlinkPeriod(1000); cursor.startBlinking(); updateColors(); warningTimer.setSingleShot(true); connect(&warningTimer, &QTimer::timeout, this, &HexWidget::hideWarningRect); } void HexWidget::setMonospaceFont(const QFont &font) { if (!(font.styleHint() & QFont::Monospace)) { /* FIXME: Use default monospace font setFont(XXX); */ } QScrollArea::setFont(font); monospaceFont = font.resolve(this->font()); updateMetrics(); fetchData(); updateCursorMeta(); viewport()->update(); } void HexWidget::setItemSize(int nbytes) { static const QVector<int> values({ 1, 2, 4, 8 }); if (!values.contains(nbytes)) return; finishEditingWord(); itemByteLen = nbytes; if (itemByteLen > rowSizeBytes) { rowSizeBytes = itemByteLen; } actionsItemFormat.at(ItemFormatFloat)->setEnabled(nbytes >= 4); actionItemBigEndian->setEnabled(nbytes != 1); refreshWordEditState(); updateItemLength(); if (!cursorOnAscii && cursor.address % itemByteLen) { moveCursor(-int(cursor.address % itemByteLen)); } fetchData(); updateCursorMeta(); viewport()->update(); } void HexWidget::setItemFormat(ItemFormat format) { finishEditingWord(); itemFormat = format; bool sizeEnabled = true; if (format == ItemFormatFloat) sizeEnabled = false; actionsItemSize.at(0)->setEnabled(sizeEnabled); actionsItemSize.at(1)->setEnabled(sizeEnabled); refreshWordEditState(); updateItemLength(); fetchData(); updateCursorMeta(); viewport()->update(); } void HexWidget::setItemGroupSize(int size) { itemGroupSize = size; updateCounts(); fetchData(); updateCursorMeta(); viewport()->update(); } /** * @brief Checks if Item at the address changed compared to the last read data. * @param address Address of Item to be compared. * @return True if Item is different, False if Item is equal or last read didn't contain the * address. * @see HexWidget#readItem * * Checks if current Item at the address changed compared to the last read data. * It is assumed that the current read data buffer contains the address. */ bool HexWidget::isItemDifferentAt(uint64_t address) { char oldItem[sizeof(uint64_t)] = {}; char newItem[sizeof(uint64_t)] = {}; if (data->copy(newItem, address, static_cast<size_t>(itemByteLen)) && oldData->copy(oldItem, address, static_cast<size_t>(itemByteLen))) { return memcmp(oldItem, newItem, sizeof(oldItem)) != 0; } return false; } void HexWidget::updateCounts() { actionHexPairs->setEnabled(rowSizeBytes > 1 && itemByteLen == 1 && itemFormat == ItemFormat::ItemFormatHex); actionHexPairs->setChecked(Core()->getConfigb("hex.pairs")); if (actionHexPairs->isChecked() && actionHexPairs->isEnabled()) { itemGroupSize = 2; } else { itemGroupSize = 1; } if (columnMode == ColumnMode::PowerOf2) { int last_good_size = itemGroupByteLen(); for (int i = itemGroupByteLen(); i <= MAX_LINE_WIDTH_BYTES; i *= 2) { rowSizeBytes = i; itemColumns = rowSizeBytes / itemGroupByteLen(); updateAreasPosition(); if (horizontalScrollBar()->maximum() == 0) { last_good_size = rowSizeBytes; } else { break; } } rowSizeBytes = last_good_size; } itemColumns = rowSizeBytes / itemGroupByteLen(); // ensure correct action is selected when changing line size programmatically if (columnMode == ColumnMode::Fixed) { int w = 1; const auto &actions = rowSizeMenu->actions(); for (auto action : actions) { action->setChecked(false); } for (auto action : actions) { if (w > MAX_LINE_WIDTH_PRESET) { break; } if (rowSizeBytes == w) { action->setChecked(true); } w *= 2; } } else if (columnMode == ColumnMode::PowerOf2) { actionRowSizePowerOf2->setChecked(true); } updateAreasPosition(); } void HexWidget::setFixedLineSize(int lineSize) { if (lineSize < 1 || lineSize < itemGroupByteLen() || lineSize % itemGroupByteLen()) { updateCounts(); return; } rowSizeBytes = lineSize; columnMode = ColumnMode::Fixed; updateCounts(); fetchData(); updateCursorMeta(); viewport()->update(); } void HexWidget::setColumnMode(ColumnMode mode) { columnMode = mode; updateCounts(); fetchData(); updateCursorMeta(); viewport()->update(); } void HexWidget::selectRange(RVA start, RVA end) { BasicCursor endCursor(end); endCursor += 1; setCursorAddr(endCursor); selection.set(start, end); cursorEnabled = false; emit selectionChanged(getSelection()); } void HexWidget::clearSelection() { setCursorAddr(BasicCursor(cursor.address), false); emit selectionChanged(getSelection()); } HexWidget::Selection HexWidget::getSelection() { return Selection { selection.isEmpty(), selection.start(), selection.end() }; } void HexWidget::seek(uint64_t address) { if (!cursorOnAscii) { // when other widget causes seek to the middle of word // switch to ascii column which operates with byte positions auto viewOffset = startAddress % itemByteLen; auto addrOffset = address % itemByteLen; if ((addrOffset + itemByteLen - viewOffset) % itemByteLen) { setCursorOnAscii(true); } } setCursorAddr(BasicCursor(address)); } void HexWidget::refresh() { fetchData(); viewport()->update(); } void HexWidget::setItemEndianness(bool bigEndian) { finishEditingWord(); itemBigEndian = bigEndian; updateCursorMeta(); // Update cached item character viewport()->update(); } void HexWidget::updateColors() { borderColor = Config()->getColor("gui.border"); backgroundColor = Config()->getColor("gui.background"); b0x00Color = Config()->getColor("b0x00"); b0x7fColor = Config()->getColor("b0x7f"); b0xffColor = Config()->getColor("b0xff"); printableColor = Config()->getColor("ai.write"); defColor = Config()->getColor("btext"); addrColor = Config()->getColor("func_var_addr"); diffColor = Config()->getColor("graph.diff.unmatch"); warningColor = QColor("red"); updateCursorMeta(); viewport()->update(); } void HexWidget::paintEvent(QPaintEvent *event) { QPainter painter(viewport()); painter.setFont(monospaceFont); int xOffset = horizontalScrollBar()->value(); if (xOffset > 0) painter.translate(QPoint(-xOffset, 0)); if (event->rect() == cursor.screenPos.toAlignedRect()) { /* Cursor blink */ drawCursor(painter); return; } painter.fillRect(event->rect().translated(xOffset, 0), backgroundColor); drawHeader(painter); drawAddrArea(painter); drawItemArea(painter); drawAsciiArea(painter); if (warningRectVisible) { painter.setPen(warningColor); painter.drawRect(warningRect); } if (!cursorEnabled) return; drawCursor(painter, true); } void HexWidget::updateWidth() { int max = (showAscii ? asciiArea.right() : itemArea.right()) - viewport()->width(); if (max < 0) max = 0; else max += charWidth; horizontalScrollBar()->setMaximum(max); horizontalScrollBar()->setSingleStep(charWidth); } bool HexWidget::isFixedWidth() const { return itemFormat == ItemFormatHex || itemFormat == ItemFormatOct; } void HexWidget::resizeEvent(QResizeEvent *event) { int oldByteCount = bytesPerScreen(); updateCounts(); if (event->oldSize().height() == event->size().height() && oldByteCount == bytesPerScreen()) return; updateAreasHeight(); fetchData(); // rowCount was changed updateCursorMeta(); viewport()->update(); } void HexWidget::mouseMoveEvent(QMouseEvent *event) { QPoint pos = event->pos(); pos.rx() += horizontalScrollBar()->value(); auto mouseAddr = mousePosToAddr(pos).address; QString metaData = getFlagsAndComment(mouseAddr); if (!metaData.isEmpty() && itemArea.contains(pos)) { QToolTip::showText(mapToGlobal(event->pos()), metaData.replace(",", ", "), this); } else { QToolTip::hideText(); } if (!updatingSelection) { if (itemArea.contains(pos) || asciiArea.contains(pos)) setCursor(Qt::IBeamCursor); else setCursor(Qt::ArrowCursor); return; } auto &area = currentArea(); if (pos.x() < area.left()) pos.setX(area.left()); else if (pos.x() > area.right()) pos.setX(area.right()); auto addr = currentAreaPosToAddr(pos, true); setCursorAddr(addr, true); /* Stop blinking */ cursorEnabled = false; viewport()->update(); } void HexWidget::mousePressEvent(QMouseEvent *event) { QPoint pos(event->pos()); pos.rx() += horizontalScrollBar()->value(); if (event->button() == Qt::LeftButton) { bool selectingData = itemArea.contains(pos); bool selecting = selectingData || asciiArea.contains(pos); bool holdingShift = event->modifiers() == Qt::ShiftModifier; // move cursor within actively edited item if (selectingData && !holdingShift && editWordState >= EditWordState::WriteNotEdited) { auto editWordArea = itemRectangle(cursor.address - startAddress); if (editWordArea.contains(pos)) { int wordOffset = 0; auto cursorPosition = screenPosToAddr(pos, false, &wordOffset); if (cursorPosition.address == cursor.address // allow selecting after last character only when cursor limited to current word && (wordOffset < editWord.length() || navigationMode == HexNavigationMode::WordChar)) { editWordPos = std::max(0, wordOffset); editWordPos = std::min<int>(editWordPos, editWord.length()); if (isFixedWidth()) { updatingSelection = true; auto selectionCursor = cursorPosition; if (editWordPos > itemCharLen / 2) { selectionCursor += itemByteLen; } selection.init(selectionCursor); } viewport()->update(); return; } } } // cursor within any item if the mode allows if (selectingData && !holdingShift && editWordState >= EditWordState::WriteNotStarted && navigationMode == HexNavigationMode::AnyChar) { updatingSelection = true; setCursorOnAscii(false); int wordOffset = 0; auto cursorPosition = screenPosToAddr(pos, false, &wordOffset); finishEditingWord(); if (isFixedWidth() && wordOffset >= itemCharLen - itemPrefixLen) { wordOffset = 0; cursorPosition += itemByteLen; } setCursorAddr(cursorPosition, holdingShift); auto selectionPosition = currentAreaPosToAddr(pos, true); selection.init(selectionPosition); emit selectionChanged(getSelection()); if (wordOffset > 0) { startEditWord(); editWordPos = std::min<int>(wordOffset, editWord.length() - 1); } viewport()->update(); return; } if (selecting) { finishEditingWord(); updatingSelection = true; setCursorOnAscii(!selectingData); auto cursorPosition = currentAreaPosToAddr(pos, true); setCursorAddr(cursorPosition, holdingShift); viewport()->update(); } } } void HexWidget::mouseDoubleClickEvent(QMouseEvent *event) { QPoint pos(event->pos()); pos.rx() += horizontalScrollBar()->value(); if (event->button() == Qt::LeftButton && !isFixedWidth() && editWordState == EditWordState::WriteNotStarted && itemArea.contains(pos)) { int wordOffset = 0; auto cursorPosition = screenPosToAddr(pos, false, &wordOffset); setCursorAddr(cursorPosition, false); startEditWord(); int padding = std::max<int>(0, itemCharLen - editWord.length()); editWordPos = std::max(0, wordOffset - padding); editWordPos = std::min<int>(editWordPos, editWord.length()); } } void HexWidget::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { if (selection.isEmpty()) { selection.init(BasicCursor(cursor.address)); cursorEnabled = true; viewport()->update(); } updatingSelection = false; } } void HexWidget::wheelEvent(QWheelEvent *event) { // according to Qt doc 1 row per 5 degrees, angle measured in 1/8 of degree int dy = event->angleDelta().y() / (8 * 5); int64_t delta = -dy * itemRowByteLen(); if (dy == 0) return; if (delta < 0 && startAddress < static_cast<uint64_t>(-delta)) { startAddress = 0; } else if (delta > 0 && data->maxIndex() < static_cast<uint64_t>(bytesPerScreen())) { startAddress = 0; } else if ((data->maxIndex() - startAddress) <= static_cast<uint64_t>(bytesPerScreen() + delta - 1)) { startAddress = (data->maxIndex() - bytesPerScreen()) + 1; } else { startAddress += delta; } fetchData(); if (cursor.address >= startAddress && cursor.address <= lastVisibleAddr()) { /* Don't enable cursor blinking if selection isn't empty */ cursorEnabled = selection.isEmpty(); updateCursorMeta(); } else { cursorEnabled = false; } viewport()->update(); } bool HexWidget::validCharForEdit(QChar digit) { switch (itemFormat) { case ItemFormatHex: return (digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f') || (digit >= 'A' && digit <= 'F'); case ItemFormatOct: { if (editWordPos > 0) { return (digit >= '0' && digit <= '7'); } else { int bitsInMSD = (itemByteLen * 8) % 3; int biggestDigit = (1 << bitsInMSD) - 1; return digit >= '0' && digit <= char('0' + biggestDigit); } } case ItemFormatDec: return (digit >= '0' && digit <= '9'); case ItemFormatSignedDec: return (digit >= '0' && digit <= '9') || digit == '-'; case ItemFormatFloat: return (digit >= '0' && digit <= '9') || digit == '-' || digit == '+' || digit == '.' || digit == ',' || digit == '+' || digit == 'e' || digit == 'E' || digit == 'i' || digit == 'n' || digit == 'f' || digit == 'I' || digit == 'N' || digit == 'F' || digit == 'a' || digit == 'A'; } return false; } void HexWidget::movePrevEditCharAny() { if (!selection.isEmpty()) { clearSelection(); } editWordPos -= 1; if (editWordPos < 0) { finishEditingWord(); if (moveCursor(-itemByteLen, false, OverflowMove::Ignore)) { startEditWord(); editWordPos = editWord.length() - 1; } } viewport()->update(); } void HexWidget::typeOverwriteModeChar(QChar c) { if (editWordState < EditWordState::WriteNotEdited || !isFixedWidth()) { return; } editWord[editWordPos] = c; editWordPos++; editWordState = EditWordState::WriteEdited; if (editWordPos >= editWord.length()) { finishEditingWord(); bool moved = moveCursor(itemByteLen, false, OverflowMove::Ignore); startEditWord(); if (!moved) { editWordPos = editWord.length() - 1; } } } HexWidget::HexNavigationMode HexWidget::defaultNavigationMode() { switch (editWordState) { case EditWordState::Read: return HexNavigationMode::Words; case EditWordState::WriteNotStarted: return isFixedWidth() ? HexNavigationMode::AnyChar : HexNavigationMode::Words; case EditWordState::WriteNotEdited: case EditWordState::WriteEdited: return isFixedWidth() ? HexNavigationMode::AnyChar : HexNavigationMode::WordChar; } return HexNavigationMode::Words; } void HexWidget::refreshWordEditState() { navigationMode = defaultNavigationMode(); } bool HexWidget::handleAsciiWrite(QKeyEvent *event) { if (!cursorOnAscii || !canKeyboardEdit()) { return false; } if (event->key() == Qt::Key_Backspace || event->matches(QKeySequence::Backspace)) { if (!selection.isEmpty()) { writeZeros(selection.start(), selection.size()); } else { moveCursor(-1, false); writeZeros(cursor.address, 1); } return true; } if (event->key() == Qt::Key_Delete || event->matches(QKeySequence::Delete)) { if (!selection.isEmpty()) { writeZeros(selection.start(), selection.size()); } else { writeZeros(cursor.address, 1); moveCursor(1, false); } return true; } QString text; if (event->matches(QKeySequence::Paste)) { text = QApplication::clipboard()->text(); if (text.length() <= 0) { return false; } } else { text = event->text(); if (text.length() <= 0) { return false; } QChar c = text[0]; if (c <= '\x1f' || c == '\x7f') { return false; } } auto bytes = text.toUtf8(); // TODO:#3028 use selected text encoding auto address = getLocationAddress(); clearSelection(); data->write(reinterpret_cast<const uint8_t *>(bytes.data()), address, bytes.length()); seek(address + bytes.length()); viewport()->update(); return true; } bool HexWidget::handleNumberWrite(QKeyEvent *event) { if (editWordState < EditWordState::WriteNotStarted) { return false; } bool overwrite = isFixedWidth(); auto keyText = event->text(); bool editingWord = editWordState >= EditWordState::WriteNotEdited; if (keyText.length() > 0 && validCharForEdit(keyText[0])) { if (!selection.isEmpty()) { setCursorAddr(BasicCursor(selection.start())); } if (!editingWord) { startEditWord(); } if (overwrite) { typeOverwriteModeChar(keyText[0]); } else if (!editingWord /* && !overwrite */) { editWord = keyText; editWordPos = editWord.length(); editWordState = EditWordState::WriteEdited; } else if (itemFormat == ItemFormatFloat || editWord.length() < itemCharLen) { editWord.insert(editWordPos, keyText); editWordPos += keyText.length(); editWordState = EditWordState::WriteEdited; } maybeFlushCharEdit(); return true; } if (event->matches(QKeySequence::Paste) && (editingWord || overwrite)) { QString text = QApplication::clipboard()->text(); if (text.length() > 0) { if (overwrite) { startEditWord(); for (QChar c : text) { if (validCharForEdit(c)) { typeOverwriteModeChar(c); } } } else { editWord.insert(editWordPos, text); editWordPos += text.length(); editWordState = EditWordState::WriteEdited; } } maybeFlushCharEdit(); return true; } if (editingWord) { if (event->matches(QKeySequence::Cancel)) { cancelEditedWord(); return true; } else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { bool needToAdvance = !(editWordPos == 0 && overwrite && editWordState < EditWordState::WriteEdited); if (finishEditingWord(false) && needToAdvance) { moveCursor(itemByteLen); } return true; } } if (event->matches(QKeySequence::Delete)) { if (!selection.isEmpty()) { writeZeros(selection.start(), selection.size()); clearSelection(); } else { startEditWord(); if (overwrite) { typeOverwriteModeChar('0'); } else if (editWordPos < editWord.length()) { editWord.remove(editWordPos, 1); editWordState = EditWordState::WriteEdited; } } maybeFlushCharEdit(); return true; } if (event->matches(QKeySequence::DeleteEndOfWord) && selection.isEmpty()) { startEditWord(); if (overwrite) { for (int i = editWordPos; i < editWord.length(); i++) { typeOverwriteModeChar('0'); } } else if (editWordPos < editWord.length()) { editWord.remove(editWordPos, editWord.length()); editWordState = EditWordState::WriteEdited; } maybeFlushCharEdit(); return true; } if (event->matches(QKeySequence::DeleteStartOfWord) && selection.isEmpty()) { if (!editingWord || (overwrite && editWordPos == 0)) { if (!moveCursor(-itemByteLen, false, OverflowMove::Ignore)) { return false; } startEditWord(); editWordPos = editWord.length(); } if (overwrite) { while (editWordPos > 0) { editWordPos--; editWord[editWordPos] = '0'; } editWordState = EditWordState::WriteEdited; maybeFlushCharEdit(); return true; } else { if (editWordPos > 0) { editWord.remove(0, editWordPos); editWordState = EditWordState::WriteEdited; editWordPos = 0; maybeFlushCharEdit(); return true; } } return false; } if (event->key() == Qt::Key_Backspace) { if (!selection.isEmpty()) { writeZeros(selection.start(), selection.size()); clearSelection(); setCursorAddr(BasicCursor(selection.start()), false); return true; } else { if (!editingWord || (overwrite && editWordPos == 0)) { if (!moveCursor(-itemByteLen, false, OverflowMove::Ignore)) { return false; } startEditWord(); editWordPos = editWord.length(); } if (editWordPos > 0) { editWordPos -= 1; if (overwrite) { editWord[editWordPos] = '0'; } else { editWord.remove(editWordPos, 1); } editWordState = EditWordState::WriteEdited; maybeFlushCharEdit(); return true; } } return false; } return false; } bool HexWidget::event(QEvent *event) { // prefer treating keys like 's' 'g' '.' as typing input instead of global shortcuts if (event->type() == QEvent::ShortcutOverride) { auto keyEvent = static_cast<QKeyEvent *>(event); auto modifiers = keyEvent->modifiers(); if ((modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier || modifiers == Qt::KeypadModifier) && keyEvent->key() < Qt::Key_Escape && canKeyboardEdit()) { keyEvent->accept(); return true; } } return QScrollArea::event(event); } void HexWidget::keyPressEvent(QKeyEvent *event) { bool select = false; auto moveOrSelect = [event, &select](QKeySequence::StandardKey moveSeq, QKeySequence::StandardKey selectSeq) -> bool { if (event->matches(moveSeq)) { select = false; return true; } else if (event->matches(selectSeq)) { select = true; return true; } return false; }; if (canKeyboardEdit()) { if (handleAsciiWrite(event)) { viewport()->update(); return; } if (editWordState >= EditWordState::WriteNotStarted && !cursorOnAscii) { if (handleNumberWrite(event)) { viewport()->update(); return; } } } if (cursorOnAscii || navigationMode == HexNavigationMode::Words || navigationMode == HexNavigationMode::AnyChar) { if (moveOrSelect(QKeySequence::MoveToNextPage, QKeySequence::SelectNextPage)) { moveCursor(bytesPerScreen(), select); } else if (moveOrSelect(QKeySequence::MoveToPreviousPage, QKeySequence::SelectPreviousPage)) { moveCursor(-bytesPerScreen(), select); } else if (moveOrSelect(QKeySequence::MoveToStartOfLine, QKeySequence::SelectStartOfLine)) { int linePos = int((cursor.address % itemRowByteLen()) - (startAddress % itemRowByteLen())); moveCursor(-linePos, select); } else if (moveOrSelect(QKeySequence::MoveToEndOfLine, QKeySequence::SelectEndOfLine)) { int linePos = int((cursor.address % itemRowByteLen()) - (startAddress % itemRowByteLen())); moveCursor(itemRowByteLen() - linePos, select); } } if (navigationMode == HexNavigationMode::Words || cursorOnAscii) { if (moveOrSelect(QKeySequence::MoveToNextLine, QKeySequence::SelectNextLine)) { moveCursor(itemRowByteLen(), select, OverflowMove::Ignore); } else if (moveOrSelect(QKeySequence::MoveToPreviousLine, QKeySequence::SelectPreviousLine)) { moveCursor(-itemRowByteLen(), select, OverflowMove::Ignore); } else if (moveOrSelect(QKeySequence::MoveToNextChar, QKeySequence::SelectNextChar) || moveOrSelect(QKeySequence::MoveToNextWord, QKeySequence::SelectNextWord)) { moveCursor(cursorOnAscii ? 1 : itemByteLen, select); } else if (moveOrSelect(QKeySequence::MoveToPreviousChar, QKeySequence::SelectPreviousChar) || moveOrSelect(QKeySequence::MoveToPreviousWord, QKeySequence::SelectPreviousWord)) { moveCursor(cursorOnAscii ? -1 : -itemByteLen, select); } } else if (navigationMode == HexNavigationMode::AnyChar && !cursorOnAscii) { if (moveOrSelect(QKeySequence::MoveToNextLine, QKeySequence::SelectNextLine)) { moveCursorKeepEditOffset(itemRowByteLen(), select, OverflowMove::Ignore); } else if (moveOrSelect(QKeySequence::MoveToPreviousLine, QKeySequence::SelectPreviousLine)) { moveCursorKeepEditOffset(-itemRowByteLen(), select, OverflowMove::Ignore); } else if (moveOrSelect(QKeySequence::MoveToNextChar, QKeySequence::SelectNextChar)) { if (select) { moveCursor(itemByteLen, select); } else { if (!selection.isEmpty()) { clearSelection(); } if (editWordState == EditWordState::WriteNotStarted) { startEditWord(); } editWordPos += 1; if (editWordPos >= editWord.length()) { bool moved = moveCursor(itemByteLen, false, OverflowMove::Ignore); startEditWord(); if (!moved) { editWordPos = editWord.length() - 1; } } } viewport()->update(); } else if (event->matches(QKeySequence::MoveToPreviousChar)) { movePrevEditCharAny(); } else if (event->matches(QKeySequence::SelectPreviousChar)) { moveCursor(-itemByteLen, true); } else if (moveOrSelect(QKeySequence::MoveToNextWord, QKeySequence::SelectNextWord)) { moveCursor(itemByteLen, select); } else if (event->matches(QKeySequence::MoveToPreviousWord)) { if (editWordPos > 0) { editWordPos = 0; viewport()->update(); } else { moveCursor(-itemByteLen, false); } } else if (event->matches(QKeySequence::SelectPreviousWord)) { moveCursor(-itemByteLen, true); } } else if (navigationMode == HexNavigationMode::WordChar) { if (event->matches(QKeySequence::MoveToNextChar)) { editWordPos = std::min<int>(editWord.length(), editWordPos + 1); viewport()->update(); } else if (event->matches(QKeySequence::MoveToPreviousChar)) { editWordPos = std::max(0, editWordPos - 1); viewport()->update(); } else if (event->matches(QKeySequence::MoveToStartOfLine)) { editWordPos = 0; viewport()->update(); } else if (event->matches(QKeySequence::MoveToEndOfLine)) { editWordPos = editWord.length(); viewport()->update(); } else if (event->matches(QKeySequence::MoveToPreviousWord)) { if (editWordPos > 0) { editWordPos = 0; } else { moveCursor(-itemByteLen, select); startEditWord(); } viewport()->update(); } else if (event->matches(QKeySequence::MoveToNextWord)) { if (editWordPos < editWord.length()) { editWordPos = editWord.length(); } else { moveCursor(itemByteLen, select); startEditWord(); editWordPos = editWord.length(); } viewport()->update(); } } } void HexWidget::contextMenuEvent(QContextMenuEvent *event) { QPoint pt = event->pos(); bool mouseOutsideSelection = false; if (event->reason() == QContextMenuEvent::Mouse) { auto mouseAddr = mousePosToAddr(pt).address; if (asciiArea.contains(pt)) { cursorOnAscii = true; } else if (itemArea.contains(pt)) { cursorOnAscii = false; } if (selection.isEmpty()) { seek(mouseAddr); } else { mouseOutsideSelection = !selection.contains(mouseAddr); } } auto disableOutsideSelectionActions = [this](bool disable) { actionCopyAddress->setDisabled(disable); }; QString comment = Core()->getCommentAt(cursor.address); if (comment.isNull() || comment.isEmpty()) { actionDeleteComment->setVisible(false); actionComment->setText(tr("Add Comment")); } else { actionDeleteComment->setVisible(true); actionComment->setText(tr("Edit Comment")); } if (!ioModesController.canWrite()) { actionKeyboardEdit->setChecked(false); } auto *menu = new QMenu(this); QMenu *sizeMenu = menu->addMenu(tr("Item size:")); sizeMenu->addActions(actionsItemSize); QMenu *formatMenu = menu->addMenu(tr("Item format:")); formatMenu->addActions(actionsItemFormat); menu->addMenu(rowSizeMenu); menu->addAction(actionHexPairs); menu->addAction(actionItemBigEndian); QMenu *writeMenu = menu->addMenu(tr("Edit")); writeMenu->addActions(actionsWriteString); writeMenu->addSeparator(); writeMenu->addActions(actionsWriteOther); menu->addAction(actionKeyboardEdit); menu->addSeparator(); menu->addAction(actionCopy); disableOutsideSelectionActions(mouseOutsideSelection); menu->addAction(actionCopyAddress); menu->addActions(this->actions()); menu->exec(mapToGlobal(pt)); disableOutsideSelectionActions(false); menu->deleteLater(); } void HexWidget::onCursorBlinked() { if (!cursorEnabled) return; cursor.blink(); QRect cursorRect = cursor.screenPos.toAlignedRect(); viewport()->update(cursorRect.translated(-horizontalScrollBar()->value(), 0)); } void HexWidget::onHexPairsModeEnabled(bool enable) { // Sync configuration Core()->setConfig("hex.pairs", enable); if (enable) { setItemGroupSize(2); } else { setItemGroupSize(1); } } void HexWidget::copy() { if (selection.isEmpty() || selection.size() > MAX_COPY_SIZE) return; auto x = cursorOnAscii ? Core()->getString(selection.start(), selection.size(), RZ_STRING_ENC_8BIT, true) : Core()->ioRead(selection.start(), (int)selection.size()).toHex(); QApplication::clipboard()->setText(x); } void HexWidget::copyAddress() { uint64_t addr = getLocationAddress(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(RzAddressString(addr)); } // slot for add comment action void HexWidget::onActionAddCommentTriggered() { uint64_t addr = cursor.address; CommentsDialog::addOrEditComment(addr, this); } // slot for deleting comment action void HexWidget::onActionDeleteCommentTriggered() { uint64_t addr = cursor.address; Core()->delComment(addr); } void HexWidget::onRangeDialogAccepted() { if (rangeDialog.empty()) { seek(rangeDialog.getStartAddress()); return; } selectRange(rangeDialog.getStartAddress(), rangeDialog.getEndAddress()); } void HexWidget::writeZeros(uint64_t address, uint64_t length) { const uint64_t MAX_BUFFER = 1024; std::vector<uint8_t> zeroes(std::min(MAX_BUFFER, length), 0); while (length > zeroes.size()) { data->write(zeroes.data(), address, zeroes.size()); address += zeroes.size(); length -= zeroes.size(); } if (length > 0) { data->write(zeroes.data(), address, length); } } void HexWidget::w_writeString() { if (!ioModesController.prepareForWriting()) { return; } bool ok = false; QString str = QInputDialog::getText(this, tr("Write string"), tr("String:"), QLineEdit::Normal, "", &ok); if (!ok || str.isEmpty()) { return; } { RzCoreLocked core(Core()); rz_core_write_string_at(core, getLocationAddress(), str.toUtf8().constData()); } refresh(); } void HexWidget::w_increaseDecrease() { if (!ioModesController.prepareForWriting()) { return; } IncrementDecrementDialog d; int ret = d.exec(); if (ret == QDialog::Rejected) { return; } int64_t value = (int64_t)d.getValue(); uint8_t sz = d.getNBytes(); if (d.getMode() == IncrementDecrementDialog::Decrease) { value *= -1; } { RzCoreLocked core(Core()); rz_core_write_value_inc_at(core, getLocationAddress(), value, sz); } refresh(); } void HexWidget::w_writeBytes() { if (!ioModesController.prepareForWriting()) { return; } bool ok = false; int size = INT_MAX; if (!selection.isEmpty() && selection.size() <= INT_MAX) { size = static_cast<int>(selection.size()); } QByteArray bytes = QInputDialog::getText(this, tr("Write hex bytes"), tr("Hex byte string:"), QLineEdit::Normal, "", &ok) .toUtf8(); const int offset = bytes.startsWith("\\x") ? 2 : 0; const int incr = offset + 2; const int bytes_size = qMin(bytes.size() / incr, size); if (!ok || !bytes_size) { return; } { auto *buf = (uint8_t *)malloc(static_cast<size_t>(bytes_size)); if (!buf) { return; } for (int i = 0, j = 0, sz = bytes.size(); i < sz; i += incr, j++) { buf[j] = static_cast<uint8_t>(bytes.mid(i + offset, 2).toInt(nullptr, 16)); } RzCoreLocked core(Core()); rz_core_write_at(core, getLocationAddress(), buf, bytes_size); free(buf); } refresh(); } void HexWidget::w_writeZeros() { if (!ioModesController.prepareForWriting()) { return; } int size = 1; if (!selection.isEmpty() && selection.size() <= INT_MAX) { size = static_cast<int>(selection.size()); } bool ok = false; int len = QInputDialog::getInt(this, tr("Write zeros"), tr("Number of zeros:"), size, 1, 0x7FFFFFFF, 1, &ok); if (!ok) { return; } { writeZeros(getLocationAddress(), len); } refresh(); } void HexWidget::w_write64() { if (!ioModesController.prepareForWriting()) { return; } Base64EnDecodedWriteDialog d; int ret = d.exec(); if (ret == QDialog::Rejected) { return; } QByteArray str = d.getData(); if (d.getMode() == Base64EnDecodedWriteDialog::Decode && (QString(str).contains(QRegularExpression("[^a-zA-Z0-9+/=]")) || str.length() % 4 != 0 || str.isEmpty())) { QMessageBox::critical( this, tr("Error"), tr("Error occured during decoding your input.\n" "Please, make sure, that it is a valid base64 string and try again.")); return; } { RzCoreLocked core(Core()); if (d.getMode() == Base64EnDecodedWriteDialog::Encode) { rz_core_write_base64_at(core, getLocationAddress(), str.toHex().constData()); } else { rz_core_write_base64d_at(core, getLocationAddress(), str.constData()); } } refresh(); } void HexWidget::w_writeRandom() { if (!ioModesController.prepareForWriting()) { return; } int size = 1; if (!selection.isEmpty() && selection.size() <= INT_MAX) { size = static_cast<int>(selection.size()); } bool ok = false; int nbytes = QInputDialog::getInt(this, tr("Write random bytes"), tr("Number of bytes:"), size, 1, 0x7FFFFFFF, 1, &ok); if (!ok) { return; } { RzCoreLocked core(Core()); rz_core_write_random_at(core, getLocationAddress(), nbytes); } refresh(); } void HexWidget::w_duplFromOffset() { if (!ioModesController.prepareForWriting()) { return; } DuplicateFromOffsetDialog d; int ret = d.exec(); if (ret == QDialog::Rejected) { return; } RVA src = d.getOffset(); int len = (int)d.getNBytes(); { RzCoreLocked core(Core()); rz_core_write_duplicate_at(core, getLocationAddress(), src, len); } refresh(); } void HexWidget::w_writePascalString() { if (!ioModesController.prepareForWriting()) { return; } bool ok = false; QString str = QInputDialog::getText(this, tr("Write Pascal string"), tr("String:"), QLineEdit::Normal, "", &ok); if (!ok || str.isEmpty()) { return; } { RzCoreLocked core(Core()); rz_core_write_length_string_at(core, getLocationAddress(), str.toUtf8().constData()); } refresh(); } void HexWidget::w_writeWideString() { if (!ioModesController.prepareForWriting()) { return; } bool ok = false; QString str = QInputDialog::getText(this, tr("Write wide string"), tr("String:"), QLineEdit::Normal, "", &ok); if (!ok || str.isEmpty()) { return; } { RzCoreLocked core(Core()); rz_core_write_string_wide_at(core, getLocationAddress(), str.toUtf8().constData()); } refresh(); } void HexWidget::w_writeCString() { if (!ioModesController.prepareForWriting()) { return; } bool ok = false; QString str = QInputDialog::getText(this, tr("Write zero-terminated string"), tr("String:"), QLineEdit::Normal, "", &ok); if (!ok || str.isEmpty()) { return; } { RzCoreLocked core(Core()); rz_core_write_string_zero_at(core, getLocationAddress(), str.toUtf8().constData()); } refresh(); } void HexWidget::onKeyboardEditTriggered(bool enabled) { if (!enabled) { return; } if (!ioModesController.prepareForWriting()) { actionKeyboardEdit->setChecked(false); } } void HexWidget::onKeyboardEditChanged(bool enabled) { if (!enabled) { finishEditingWord(); navigationMode = HexNavigationMode::Words; editWordState = EditWordState::Read; } else { editWordState = EditWordState::WriteNotStarted; navigationMode = defaultNavigationMode(); } updateCursorMeta(); viewport()->update(); } void HexWidget::updateItemLength() { itemPrefixLen = 0; itemPrefix.clear(); switch (itemFormat) { case ItemFormatHex: itemCharLen = 2 * itemByteLen; if (itemByteLen > 1 && showExHex) { itemPrefixLen = hexPrefix.length(); itemPrefix = hexPrefix; } break; case ItemFormatOct: itemCharLen = (itemByteLen * 8 + 3) / 3; break; case ItemFormatDec: switch (itemByteLen) { case 1: itemCharLen = 3; break; case 2: itemCharLen = 5; break; case 4: itemCharLen = 10; break; case 8: itemCharLen = 20; break; } break; case ItemFormatSignedDec: switch (itemByteLen) { case 1: itemCharLen = 4; break; case 2: itemCharLen = 6; break; case 4: itemCharLen = 11; break; case 8: itemCharLen = 20; break; } break; case ItemFormatFloat: if (itemByteLen < 4) itemByteLen = 4; // FIXME itemCharLen = 3 * itemByteLen; break; } itemCharLen += itemPrefixLen; updateCounts(); } void HexWidget::drawHeader(QPainter &painter) { if (!showHeader) return; int offset = 0; QRectF rect(itemArea.left(), 0, itemWidth(), lineHeight); painter.setPen(addrColor); for (int j = 0; j < itemColumns; ++j) { for (int k = 0; k < itemGroupSize; ++k, offset += itemByteLen) { painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, QString::number(offset, 16).toUpper()); rect.translate(itemWidth(), 0); } rect.translate(columnSpacingWidth(), 0); } rect.moveLeft(asciiArea.left()); rect.setWidth(charWidth); for (int j = 0; j < itemRowByteLen(); ++j) { painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, QString::number(j % 16, 16).toUpper()); rect.translate(charWidth, 0); } } void HexWidget::drawCursor(QPainter &painter, bool shadow) { if (shadow) { QPen pen(Qt::gray); pen.setStyle(Qt::DashLine); painter.setPen(pen); qreal shadowWidth = charWidth; if (cursorOnAscii) { shadowWidth = itemWidth(); } else if (editWordState >= EditWordState::WriteNotEdited) { shadowWidth = itemByteLen * charWidth; } shadowCursor.screenPos.setWidth(shadowWidth); painter.drawRect(shadowCursor.screenPos); painter.setPen(Qt::SolidLine); } painter.setPen(cursor.cachedColor); QRectF charRect(cursor.screenPos); charRect.setWidth(charWidth); painter.fillRect(charRect, backgroundColor); painter.drawText(charRect, Qt::AlignVCenter, cursor.cachedChar); if (cursor.isVisible) { painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination); painter.fillRect(cursor.screenPos, QColor(0xff, 0xff, 0xff)); } } void HexWidget::drawAddrArea(QPainter &painter) { uint64_t offset = startAddress; QString addrString; QSizeF areaSize((addrCharLen + (showExAddr ? 2 : 0)) * charWidth, lineHeight); QRectF strRect(addrArea.topLeft(), areaSize); painter.setPen(addrColor); for (int line = 0; line < visibleLines && offset <= data->maxIndex(); ++line, strRect.translate(0, lineHeight), offset += itemRowByteLen()) { addrString = QString("%1").arg(offset, addrCharLen, 16, QLatin1Char('0')); if (showExAddr) addrString.prepend(hexPrefix); painter.drawText(strRect, Qt::AlignVCenter, addrString); } painter.setPen(borderColor); qreal vLineOffset = itemArea.left() - charWidth; painter.drawLine(QLineF(vLineOffset, 0, vLineOffset, viewport()->height())); } void HexWidget::drawItemArea(QPainter &painter) { QRectF itemRect(itemArea.topLeft(), QSizeF(itemWidth(), lineHeight)); QColor itemColor; QString itemString; fillSelectionBackground(painter); bool haveEditWord = false; QRectF editWordRect; QColor editWordColor; uint64_t itemAddr = startAddress; for (int line = 0; line < visibleLines; ++line) { itemRect.moveLeft(itemArea.left()); for (int j = 0; j < itemColumns; ++j) { for (int k = 0; k < itemGroupSize && itemAddr <= data->maxIndex(); ++k, itemAddr += itemByteLen) { itemString = renderItem(itemAddr - startAddress, &itemColor); if (!getFlagsAndComment(itemAddr).isEmpty()) { QColor markerColor(borderColor); markerColor.setAlphaF(0.5); painter.setPen(markerColor); for (const auto &shape : rangePolygons(itemAddr, itemAddr, false)) { painter.drawPolyline(shape); } } if (selection.contains(itemAddr) && !cursorOnAscii) { itemColor = palette().highlightedText().color(); } if (isItemDifferentAt(itemAddr)) { itemColor.setRgb(diffColor.rgb()); } if (editWordState <= EditWordState::WriteNotStarted || cursor.address != itemAddr) { painter.setPen(itemColor); painter.drawText(itemRect, Qt::AlignVCenter, itemString); itemRect.translate(itemWidth(), 0); if (cursor.address == itemAddr) { auto &itemCursor = cursorOnAscii ? shadowCursor : cursor; int itemCharPos = 0; if (editWordState > EditWordState::Read) { itemCharPos += itemPrefixLen; } if (itemCharPos < itemString.length()) { itemCursor.cachedChar = itemString.at(itemCharPos); } else { itemCursor.cachedChar = ' '; } itemCursor.cachedColor = itemColor; } } else { haveEditWord = true; editWordRect = itemRect; editWordColor = itemColor; auto &itemCursor = cursor; itemCursor.cachedChar = editWordPos < editWord.length() ? editWord[editWordPos] : QChar(' '); itemCursor.cachedColor = itemColor; itemCursor.screenPos.moveTopLeft(itemRect.topLeft()); itemCursor.screenPos.translate(charWidth * (editWordPos + itemPrefixLen), 0); itemRect.translate(itemWidth(), 0); } } itemRect.translate(columnSpacingWidth(), 0); } itemRect.translate(0, lineHeight); } if (haveEditWord) { auto length = std::max<int>(itemCharLen, editWord.length()); auto rect = editWordRect; rect.setWidth(length * charWidth); painter.fillRect(rect, backgroundColor); painter.setPen(editWordColor); editWordRect.setWidth(4000); painter.drawText(editWordRect, Qt::AlignVCenter | Qt::AlignLeft, itemPrefix + editWord); } painter.setPen(borderColor); qreal vLineOffset = asciiArea.left() - charWidth; painter.drawLine(QLineF(vLineOffset, 0, vLineOffset, viewport()->height())); } void HexWidget::drawAsciiArea(QPainter &painter) { QRectF charRect(asciiArea.topLeft(), QSizeF(charWidth, lineHeight)); fillSelectionBackground(painter, true); uint64_t address = startAddress; QChar ascii; QColor color; for (int line = 0; line < visibleLines; ++line, charRect.translate(0, lineHeight)) { charRect.moveLeft(asciiArea.left()); for (int j = 0; j < itemRowByteLen() && address <= data->maxIndex(); ++j, ++address) { ascii = renderAscii(address - startAddress, &color); if (selection.contains(address) && cursorOnAscii) { color = palette().highlightedText().color(); } if (isItemDifferentAt(address)) { color.setRgb(diffColor.rgb()); } painter.setPen(color); /* Dots look ugly. Use fillRect() instead of drawText(). */ if (ascii == '.') { qreal a = cursor.screenPos.width(); QPointF p = charRect.bottomLeft(); p.rx() += (charWidth - a) / 2 + 1; p.ry() += -2 * a; painter.fillRect(QRectF(p, QSizeF(a, a)), color); } else { painter.drawText(charRect, Qt::AlignVCenter, ascii); } charRect.translate(charWidth, 0); if (cursor.address == address) { auto &itemCursor = cursorOnAscii ? cursor : shadowCursor; itemCursor.cachedChar = ascii; itemCursor.cachedColor = color; } } } } void HexWidget::fillSelectionBackground(QPainter &painter, bool ascii) { if (selection.isEmpty()) { return; } const auto parts = rangePolygons(selection.start(), selection.end(), ascii); for (const auto &shape : parts) { QColor highlightColor = palette().color(QPalette::Highlight); if (ascii == cursorOnAscii) { painter.setBrush(highlightColor); painter.drawPolygon(shape); } else { painter.setPen(highlightColor); painter.drawPolyline(shape); } } } QVector<QPolygonF> HexWidget::rangePolygons(RVA start, RVA last, bool ascii) { if (last < startAddress || start > lastVisibleAddr()) { return {}; } QRectF rect; const QRectF area = QRectF(ascii ? asciiArea : itemArea); /* Convert absolute values to relative */ int startOffset = std::max(uint64_t(start), startAddress) - startAddress; int endOffset = std::min(uint64_t(last), lastVisibleAddr()) - startAddress; QVector<QPolygonF> parts; auto getRectangle = [&](int offset) { return QRectF(ascii ? asciiRectangle(offset) : itemRectangle(offset)); }; auto startRect = getRectangle(startOffset); auto endRect = getRectangle(endOffset); bool startJagged = false; bool endJagged = false; if (!ascii) { if (int startFraction = startOffset % itemByteLen) { startRect.setLeft(startRect.left() + startFraction * startRect.width() / itemByteLen); startJagged = true; } if (int endFraction = itemByteLen - 1 - (endOffset % itemByteLen)) { endRect.setRight(endRect.right() - endFraction * endRect.width() / itemByteLen); endJagged = true; } } if (endOffset - startOffset + 1 <= rowSizeBytes) { if (startOffset / rowSizeBytes == endOffset / rowSizeBytes) { // single row rect = startRect; rect.setRight(endRect.right()); parts.push_back(QPolygonF(rect)); } else { // two separate rectangles rect = startRect; rect.setRight(area.right()); parts.push_back(QPolygonF(rect)); rect = endRect; rect.setLeft(area.left()); parts.push_back(QPolygonF(rect)); } } else { // single multiline shape QPolygonF shape; shape << startRect.topLeft(); rect = getRectangle(startOffset + rowSizeBytes - 1 - startOffset % rowSizeBytes); shape << rect.topRight(); if (endOffset % rowSizeBytes != rowSizeBytes - 1) { rect = getRectangle(endOffset - endOffset % rowSizeBytes - 1); shape << rect.bottomRight() << endRect.topRight(); } shape << endRect.bottomRight(); shape << getRectangle(endOffset - endOffset % rowSizeBytes).bottomLeft(); if (startOffset % rowSizeBytes) { rect = getRectangle(startOffset - startOffset % rowSizeBytes + rowSizeBytes); shape << rect.topLeft() << startRect.bottomLeft(); } shape << shape.first(); // close the shape parts.push_back(shape); } if (!ascii && (startJagged || endJagged) && parts.length() >= 1) { QPolygonF top; top.reserve(3); top << QPointF(0, 0) << QPointF(charWidth, lineHeight / 3) << QPointF(0, lineHeight / 2); QPolygonF bottom; bottom.reserve(3); bottom << QPointF(0, lineHeight / 2) << QPointF(-charWidth, 2 * lineHeight / 3) << QPointF(0, lineHeight); // small adjustment to make sure that edges don't overlap with rect edges, QPolygonF doesn't // handle it properly QPointF adjustment(charWidth / 16, 0); top.translate(-adjustment); bottom.translate(adjustment); if (startJagged) { auto movedTop = top.translated(startRect.topLeft()); auto movedBottom = bottom.translated(startRect.topLeft()); parts[0] = parts[0].subtracted(movedTop).united(movedBottom); } if (endJagged) { auto movedTop = top.translated(endRect.topRight()); auto movedBottom = bottom.translated(endRect.topRight()); parts.last() = parts.last().subtracted(movedBottom).united(movedTop); } } return parts; } void HexWidget::updateMetrics() { QFontMetricsF fontMetrics(this->monospaceFont); lineHeight = fontMetrics.height(); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) charWidth = fontMetrics.width('A'); #else charWidth = fontMetrics.horizontalAdvance('A'); #endif updateCounts(); updateAreasHeight(); qreal cursorWidth = std::max(charWidth / 3, 1.); cursor.screenPos.setHeight(lineHeight); shadowCursor.screenPos.setHeight(lineHeight); cursor.screenPos.setWidth(cursorWidth); if (cursorOnAscii) { cursor.screenPos.moveTopLeft(asciiArea.topLeft()); shadowCursor.screenPos.setWidth(itemWidth()); shadowCursor.screenPos.moveTopLeft(itemArea.topLeft()); } else { cursor.screenPos.moveTopLeft(itemArea.topLeft()); shadowCursor.screenPos.setWidth(charWidth); shadowCursor.screenPos.moveTopLeft(asciiArea.topLeft()); } } void HexWidget::updateAreasPosition() { const qreal spacingWidth = areaSpacingWidth(); qreal yOffset = showHeader ? lineHeight : 0; addrArea.setTopLeft(QPointF(0, yOffset)); addrArea.setWidth((addrCharLen + (showExAddr ? 2 : 0)) * charWidth); itemArea.setTopLeft(QPointF(addrArea.right() + spacingWidth, yOffset)); itemArea.setWidth(itemRowWidth()); asciiArea.setTopLeft(QPointF(itemArea.right() + spacingWidth, yOffset)); asciiArea.setWidth(asciiRowWidth()); updateWidth(); } void HexWidget::updateAreasHeight() { visibleLines = static_cast<int>((viewport()->height() - itemArea.top()) / lineHeight); qreal height = visibleLines * lineHeight; addrArea.setHeight(height); itemArea.setHeight(height); asciiArea.setHeight(height); } bool HexWidget::moveCursor(int offset, bool select, OverflowMove overflowMove) { BasicCursor addr(cursor.address); if (overflowMove == OverflowMove::Ignore) { if (addr.moveChecked(offset)) { if (addr.address > data->maxIndex()) { addr.address = data->maxIndex(); addr.pastEnd = true; } setCursorAddr(addr, select); return true; } return false; } else { addr += offset; if (addr.address > data->maxIndex()) { addr.address = data->maxIndex(); } setCursorAddr(addr, select); return true; } } void HexWidget::moveCursorKeepEditOffset(int byteOffset, bool select, OverflowMove overflowMove) { int wordOffset = editWordPos; moveCursor(byteOffset, select, overflowMove); // preserve position within word when moving vertically in hex or oct modes if (!cursorOnAscii && !select && wordOffset > 0 && navigationMode == HexNavigationMode::AnyChar && editWordState > EditWordState::Read) { startEditWord(); editWordPos = wordOffset; } } void HexWidget::setCursorAddr(BasicCursor addr, bool select) { finishEditingWord(); if (!select) { bool clearingSelection = !selection.isEmpty(); selection.init(addr); if (clearingSelection) emit selectionChanged(getSelection()); } emit positionChanged(addr.address); cursor.address = addr.address; if (!cursorOnAscii) { cursor.address -= cursor.address % itemByteLen; } /* Pause cursor repainting */ cursorEnabled = false; if (select) { selection.update(addr); emit selectionChanged(getSelection()); } uint64_t addressValue = cursor.address; /* Update data cache if necessary */ if (!(addressValue >= startAddress && addressValue <= lastVisibleAddr())) { /* Align start address */ addressValue -= (addressValue % itemRowByteLen()); /* FIXME: handling Page Up/Down */ uint64_t rowAfterVisibleAddress = startAddress + bytesPerScreen(); if (addressValue == rowAfterVisibleAddress && addressValue > startAddress) { // when pressing down add only one new row startAddress += itemRowByteLen(); } else { startAddress = addressValue; } fetchData(); if (startAddress > (data->maxIndex() - bytesPerScreen()) + 1) { startAddress = (data->maxIndex() - bytesPerScreen()) + 1; } } updateCursorMeta(); /* Draw cursor */ cursor.isVisible = !select; viewport()->update(); /* Resume cursor repainting */ cursorEnabled = selection.isEmpty(); } void HexWidget::updateCursorMeta() { QPointF point; QPointF pointAscii; int offset = cursor.address - startAddress; int itemOffset = offset; int asciiOffset; /* Calc common Y coordinate */ point.ry() = (itemOffset / itemRowByteLen()) * lineHeight; pointAscii.setY(point.y()); itemOffset %= itemRowByteLen(); asciiOffset = itemOffset; /* Calc X coordinate on the item area */ point.rx() = (itemOffset / itemGroupByteLen()) * columnExWidth(); itemOffset %= itemGroupByteLen(); point.rx() += (itemOffset / itemByteLen) * itemWidth(); /* Calc X coordinate on the ascii area */ pointAscii.rx() = asciiOffset * charWidth; point += itemArea.topLeft(); pointAscii += asciiArea.topLeft(); if (editWordState > EditWordState::Read && !cursorOnAscii) { point.rx() += itemPrefixLen * charWidth; } cursor.screenPos.moveTopLeft(cursorOnAscii ? pointAscii : point); shadowCursor.screenPos.moveTopLeft(cursorOnAscii ? point : pointAscii); } void HexWidget::setCursorOnAscii(bool ascii) { cursorOnAscii = ascii; } QColor HexWidget::itemColor(uint8_t byte) { QColor color(defColor); if (byte == 0x00) color = b0x00Color; else if (byte == 0x7f) color = b0x7fColor; else if (byte == 0xff) color = b0xffColor; else if (IS_PRINTABLE(byte)) { color = printableColor; } return color; } template<class T> static T fromBigEndian(const void *src) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) return qFromBigEndian<T>(src); #else T result; memcpy(&result, src, sizeof(T)); return qFromBigEndian<T>(result); #endif } template<class T> static T fromLittleEndian(const void *src) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) return qFromLittleEndian<T>(src); #else T result; memcpy(&result, src, sizeof(T)); return qFromLittleEndian<T>(result); #endif } QVariant HexWidget::readItem(int offset, QColor *color) { quint8 byte; quint16 word; quint32 dword; quint64 qword; float float32; double float64; quint8 bytes[sizeof(uint64_t)]; data->copy(bytes, startAddress + offset, static_cast<size_t>(itemByteLen)); const bool signedItem = itemFormat == ItemFormatSignedDec; if (color) { *color = defColor; } switch (itemByteLen) { case 1: byte = bytes[0]; if (color) *color = itemColor(byte); if (!signedItem) return QVariant(static_cast<quint64>(byte)); return QVariant(static_cast<qint64>(static_cast<qint8>(byte))); case 2: if (itemBigEndian) word = fromBigEndian<quint16>(bytes); else word = fromLittleEndian<quint16>(bytes); if (!signedItem) return QVariant(static_cast<quint64>(word)); return QVariant(static_cast<qint64>(static_cast<qint16>(word))); case 4: if (itemBigEndian) dword = fromBigEndian<quint32>(bytes); else dword = fromLittleEndian<quint32>(bytes); if (itemFormat == ItemFormatFloat) { memcpy(&float32, &dword, sizeof(float32)); return QVariant(float32); } if (!signedItem) return QVariant(static_cast<quint64>(dword)); return QVariant(static_cast<qint64>(static_cast<qint32>(dword))); case 8: if (itemBigEndian) qword = fromBigEndian<quint64>(bytes); else qword = fromLittleEndian<quint64>(bytes); if (itemFormat == ItemFormatFloat) { memcpy(&float64, &qword, sizeof(float64)); return QVariant(float64); } if (!signedItem) return QVariant(qword); return QVariant(static_cast<qint64>(qword)); } return QVariant(); } QString HexWidget::renderItem(int offset, QColor *color) { QString item; QVariant itemVal = readItem(offset, color); int itemLen = itemCharLen - itemPrefixLen; /* Reserve space for prefix */ // FIXME: handle broken itemVal ( QVariant() ) switch (itemFormat) { case ItemFormatHex: item = QString("%1").arg(itemVal.toULongLong(), itemLen, 16, QLatin1Char('0')); if (itemByteLen > 1 && showExHex) item.prepend(hexPrefix); break; case ItemFormatOct: item = QString("%1").arg(itemVal.toULongLong(), itemLen, 8, QLatin1Char('0')); break; case ItemFormatDec: item = QString("%1").arg(itemVal.toULongLong(), itemLen, 10); break; case ItemFormatSignedDec: item = QString("%1").arg(itemVal.toLongLong(), itemLen, 10); break; case ItemFormatFloat: item = QString("%1").arg(itemVal.toDouble(), itemLen, 'g', itemByteLen == 4 ? 6 : 15); break; } return item; } QChar HexWidget::renderAscii(int offset, QColor *color) { uchar byte; data->copy(&byte, startAddress + offset, sizeof(byte)); if (color) { *color = itemColor(byte); } if (!IS_PRINTABLE(byte)) { byte = '.'; } return QChar(byte); } /** * @brief Gets the available flags and comment at a specific address. * @param address Address of Item to be checked. * @return String containing the flags and comment available at the address. */ QString HexWidget::getFlagsAndComment(uint64_t address) { QString flagNames = Core()->listFlagsAsStringAt(address); QString metaData = flagNames.isEmpty() ? "" : "Flags: " + flagNames.trimmed(); QString comment = Core()->getCommentAt(address); if (!comment.isEmpty()) { if (!metaData.isEmpty()) { metaData.append("\n"); } metaData.append("Comment: " + comment.trimmed()); } return metaData; } bool HexWidget::canKeyboardEdit() { return ioModesController.canWrite() && actionKeyboardEdit->isChecked(); } template<class T, class BigValue> static bool checkRange(BigValue v) { return v >= std::numeric_limits<T>::min() && v <= std::numeric_limits<T>::max(); } template<class T, class BigInteger> static bool checkAndWrite(BigInteger value, uint8_t *buf, bool littleEndian) { if (!checkRange<T>(value)) { return false; } if (littleEndian) { qToLittleEndian((T)value, buf); } else { qToBigEndian((T)value, buf); } return true; } template<class UType, class SType> static bool checkAndWriteWithSign(const QVariant &value, uint8_t *buf, bool isSigned, bool littleEndian) { if (isSigned) { return checkAndWrite<SType>(value.toLongLong(), buf, littleEndian); } else { return checkAndWrite<UType>(value.toULongLong(), buf, littleEndian); } } bool HexWidget::parseWord(QString word, uint8_t *buf, size_t bufferSize) const { bool parseOk = false; if (bufferSize < size_t(itemByteLen)) { return false; } if (itemFormat == ItemFormatFloat) { if (itemByteLen == 4) { float value = word.toFloat(&parseOk); if (!parseOk) { return false; } if (itemBigEndian) { rz_write_be_float(buf, value); } else { rz_write_le_float(buf, value); } return true; } else if (itemByteLen == 8) { double value = word.toDouble(&parseOk); if (!parseOk) { return false; } if (itemBigEndian) { rz_write_be_double(buf, value); } else { rz_write_le_double(buf, value); } return true; } return false; } else { QVariant value; bool isSigned = false; switch (itemFormat) { case ItemFormatHex: value = word.toULongLong(&parseOk, 16); break; case ItemFormatOct: value = word.toULongLong(&parseOk, 8); break; case ItemFormatDec: value = word.toULongLong(&parseOk, 10); break; case ItemFormatSignedDec: isSigned = true; value = word.toLongLong(&parseOk, 10); break; default: break; } if (!parseOk) { return false; } switch (itemByteLen) { case 1: return checkAndWriteWithSign<uint8_t, int8_t>(value, buf, isSigned, !itemBigEndian); case 2: return checkAndWriteWithSign<uint16_t, int16_t>(value, buf, isSigned, !itemBigEndian); case 4: return checkAndWriteWithSign<quint32, qint32>(value, buf, isSigned, !itemBigEndian); case 8: return checkAndWriteWithSign<quint64, qint64>(value, buf, isSigned, !itemBigEndian); } } return false; } bool HexWidget::flushCurrentlyEditedWord() { if (editWordState < EditWordState::WriteEdited) { return true; } uint8_t buf[16]; if (parseWord(editWord, buf, sizeof(buf))) { data->write(buf, cursor.address, itemByteLen); return true; } editWordState = EditWordState::WriteNotEdited; return false; } bool HexWidget::finishEditingWord(bool force) { if (editWordState == EditWordState::WriteEdited) { if (!flushCurrentlyEditedWord() && !force) { qWarning() << "Not a valid number in current format or size" << editWord; showWarningRect(itemRectangle(cursor.address - startAddress).adjusted(-1, -1, 1, 1)); return false; } } editWord.clear(); editWordPos = 0; editWordState = canKeyboardEdit() ? EditWordState::WriteNotStarted : EditWordState::Read; navigationMode = defaultNavigationMode(); return true; } void HexWidget::cancelEditedWord() { editWordPos = 0; editWordState = canKeyboardEdit() ? EditWordState::WriteNotStarted : EditWordState::Read; editWord.clear(); navigationMode = defaultNavigationMode(); updateCursorMeta(); viewport()->update(); } void HexWidget::maybeFlushCharEdit() { if (editWordState < EditWordState::WriteEdited) { return; } if ((itemFormat == ItemFormatHex && earlyEditFlush >= EarlyEditFlush::EditNibble) || (isFixedWidth() && earlyEditFlush >= EarlyEditFlush::EditFixedWidthChar)) { flushCurrentlyEditedWord(); if (!flushCurrentlyEditedWord()) { showWarningRect(itemRectangle(cursor.address - startAddress).adjusted(-1, -1, 1, 1)); } } viewport()->update(); } void HexWidget::startEditWord() { if (!canKeyboardEdit()) { return; } if (editWordState >= EditWordState::WriteNotEdited) { return; } editWordPos = 0; editWordState = EditWordState::WriteNotEdited; navigationMode = defaultNavigationMode(); editWord = renderItem(cursor.address - startAddress).trimmed(); if (itemPrefixLen > 0) { editWord = editWord.mid(itemPrefixLen); } viewport()->update(); } void HexWidget::fetchData() { data.swap(oldData); data->fetch(startAddress, bytesPerScreen()); } BasicCursor HexWidget::screenPosToAddr(const QPoint &point, bool middle, int *wordOffset) const { QPointF pt = point - itemArea.topLeft(); int relativeAddress = 0; int line = static_cast<int>(pt.y() / lineHeight); relativeAddress += line * itemRowByteLen(); int column = static_cast<int>(pt.x() / columnExWidth()); relativeAddress += column * itemGroupByteLen(); pt.rx() -= column * columnExWidth(); auto roundingOffset = middle ? itemWidth() / 2 : 0; int posInGroup = static_cast<int>((pt.x() + roundingOffset) / itemWidth()); if (!middle) { posInGroup = std::min(posInGroup, itemGroupSize - 1); } relativeAddress += posInGroup * itemByteLen; pt.rx() -= posInGroup * itemWidth(); BasicCursor result(startAddress); result += relativeAddress; if (!middle && wordOffset != nullptr) { int charPos = static_cast<int>((pt.x() / charWidth) + 0.5); charPos -= itemPrefixLen; charPos = std::max(0, charPos); *wordOffset = charPos; } return result; } BasicCursor HexWidget::asciiPosToAddr(const QPoint &point, bool middle) const { QPointF pt = point - asciiArea.topLeft(); int relativeAddress = 0; relativeAddress += static_cast<int>(pt.y() / lineHeight) * itemRowByteLen(); auto roundingOffset = middle ? (charWidth / 2) : 0; relativeAddress += static_cast<int>((pt.x() + (roundingOffset)) / charWidth); BasicCursor result(startAddress); result += relativeAddress; return result; } BasicCursor HexWidget::currentAreaPosToAddr(const QPoint &point, bool middle) const { return cursorOnAscii ? asciiPosToAddr(point, middle) : screenPosToAddr(point, middle); } BasicCursor HexWidget::mousePosToAddr(const QPoint &point, bool middle) const { return asciiArea.contains(point) ? asciiPosToAddr(point, middle) : screenPosToAddr(point, middle); } QRectF HexWidget::itemRectangle(int offset) { qreal x; qreal y; qreal width = itemWidth(); y = (offset / itemRowByteLen()) * lineHeight; offset %= itemRowByteLen(); x = (offset / itemGroupByteLen()) * columnExWidth(); offset %= itemGroupByteLen(); x += (offset / itemByteLen) * itemWidth(); if (offset == 0) { x -= charWidth / 2; width += charWidth / 2; } if (static_cast<int>(offset) == itemGroupByteLen() - 1) { width += charWidth / 2; } x += itemArea.x(); y += itemArea.y(); return QRectF(x, y, width, lineHeight); } QRectF HexWidget::asciiRectangle(int offset) { QPointF p; p.ry() = (offset / itemRowByteLen()) * lineHeight; offset %= itemRowByteLen(); p.rx() = offset * charWidth; p += asciiArea.topLeft(); return QRectF(p, QSizeF(charWidth, lineHeight)); } RVA HexWidget::getLocationAddress() { return !selection.isEmpty() ? selection.start() : cursor.address; } void HexWidget::hideWarningRect() { warningRectVisible = false; viewport()->update(); } void HexWidget::showWarningRect(QRectF rect) { warningRect = rect; warningRectVisible = true; warningTimer.start(WARNING_TIME_MS); viewport()->update(); }
82,010
C++
.cpp
2,260
28.461504
100
0.617126
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,586
BreakpointWidget.cpp
rizinorg_cutter/src/widgets/BreakpointWidget.cpp
#include "BreakpointWidget.h" #include "ui_BreakpointWidget.h" #include "dialogs/BreakpointsDialog.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "widgets/BoolToggleDelegate.h" #include <QMenu> #include <QStyledItemDelegate> #include <QCheckBox> BreakpointModel::BreakpointModel(QObject *parent) : AddressableItemModel<QAbstractListModel>(parent) { } void BreakpointModel::refresh() { beginResetModel(); breakpoints = Core()->getBreakpoints(); endResetModel(); } int BreakpointModel::rowCount(const QModelIndex &) const { return breakpoints.count(); } int BreakpointModel::columnCount(const QModelIndex &) const { return BreakpointModel::ColumnCount; } static QString formatHwBreakpoint(int permission) { char data[] = "rwx"; if ((permission & (RZ_PERM_R | RZ_PERM_RW)) == 0) { data[0] = '-'; } if ((permission & (RZ_PERM_W | RZ_PERM_RW)) == 0) { data[1] = '-'; } if ((permission & RZ_PERM_X) == 0) { data[2] = '-'; } return data; } QVariant BreakpointModel::data(const QModelIndex &index, int role) const { if (index.row() >= breakpoints.count()) return QVariant(); const BreakpointDescription &breakpoint = breakpoints.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case AddrColumn: return RzAddressString(breakpoint.addr); case NameColumn: return breakpoint.name; case TypeColumn: if (breakpoint.hw) { return tr("HW %1").arg(formatHwBreakpoint(breakpoint.permission)); } else { return tr("SW"); } case TraceColumn: return breakpoint.trace; case EnabledColumn: return breakpoint.enabled; case CommentColumn: return Core()->getCommentAt(breakpoint.addr); default: return QVariant(); } case Qt::EditRole: switch (index.column()) { case AddrColumn: return breakpoint.addr; case TraceColumn: return breakpoint.trace; case EnabledColumn: return breakpoint.enabled; default: return data(index, Qt::DisplayRole); } case BreakpointDescriptionRole: return QVariant::fromValue(breakpoint); default: return QVariant(); } } QVariant BreakpointModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case AddrColumn: return tr("Offset"); case NameColumn: return tr("Name"); case TypeColumn: return tr("Type"); case TraceColumn: return tr("Tracing"); case EnabledColumn: return tr("Enabled"); case CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } bool BreakpointModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.row() >= breakpoints.count()) return false; BreakpointDescription &breakpoint = breakpoints[index.row()]; switch (role) { case Qt::EditRole: switch (index.column()) { case TraceColumn: breakpoint.trace = value.toBool(); Core()->setBreakpointTrace(breakpoint.index, breakpoint.trace); emit dataChanged(index, index, { role, Qt::DisplayRole }); return true; case EnabledColumn: breakpoint.enabled = value.toBool(); if (breakpoint.enabled) { Core()->enableBreakpoint(breakpoint.addr); } else { Core()->disableBreakpoint(breakpoint.addr); } emit dataChanged(index, index, { role, Qt::DisplayRole }); return true; default: return false; } default: return false; } } Qt::ItemFlags BreakpointModel::flags(const QModelIndex &index) const { switch (index.column()) { case TraceColumn: return AddressableItemModel::flags(index) | Qt::ItemFlag::ItemIsEditable; case EnabledColumn: return AddressableItemModel::flags(index) | Qt::ItemFlag::ItemIsEditable; default: return AddressableItemModel::flags(index); } } RVA BreakpointModel::address(const QModelIndex &index) const { if (index.row() < breakpoints.count()) { return breakpoints.at(index.row()).addr; } return RVA_INVALID; } BreakpointProxyModel::BreakpointProxyModel(BreakpointModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { // Use numeric values instead of numbers converted to strings if available this->setSortRole(Qt::EditRole); } BreakpointWidget::BreakpointWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::BreakpointWidget) { ui->setupUi(this); ui->breakpointTreeView->setMainWindow(mainWindow); breakpointModel = new BreakpointModel(this); breakpointProxyModel = new BreakpointProxyModel(breakpointModel, this); ui->breakpointTreeView->setModel(breakpointProxyModel); ui->breakpointTreeView->sortByColumn(BreakpointModel::AddrColumn, Qt::AscendingOrder); ui->breakpointTreeView->setItemDelegate(new BoolTogggleDelegate(this)); refreshDeferrer = createRefreshDeferrer([this]() { refreshBreakpoint(); }); setScrollMode(); actionDelBreakpoint = new QAction(tr("Delete breakpoint"), this); actionDelBreakpoint->setShortcut(Qt::Key_Delete); actionDelBreakpoint->setShortcutContext(Qt::WidgetShortcut); connect(actionDelBreakpoint, &QAction::triggered, this, &BreakpointWidget::delBreakpoint); ui->breakpointTreeView->addAction(actionDelBreakpoint); actionToggleBreakpoint = new QAction(tr("Toggle breakpoint"), this); actionToggleBreakpoint->setShortcut(Qt::Key_Space); actionToggleBreakpoint->setShortcutContext(Qt::WidgetShortcut); connect(actionToggleBreakpoint, &QAction::triggered, this, &BreakpointWidget::toggleBreakpoint); ui->breakpointTreeView->addAction(actionToggleBreakpoint); actionEditBreakpoint = new QAction(tr("Edit"), this); connect(actionEditBreakpoint, &QAction::triggered, this, &BreakpointWidget::editBreakpoint); auto contextMenu = ui->breakpointTreeView->getItemContextMenu(); contextMenu->addAction(actionEditBreakpoint); contextMenu->addAction(actionToggleBreakpoint); contextMenu->addAction(actionDelBreakpoint); connect(Core(), &CutterCore::refreshAll, this, &BreakpointWidget::refreshBreakpoint); connect(Core(), &CutterCore::breakpointsChanged, this, &BreakpointWidget::refreshBreakpoint); connect(Core(), &CutterCore::codeRebased, this, &BreakpointWidget::refreshBreakpoint); connect(Core(), &CutterCore::refreshCodeViews, this, &BreakpointWidget::refreshBreakpoint); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(breakpointModel, BreakpointModel::CommentColumn); }); connect(ui->addBreakpoint, &QAbstractButton::clicked, this, &BreakpointWidget::addBreakpointDialog); connect(ui->delBreakpoint, &QAbstractButton::clicked, this, &BreakpointWidget::delBreakpoint); connect(ui->delAllBreakpoints, &QAbstractButton::clicked, Core(), &CutterCore::delAllBreakpoints); } BreakpointWidget::~BreakpointWidget() = default; void BreakpointWidget::refreshBreakpoint() { if (editing || !refreshDeferrer->attemptRefresh(nullptr)) { return; } breakpointModel->refresh(); ui->breakpointTreeView->resizeColumnToContents(0); ui->breakpointTreeView->resizeColumnToContents(1); ui->breakpointTreeView->resizeColumnToContents(2); } void BreakpointWidget::setScrollMode() { qhelpers::setVerticalScrollMode(ui->breakpointTreeView); } void BreakpointWidget::addBreakpointDialog() { BreakpointsDialog::createNewBreakpoint(RVA_INVALID, this); } QVector<RVA> BreakpointWidget::getSelectedAddresses() const { auto selection = ui->breakpointTreeView->selectionModel()->selectedRows(); QVector<RVA> breakpointAddressese(selection.count()); int index = 0; for (auto row : selection) { breakpointAddressese[index++] = breakpointProxyModel->address(row); } return breakpointAddressese; } void BreakpointWidget::delBreakpoint() { auto breakpointsToRemove = getSelectedAddresses(); for (auto address : breakpointsToRemove) { Core()->delBreakpoint(address); } } void BreakpointWidget::toggleBreakpoint() { auto selection = ui->breakpointTreeView->selectionModel()->selectedRows(); editing = true; for (auto row : selection) { auto cell = breakpointProxyModel->index(row.row(), BreakpointModel::EnabledColumn); breakpointProxyModel->setData(cell, !cell.data(Qt::EditRole).toBool()); } editing = false; } void BreakpointWidget::editBreakpoint() { auto index = ui->breakpointTreeView->currentIndex(); if (index.isValid()) { auto data = breakpointProxyModel->data(index, BreakpointModel::BreakpointDescriptionRole); if (!data.isNull()) { auto breakpoint = data.value<BreakpointDescription>(); BreakpointsDialog::editBreakpoint(breakpoint, this); } } }
9,437
C++
.cpp
259
30.277992
100
0.691424
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,587
ProcessesWidget.cpp
rizinorg_cutter/src/widgets/ProcessesWidget.cpp
#include <QShortcut> #include "ProcessesWidget.h" #include "ui_ProcessesWidget.h" #include "common/JsonModel.h" #include "QuickFilterView.h" #include <rz_debug.h> #include "core/MainWindow.h" #define DEBUGGED_PID (-1) ProcessesWidget::ProcessesWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::ProcessesWidget) { ui->setupUi(this); // Setup processes model modelProcesses = new QStandardItemModel(1, 4, this); modelProcesses->setHorizontalHeaderItem(ProcessesWidget::COLUMN_PID, new QStandardItem(tr("PID"))); modelProcesses->setHorizontalHeaderItem(ProcessesWidget::COLUMN_UID, new QStandardItem(tr("UID"))); modelProcesses->setHorizontalHeaderItem(ProcessesWidget::COLUMN_STATUS, new QStandardItem(tr("Status"))); modelProcesses->setHorizontalHeaderItem(ProcessesWidget::COLUMN_PATH, new QStandardItem(tr("Path"))); ui->viewProcesses->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); ui->viewProcesses->verticalHeader()->setVisible(false); ui->viewProcesses->setFont(Config()->getFont()); modelFilter = new ProcessesFilterModel(this); modelFilter->setSourceModel(modelProcesses); ui->viewProcesses->setModel(modelFilter); // CTRL+F switches to the filter view and opens it in case it's hidden QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // ESC switches back to the processes table and clears the buffer QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, this, [this]() { ui->quickFilterView->clearFilter(); ui->viewProcesses->setFocus(); }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, modelFilter, &ProcessesFilterModel::setFilterWildcard); connect(Core(), &CutterCore::refreshAll, this, &ProcessesWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &ProcessesWidget::updateContents); connect(Core(), &CutterCore::debugTaskStateChanged, this, &ProcessesWidget::updateContents); // Seek doesn't necessarily change when switching processes connect(Core(), &CutterCore::switchedProcess, this, &ProcessesWidget::updateContents); connect(Config(), &Configuration::fontsUpdated, this, &ProcessesWidget::fontsUpdatedSlot); connect(ui->viewProcesses, &QTableView::activated, this, &ProcessesWidget::onActivated); } ProcessesWidget::~ProcessesWidget() {} void ProcessesWidget::updateContents() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } if (!Core()->currentlyDebugging) { // Remove rows from the previous debugging session modelProcesses->removeRows(0, modelProcesses->rowCount()); return; } if (Core()->isDebugTaskInProgress()) { ui->viewProcesses->setDisabled(true); } else { setProcessesGrid(); ui->viewProcesses->setDisabled(false); } } QString ProcessesWidget::translateStatus(const char status) { switch (status) { case RZ_DBG_PROC_STOP: return "Stopped"; case RZ_DBG_PROC_RUN: return "Running"; case RZ_DBG_PROC_SLEEP: return "Sleeping"; case RZ_DBG_PROC_ZOMBIE: return "Zombie"; case RZ_DBG_PROC_DEAD: return "Dead"; case RZ_DBG_PROC_RAISED: return "Raised event"; default: return "Unknown status"; } } void ProcessesWidget::setProcessesGrid() { int i = 0; QFont font; for (const auto &processesItem : Core()->getProcessThreads(DEBUGGED_PID)) { st64 pid = processesItem.pid; st64 uid = processesItem.uid; QString status = translateStatus(processesItem.status); QString path = processesItem.path; bool current = processesItem.current; // Use bold font to highlight active thread font.setBold(current); QStandardItem *rowPid = new QStandardItem(QString::number(pid)); QStandardItem *rowUid = new QStandardItem(QString::number(uid)); QStandardItem *rowStatus = new QStandardItem(status); QStandardItem *rowPath = new QStandardItem(path); rowPid->setFont(font); rowUid->setFont(font); rowStatus->setFont(font); rowPath->setFont(font); modelProcesses->setItem(i, ProcessesWidget::COLUMN_PID, rowPid); modelProcesses->setItem(i, ProcessesWidget::COLUMN_UID, rowUid); modelProcesses->setItem(i, ProcessesWidget::COLUMN_STATUS, rowStatus); modelProcesses->setItem(i, ProcessesWidget::COLUMN_PATH, rowPath); i++; } // Remove irrelevant old rows if (modelProcesses->rowCount() > i) { modelProcesses->removeRows(i, modelProcesses->rowCount() - i); } modelFilter->setSourceModel(modelProcesses); ui->viewProcesses->resizeColumnsToContents(); } void ProcessesWidget::fontsUpdatedSlot() { ui->viewProcesses->setFont(Config()->getFont()); } void ProcessesWidget::onActivated(const QModelIndex &index) { if (!index.isValid()) return; int pid = modelFilter->data(index.sibling(index.row(), ProcessesWidget::COLUMN_PID)).toInt(); // Verify that the selected pid is still in the processes list since dp= will // attach to any given id. If it isn't found simply update the UI. for (const auto &value : Core()->getAllProcesses()) { if (pid == value.pid) { QMessageBox msgBox; switch (value.status) { case RZ_DBG_PROC_ZOMBIE: case RZ_DBG_PROC_DEAD: msgBox.setText(tr("Unable to switch to the requested process.")); msgBox.exec(); break; default: Core()->setCurrentDebugProcess(pid); break; } } } updateContents(); } ProcessesFilterModel::ProcessesFilterModel(QObject *parent) : QSortFilterProxyModel(parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool ProcessesFilterModel::filterAcceptsRow(int row, const QModelIndex &parent) const { // All columns are checked for a match for (int i = ProcessesWidget::COLUMN_PID; i <= ProcessesWidget::COLUMN_PATH; ++i) { QModelIndex index = sourceModel()->index(row, i, parent); if (qhelpers::filterStringContains(sourceModel()->data(index).toString(), this)) { return true; } } return false; }
6,982
C++
.cpp
165
35.133333
97
0.681249
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,588
RegisterRefsWidget.cpp
rizinorg_cutter/src/widgets/RegisterRefsWidget.cpp
#include "RegisterRefsWidget.h" #include "ui_RegisterRefsWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QJsonObject> #include <QMenu> #include <QClipboard> #include <QShortcut> RegisterRefModel::RegisterRefModel(QList<RegisterRefDescription> *registerRefs, QObject *parent) : QAbstractListModel(parent), registerRefs(registerRefs) { } int RegisterRefModel::rowCount(const QModelIndex &) const { return registerRefs->count(); } int RegisterRefModel::columnCount(const QModelIndex &) const { return RegisterRefModel::ColumnCount; } QVariant RegisterRefModel::data(const QModelIndex &index, int role) const { if (index.row() >= registerRefs->count()) return QVariant(); const RegisterRefDescription &registerRef = registerRefs->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case RegColumn: return registerRef.reg; case ValueColumn: return registerRef.value; case RefColumn: return registerRef.refDesc.ref; case CommentColumn: return Core()->getCommentAt(Core()->math(registerRef.value)); default: return QVariant(); } case Qt::ForegroundRole: switch (index.column()) { case RefColumn: return registerRef.refDesc.refColor; default: return QVariant(); } case RegisterRefDescriptionRole: return QVariant::fromValue(registerRef); default: return QVariant(); } } QVariant RegisterRefModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case RegColumn: return tr("Register"); case ValueColumn: return tr("Value"); case RefColumn: return tr("Reference"); case CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RegisterRefProxyModel::RegisterRefProxyModel(RegisterRefModel *sourceModel, QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(sourceModel); } bool RegisterRefProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); RegisterRefDescription item = index.data(RegisterRefModel::RegisterRefDescriptionRole) .value<RegisterRefDescription>(); return qhelpers::filterStringContains(item.reg, this); } bool RegisterRefProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { RegisterRefDescription leftRegRef = left.data(RegisterRefModel::RegisterRefDescriptionRole).value<RegisterRefDescription>(); RegisterRefDescription rightRegRef = right.data(RegisterRefModel::RegisterRefDescriptionRole) .value<RegisterRefDescription>(); switch (left.column()) { case RegisterRefModel::RegColumn: return leftRegRef.reg < rightRegRef.reg; case RegisterRefModel::RefColumn: return leftRegRef.refDesc.ref < rightRegRef.refDesc.ref; case RegisterRefModel::ValueColumn: return leftRegRef.value < rightRegRef.value; case RegisterRefModel::CommentColumn: return Core()->getCommentAt(Core()->math(leftRegRef.value)) < Core()->getCommentAt(Core()->math(rightRegRef.value)); default: break; } return leftRegRef.reg < rightRegRef.reg; } RegisterRefsWidget::RegisterRefsWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::RegisterRefsWidget), tree(new CutterTreeWidget(this)), addressableItemContextMenu(this, main) { ui->setupUi(this); // Add Status Bar footer tree->addStatusBar(ui->verticalLayout); registerRefModel = new RegisterRefModel(&registerRefs, this); registerRefProxyModel = new RegisterRefProxyModel(registerRefModel, this); ui->registerRefTreeView->setModel(registerRefProxyModel); ui->registerRefTreeView->setAutoScroll(false); ui->registerRefTreeView->sortByColumn(RegisterRefModel::RegColumn, Qt::AscendingOrder); actionCopyValue = new QAction(tr("Copy register value"), this); actionCopyRef = new QAction(tr("Copy register reference"), this); addressableItemContextMenu.addAction(actionCopyValue); addressableItemContextMenu.addAction(actionCopyRef); addActions(addressableItemContextMenu.actions()); connect(ui->registerRefTreeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &RegisterRefsWidget::onCurrentChanged); refreshDeferrer = createRefreshDeferrer([this]() { refreshRegisterRef(); }); // Ctrl-F to show/hide the filter entry QShortcut *search_shortcut = new QShortcut(QKeySequence::Find, this); connect(search_shortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); search_shortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, registerRefProxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->registerRefTreeView, [this]() { ui->registerRefTreeView->setFocus(); }); setScrollMode(); connect(Core(), &CutterCore::refreshAll, this, &RegisterRefsWidget::refreshRegisterRef); connect(Core(), &CutterCore::registersChanged, this, &RegisterRefsWidget::refreshRegisterRef); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(registerRefModel, RegisterRefModel::CommentColumn); }); connect(actionCopyValue, &QAction::triggered, this, [this]() { copyClip(RegisterRefModel::ValueColumn); }); connect(actionCopyRef, &QAction::triggered, this, [this]() { copyClip(RegisterRefModel::RefColumn); }); ui->registerRefTreeView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->registerRefTreeView, &QMenu::customContextMenuRequested, this, &RegisterRefsWidget::customMenuRequested); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, [this] { tree->showItemsNumber(registerRefProxyModel->rowCount()); }); } RegisterRefsWidget::~RegisterRefsWidget() = default; void RegisterRefsWidget::refreshRegisterRef() { if (!refreshDeferrer->attemptRefresh(nullptr)) { return; } registerRefModel->beginResetModel(); registerRefs.clear(); for (const RegisterRef &reg : Core()->getRegisterRefs()) { RegisterRefDescription desc; desc.value = RzAddressString(reg.value); desc.reg = reg.name; desc.refDesc = Core()->formatRefDesc(QSharedPointer<AddrRefs>::create(reg.ref)); registerRefs.push_back(desc); } registerRefModel->endResetModel(); ui->registerRefTreeView->resizeColumnToContents(0); ui->registerRefTreeView->resizeColumnToContents(1); ui->registerRefTreeView->resizeColumnToContents(2); tree->showItemsNumber(registerRefProxyModel->rowCount()); } void RegisterRefsWidget::setScrollMode() { qhelpers::setVerticalScrollMode(ui->registerRefTreeView); } void RegisterRefsWidget::on_registerRefTreeView_doubleClicked(const QModelIndex &index) { RegisterRefDescription item = index.data(RegisterRefModel::RegisterRefDescriptionRole) .value<RegisterRefDescription>(); Core()->seekAndShow(item.value); } void RegisterRefsWidget::customMenuRequested(QPoint pos) { addressableItemContextMenu.exec(ui->registerRefTreeView->viewport()->mapToGlobal(pos)); } void RegisterRefsWidget::onCurrentChanged(const QModelIndex &current, const QModelIndex &previous) { Q_UNUSED(current) Q_UNUSED(previous) auto currentIndex = ui->registerRefTreeView->selectionModel()->currentIndex(); // Use the value column as the offset QString offsetString; if (currentIndex.column() != RegisterRefModel::RefColumn) { offsetString = currentIndex.data().toString(); } else { offsetString = currentIndex.sibling(currentIndex.row(), RegisterRefModel::ValueColumn) .data() .toString(); } RVA offset = Core()->math(offsetString); addressableItemContextMenu.setTarget(offset); } void RegisterRefsWidget::copyClip(int column) { int row = ui->registerRefTreeView->selectionModel()->currentIndex().row(); QString value = ui->registerRefTreeView->selectionModel() ->currentIndex() .sibling(row, column) .data() .toString(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(value); }
8,971
C++
.cpp
215
34.753488
100
0.704485
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,589
ResourcesWidget.cpp
rizinorg_cutter/src/widgets/ResourcesWidget.cpp
#include "common/Helpers.h" #include "ResourcesWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include <QVBoxLayout> ResourcesModel::ResourcesModel(QList<ResourcesDescription> *resources, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), resources(resources) { } int ResourcesModel::rowCount(const QModelIndex &) const { return resources->count(); } int ResourcesModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant ResourcesModel::data(const QModelIndex &index, int role) const { const ResourcesDescription &res = resources->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case NAME: return res.name; case VADDR: return RzAddressString(res.vaddr); case INDEX: return QString::number(res.index); case TYPE: return res.type; case SIZE: return qhelpers::formatBytecount(res.size); case LANG: return res.lang; case COMMENT: return Core()->getCommentAt(res.vaddr); default: return QVariant(); } case Qt::EditRole: switch (index.column()) { case NAME: return res.name; case VADDR: return res.vaddr; case INDEX: return res.index; case TYPE: return res.type; case SIZE: return res.size; case LANG: return res.lang; default: return QVariant(); } case Qt::UserRole: return QVariant::fromValue(res); default: return QVariant(); } } QVariant ResourcesModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case NAME: return tr("Name"); case VADDR: return tr("Vaddr"); case INDEX: return tr("Index"); case TYPE: return tr("Type"); case SIZE: return tr("Size"); case LANG: return tr("Lang"); case COMMENT: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA ResourcesModel::address(const QModelIndex &index) const { const ResourcesDescription &res = resources->at(index.row()); return res.vaddr; } ResourcesWidget::ResourcesWidget(MainWindow *main) : ListDockWidget(main, ListDockWidget::SearchBarPolicy::HideByDefault) { setObjectName("ResourcesWidget"); model = new ResourcesModel(&resources, this); filterModel = new AddressableFilterProxyModel(model, this); filterModel->setSortRole(Qt::EditRole); setModels(filterModel); ui->treeView->sortByColumn(0, Qt::AscendingOrder); showCount(false); // Configure widget this->setWindowTitle(tr("Resources")); connect(Core(), &CutterCore::refreshAll, this, &ResourcesWidget::refreshResources); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(model, ResourcesModel::COMMENT); }); } void ResourcesWidget::refreshResources() { model->beginResetModel(); resources = Core()->getAllResources(); model->endResetModel(); }
3,379
C++
.cpp
116
22.25
87
0.631579
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,590
SymbolsWidget.cpp
rizinorg_cutter/src/widgets/SymbolsWidget.cpp
#include "SymbolsWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QShortcut> SymbolsModel::SymbolsModel(QList<SymbolDescription> *symbols, QObject *parent) : AddressableItemModel<QAbstractListModel>(parent), symbols(symbols) { } int SymbolsModel::rowCount(const QModelIndex &) const { return symbols->count(); } int SymbolsModel::columnCount(const QModelIndex &) const { return SymbolsModel::ColumnCount; } QVariant SymbolsModel::data(const QModelIndex &index, int role) const { if (index.row() >= symbols->count()) { return QVariant(); } const SymbolDescription &symbol = symbols->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case SymbolsModel::AddressColumn: return RzAddressString(symbol.vaddr); case SymbolsModel::TypeColumn: return QString("%1 %2").arg(symbol.bind, symbol.type).trimmed(); case SymbolsModel::NameColumn: return symbol.name; case SymbolsModel::CommentColumn: return Core()->getCommentAt(symbol.vaddr); default: return QVariant(); } case SymbolsModel::SymbolDescriptionRole: return QVariant::fromValue(symbol); default: return QVariant(); } } QVariant SymbolsModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case SymbolsModel::AddressColumn: return tr("Address"); case SymbolsModel::TypeColumn: return tr("Type"); case SymbolsModel::NameColumn: return tr("Name"); case SymbolsModel::CommentColumn: return tr("Comment"); default: return QVariant(); } default: return QVariant(); } } RVA SymbolsModel::address(const QModelIndex &index) const { const SymbolDescription &symbol = symbols->at(index.row()); return symbol.vaddr; } QString SymbolsModel::name(const QModelIndex &index) const { const SymbolDescription &symbol = symbols->at(index.row()); return symbol.name; } SymbolsProxyModel::SymbolsProxyModel(SymbolsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool SymbolsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); auto symbol = index.data(SymbolsModel::SymbolDescriptionRole).value<SymbolDescription>(); return qhelpers::filterStringContains(symbol.name, this); } bool SymbolsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftSymbol = left.data(SymbolsModel::SymbolDescriptionRole).value<SymbolDescription>(); auto rightSymbol = right.data(SymbolsModel::SymbolDescriptionRole).value<SymbolDescription>(); switch (left.column()) { case SymbolsModel::AddressColumn: return leftSymbol.vaddr < rightSymbol.vaddr; case SymbolsModel::TypeColumn: return leftSymbol.type < rightSymbol.type; case SymbolsModel::NameColumn: return leftSymbol.name < rightSymbol.name; case SymbolsModel::CommentColumn: return Core()->getCommentAt(leftSymbol.vaddr) < Core()->getCommentAt(rightSymbol.vaddr); default: break; } return false; } SymbolsWidget::SymbolsWidget(MainWindow *main) : ListDockWidget(main) { setWindowTitle(tr("Symbols")); setObjectName("SymbolsWidget"); symbolsModel = new SymbolsModel(&symbols, this); symbolsProxyModel = new SymbolsProxyModel(symbolsModel, this); setModels(symbolsProxyModel); ui->treeView->sortByColumn(SymbolsModel::AddressColumn, Qt::AscendingOrder); connect(Core(), &CutterCore::codeRebased, this, &SymbolsWidget::refreshSymbols); connect(Core(), &CutterCore::refreshAll, this, &SymbolsWidget::refreshSymbols); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(symbolsModel, SymbolsModel::CommentColumn); }); } SymbolsWidget::~SymbolsWidget() {} void SymbolsWidget::refreshSymbols() { symbolsModel->beginResetModel(); symbols = Core()->getAllSymbols(); symbolsModel->endResetModel(); qhelpers::adjustColumns(ui->treeView, SymbolsModel::ColumnCount, 0); }
4,497
C++
.cpp
124
30.991935
98
0.715468
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,591
RelocsWidget.cpp
rizinorg_cutter/src/widgets/RelocsWidget.cpp
#include "RelocsWidget.h" #include "ui_ListDockWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QShortcut> #include <QTreeWidget> RelocsModel::RelocsModel(QObject *parent) : AddressableItemModel<QAbstractTableModel>(parent) {} int RelocsModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : relocs.count(); } int RelocsModel::columnCount(const QModelIndex &) const { return RelocsModel::ColumnCount; } QVariant RelocsModel::data(const QModelIndex &index, int role) const { const RelocDescription &reloc = relocs.at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case RelocsModel::VAddrColumn: return RzAddressString(reloc.vaddr); case RelocsModel::TypeColumn: return reloc.type; case RelocsModel::NameColumn: return reloc.name; case RelocsModel::CommentColumn: return Core()->getCommentAt(reloc.vaddr); default: break; } break; case RelocsModel::RelocDescriptionRole: return QVariant::fromValue(reloc); case RelocsModel::AddressRole: return reloc.vaddr; default: break; } return QVariant(); } QVariant RelocsModel::headerData(int section, Qt::Orientation, int role) const { if (role == Qt::DisplayRole) switch (section) { case RelocsModel::VAddrColumn: return tr("Address"); case RelocsModel::TypeColumn: return tr("Type"); case RelocsModel::NameColumn: return tr("Name"); case RelocsModel::CommentColumn: return tr("Comment"); } return QVariant(); } RVA RelocsModel::address(const QModelIndex &index) const { const RelocDescription &reloc = relocs.at(index.row()); return reloc.vaddr; } QString RelocsModel::name(const QModelIndex &index) const { const RelocDescription &reloc = relocs.at(index.row()); return reloc.name; } void RelocsModel::reload() { beginResetModel(); relocs = Core()->getAllRelocs(); endResetModel(); } RelocsProxyModel::RelocsProxyModel(RelocsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool RelocsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); auto reloc = index.data(RelocsModel::RelocDescriptionRole).value<RelocDescription>(); return qhelpers::filterStringContains(reloc.name, this); } bool RelocsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { if (!left.isValid() || !right.isValid()) return false; if (left.parent().isValid() || right.parent().isValid()) return false; auto leftReloc = left.data(RelocsModel::RelocDescriptionRole).value<RelocDescription>(); auto rightReloc = right.data(RelocsModel::RelocDescriptionRole).value<RelocDescription>(); switch (left.column()) { case RelocsModel::VAddrColumn: return leftReloc.vaddr < rightReloc.vaddr; case RelocsModel::TypeColumn: return leftReloc.type < rightReloc.type; case RelocsModel::NameColumn: return leftReloc.name < rightReloc.name; case RelocsModel::CommentColumn: return Core()->getCommentAt(leftReloc.vaddr) < Core()->getCommentAt(rightReloc.vaddr); default: break; } return false; } RelocsWidget::RelocsWidget(MainWindow *main) : ListDockWidget(main), relocsModel(new RelocsModel(this)), relocsProxyModel(new RelocsProxyModel(relocsModel, this)) { setWindowTitle(tr("Relocs")); setObjectName("RelocsWidget"); setModels(relocsProxyModel); ui->treeView->sortByColumn(RelocsModel::NameColumn, Qt::AscendingOrder); connect(Core(), &CutterCore::codeRebased, this, &RelocsWidget::refreshRelocs); connect(Core(), &CutterCore::refreshAll, this, &RelocsWidget::refreshRelocs); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(relocsModel, RelocsModel::CommentColumn); }); } RelocsWidget::~RelocsWidget() {} void RelocsWidget::refreshRelocs() { relocsModel->reload(); qhelpers::adjustColumns(ui->treeView, 3, 0); }
4,413
C++
.cpp
127
29.543307
96
0.70849
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,592
SdbWidget.cpp
rizinorg_cutter/src/widgets/SdbWidget.cpp
#include "SdbWidget.h" #include "ui_SdbWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QDebug> #include <QTreeWidget> SdbWidget::SdbWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::SdbWidget) { ui->setupUi(this); path.clear(); connect(Core(), &CutterCore::refreshAll, this, [this]() { reload(); }); reload(); } void SdbWidget::reload(QString _path) { path = _path; ui->lineEdit->setText(path); /* insert root sdb keyvalue pairs */ ui->treeWidget->clear(); QList<QString> keys; /* key-values */ keys = Core()->sdbListKeys(path); for (const QString &key : keys) { QTreeWidgetItem *tempItem = new QTreeWidgetItem(); tempItem->setText(0, key); tempItem->setText(1, Core()->sdbGet(path, key)); tempItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsEditable); ui->treeWidget->insertTopLevelItem(0, tempItem); } qhelpers::adjustColumns(ui->treeWidget, 0); /* namespaces */ keys = Core()->sdbList(path); if (!path.isEmpty()) { keys.append(".."); } for (const QString &key : keys) { QTreeWidgetItem *tempItem = new QTreeWidgetItem(); tempItem->setText(0, key + "/"); tempItem->setText(1, ""); ui->treeWidget->insertTopLevelItem(0, tempItem); } qhelpers::adjustColumns(ui->treeWidget, 0); } void SdbWidget::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { if (column < 0) return; QString newpath; if (column == 0) { if (item->text(0) == "../") { int idx = path.lastIndexOf(QLatin1Char('/')); if (idx != -1) { newpath = path.mid(0, idx); } else { newpath.clear(); } reload(newpath); } else if (item->text(0).indexOf(QLatin1Char('/')) != -1) { if (!path.isEmpty()) { newpath = path + "/" + item->text(0).remove(QLatin1Char('/')); } else { newpath = path + item->text(0).remove(QLatin1Char('/')); } // enter directory reload(newpath); } } } SdbWidget::~SdbWidget() = default; void SdbWidget::on_lockButton_clicked() { if (ui->lockButton->isChecked()) { this->setAllowedAreas(Qt::NoDockWidgetArea); ui->lockButton->setIcon(QIcon(":/lock")); } else { this->setAllowedAreas(Qt::AllDockWidgetAreas); ui->lockButton->setIcon(QIcon(":/unlock")); } } void SdbWidget::on_treeWidget_itemChanged(QTreeWidgetItem *item, int column) { Core()->sdbSet(path, item->text(0), item->text(column)); }
2,785
C++
.cpp
84
26.369048
93
0.592703
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,593
SimpleTextGraphView.cpp
rizinorg_cutter/src/widgets/SimpleTextGraphView.cpp
#include "SimpleTextGraphView.h" #include "core/Cutter.h" #include "core/MainWindow.h" #include "common/Configuration.h" #include "common/SyntaxHighlighter.h" #include "common/Helpers.h" #include <QPainter> #include <QJsonObject> #include <QJsonArray> #include <QMouseEvent> #include <QPropertyAnimation> #include <QShortcut> #include <QToolTip> #include <QTextEdit> #include <QVBoxLayout> #include <QStandardPaths> #include <QClipboard> #include <QApplication> #include <QAction> #include <cmath> SimpleTextGraphView::SimpleTextGraphView(QWidget *parent, MainWindow *mainWindow) : CutterGraphView(parent), contextMenu(new QMenu(this)), addressableItemContextMenu(this, mainWindow), copyAction(tr("Copy"), this) { copyAction.setShortcut(QKeySequence::StandardKey::Copy); copyAction.setShortcutContext(Qt::WidgetShortcut); connect(&copyAction, &QAction::triggered, this, &SimpleTextGraphView::copyBlockText); contextMenu->addAction(&copyAction); contextMenu->addAction(&actionExportGraph); contextMenu->addMenu(layoutMenu); addressableItemContextMenu.insertAction(addressableItemContextMenu.actions().first(), &copyAction); addressableItemContextMenu.addSeparator(); addressableItemContextMenu.addAction(&actionExportGraph); addressableItemContextMenu.addMenu(layoutMenu); addActions(addressableItemContextMenu.actions()); addAction(&copyAction); enableAddresses(haveAddresses); } SimpleTextGraphView::~SimpleTextGraphView() { for (QShortcut *shortcut : shortcuts) { delete shortcut; } } void SimpleTextGraphView::refreshView() { initFont(); setLayoutConfig(getLayoutConfig()); saveCurrentBlock(); loadCurrentGraph(); if (blocks.find(selectedBlock) == blocks.end()) { selectedBlock = NO_BLOCK_SELECTED; } restoreCurrentBlock(); emit viewRefreshed(); } void SimpleTextGraphView::selectBlockWithId(ut64 blockId) { if (!enableBlockSelection) { return; } auto contentIt = blockContent.find(blockId); if (contentIt != blockContent.end()) { selectedBlock = blockId; if (haveAddresses) { addressableItemContextMenu.setTarget(contentIt->second.address, contentIt->second.text); } viewport()->update(); } else { selectedBlock = NO_BLOCK_SELECTED; } } void SimpleTextGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, bool interactive) { QRectF blockRect(block.x, block.y, block.width, block.height); p.setPen(Qt::black); p.setBrush(Qt::gray); p.setFont(Config()->getFont()); p.drawRect(blockRect); // Render node auto &content = blockContent[block.entry]; p.setPen(QColor(0, 0, 0, 0)); p.setBrush(QColor(0, 0, 0, 100)); p.setPen(QPen(graphNodeColor, 1)); bool blockSelected = interactive && (block.entry == selectedBlock); if (blockSelected) { p.setBrush(disassemblySelectedBackgroundColor); } else { p.setBrush(disassemblyBackgroundColor); } // Draw basic block background p.drawRect(blockRect); // Stop rendering text when it's too small auto transform = p.combinedTransform(); QRect screenChar = transform.mapRect(QRect(0, 0, ACharWidth, charHeight)); if (screenChar.width() < Config()->getGraphMinFontSize()) { return; } p.setPen(palette().color(QPalette::WindowText)); // Render node text QFontMetrics fm = QFontMetrics(p.font()); auto x = block.x + padding / 2; int y = block.y + padding / 2 + fm.ascent(); p.drawText(QPoint(x, y), content.text); } GraphView::EdgeConfiguration SimpleTextGraphView::edgeConfiguration(GraphView::GraphBlock &from, GraphView::GraphBlock *to, bool interactive) { EdgeConfiguration ec; ec.color = jmpColor; ec.start_arrow = false; ec.end_arrow = true; if (interactive && (selectedBlock == from.entry || selectedBlock == to->entry)) { ec.width_scale = 2.0; } return ec; } void SimpleTextGraphView::setBlockSelectionEnabled(bool value) { enableBlockSelection = value; if (!value) { selectedBlock = NO_BLOCK_SELECTED; } } void SimpleTextGraphView::addBlock(GraphLayout::GraphBlock block, const QString &text, RVA address) { auto &content = blockContent[block.entry]; content.text = text; content.address = address; int height = 1; int width = mFontMetrics->width(text); block.width = static_cast<int>(width + padding); block.height = (height * charHeight) + padding; GraphView::addBlock(std::move(block)); } void SimpleTextGraphView::enableAddresses(bool enabled) { haveAddresses = enabled; if (!enabled) { addressableItemContextMenu.clearTarget(); // Clearing addreassable item context menu disables all the actions inside it including // extra ones added by SimpleTextGraphView. Re-enable them because they are in the regular // context menu as well and shouldn't be disabled. for (auto action : contextMenu->actions()) { action->setEnabled(true); } }; } void SimpleTextGraphView::copyBlockText() { auto blockIt = blockContent.find(selectedBlock); if (blockIt != blockContent.end()) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(blockIt->second.text); } } void SimpleTextGraphView::contextMenuEvent(QContextMenuEvent *event) { GraphView::contextMenuEvent(event); if (!event->isAccepted() && event->reason() != QContextMenuEvent::Mouse && enableBlockSelection && selectedBlock != NO_BLOCK_SELECTED) { auto blockIt = blocks.find(selectedBlock); if (blockIt != blocks.end()) { blockContextMenuRequested(blockIt->second, event, {}); } } if (!event->isAccepted()) { contextMenu->exec(event->globalPos()); event->accept(); } } void SimpleTextGraphView::blockContextMenuRequested(GraphView::GraphBlock &block, QContextMenuEvent *event, QPoint /*pos*/) { if (haveAddresses) { const auto &content = blockContent[block.entry]; addressableItemContextMenu.setTarget(content.address, content.text); QPoint pos = event->globalPos(); if (event->reason() != QContextMenuEvent::Mouse) { QPoint blockPosition(block.x + block.width / 2, block.y + block.height / 2); blockPosition = logicalToViewCoordinates(blockPosition); if (viewport()->rect().contains(blockPosition)) { pos = mapToGlobal(blockPosition); } } addressableItemContextMenu.exec(pos); event->accept(); } } void SimpleTextGraphView::blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, QPoint /*pos*/) { if (haveAddresses) { QToolTip::showText(event->globalPos(), RzAddressString(blockContent[block.entry].address)); } } void SimpleTextGraphView::blockClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint /*pos*/) { if ((event->button() == Qt::LeftButton || event->button() == Qt::RightButton) && enableBlockSelection) { selectBlockWithId(block.entry); } } void SimpleTextGraphView::restoreCurrentBlock() { if (enableBlockSelection) { auto blockIt = blocks.find(selectedBlock); if (blockIt != blocks.end()) { showBlock(blockIt->second, true); } } } void SimpleTextGraphView::paintEvent(QPaintEvent *event) { // SimpleTextGraphView is always dirty setCacheDirty(); GraphView::paintEvent(event); }
7,907
C++
.cpp
223
29.161435
100
0.673592
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,594
TypesWidget.cpp
rizinorg_cutter/src/widgets/TypesWidget.cpp
#include "TypesWidget.h" #include "ui_TypesWidget.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include "dialogs/TypesInteractionDialog.h" #include <QMenu> #include <QFileDialog> #include <QShortcut> #include <QIcon> TypesModel::TypesModel(QList<TypeDescription> *types, QObject *parent) : QAbstractListModel(parent), types(types) { } QVariant TypesModel::toolTipValue(const QModelIndex &index) const { TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); if (t.category == "Primitive") { return QVariant(); } return Core()->getTypeAsC(t.type).trimmed(); } int TypesModel::rowCount(const QModelIndex &) const { return types->count(); } int TypesModel::columnCount(const QModelIndex &) const { return Columns::COUNT; } QVariant TypesModel::data(const QModelIndex &index, int role) const { if (index.row() >= types->count()) return QVariant(); const TypeDescription &exp = types->at(index.row()); switch (role) { case Qt::DisplayRole: switch (index.column()) { case TYPE: return exp.type; case SIZE: return exp.size ? exp.size : QVariant(); case FORMAT: return exp.format; case CATEGORY: return exp.category; default: return QVariant(); } case Qt::ToolTipRole: return toolTipValue(index); case TypeDescriptionRole: return QVariant::fromValue(exp); default: return QVariant(); } } QVariant TypesModel::headerData(int section, Qt::Orientation, int role) const { switch (role) { case Qt::DisplayRole: switch (section) { case TYPE: return tr("Type / Name"); case SIZE: return tr("Size"); case FORMAT: return tr("Format"); case CATEGORY: return tr("Category"); default: return QVariant(); } default: return QVariant(); } } bool TypesModel::removeRows(int row, int count, const QModelIndex &parent) { RzCoreLocked core(Core()); rz_type_db_del(core->analysis->typedb, types->at(row).type.toUtf8().constData()); beginRemoveRows(parent, row, row + count - 1); while (count--) { types->removeAt(row); } endRemoveRows(); return true; } TypesSortFilterProxyModel::TypesSortFilterProxyModel(TypesModel *source_model, QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(source_model); } void TypesSortFilterProxyModel::setCategory(QString category) { selectedCategory = category; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) invalidateFilter(); #else invalidateRowsFilter(); #endif } bool TypesSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); TypeDescription exp = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); if (!selectedCategory.isEmpty() && selectedCategory != exp.category) { return false; } return qhelpers::filterStringContains(exp.type, this); } bool TypesSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { TypeDescription left_exp = left.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); TypeDescription right_exp = right.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); switch (left.column()) { case TypesModel::TYPE: return left_exp.type < right_exp.type; case TypesModel::SIZE: return left_exp.size < right_exp.size; case TypesModel::FORMAT: return left_exp.format < right_exp.format; case TypesModel::CATEGORY: return left_exp.category < right_exp.category; default: break; } return left_exp.size < right_exp.size; } TypesWidget::TypesWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::TypesWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); ui->quickFilterView->setLabelText(tr("Category")); // Add status bar which displays the count tree->addStatusBar(ui->verticalLayout); // Set single select mode ui->typesTreeView->setSelectionMode(QAbstractItemView::SingleSelection); // Setup up the model and the proxy model types_model = new TypesModel(&types, this); types_proxy_model = new TypesSortFilterProxyModel(types_model, this); ui->typesTreeView->setModel(types_proxy_model); ui->typesTreeView->sortByColumn(TypesModel::TYPE, Qt::AscendingOrder); setScrollMode(); // Setup custom context menu connect(ui->typesTreeView, &QWidget::customContextMenuRequested, this, &TypesWidget::showTypesContextMenu); ui->typesTreeView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, types_proxy_model, &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, [this] { tree->showItemsNumber(types_proxy_model->rowCount()); }); QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); connect(clearShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::clearFilter); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(Core(), &CutterCore::refreshAll, this, &TypesWidget::refreshTypes); connect(ui->quickFilterView->comboBox(), &QComboBox::currentTextChanged, this, [this]() { types_proxy_model->setCategory(ui->quickFilterView->comboBox()->currentData().toString()); tree->showItemsNumber(types_proxy_model->rowCount()); }); actionViewType = new QAction(tr("View Type"), this); actionEditType = new QAction(tr("Edit Type"), this); connect(actionViewType, &QAction::triggered, [this]() { viewType(true); }); connect(actionEditType, &QAction::triggered, [this]() { viewType(false); }); connect(ui->typesTreeView, &QTreeView::doubleClicked, this, &TypesWidget::typeItemDoubleClicked); } TypesWidget::~TypesWidget() {} void TypesWidget::refreshTypes() { types_model->beginResetModel(); types = Core()->getAllTypes(); types_model->endResetModel(); QStringList categories; for (TypeDescription exp : types) { categories << exp.category; } categories.removeDuplicates(); refreshCategoryCombo(categories); qhelpers::adjustColumns(ui->typesTreeView, 4, 0); } void TypesWidget::refreshCategoryCombo(const QStringList &categories) { QComboBox *combo = ui->quickFilterView->comboBox(); combo->clear(); combo->addItem(tr("(All)")); for (const QString &category : categories) { combo->addItem(category, category); } types_proxy_model->setCategory(QString()); } void TypesWidget::setScrollMode() { qhelpers::setVerticalScrollMode(ui->typesTreeView); } void TypesWidget::showTypesContextMenu(const QPoint &pt) { QModelIndex index = ui->typesTreeView->indexAt(pt); QMenu menu(ui->typesTreeView); menu.addAction(ui->actionLoad_New_Types); if (index.isValid()) { TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); if (t.category != "Primitive") { // Add "Link To Address" option menu.addAction(actionViewType); menu.addAction(actionEditType); } } menu.addAction(ui->actionExport_Types); if (index.isValid()) { TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); if (t.category != "Typedef") { menu.addSeparator(); menu.addAction(ui->actionDelete_Type); } } menu.exec(ui->typesTreeView->mapToGlobal(pt)); } void TypesWidget::on_actionExport_Types_triggered() { char *str = rz_core_types_as_c_all(Core()->core(), true); if (!str) { return; } QString filename = QFileDialog::getSaveFileName(this, tr("Save File"), Config()->getRecentFolder()); if (filename.isEmpty()) { return; } Config()->setRecentFolder(QFileInfo(filename).absolutePath()); QFile file(filename); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::critical(this, tr("Error"), file.errorString()); on_actionExport_Types_triggered(); return; } QTextStream fileOut(&file); fileOut << str; free(str); file.close(); } void TypesWidget::on_actionLoad_New_Types_triggered() { QModelIndex index = ui->typesTreeView->currentIndex(); if (!index.isValid()) { return; } TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); TypesInteractionDialog dialog(this); connect(&dialog, &TypesInteractionDialog::newTypesLoaded, this, &TypesWidget::refreshTypes); dialog.setWindowTitle(tr("Load New Types")); dialog.exec(); } void TypesWidget::viewType(bool readOnly) { QModelIndex index = ui->typesTreeView->currentIndex(); if (!index.isValid()) { return; } TypesInteractionDialog dialog(this, readOnly); TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); if (!readOnly) { dialog.setWindowTitle(tr("Edit Type: ") + t.type); connect(&dialog, &TypesInteractionDialog::newTypesLoaded, this, &TypesWidget::refreshTypes); } else { dialog.setWindowTitle(tr("View Type: ") + t.type + tr(" (Read Only)")); } dialog.fillTextArea(Core()->getTypeAsC(t.type)); dialog.setTypeName(t.type); dialog.exec(); } void TypesWidget::on_actionDelete_Type_triggered() { QModelIndex proxyIndex = ui->typesTreeView->currentIndex(); if (!proxyIndex.isValid()) { return; } QModelIndex index = types_proxy_model->mapToSource(proxyIndex); if (!index.isValid()) { return; } TypeDescription exp = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); QMessageBox::StandardButton reply = QMessageBox::question( this, tr("Cutter"), tr("Are you sure you want to delete \"%1\"?").arg(exp.type)); if (reply == QMessageBox::Yes) { types_model->removeRow(index.row()); } } void TypesWidget::typeItemDoubleClicked(const QModelIndex &index) { if (!index.isValid()) { return; } TypesInteractionDialog dialog(this, true); TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value<TypeDescription>(); if (t.category == "Primitive") { return; } dialog.fillTextArea(Core()->getTypeAsC(t.type)); dialog.setWindowTitle(tr("View Type: ") + t.type + tr(" (Read Only)")); dialog.setTypeName(t.type); dialog.exec(); }
11,141
C++
.cpp
308
30.665584
100
0.689037
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,595
ImportsWidget.cpp
rizinorg_cutter/src/widgets/ImportsWidget.cpp
#include "ImportsWidget.h" #include "ui_ListDockWidget.h" #include "WidgetShortcuts.h" #include "core/MainWindow.h" #include "common/Helpers.h" #include <QPainter> #include <QPen> #include <QShortcut> #include <QTreeWidget> ImportsModel::ImportsModel(QObject *parent) : AddressableItemModel(parent) {} int ImportsModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : imports.count(); } int ImportsModel::columnCount(const QModelIndex &) const { return ImportsModel::ColumnCount; } QVariant ImportsModel::data(const QModelIndex &index, int role) const { const ImportDescription &import = imports.at(index.row()); switch (role) { case Qt::ForegroundRole: if (index.column() < ImportsModel::ColumnCount) { // Red color for unsafe functions if (banned.match(import.name).hasMatch()) return Config()->getColor("gui.item_unsafe"); // Grey color for symbols at offset 0 which can only be filled at runtime if (import.plt == 0) return Config()->getColor("gui.item_invalid"); } break; case Qt::DisplayRole: switch (index.column()) { case ImportsModel::AddressColumn: return RzAddressString(import.plt); case ImportsModel::TypeColumn: return import.type; case ImportsModel::SafetyColumn: return banned.match(import.name).hasMatch() ? tr("Unsafe") : QStringLiteral(""); case ImportsModel::LibraryColumn: return import.libname; case ImportsModel::NameColumn: return import.name; case ImportsModel::CommentColumn: return Core()->getCommentAt(import.plt); default: break; } break; case ImportsModel::ImportDescriptionRole: return QVariant::fromValue(import); case ImportsModel::AddressRole: return import.plt; default: break; } return QVariant(); } QVariant ImportsModel::headerData(int section, Qt::Orientation, int role) const { if (role == Qt::DisplayRole) { switch (section) { case ImportsModel::AddressColumn: return tr("Address"); case ImportsModel::TypeColumn: return tr("Type"); case ImportsModel::SafetyColumn: return tr("Safety"); case ImportsModel::LibraryColumn: return tr("Library"); case ImportsModel::NameColumn: return tr("Name"); case ImportsModel::CommentColumn: return tr("Comment"); default: break; } } return QVariant(); } RVA ImportsModel::address(const QModelIndex &index) const { const ImportDescription &import = imports.at(index.row()); return import.plt; } QString ImportsModel::name(const QModelIndex &index) const { const ImportDescription &import = imports.at(index.row()); return import.name; } QString ImportsModel::libname(const QModelIndex &index) const { const ImportDescription &import = imports.at(index.row()); return import.libname; } void ImportsModel::reload() { beginResetModel(); imports = Core()->getAllImports(); endResetModel(); } ImportsProxyModel::ImportsProxyModel(ImportsModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } bool ImportsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); auto import = index.data(ImportsModel::ImportDescriptionRole).value<ImportDescription>(); return qhelpers::filterStringContains(import.name, this); } bool ImportsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { if (!left.isValid() || !right.isValid()) return false; if (left.parent().isValid() || right.parent().isValid()) return false; auto leftImport = left.data(ImportsModel::ImportDescriptionRole).value<ImportDescription>(); auto rightImport = right.data(ImportsModel::ImportDescriptionRole).value<ImportDescription>(); switch (left.column()) { case ImportsModel::AddressColumn: return leftImport.plt < rightImport.plt; case ImportsModel::TypeColumn: return leftImport.type < rightImport.type; case ImportsModel::SafetyColumn: break; case ImportsModel::LibraryColumn: if (leftImport.libname != rightImport.libname) return leftImport.libname < rightImport.libname; // fallthrough case ImportsModel::NameColumn: return leftImport.name < rightImport.name; case ImportsModel::CommentColumn: return Core()->getCommentAt(leftImport.plt) < Core()->getCommentAt(rightImport.plt); default: break; } return false; } /* * Imports Widget */ ImportsWidget::ImportsWidget(MainWindow *main) : ListDockWidget(main), importsModel(new ImportsModel(this)), importsProxyModel(new ImportsProxyModel(importsModel, this)) { setWindowTitle(tr("Imports")); setObjectName("ImportsWidget"); setModels(importsProxyModel); // Sort by library name by default to create a solid context per each group of imports ui->treeView->sortByColumn(ImportsModel::LibraryColumn, Qt::AscendingOrder); QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["ImportsWidget"], main); connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(Core(), &CutterCore::codeRebased, this, &ImportsWidget::refreshImports); connect(Core(), &CutterCore::refreshAll, this, &ImportsWidget::refreshImports); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(importsModel, ImportsModel::CommentColumn); }); } ImportsWidget::~ImportsWidget() {} void ImportsWidget::refreshImports() { importsModel->reload(); qhelpers::adjustColumns(ui->treeView, 4, 0); }
6,087
C++
.cpp
168
30.404762
98
0.695792
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,596
GraphHorizontalAdapter.cpp
rizinorg_cutter/src/widgets/GraphHorizontalAdapter.cpp
#include "GraphHorizontalAdapter.h" GraphHorizontalAdapter::GraphHorizontalAdapter(std::unique_ptr<GraphLayout> layout) : GraphLayout({}), layout(std::move(layout)) { swapLayoutConfigDirection(); } void GraphHorizontalAdapter::CalculateLayout(GraphLayout::Graph &blocks, unsigned long long entry, int &width, int &height) const { for (auto &block : blocks) { std::swap(block.second.width, block.second.height); } layout->CalculateLayout(blocks, entry, height, width); // intentionally swapping height and width for (auto &block : blocks) { std::swap(block.second.width, block.second.height); std::swap(block.second.x, block.second.y); for (auto &edge : block.second.edges) { for (auto &point : edge.polyline) { std::swap(point.rx(), point.ry()); } switch (edge.arrow) { case GraphEdge::Down: edge.arrow = GraphEdge::Right; break; case GraphEdge::Left: edge.arrow = GraphEdge::Up; break; case GraphEdge::Up: edge.arrow = GraphEdge::Left; break; case GraphEdge::Right: edge.arrow = GraphEdge::Down; break; case GraphEdge::None: edge.arrow = GraphEdge::None; break; } } } } void GraphHorizontalAdapter::setLayoutConfig(const GraphLayout::LayoutConfig &config) { GraphLayout::setLayoutConfig(config); swapLayoutConfigDirection(); layout->setLayoutConfig(config); } void GraphHorizontalAdapter::swapLayoutConfigDirection() { std::swap(layoutConfig.edgeVerticalSpacing, layoutConfig.edgeHorizontalSpacing); std::swap(layoutConfig.blockVerticalSpacing, layoutConfig.blockHorizontalSpacing); }
1,935
C++
.cpp
52
27.576923
98
0.610963
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false