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
14,703
ConnectionDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/ConnectionDialog.cpp
#include "robomongo/gui/dialogs/ConnectionDialog.h" #include <QPushButton> #include <QCloseEvent> #include <QHBoxLayout> #include <QVBoxLayout> #include <QMessageBox> #include <QApplication> #include <QDialogButtonBox> #include <QSettings> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/dialogs/ConnectionAuthTab.h" #include "robomongo/gui/dialogs/ConnectionBasicTab.h" #include "robomongo/gui/dialogs/ConnectionAdvancedTab.h" #include "robomongo/gui/dialogs/SSHTunnelTab.h" #include "robomongo/gui/dialogs/SSLTab.h" #include "robomongo/gui/dialogs/ConnectionDiagnosticDialog.h" namespace Robomongo { /** * @brief Constructs dialog with specified connection */ ConnectionDialog::ConnectionDialog(ConnectionSettings *connection, QWidget *parent /* = nullptr */) : QDialog(parent), _connection(connection) { setWindowTitle("Connection Settings"); setWindowIcon(GuiRegistry::instance().serverIcon()); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?) QPushButton *testButton = new QPushButton("&Test"); testButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation)); VERIFY(connect(testButton, SIGNAL(clicked()), this, SLOT(testConnection()))); QHBoxLayout *bottomLayout = new QHBoxLayout; bottomLayout->addWidget(testButton, 1, Qt::AlignLeft); QDialogButtonBox *buttonBox = new QDialogButtonBox(this); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); bottomLayout->addWidget(buttonBox); QTabWidget *tabWidget = new QTabWidget; _basicTab = new ConnectionBasicTab(_connection, this); _authTab = new ConnectionAuthTab(_connection); _advancedTab = new ConnectionAdvancedTab(_connection); _sshTab = new SshTunnelTab(_connection); _sslTab = new SSLTab(_connection); tabWidget->addTab(_basicTab, "Connection"); tabWidget->addTab(_authTab, "Authentication"); tabWidget->addTab(_sshTab, "SSH"); tabWidget->addTab(_sslTab, "TLS"); tabWidget->addTab(_advancedTab, "Advanced"); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(tabWidget); mainLayout->addLayout(bottomLayout); setLayout(mainLayout); _basicTab->setFocus(); adjustSize(); #ifdef _WIN32 setMinimumWidth(500); #elif __APPLE__ setMinimumWidth(660); #elif __linux__ setMinimumWidth(900); #endif restoreWindowSettings(); } /** * @brief Accept() is called when user agree with entered data. */ void ConnectionDialog::accept() { saveWindowSettings(); if (validateAndApply()) QDialog::accept(); } void ConnectionDialog::reject() { saveWindowSettings(); QDialog::reject(); } void ConnectionDialog::closeEvent(QCloseEvent *event) { saveWindowSettings(); QWidget::closeEvent(event); } void ConnectionDialog::setAuthTab( QString const& db, QString const& username, QString const& pwd, AuthMechanism authMech ) { _authTab->setAuthTab(db, username, pwd, authMech); } void ConnectionDialog::setDefaultDb(QString const& defaultDb) { _advancedTab->setDefaultDb(defaultDb); } void ConnectionDialog::toggleSshSupport(bool isReplicaSet) { if (!_sshTab) return; _sshTab->setDisabled(isReplicaSet); _sshTab->toggleSshCheckboxToolTip(isReplicaSet); } void ConnectionDialog::clearConnAuthTab() { _authTab->clearTab(); } void ConnectionDialog::clearSslTab() { _sslTab->clearTab(); } void ConnectionDialog::setSslTab( int index, bool allowInvalidHostnames, std::string_view caFile, std::string_view certPemFile, std::string_view certPemFilePwd ) { _sslTab->setSslOptions(index, allowInvalidHostnames, caFile, certPemFile, certPemFilePwd); } void ConnectionDialog::restoreWindowSettings() { QSettings settings("3T", "Robomongo"); resize(settings.value("ConnectionDialog/size").toSize()); } void ConnectionDialog::saveWindowSettings() const { QSettings settings("3T", "Robomongo"); settings.setValue("ConnectionDialog/size", size()); } bool ConnectionDialog::validateAndApply() { _authTab->accept(); _advancedTab->accept(); if (!_basicTab->accept() || !_sshTab->accept() || !_sslTab->accept()) return false; return true; } /** * @brief Test current connection */ void ConnectionDialog::testConnection() { if (!validateAndApply()) return; ConnectionDiagnosticDialog diag(_connection, this); if (!diag.continueExec()) return; diag.exec(); } }
5,354
C++
.cpp
151
28.463576
103
0.66317
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
14,704
CopyCollectionDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/CopyCollectionDialog.cpp
#include "robomongo/gui/dialogs/CopyCollectionDialog.h" #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QLineEdit> #include <QComboBox> #include <QDialogButtonBox> #include <QLabel> #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/GuiRegistry.h" namespace Robomongo { const QSize CopyCollection::minimumSize = QSize(300, 150); CopyCollection::CopyCollection(const QString &serverName, const QString &database, const QString &collection, QWidget *parent) : QDialog(parent), _currentServerName(serverName), _currentDatabase(database) { QSet<QString> uniqueConnectionsNames; for (auto const& server : AppRegistry::instance().app()->getServers()) { if (server->isConnected()) { _servers.push_back(server.get()); uniqueConnectionsNames.insert(QtUtils::toQString(server->connectionRecord()->connectionName())); } } setWindowTitle("Copy Collection"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?) setMinimumSize(minimumSize); Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), _currentServerName); QFrame *hline = new QFrame(); hline->setFrameShape(QFrame::HLine); hline->setFrameShadow(QFrame::Sunken); _buttonBox = new QDialogButtonBox(this); _buttonBox->setOrientation(Qt::Horizontal); _buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); _buttonBox->button(QDialogButtonBox::Save)->setText("Copy"); VERIFY(connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->addStretch(1); hlayout->addWidget(_buttonBox); QHBoxLayout *vlayout = new QHBoxLayout(); vlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); vlayout->addWidget(new Indicator(GuiRegistry::instance().databaseIcon(), _currentDatabase), 0, Qt::AlignLeft); vlayout->addWidget(new Indicator(GuiRegistry::instance().collectionIcon(), collection), 0, Qt::AlignLeft); QVBoxLayout *serverlayout = new QVBoxLayout(); serverlayout->setContentsMargins(0, 3, 0, 0); _serverComboBox = new QComboBox(); QLabel *serverLabel = new QLabel("Select server:"); QLabel *description = new QLabel( QString("Copy <b>%1</b> collection to database on this or another server. " "You need to be already connected to destination server, in order to see this server in the list below. " "This operation will <i>not</i> overwrite existing documents with the same _id.") .arg(collection)); description->setWordWrap(true); serverlayout->addWidget(description); serverlayout->addSpacing(14); serverlayout->addWidget(serverLabel); serverlayout->addWidget(_serverComboBox); QVBoxLayout *databaselayout = new QVBoxLayout(); databaselayout->setContentsMargins(0, 8, 0, 7); _databaseComboBox = new QComboBox(); QLabel *databaseLabel = new QLabel("Select database:"); databaselayout->addWidget(databaseLabel); databaselayout->addWidget(_databaseComboBox); VERIFY(connect(_serverComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateDatabaseComboBox(int)))); _serverComboBox->addItems(uniqueConnectionsNames.toList()); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(vlayout); layout->addWidget(hline); layout->addLayout(serverlayout); layout->addLayout(databaselayout); layout->addLayout(hlayout); setLayout(layout); } void CopyCollection::updateDatabaseComboBox(int index) { _databaseComboBox->clear(); const QString &curentServerName = _serverComboBox->currentText(); MongoServer *server = nullptr; for (auto const& ser : _servers) { if (curentServerName == QtUtils::toQString(ser->connectionRecord()->connectionName())) { server = ser; break; } } if (!server) return; _databaseComboBox->addItems(server->getDatabasesNames()); if (_currentServerName == QtUtils::toQString(server->connectionRecord()->getFullAddress())) { _databaseComboBox->removeItem(_databaseComboBox->findText(_currentDatabase)); } } MongoDatabase *CopyCollection::selectedDatabase() { MongoDatabase *result = NULL; const QString &serverName = _serverComboBox->currentText(); const QString &dataBaseName = _databaseComboBox->currentText(); if (!serverName.isEmpty() && !dataBaseName.isEmpty()) { MongoServer *server = _servers[_serverComboBox->currentIndex()]; result = server->findDatabaseByName(QtUtils::toStdString(dataBaseName)); } return result; } void CopyCollection::accept() { if (!selectedDatabase()) return; QDialog::accept(); } }
5,553
C++
.cpp
115
39.313043
121
0.66525
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,706
ExportDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/ExportDialog.cpp
#include "robomongo/gui/dialogs/ExportDialog.h" #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QLineEdit> #include <QTextEdit> #include <QLabel> #include <QDialogButtonBox> #include <QTreeWidget> #include <QComboBox> #include <QGroupBox> #include <QApplication> #include <QProcess> #include <QDir> #include <QFileDialog> #include <QDateTime> #include <QMessageBox> #include <QPlainTextEdit> #include <QFileInfo> #include <QSizePolicy> #include <QProgressDialog> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/domain/MongoCollection.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/gui/widgets/explorer/ExplorerServerTreeItem.h" #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/widgets/explorer/ExplorerWidget.h" #include "robomongo/gui/widgets/explorer/ExplorerTreeWidget.h" #include "robomongo/gui/widgets/explorer/ExplorerServerTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionIndexesDir.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseCategoryTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerReplicaSetTreeItem.h" #include "robomongo/gui/utils/GuiConstants.h" #include "robomongo/gui/GuiRegistry.h" namespace Robomongo { namespace { const QString defaultDir = "D:\\exports\\"; // Default location auto const AUTO_MODE_SIZE = QSize(500, 450); auto const MANUAL_MODE_SIZE = QSize(500, 400); auto const SHOW_DETAILS = "<a href='error' style='color: #777777;'>Show details</a>"; auto const HIDE_DETAILS = "<a href='error' style='color: #777777;'>Hide details</a>"; // This structure represents the arguments as in "mongoexport.exe --help" // See http://docs.mongodb.org/manual/reference/program/mongoexport/ for more information struct MongoExportArgs { static QString db(const QString& dbName) { return ("--db" + dbName); } static QString collection(const QString& collection) { return ("--collection" + collection); } // i.e. absFilePath: "/exports/coll1.json" static QString out(const QString& absFilePath) { return ("--out " + absFilePath); } }; } ExportDialog::ExportDialog(QString const& dbName, QString const& collName, QWidget *parent) : QDialog(parent), _mode(AUTO), _mongoExportArgs(), _activeProcess(nullptr) { setWindowTitle("Export Collection"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?) setMinimumSize(AUTO_MODE_SIZE); //setFixedHeight(AUTO_MODE_SIZE.height()); _activeProcess = new QProcess(this); //_activeProcess->setProcessChannelMode(QProcess::MergedChannels); VERIFY(connect(_activeProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(on_exportFinished(int, QProcess::ExitStatus)))); VERIFY(connect(_activeProcess, SIGNAL(errorOccurred(QProcess::ProcessError)), this, SLOT(on_processErrorOccurred(QProcess::ProcessError)))); // todo: move to a global location // Enable copyable text for QMessageBox qApp->setStyleSheet("QMessageBox { messagebox-text-interaction-flags: 5; }"); const QString serverName = "localhost:20017"; // todo: remove Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), serverName); // Horizontal line QFrame *horline = new QFrame(); horline->setFrameShape(QFrame::HLine); horline->setFrameShadow(QFrame::Sunken); // Widgets related to Input auto dbNameLabel = new QLabel("Database Name:"); auto dbNameLineEdit = new QLineEdit; auto dbNameLay = new QHBoxLayout; dbNameLay->addWidget(dbNameLabel); dbNameLay->addWidget(dbNameLineEdit); auto collNameLabel = new QLabel("Collection Name:"); auto collNameLineEdit = new QLineEdit; auto collNameLay = new QHBoxLayout; collNameLay->addWidget(collNameLabel); collNameLay->addWidget(collNameLineEdit); auto selectedCollLay = new QGridLayout; selectedCollLay->setAlignment(Qt::AlignTop); selectedCollLay->setColumnStretch(2, 1); auto serverIcon = new QLabel("<html><img src=':/robomongo/icons/server_16x16.png'></html>"); auto dbIcon = new QLabel("<html><img src=':/robomongo/icons/database_16x16.png'></html>"); auto collIcon = new QLabel("<html><img src=':/robomongo/icons/collection_16x16.png'></html>"); selectedCollLay->addWidget(serverIcon, 1, 0); selectedCollLay->addWidget(new QLabel("Server: "), 1, 1); selectedCollLay->addWidget(new QLabel("local_(2)"), 1, 2); selectedCollLay->addWidget(dbIcon, 2, 0); selectedCollLay->addWidget(new QLabel("Database: "), 2, 1); selectedCollLay->addWidget(new QLabel(dbName), 2, 2); selectedCollLay->addWidget(collIcon, 3, 0); selectedCollLay->addWidget(new QLabel("Collection: "), 3, 1); selectedCollLay->addWidget(new QLabel(collName), 3, 2); // Widgets related to Output _formatComboBox = new QComboBox; _formatComboBox->addItem("JSON"); _formatComboBox->addItem("CSV"); VERIFY(connect(_formatComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_formatComboBox_change(int)))); _fieldsLabel = new QLabel("Fields:"); _fields = new QLineEdit; // todo: use textedit // Initially hidden _fieldsLabel->setHidden(true); _fields->setHidden(true); _query = new QLineEdit("{}"); // todo: JSON frame can be used _outputFileName = new QLineEdit; _outputDir = new QLineEdit; _browseButton = new QPushButton("..."); _browseButton->setMaximumWidth(50); VERIFY(connect(_browseButton, SIGNAL(clicked()), this, SLOT(on_browseButton_clicked()))); // Export summary widgets _exportOutput = new QTextEdit; QFontMetrics font(_exportOutput->font()); _exportOutput->setFixedHeight((4+1.5) * (font.lineSpacing())); // 4-line text edit _exportOutput->setReadOnly(true); _mongoExportOutput = new QTextEdit; _mongoExportOutput->setFixedHeight(4 * (font.lineSpacing() + 8)); // 4-line text edit _mongoExportOutput->setReadOnly(true); _mongoExportOutput->setHidden(true); // Attempt to fix issue for Windows High DPI button height is slightly taller than other widgets #ifdef Q_OS_WIN _browseButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); #endif auto outputsInnerLay = new QGridLayout; outputsInnerLay->addWidget(new QLabel("Format:"), 0, 0); outputsInnerLay->addWidget(_formatComboBox, 0, 1, 1, 2); outputsInnerLay->addWidget(_fieldsLabel, 1, 0, Qt::AlignTop); outputsInnerLay->addWidget(_fields, 1, 1, 1, 2); outputsInnerLay->addWidget(new QLabel("Query:"), 2, 0); outputsInnerLay->addWidget(_query, 2, 1, 1, 2); outputsInnerLay->addWidget(new QLabel("File Name:"), 3, 0); outputsInnerLay->addWidget(_outputFileName, 3, 1, 1, 2); outputsInnerLay->addWidget(new QLabel("Directory:"), 4, 0); outputsInnerLay->addWidget(_outputDir, 4, 1); outputsInnerLay->addWidget(_browseButton, 4, 2); //outputsInnerLay->addWidget(new QLabel("Result:"), 5, 0, Qt::AlignTop); //outputsInnerLay->addWidget(_exportOutput, 6, 0, 1, 3, Qt::AlignTop); auto manualLayout = new QGridLayout; auto cmdLabel = new QLabel("Command:"); cmdLabel->setFixedHeight(cmdLabel->sizeHint().height()); _manualExportCmd = new QTextEdit; QFontMetrics font1(_manualExportCmd->font()); _manualExportCmd->setFixedHeight(2 * (font1.lineSpacing()+8)); // 2-line text edit manualLayout->addWidget(cmdLabel, 0, 0, Qt::AlignTop); manualLayout->addWidget(_manualExportCmd, 1, 0, Qt::AlignTop); // Button box and Manual Mode button _modeButton = new QPushButton("Manual Mode"); VERIFY(connect(_modeButton, SIGNAL(clicked()), this, SLOT(on_modeButton_clicked()))); _buttonBox = new QDialogButtonBox(this); _buttonBox->setOrientation(Qt::Horizontal); _buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); _buttonBox->button(QDialogButtonBox::Save)->setText("E&xport"); _buttonBox->button(QDialogButtonBox::Save)->setMaximumWidth(70); _buttonBox->button(QDialogButtonBox::Cancel)->setMaximumWidth(70); VERIFY(connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); // Sub layouts auto serverIndicatorlayout = new QHBoxLayout(); if (!serverName.isEmpty()) { serverIndicatorlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); } // Input layout _inputsGroupBox = new QGroupBox("Selected Collection"); _inputsGroupBox->setLayout(selectedCollLay); _inputsGroupBox->setStyleSheet("QGroupBox::title { left: 0px }"); _inputsGroupBox->setFixedHeight(_inputsGroupBox->sizeHint().height()); // Outputs _autoOutputsGroup = new QGroupBox("Output Properties"); _autoOutputsGroup->setLayout(outputsInnerLay); _autoOutputsGroup->setStyleSheet("QGroupBox::title { left: 0px }"); _autoOutputsGroup->setFixedHeight(_autoOutputsGroup->sizeHint().height()); // Manual Groupbox _manualGroupBox = new QGroupBox("Manual Export"); _manualGroupBox->setLayout(manualLayout); _manualGroupBox->setStyleSheet("QGroupBox::title { left: 0px }"); _manualGroupBox->setHidden(true); // Export Summary auto exportSummaryGroup = new QGroupBox("Export Summary"); exportSummaryGroup->setStyleSheet("QGroupBox::title { left: 0px }"); _viewOutputLink = new QLabel(SHOW_DETAILS); VERIFY(connect(_viewOutputLink, SIGNAL(linkActivated(QString)), this, SLOT(on_viewOutputLink(QString)))); _viewOutputLink->setFixedHeight(_viewOutputLink->sizeHint().height()); auto tempLayout = new QVBoxLayout(); //tempLayout->setSizeConstraint(QLayout::SetFixedSize); tempLayout->addWidget(_exportOutput, Qt::AlignTop); tempLayout->addWidget(_viewOutputLink, Qt::AlignLeft | Qt::AlignTop); //tempLayout->addWidget(_mongoExportOutput); exportSummaryGroup->setLayout(tempLayout); exportSummaryGroup->setFixedHeight(exportSummaryGroup->sizeHint().height()); // Buttonbox layout auto hButtonBoxlayout = new QHBoxLayout(); hButtonBoxlayout->addStretch(1); hButtonBoxlayout->addWidget(_buttonBox); hButtonBoxlayout->addWidget(_modeButton); // Main Layout auto layout = new QVBoxLayout(); layout->addWidget(_inputsGroupBox, Qt::AlignTop); //layout->addWidget(horline, Qt::AlignTop); layout->addWidget(_autoOutputsGroup, Qt::AlignTop); layout->addWidget(_manualGroupBox); layout->addWidget(exportSummaryGroup, Qt::AlignTop); layout->addLayout(hButtonBoxlayout); setLayout(layout); // todo: move to a function // Help user filling inputs automatically auto date = QDateTime::currentDateTime().toString("dd.MM.yyyy"); auto time = QDateTime::currentDateTime().toString("hh.mm.ss"); auto timeStamp = date + "_" + time; auto format = _formatComboBox->currentIndex() == 0 ? "json" : "csv"; _outputFileName->setText(dbName + "." + collName + "_" + timeStamp + "." + format); _outputDir->setText(defaultDir); _manualExportCmd->setText("mongoexport --db " + dbName + " --collection " + collName + " --out " + _outputDir->text() + _outputFileName->text()); // todo: setExportArgs() // First set db and coll _mongoExportArgs = " --db " + dbName + " --collection " + collName; _outputFileName->setFocus(); } void ExportDialog::setOkButtonText(const QString &text) { _buttonBox->button(QDialogButtonBox::Save)->setText(text); } // todo: remove void ExportDialog::setInputLabelText(const QString &text) { //_inputLabel->setText(text); } void ExportDialog::accept() { QString mongoExport = "D:\\mongo_export\\bin\\mongoexport.exe"; bool disable = false; enableDisableWidgets(disable); if (AUTO == _mode) { _exportOutput->clear(); _exportOutput->setText("Exporting..."); // If CSV append output format and fields if (_formatComboBox->currentIndex() == 1) { if (_fields->text().isEmpty()) { QMessageBox::critical(this, "Error", "\"Fields\" option is required in CSV mode."); return; } _mongoExportArgs.append(" --type=csv"); _mongoExportArgs.append(" --fields " + _fields->text().replace(" ", "")); } if (!_query->text().isEmpty() && _query->text() != "{}") { _mongoExportArgs.append(" --query " + _query->text()); } // Append file path and name auto absFilePath = _outputDir->text() + _outputFileName->text(); _mongoExportArgs.append(" --out " + absFilePath); // Start mongoexport non-blocking _activeProcess->start(mongoExport + _mongoExportArgs); } else if (MANUAL == _mode) { _exportOutput->clear(); _exportOutput->setText("Exporting..."); // todo: check if _activeProcess->state() is QProcess::NotRunning // Start mongoexport non-blocking _activeProcess->start("D:\\mongo_export\\bin\\" + _manualExportCmd->toPlainText()); } } void ExportDialog::ui_itemExpanded(QTreeWidgetItem *item) { auto categoryItem = dynamic_cast<ExplorerDatabaseCategoryTreeItem *>(item); if (categoryItem) { categoryItem->expand(); return; } ExplorerServerTreeItem *serverItem = dynamic_cast<ExplorerServerTreeItem *>(item); if (serverItem) { serverItem->expand(); return; } auto dirItem = dynamic_cast<ExplorerCollectionIndexesDir *>(item); if (dirItem) { dirItem->expand(); } } void ExportDialog::ui_itemDoubleClicked(QTreeWidgetItem *item, int column) { // todo } void ExportDialog::on_browseButton_clicked() { // Select output directory QString origDir = QFileDialog::getExistingDirectory(this, tr("Select Directory"), defaultDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); auto dir = QDir::toNativeSeparators(origDir); QApplication::activeModalWidget()->raise(); QApplication::activeModalWidget()->activateWindow(); if (dir.isNull()) return; _outputDir->setText(dir + "\\"); } void ExportDialog::on_formatComboBox_change(int index) { bool const isCsv = static_cast<bool>(index); _fieldsLabel->setVisible(isCsv); _fields->setVisible(isCsv); // todo: divide ui_itemClicked() //ui_itemClicked(_treeWidget->currentItem()); } void ExportDialog::on_modeButton_clicked() { _exportOutput->clear(); _mode = (AUTO == _mode ? MANUAL : AUTO); _modeButton->setText(AUTO == _mode ? "Manual Mode" : "Auto Mode"); _autoOutputsGroup->setVisible(AUTO == _mode); _manualGroupBox->setVisible(MANUAL == _mode); setMinimumSize(AUTO == _mode ? AUTO_MODE_SIZE : MANUAL_MODE_SIZE); _inputsGroupBox->setTitle(AUTO == _mode ? "Selected Collection" : "Selected Server"); adjustSize(); } void ExportDialog::on_exportFinished(int exitCode, QProcess::ExitStatus exitStatus) { bool enable = true; enableDisableWidgets(enable); // Extract absolute file path QString absFilePath; if (AUTO == _mode) { absFilePath = _outputDir->text() + _outputFileName->text(); } else if (MANUAL == _mode) { // extract absolute file path string QStringList strlist1 = _manualExportCmd->toPlainText().split("--out"); if (strlist1.size() > 1) { QString str1 = strlist1[1]; QStringList strlist2 = str1.split("--"); if (strlist2.size() > 1) { absFilePath = strlist2[0]; } else { absFilePath = str1; } } } absFilePath.replace(" ", ""); // todo: handle paths with white spaces // todo: also check process exit code // Check exported file exists and mongoexport output does not contain error QFileInfo const file(absFilePath); _mongoExportOutputStr = _activeProcess->readAllStandardError(); // Extract mongoexport command output if (file.exists() && file.isFile() && _mongoExportOutputStr.contains("exported")) { QStringList splitA = _mongoExportOutputStr.split("exported"); QStringList splitB = splitA[1].split("records"); _exportResult = "Export Successful: \n" "Exported file: " + absFilePath + "\n" "Number of records exported:" + splitB[0]; _exportOutput->setText(_exportResult); } else { _exportOutput->setText("Export Failed.\n"); _exportOutput->append("Output:\n" + _mongoExportOutputStr); } _exportOutput->moveCursor(QTextCursor::Start); } void ExportDialog::on_processErrorOccurred(QProcess::ProcessError error) { bool enable = true; enableDisableWidgets(enable); if (QProcess::FailedToStart == error) { _exportOutput->setText("Error: \"mongoexport\" process failed to start. Either the " "invoked program is missing, or you may have insufficient permissions to invoke the program."); } else if (QProcess::Crashed == error) { _exportOutput->setText("Error: \"mongoexport\" process crashed some time after starting" " successfully.."); } else { _exportOutput->setText("Error: \"mongoexport\" process failed. Error code: " + QString::number(error)); } _exportOutput->moveCursor(QTextCursor::Start); } void ExportDialog::on_viewOutputLink(QString) { QMessageBox::information(this, "Details", _mongoExportOutputStr); } Indicator *ExportDialog::createDatabaseIndicator(const QString &database) { return new Indicator(GuiRegistry::instance().databaseIcon(), database); } Indicator *ExportDialog::createCollectionIndicator(const QString &collection) { return new Indicator(GuiRegistry::instance().collectionIcon(), collection); } void ExportDialog::enableDisableWidgets(bool enable) const { // Auto mode widgets //_treeWidget->setEnabled(enable); _formatComboBox->setEnabled(enable); _fieldsLabel->setEnabled(enable); _fields->setEnabled(enable); _query->setEnabled(enable); _outputFileName->setEnabled(enable); _outputDir->setEnabled(enable); _browseButton->setEnabled(enable); _buttonBox->button(QDialogButtonBox::Save)->setEnabled(enable); _modeButton->setEnabled(enable); // Manual mode widgets //_treeWidget->setEnabled(enable); _manualExportCmd->setEnabled(enable); _buttonBox->button(QDialogButtonBox::Save)->setEnabled(enable); _modeButton->setEnabled(enable); } }
20,772
C++
.cpp
420
40.414286
118
0.636512
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,707
FunctionTextEditor.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/FunctionTextEditor.cpp
#include "robomongo/gui/dialogs/FunctionTextEditor.h" #include <QApplication> #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include <QMessageBox> #include <QLabel> #include <QDialogButtonBox> #include <Qsci/qscilexerjavascript.h> #include <Qsci/qsciscintilla.h> #include "robomongo/gui/editors/JSLexer.h" #include "robomongo/gui/editors/FindFrame.h" #include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { FunctionTextEditor::FunctionTextEditor(const QString &server, const QString &database, const MongoFunction &function, QWidget *parent) : QDialog(parent), _function(function) { setMinimumWidth(700); setMinimumHeight(550); Indicator *databaseIndicator = new Indicator(GuiRegistry::instance().databaseIcon(), database); Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), server); _nameEdit = new QLineEdit(QtUtils::toQString(function.name())); _queryText = new FindFrame(this); _configureQueryText(); _queryText->sciScintilla()->setText(QtUtils::toQString(_function.code())); QFrame *hline = new QFrame(this); hline->setFrameShape(QFrame::HLine); hline->setFrameShadow(QFrame::Sunken); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(2, 0, 5, 1); hlayout->setSpacing(0); hlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); hlayout->addWidget(databaseIndicator, 0, Qt::AlignLeft); hlayout->addStretch(1); QDialogButtonBox *buttonBox = new QDialogButtonBox(this); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); QHBoxLayout *bottomlayout = new QHBoxLayout(); bottomlayout->addStretch(1); bottomlayout->addWidget(buttonBox); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(hlayout); layout->addWidget(hline); layout->addWidget(new QLabel("Name:")); layout->addWidget(_nameEdit); layout->addWidget(new QLabel("Code:")); layout->addWidget(_queryText); layout->addLayout(bottomlayout); setLayout(layout); _nameEdit->setFocus(); } void FunctionTextEditor::setCursorPosition(int line, int column) { _queryText->sciScintilla()->setCursorPosition(line, column); } void FunctionTextEditor::setCode(const QString &code) { _queryText->sciScintilla()->setText(code); } void FunctionTextEditor::accept() { if (_nameEdit->text().isEmpty() && _queryText->sciScintilla()->text().isEmpty()) return; _function.setName(QtUtils::toStdString(_nameEdit->text())); _function.setCode(QtUtils::toStdString(_queryText->sciScintilla()->text())); BaseClass::accept(); } /* ** Configure QsciScintilla query widget */ void FunctionTextEditor::_configureQueryText() { const QFont &textFont = GuiRegistry::instance().font(); QsciLexerJavaScript *javaScriptLexer = new JSLexer(this); javaScriptLexer->setFont(textFont); _queryText->sciScintilla()->setAppropriateBraceMatching(); _queryText->sciScintilla()->setFont(textFont); _queryText->sciScintilla()->setPaper(QColor(255, 0, 0, 127)); _queryText->sciScintilla()->setLexer(javaScriptLexer); _queryText->sciScintilla()->setWrapMode((QsciScintilla::WrapMode)QsciScintilla::SC_WRAP_WORD); _queryText->sciScintilla()->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); _queryText->sciScintilla()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); _queryText->sciScintilla()->setStyleSheet("QFrame { background-color: rgb(73, 76, 78); border: 1px solid #c7c5c4; border-radius: 4px; margin: 0px; padding: 0px;}"); } }
4,289
C++
.cpp
93
38.817204
172
0.687096
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,708
CreateUserDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/CreateUserDialog.cpp
#include "robomongo/gui/dialogs/CreateUserDialog.h" #include <QHBoxLayout> #include <QPushButton> #include <QCheckBox> #include <QDialogButtonBox> #include <QLabel> #include <QLineEdit> #include <QMessageBox> #include <QComboBox> #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/utils/ComboBoxUtils.h" #include "robomongo/core/domain/MongoUtils.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" namespace Robomongo { const char * rolesText[CreateUserDialog::RolesCount] = { "read", "readWrite", "dbAdmin", "userAdmin", "clusterAdmin", "readAnyDatabase", "readWriteAnyDatabase", "userAdminAnyDatabase", "dbAdminAnyDatabase" }; const QSize CreateUserDialog::minimumSize = QSize(400, 200); bool containsWord(const std::string& sentence, const std::string& word) { size_t pos = 0; while ((pos = sentence.substr(pos).find(word)) != std::string::npos) { if (pos + word.size() < sentence.size()) { char c = sentence[pos + word.size()]; bool isLastAlpha = isalpha(c); bool isFirstAlpha = false; if (pos) { isFirstAlpha = isalpha(sentence[pos - 1]); } if (!isFirstAlpha && !isLastAlpha) return true; } pos++; } return false; } CreateUserDialog::CreateUserDialog(const QStringList &databases, const QString &serverName, const QString &database, const MongoUser &user, QWidget *parent) : QDialog(parent), _user(user) { setWindowTitle("Add User"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?) setMinimumSize(minimumSize); Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), serverName); Indicator *databaseIndicator = new Indicator(GuiRegistry::instance().databaseIcon(), database); QFrame *hline = new QFrame(); hline->setFrameShape(QFrame::HLine); hline->setFrameShadow(QFrame::Sunken); _userNameLabel = new QLabel("Name:"); _userNameEdit = new QLineEdit(); _userNameEdit->setText(QtUtils::toQString(user.name())); _userPassLabel = new QLabel("Password:"); _userPassEdit = new QLineEdit(); _userPassEdit->setEchoMode(QLineEdit::Password); _userSourceLabel = new QLabel("UserSource:"); _userSourceComboBox = new QComboBox(); _userSourceComboBox->addItems(QStringList() << databases); //setText(QtUtils::toQString(user.userSource())); _userSourceComboBox->setCurrentIndex(databases.indexOf(database)); utils::setCurrentText(_userSourceComboBox, QtUtils::toQString(user.userSource())); QGridLayout *gridRoles = new QGridLayout(); MongoUser::RolesVector userRoles = user.roles(); for (unsigned i = 0; i<RolesCount; ++i) { int row = i%3; int col = i/3; _rolesArray[i] = new QCheckBox(rolesText[i], this); MongoUser::RolesVector::const_iterator it = std::find(userRoles.begin(), userRoles.end(), rolesText[i]); _rolesArray[i]->setChecked(it!= userRoles.end()); gridRoles->addWidget(_rolesArray[i], row, col); } QDialogButtonBox *buttonBox = new QDialogButtonBox(this); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->addStretch(1); hlayout->addWidget(buttonBox); QHBoxLayout *vlayout = new QHBoxLayout(); vlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); vlayout->addWidget(databaseIndicator, 0, Qt::AlignLeft); vlayout->addStretch(1); QGridLayout *namelayout = new QGridLayout(); namelayout->setContentsMargins(0, 7, 0, 7); namelayout->addWidget(_userNameLabel, 0, 0); namelayout->addWidget(_userNameEdit, 0, 1); namelayout->addWidget(_userPassLabel, 1, 0); namelayout->addWidget(_userPassEdit, 1, 1); namelayout->addWidget(_userSourceLabel, 2, 0); namelayout->addWidget(_userSourceComboBox, 2, 1); namelayout->addLayout(gridRoles, 3, 1); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(vlayout); layout->addWidget(hline); layout->addLayout(namelayout); layout->addLayout(hlayout); setLayout(layout); _userNameEdit->setFocus(); } CreateUserDialog::CreateUserDialog(const QString &serverName, const QString &database, const MongoUser &user, QWidget *parent) : QDialog(parent), _user(user) { setWindowTitle("Add User"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?) setMinimumSize(minimumSize); Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), serverName); Indicator *databaseIndicator = new Indicator(GuiRegistry::instance().databaseIcon(), database); QFrame *hline = new QFrame(); hline->setFrameShape(QFrame::HLine); hline->setFrameShadow(QFrame::Sunken); _userNameLabel = new QLabel("Name:"); _userNameEdit = new QLineEdit(); _userNameEdit->setText(QtUtils::toQString(user.name())); _userPassLabel= new QLabel("Password:"); _userPassEdit = new QLineEdit(); _userPassEdit->setEchoMode(QLineEdit::Password); _readOnlyCheckBox = new QCheckBox("Read Only"); _readOnlyCheckBox->setChecked(user.readOnly()); QDialogButtonBox *buttonBox = new QDialogButtonBox(this); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->addStretch(1); hlayout->addWidget(buttonBox); QHBoxLayout *vlayout = new QHBoxLayout(); vlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); vlayout->addWidget(databaseIndicator, 0, Qt::AlignLeft); vlayout->addStretch(1); QGridLayout *namelayout = new QGridLayout(); namelayout->setContentsMargins(0, 7, 0, 7); namelayout->addWidget(_userNameLabel, 0, 0); namelayout->addWidget(_userNameEdit, 0, 1); namelayout->addWidget(_userPassLabel, 1, 0); namelayout->addWidget(_userPassEdit, 1, 1); namelayout->addWidget(_readOnlyCheckBox, 2, 1); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(vlayout); layout->addWidget(hline); layout->addLayout(namelayout); layout->addLayout(hlayout); setLayout(layout); _userNameEdit->setFocus(); } void CreateUserDialog::setUserPasswordLabelText(const QString &text) { _userPassLabel->setText(text); } void CreateUserDialog::accept() { std::string username = QtUtils::toStdString(_userNameEdit->text()); std::string pass = QtUtils::toStdString(_userPassEdit->text()); if (_user.version() < MongoUser::minimumSupportedVersion) { if (username.empty() || pass.empty()) return; _user.setName(username); _user.setPassword(pass); _user.setReadOnly(_readOnlyCheckBox->isChecked()); } else { std::string userSource = QtUtils::toStdString(_userSourceComboBox->currentText()); if (username.empty()) return; if (userSource.empty() && pass.empty()) return; _user.setName(username); _user.setPassword(pass); _user.setUserSource(userSource); MongoUser::RolesVector roles; for (unsigned i = 0; i < RolesCount; ++i) { if (_rolesArray[i]->isChecked()) { roles.push_back(rolesText[i]); } } _user.setRoles(roles); } QDialog::accept(); } }
8,701
C++
.cpp
193
35.455959
120
0.629354
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,709
ConnectionDiagnosticDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/ConnectionDiagnosticDialog.cpp
#include "robomongo/gui/dialogs/ConnectionDiagnosticDialog.h" #include <QGridLayout> #include <QApplication> #include <QLabel> #include <QPushButton> #include <QMovie> #include <QMessageBox> #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/CredentialSettings.h" #include "robomongo/core/settings/SshSettings.h" #include "robomongo/core/settings/SslSettings.h" #include "robomongo/core/settings/ReplicaSetSettings.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/EventBus.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/mongodb/SshTunnelWorker.h" namespace Robomongo { ConnectionDiagnosticDialog::ConnectionDiagnosticDialog(ConnectionSettings *connection, QWidget *parent) : QDialog(parent), _connSettings(connection->clone()), _server(NULL), _serverHandle(0), _continueExec(true) { AppRegistry::instance().bus()->subscribe(this, ConnectionEstablishedEvent::Type); AppRegistry::instance().bus()->subscribe(this, ConnectionFailedEvent::Type); setWindowTitle("Diagnostic"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?) _yesIcon = GuiRegistry::instance().yesMarkIcon(); _noIcon = GuiRegistry::instance().noMarkIcon(); _questionIcon = GuiRegistry::instance().questionMarkIcon(); _yesPixmap = _yesIcon.pixmap(20, 20); _noPixmap = _noIcon.pixmap(20, 20); _questionPixmap = _questionIcon.pixmap(20, 20); QPushButton *closeButton = new QPushButton("&Close"); VERIFY(connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()))); _connectionIconLabel = new QLabel; _connectionLabel = new QLabel; _authIconLabel = new QLabel; _authLabel = new QLabel; _sshIconLabel = new QLabel; _sshLabel = new QLabel; _listIconLabel = new QLabel; _listLabel = new QLabel; _viewErrorLink = new QLabel("<a href='error' style='color: #777777;'>Show error details</a>"); VERIFY(connect(_viewErrorLink, SIGNAL(linkActivated(QString)), this, SLOT(errorLinkActivated(QString)))); _loadingMovie = new QMovie(":robomongo/icons/loading_ticks_40x40.gif", QByteArray(), this); _loadingMovie->setScaledSize(QSize(20, 20)); _loadingMovie->start(); _connectionIconLabel->setMovie(_loadingMovie); _sshIconLabel->setMovie(_loadingMovie); _authIconLabel->setMovie(_loadingMovie); _listIconLabel->setMovie(_loadingMovie); QGridLayout *layout = new QGridLayout(); layout->setContentsMargins(20, 20, 20, 10); layout->addWidget(_sshIconLabel, 0, 0); layout->addWidget(_sshLabel, 0, 1, Qt::AlignLeft); layout->addWidget(_connectionIconLabel, 1, 0); layout->addWidget(_connectionLabel, 1, 1, Qt::AlignLeft); layout->addWidget(_authIconLabel, 2, 0); layout->addWidget(_authLabel, 2, 1, Qt::AlignLeft); layout->addWidget(_listIconLabel, 3, 0); layout->addWidget(_listLabel, 3, 1, Qt::AlignLeft); layout->setColumnStretch(0, 0) ; // Give column 0 no stretch ability layout->setColumnStretch(1, 1) ; // Give column 1 stretch ability of ratio 1 QHBoxLayout *hbox = new QHBoxLayout; hbox->addSpacing(21); hbox->addWidget(_viewErrorLink, 1, Qt::AlignLeft); hbox->addWidget(closeButton, 0, Qt::AlignRight); QVBoxLayout *box = new QVBoxLayout; box->addLayout(layout); box->addSpacing(10); box->addLayout(hbox); setLayout(box); sshStatus(InitialState); connectionStatus(InitialState); authStatus(InitialState); listStatus(InitialState); _viewErrorLink->hide(); if (!AppRegistry::instance().app()->openServer(_connSettings, ConnectionTest)) { _continueExec = false; return; } _serverHandle = AppRegistry::instance().app()->getLastServerHandle(); } ConnectionDiagnosticDialog::~ConnectionDiagnosticDialog() { if (_server) AppRegistry::instance().app()->closeServer(_server); } void ConnectionDiagnosticDialog::errorLinkActivated(const QString &link) { if (_lastErrorMessage.empty()) return; QMessageBox::information(this, "Error details", QtUtils::toQString(_lastErrorMessage)); } void ConnectionDiagnosticDialog::sshStatus(State state) { if (!_connSettings->sshSettings()->enabled()) { _sshIconLabel->setVisible(false); _sshLabel->setVisible(false); return; } if (state == InitialState) { _sshIconLabel->setMovie(_loadingMovie); _sshLabel->setText(QString("Connecting to SSH server at <b>%1:%2</b>...") .arg(QtUtils::toQString(_connSettings->sshSettings()->host())) .arg(_connSettings->sshSettings()->port())); } else if (state == CompletedState) { _sshIconLabel->setPixmap(_yesPixmap); _sshLabel->setText(QString("Connected to SSH server at <b>%1:%2</b>") .arg(QtUtils::toQString(_connSettings->sshSettings()->host())) .arg(_connSettings->sshSettings()->port())); } else if (state == FailedState) { _sshIconLabel->setPixmap(_noPixmap); _sshLabel->setText(QString("Unable to connect to SSH server at <b>%1:%2</b>") .arg(QtUtils::toQString(_connSettings->sshSettings()->host())) .arg(_connSettings->sshSettings()->port())); } } void ConnectionDiagnosticDialog::connectionStatus(State state) { // Add info about tunneling if SSH or SSL is used QString tunnelNote(""); // No tunnel info when neither SSH nor SSL enabled if (_connSettings->sshSettings()->enabled()) tunnelNote = " via SSH tunnel"; else if (_connSettings->sslSettings()->sslEnabled()) tunnelNote = " via TLS tunnel"; else tunnelNote = ""; auto replicaSetStr = QString::fromStdString(_connSettings->connectionName()) + " [Replica Set]"; replicaSetStr = (_connSettings->replicaSetSettings()->members().size() > 0) ? replicaSetStr + '(' + QString::fromStdString( _connSettings->replicaSetSettings()->members()[0]) + ')' : replicaSetStr + ""; QString const& serverAddress = _connSettings->isReplicaSet() ? replicaSetStr : QString::fromStdString(_connSettings->getFullAddress()); // Set main info text at dialog if (state == InitialState) { _connectionIconLabel->setMovie(_loadingMovie); _connectionLabel->setText(QString("Connecting to <b>%1</b>%2...").arg(serverAddress, tunnelNote)); } else if (state == CompletedState) { _connectionIconLabel->setPixmap(_yesPixmap); _connectionLabel->setText(QString("Connected to <b>%1</b>%2").arg(serverAddress, tunnelNote)); } else if (state == FailedState) { _connectionIconLabel->setPixmap(_noPixmap); _connectionLabel->setText(QString("Failed to connect to <b>%1</b>%2").arg(serverAddress, tunnelNote)); } else if (state == NotPerformedState) { _connectionIconLabel->setPixmap(_questionPixmap); _connectionLabel->setText(QString("No chance to try connection to <b>%1</b>%2"). arg(serverAddress, tunnelNote)); } } void ConnectionDiagnosticDialog::authStatus(State state) { if (!_connSettings->hasEnabledPrimaryCredential()) { _authIconLabel->setVisible(false); _authLabel->setVisible(false); return; } if (state == InitialState) { _authIconLabel->setMovie(_loadingMovie); _authLabel->setText(QString("Authorizing on <b>%1</b> database as <b>%2</b>...") .arg(QtUtils::toQString(_connSettings->primaryCredential()->databaseName())) .arg(QtUtils::toQString(_connSettings->primaryCredential()->userName()))); } else if (state == CompletedState) { _authIconLabel->setPixmap(_yesPixmap); _authLabel->setText(QString("Authorized on <b>%1</b> database as <b>%2</b>") .arg(QtUtils::toQString(_connSettings->primaryCredential()->databaseName())) .arg(QtUtils::toQString(_connSettings->primaryCredential()->userName()))); } else if (state == FailedState) { _authIconLabel->setPixmap(_noPixmap); _authLabel->setText(QString("Authorization failed on <b>%1</b> database as <b>%2</b>") .arg(QtUtils::toQString(_connSettings->primaryCredential()->databaseName())) .arg(QtUtils::toQString(_connSettings->primaryCredential()->userName()))); } else if (state == NotPerformedState) { _authIconLabel->setPixmap(_questionPixmap); _authLabel->setText(QString("No chance to authorize")); } } void ConnectionDiagnosticDialog::listStatus(State state) { if (_connSettings->hasEnabledPrimaryCredential()) { _listIconLabel->setVisible(false); _listLabel->setVisible(false); return; } if (state == InitialState) { _listIconLabel->setMovie(_loadingMovie); _listLabel->setText(QString("Loading list of databases...")); } else if (state == CompletedState) { _listIconLabel->setPixmap(_yesPixmap); _listLabel->setText(QString("Access to databases is available")); } else if (state == FailedState) { _listIconLabel->setPixmap(_noPixmap); _listLabel->setText(QString("Failed to load list of databases")); } else if (state == NotPerformedState) { _listIconLabel->setPixmap(_questionPixmap); _listLabel->setText(QString("No chance to load list of databases")); } } void ConnectionDiagnosticDialog::handle(ConnectionEstablishedEvent *event) { if (event->connectionType != ConnectionTest) return; sshStatus(CompletedState); connectionStatus(CompletedState); authStatus(CompletedState); listStatus(CompletedState); // Remember in order to delete on dialog close _server = static_cast<MongoServer*>(event->sender()); } void ConnectionDiagnosticDialog::handle(ConnectionFailedEvent *event) { if (event->connectionType != ConnectionTest || event->serverHandle != _serverHandle) return; sshStatus(CompletedState); connectionStatus(CompletedState); authStatus(CompletedState); listStatus(CompletedState); switch (event->reason) { case ConnectionFailedEvent::SshConnection: sshStatus(FailedState); connectionStatus(NotPerformedState); authStatus(NotPerformedState); listStatus(NotPerformedState); break; case ConnectionFailedEvent::SshChannel: case ConnectionFailedEvent::MongoConnection: connectionStatus(FailedState); authStatus(NotPerformedState); listStatus(NotPerformedState); break; case ConnectionFailedEvent::MongoAuth: authStatus(FailedState); listStatus(FailedState); break; case ConnectionFailedEvent::SslConnection: connectionStatus(FailedState); authStatus(NotPerformedState); listStatus(NotPerformedState); break; } // Show link for additional error details if (!event->message.empty()) { _lastErrorMessage = event->message; _viewErrorLink->show(); } } }
12,298
C++
.cpp
251
38.729084
114
0.628667
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,710
SSHTunnelTab.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/SSHTunnelTab.cpp
#include "robomongo/gui/dialogs/SSHTunnelTab.h" #include <QApplication> #include <QLabel> #include <QLineEdit> #include <QGridLayout> #include <QRegExpValidator> #include <QCheckBox> #include <QPushButton> #include <QFileDialog> #include <QComboBox> #include <QMessageBox> #include <QFileInfo> #include <QFrame> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/ComboBoxUtils.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/SshSettings.h" #include "robomongo/gui/utils/GuiConstants.h" namespace { const QString askPasswordText = "Ask for password each time"; const QString askPassphraseText = "Ask for passphrase each time"; bool isFileExists(const QString &path) { QFileInfo fileInfo(path); return fileInfo.exists() && fileInfo.isFile(); } } namespace Robomongo { SshTunnelTab::SshTunnelTab(ConnectionSettings *settings) : _settings(settings) { SshSettings *info = settings->sshSettings(); _useSsh = new QCheckBox("Use SSH tunnel"); _useSsh->setStyleSheet("margin-bottom: 7px"); _useSsh->setChecked(info->enabled()); _askForPassword = new QCheckBox(askPasswordText); _askForPassword->setChecked(info->askPassword()); VERIFY(connect(_askForPassword, SIGNAL(stateChanged(int)), this, SLOT(askForPasswordStateChanged(int)))); _sshHostName = new QLineEdit(QtUtils::toQString(info->host())); _userName = new QLineEdit(QtUtils::toQString(info->userName())); _sshPort = new QLineEdit(QString::number(info->port())); _sshPort->setFixedWidth(40); QRegExp rx("\\d+"); //(0-65554) _sshPort->setValidator(new QRegExpValidator(rx, this)); _security = new QComboBox(); _security->addItems(QStringList() << "Password" << "Private Key"); VERIFY(connect(_security, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(securityChange(const QString&)))); _passwordBox = new QLineEdit(QtUtils::toQString(info->userPassword())); _passwordBox->setEchoMode(QLineEdit::Password); _passwordEchoModeButton = new QPushButton; _passwordEchoModeButton->setIcon(GuiRegistry::instance().hideIcon()); VERIFY(connect(_passwordEchoModeButton, SIGNAL(clicked()), this, SLOT(togglePasswordEchoMode()))); _privateKeyBox = new QLineEdit(QtUtils::toQString(info->privateKeyFile())); _privateKeyBox->setPlaceholderText( "DSA, RSA, and on Windows/macOS ECDSA, Ed25519 keys are supported." " PPK keys must be converted to OPENSSH format." ); _passphraseBox = new QLineEdit(QtUtils::toQString(info->passphrase())); _passphraseBox->setEchoMode(QLineEdit::Password); _passphraseEchoModeButton = new QPushButton; _passphraseEchoModeButton->setIcon(GuiRegistry::instance().hideIcon()); VERIFY(connect(_passphraseEchoModeButton, SIGNAL(clicked()), this, SLOT(togglePassphraseEchoMode()))); _passwordLabel = new QLabel("User Password:"); _sshPrivateKeyLabel = new QLabel("Private key:"); _sshPassphraseLabel = new QLabel("Passphrase:"); _sshAddressLabel = new QLabel("SSH Address:"); _sshUserNameLabel = new QLabel("SSH User Name:"); _sshAuthMethodLabel = new QLabel("SSH Auth Method:"); /* // Commented because of this: // https://github.com/paralect/robomongo/issues/391 #ifdef Q_OS_WIN QRegExp pathx("([a-zA-Z]:)?([\\\\/][a-zA-Z0-9_.-]+)+[\\\\/]?"); #else QRegExp pathx("^\\/?([\\d\\w\\.]+)(/([\\d\\w\\.]+))*\\/?$"); #endif // Q_OS_WIN _publicKeyBox->setValidator(new QRegExpValidator(pathx, this)); _privateKeyBox->setValidator(new QRegExpValidator(pathx, this)); */ QHBoxLayout *hostAndPasswordLayout = new QHBoxLayout; hostAndPasswordLayout->addWidget(_sshHostName); hostAndPasswordLayout->addWidget(new QLabel(":")); hostAndPasswordLayout->addWidget(_sshPort); QGridLayout *connectionLayout = new QGridLayout; connectionLayout->setAlignment(Qt::AlignTop); connectionLayout->setColumnStretch(1, 1); connectionLayout->setColumnMinimumWidth(0, _passwordLabel->sizeHint().width() + 5); connectionLayout->addWidget(_sshAddressLabel , 1, 0); connectionLayout->addLayout(hostAndPasswordLayout, 1, 1, 1, 2); connectionLayout->addWidget(_sshUserNameLabel, 2, 0); connectionLayout->addWidget(_userName, 2, 1, 1, 2); connectionLayout->addWidget(_sshAuthMethodLabel, 4, 0); connectionLayout->addWidget(_security, 4, 1, 1, 2); connectionLayout->addWidget(_passwordLabel, 5, 0); connectionLayout->addWidget(_passwordBox, 5, 1); connectionLayout->addWidget(_passwordEchoModeButton, 5, 2); _selectPrivateFileButton = new QPushButton("..."); _selectPrivateFileButton->setMaximumWidth(50); connectionLayout->addWidget(_sshPrivateKeyLabel, 7, 0); connectionLayout->addWidget(_privateKeyBox, 7, 1); connectionLayout->addWidget(_selectPrivateFileButton, 7, 2); connectionLayout->addWidget(_sshPassphraseLabel, 8, 0); connectionLayout->addWidget(_passphraseBox, 8, 1); connectionLayout->addWidget(_passphraseEchoModeButton, 8, 2); connectionLayout->addWidget(_askForPassword, 9, 1, 1, 2); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(_useSsh); mainLayout->addLayout(connectionLayout); setLayout(mainLayout); if (info->authMethod() == "publickey") { utils::setCurrentText(_security, "Private Key"); } else { utils::setCurrentText(_security, "Password"); } securityChange(_security->currentText()); VERIFY(connect(_selectPrivateFileButton, SIGNAL(clicked()), this, SLOT(setPrivateFile()))); sshSupportStateChange(_useSsh->checkState()); VERIFY(connect(_useSsh, SIGNAL(stateChanged(int)), this, SLOT(sshSupportStateChange(int)))); _sshHostName->setFocus(); #ifdef Q_OS_MAC _passwordEchoModeButton->setMaximumWidth(_selectPrivateFileButton->width()); _passphraseEchoModeButton->setMaximumWidth(_selectPrivateFileButton->width()); #else _passwordEchoModeButton->setMinimumWidth(_selectPrivateFileButton->width()); _passphraseEchoModeButton->setMinimumWidth(_selectPrivateFileButton->width()); #endif // Attempt to fix the issue for Windows High DPI button height is slightly taller than other widgets #ifdef Q_OS_WIN _passwordEchoModeButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); _passphraseEchoModeButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); _selectPrivateFileButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); #endif setDisabled(_settings->isReplicaSet()); toggleSshCheckboxToolTip(_settings->isReplicaSet()); } void SshTunnelTab::toggleSshCheckboxToolTip(bool isReplicaSet) { _useSsh->setToolTip(!isReplicaSet ? "" : "SSH is currently not supported for Replica Set connections"); } void SshTunnelTab::setPasswordFieldsEnabled(bool enabled) { _sshPassphraseLabel->setEnabled(enabled); _passphraseBox->setEnabled(enabled); _passwordBox->setEnabled(enabled); _passwordLabel->setEnabled(enabled); _passphraseEchoModeButton->setEnabled(enabled); _passwordEchoModeButton->setEnabled(enabled); } void SshTunnelTab::askForPasswordStateChanged(int state) { bool checked = state == Qt::Checked; if (checked) { _passphraseBox->setText(""); _passwordBox->setText(""); } setPasswordFieldsEnabled(!checked && _useSsh->isChecked()); } void SshTunnelTab::sshSupportStateChange(int state) { bool checked = state == Qt::Checked; _sshHostName->setEnabled(checked); _userName->setEnabled(checked); _sshPort->setEnabled(checked); _security->setEnabled(checked); _sshPrivateKeyLabel->setEnabled(checked); _privateKeyBox->setEnabled(checked); _selectPrivateFileButton->setEnabled(checked); _sshAddressLabel->setEnabled(checked); _sshUserNameLabel->setEnabled(checked); _sshAuthMethodLabel->setEnabled(checked); _askForPassword->setEnabled(checked); askForPasswordStateChanged(_askForPassword->checkState()); if (checked) _sshHostName->setFocus(); } void SshTunnelTab::securityChange(const QString& method) { bool isKey = method == "Private Key"; _sshPrivateKeyLabel->setVisible(isKey); _privateKeyBox->setVisible(isKey); _selectPrivateFileButton->setVisible(isKey); _sshPassphraseLabel->setVisible(isKey); _passphraseBox->setVisible(isKey); _passphraseEchoModeButton->setVisible(isKey); _passwordBox->setVisible(!isKey); _passwordLabel->setVisible(!isKey); _passwordEchoModeButton->setVisible(!isKey); _askForPassword->setText(isKey ? askPassphraseText : askPasswordText); } void SshTunnelTab::setPrivateFile() { // Default location QString sshDir = QString("%1/.ssh").arg(QDir::homePath()); QString filepath = QFileDialog::getOpenFileName(this, "Select private key file", sshDir, QObject::tr("Private key files (*)")); // Some strange behaviour at least on Mac happens when you // close QFileDialog. Focus switched to a different modal // dialog, not the one that was active before openning QFileDialog. // http://stackoverflow.com/questions/17998811/window-modal-qfiledialog-pushing-parent-to-background-after-exec QApplication::activeModalWidget()->raise(); QApplication::activeModalWidget()->activateWindow(); if (filepath.isNull()) return; _privateKeyBox->setText(filepath); } // SSHInfo::SupportedAuthenticationMetods SshTunnelTab::selectedAuthMethod() // { // if (_security->currentText() == "Private Key") // return SSHInfo::PUBLICKEY; // // return SSHInfo::PASSWORD; // } bool SshTunnelTab::accept() { bool const sshEnabled = this->isEnabled() && _useSsh->isChecked(); QString authMethod = _security->currentText() == "Private Key" ? "publickey" : "password"; // Check for existence of the private key file name // and try to expand "~" character when needed QString privateKey = _privateKeyBox->text(); if (sshEnabled && authMethod == "publickey" && !isFileExists(privateKey)) { bool failed = true; // Try to expand "~" if available if (privateKey.startsWith ("~/")) { privateKey.replace (0, 1, QDir::homePath()); if (isFileExists(privateKey)) { failed = false; } } if (failed) { QString message = QString("Private key file \"%1\" doesn't exist").arg(privateKey); QMessageBox::information(this, "Settings are incomplete", message); return false; } } SshSettings *info = _settings->sshSettings(); info->setHost(QtUtils::toStdString(_sshHostName->text())); info->setPort(_sshPort->text().toInt()); info->setUserName(QtUtils::toStdString(_userName->text())); info->setUserPassword(QtUtils::toStdString(_passwordBox->text())); info->setAskPassword(_askForPassword->isChecked()); info->setPrivateKeyFile(QtUtils::toStdString(privateKey)); info->setPassphrase(QtUtils::toStdString(_passphraseBox->text())); info->setAuthMethod(QtUtils::toStdString(authMethod)); info->setEnabled(sshEnabled); return true; } void SshTunnelTab::togglePasswordEchoMode() { bool isPassword = _passwordBox->echoMode() == QLineEdit::Password; _passwordBox->setEchoMode(isPassword ? QLineEdit::Normal: QLineEdit::Password); _passwordEchoModeButton->setIcon(isPassword ? GuiRegistry::instance().showIcon() : GuiRegistry::instance().hideIcon()); } void SshTunnelTab::togglePassphraseEchoMode() { bool isPassword = _passphraseBox->echoMode() == QLineEdit::Password; _passphraseBox->setEchoMode(isPassword ? QLineEdit::Normal: QLineEdit::Password); _passphraseEchoModeButton->setIcon(isPassword ? GuiRegistry::instance().showIcon() : GuiRegistry::instance().hideIcon()); } }
13,008
C++
.cpp
261
41.89272
129
0.666193
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,711
ChangeShellTimeoutDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/ChangeShellTimeoutDialog.cpp
#include "robomongo/gui/dialogs/ChangeShellTimeoutDialog.h" #include <QDialog> #include <QDialogButtonBox> #include <QLineEdit> #include <QObject> #include <QLabel> #include <QGridLayout> #include <QIntValidator> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/utils/Logger.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/settings/SettingsManager.h" namespace Robomongo { void changeShellTimeoutDialog() { auto changeShellTimeoutDialog = new QDialog; auto settingsManager = AppRegistry::instance().settingsManager(); auto currentShellTimeout = new QLabel(QString::number(settingsManager->shellTimeoutSec())); auto newShellTimeout = new QLineEdit; newShellTimeout->setValidator(new QIntValidator(0, 100000)); auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel); QObject::connect(buttonBox, SIGNAL(accepted()), changeShellTimeoutDialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), changeShellTimeoutDialog, SLOT(reject())); auto lay = new QGridLayout; auto firstLabel = new QLabel("Enter new value for Robo 3T shell timeout in seconds:\n"); lay->addWidget(firstLabel, 0, 0, 1, 2, Qt::AlignLeft); lay->addWidget(new QLabel("Current Value: "), 1, 0); lay->addWidget(currentShellTimeout, 1, 1); lay->addWidget(new QLabel("New Value: "), 2, 0); lay->addWidget(newShellTimeout, 2, 1); lay->addWidget(buttonBox, 3, 0, 1, 2, Qt::AlignRight); changeShellTimeoutDialog->setLayout(lay); changeShellTimeoutDialog->setWindowTitle("Robo 3T"); if (changeShellTimeoutDialog->exec()) { settingsManager->setShellTimeoutSec(newShellTimeout->text().toInt()); settingsManager->save(); auto subStr = settingsManager->shellTimeoutSec() > 1 ? " seconds." : " second."; LOG_MSG("Shell timeout value changed from " + currentShellTimeout->text() + " to " + QString::number(settingsManager->shellTimeoutSec()) + subStr, mongo::logger::LogSeverity::Info()); for (auto const& server : AppRegistry::instance().app()->getServers()) server->changeWorkerShellTimeout(std::abs(newShellTimeout->text().toInt())); } } }
2,514
C++
.cpp
47
46.744681
114
0.674929
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,712
SSLTab.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/SSLTab.cpp
#include "robomongo/gui/dialogs/SSLTab.h" #include <QApplication> #include <QLabel> #include <QLineEdit> #include <QGridLayout> #include <QCheckBox> #include <QPushButton> #include <QFileDialog> #include <QComboBox> #include <QRadioButton> #include <QFileInfo> #include <QMessageBox> #include <mongo/util/net/ssl_options.h> #include <mongo/util/net/ssl_manager.h> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/SshSettings.h" #include "robomongo/core/settings/SslSettings.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/ComboBoxUtils.h" #include "robomongo/gui/utils/GuiConstants.h" namespace { // Helper function: Check file existence, return true if file exists, false otherwise bool fileExists(const QString &path) { QFileInfo fileInfo(path); return (fileInfo.exists() && fileInfo.isFile()); } // Helper hint strings QString const CA_FILE_HINT = " mongo --tlsCAFile : Certificate Authority file for TLS"; QString const PEM_FILE_HINT = " mongo --tlsCertificateKeyFile : PEM certificate/key file for TLS"; QString const PEM_PASS_HINT = " mongo --tlsCertificateKeyFilePassword : Password for key in PEM file for TLS"; QString const ALLOW_INVALID_HOSTNAME_HINT = " mongo --tlsAllowInvalidHostnames : Allow connections " "to servers with non-matching hostnames"; QString const ALLOW_INVALID_CERTIFICATES_HINT = " mongo --tlsAllowInvalidCertificates : Allow connections " "to servers with invalid certificates"; QString const CRL_FILE_HINT = " mongo --tlsCRLFile : Certificate Revocation List file for TLS"; } namespace Robomongo { SSLTab::SSLTab(ConnectionSettings *connSettings) : _connSettings(connSettings) { const SslSettings* const sslSettings = _connSettings->sslSettings(); // Use TLS section _useSslCheckBox = new QCheckBox("Use TLS protocol"); _useSslCheckBox->setStyleSheet("margin-bottom: 7px"); VERIFY(connect(_useSslCheckBox, SIGNAL(stateChanged(int)), this, SLOT(useSslCheckBoxStateChange(int)))); // Auth. Method section _authMethodLabel = new QLabel("Authentication Method: "); _authMethodComboBox = new QComboBox; _authMethodComboBox->addItem("Self-signed Certificate"); _authMethodComboBox->addItem("Use CA Certificate"); _authMethodComboBox->setItemData(0, ALLOW_INVALID_CERTIFICATES_HINT, Qt::ToolTipRole); _authMethodComboBox->setItemData(1, CA_FILE_HINT, Qt::ToolTipRole); _selfSignedInfoStr = new QLabel("In general, avoid using self-signed certificates unless the network is trusted. " "If self-signed certificate is used, the communications channel will be encrypted however there will be " "no validation of server identity."); _selfSignedInfoStr->setWordWrap(true); _selfSignedInfoStr->setToolTip(ALLOW_INVALID_CERTIFICATES_HINT); _caFileLabel = new QLabel("CA Certificate:"); _caFileLabel->setToolTip(CA_FILE_HINT); _caFilePathLineEdit = new QLineEdit; _caFileBrowseButton = new QPushButton("..."); _caFileBrowseButton->setMaximumWidth(50); VERIFY(connect(_caFileBrowseButton, SIGNAL(clicked()), this, SLOT(on_caFileBrowseButton_clicked()))); VERIFY(connect(_authMethodComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_authModeComboBox_change(int)))); // PEM file section _usePemFileCheckBox = new QCheckBox("Use PEM Cert./Key: "); _usePemFileCheckBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); _pemFileInfoStr = new QLabel("Enable this option to connect to a MongoDB that requires CA-signed client certificates/key file."); _pemFileInfoStr->setWordWrap(true); #ifdef Q_OS_WIN _pemFileInfoStr->setContentsMargins(0,2,0,0); // Top alignment adjustment required only for Windows #endif _pemFileLabel = new QLabel("PEM Certificate/Key: "); _pemFileLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); _pemFileLabel->setToolTip(PEM_FILE_HINT); _pemFilePathLineEdit = new QLineEdit; _pemFileBrowseButton = new QPushButton("..."); _pemFileBrowseButton->setMaximumWidth(50); VERIFY(connect(_usePemFileCheckBox, SIGNAL(toggled(bool)), this, SLOT(on_usePemFileCheckBox_toggle(bool)))); VERIFY(connect(_pemFileBrowseButton, SIGNAL(clicked()), this, SLOT(on_pemKeyFileBrowseButton_clicked()))); // PEM Passphrase section _pemPassLabel = new QLabel("Passphrase: "); _pemPassLabel->setToolTip(PEM_PASS_HINT); _pemPassLineEdit = new QLineEdit; _pemPassShowButton = new QPushButton; // Fix for MAC OSX: PEM pass show button was created bigger, making it same size as other pushbuttons _pemPassShowButton->setMaximumWidth(_pemFileBrowseButton->width()); VERIFY(connect(_pemPassShowButton, SIGNAL(clicked()), this, SLOT(togglePassphraseShowMode()))); togglePassphraseShowMode(); _askPemPassCheckBox = new QCheckBox("Ask for passphrase each time"); _askPemPassCheckBox->setChecked(sslSettings->askPassphrase()); VERIFY(connect(_askPemPassCheckBox, SIGNAL(toggled(bool)), this, SLOT(on_askPemPassCheckBox_toggle(bool)))); // Advanced options _useAdvancedOptionsCheckBox = new QCheckBox("Advanced Options"); _useAdvancedOptionsCheckBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); VERIFY(connect(_useAdvancedOptionsCheckBox, SIGNAL(toggled(bool)), this, SLOT(on_useAdvancedOptionsCheckBox_toggle(bool)))); _crlFileLabel = new QLabel("CRL (Revocation List): "); _crlFileLabel->setToolTip(CRL_FILE_HINT); _crlFilePathLineEdit = new QLineEdit; _crlFileBrowseButton = new QPushButton("..."); _crlFileBrowseButton->setMaximumWidth(50); VERIFY(connect(_crlFileBrowseButton, SIGNAL(clicked()), this, SLOT(on_crlFileBrowseButton_clicked()))); _allowInvalidHostnamesLabel = new QLabel("Invalid Hostnames: "); _allowInvalidHostnamesLabel->setToolTip(ALLOW_INVALID_HOSTNAME_HINT); _allowInvalidHostnamesComboBox = new QComboBox; _allowInvalidHostnamesComboBox->addItem("Not Allowed"); _allowInvalidHostnamesComboBox->addItem("Allowed"); _allowInvalidHostnamesComboBox->setCurrentIndex(sslSettings->allowInvalidHostnames()); // Layouts // Auth. method section QGridLayout* gridLayout = new QGridLayout; gridLayout->addWidget(_authMethodLabel, 0 ,0); gridLayout->addWidget(_authMethodComboBox, 0 ,1, 1, 2); gridLayout->addWidget(_selfSignedInfoStr, 1, 1, 1, 2); gridLayout->addWidget(_caFileLabel, 2, 0); gridLayout->addWidget(_caFilePathLineEdit, 2, 1); gridLayout->addWidget(_caFileBrowseButton, 2, 2); #ifdef _WIN32 gridLayout->addWidget(new QLabel(""), 3, 0); #endif // PEM File Section gridLayout->addWidget(_usePemFileCheckBox, 4, 0, Qt::AlignTop); gridLayout->addWidget(_pemFileInfoStr, 4, 1, 1, 2); gridLayout->addWidget(_pemFileLabel, 5, 0); gridLayout->addWidget(_pemFilePathLineEdit, 5, 1); gridLayout->addWidget(_pemFileBrowseButton, 5, 2); gridLayout->addWidget(_pemPassLabel, 6, 0); gridLayout->addWidget(_pemPassLineEdit, 6, 1); gridLayout->addWidget(_pemPassShowButton, 6, 2); gridLayout->addWidget(_askPemPassCheckBox, 7, 1, 1, 2); #ifdef _WIN32 gridLayout->addWidget(new QLabel(""), 8, 0); #endif // Advanced section gridLayout->addWidget(_useAdvancedOptionsCheckBox, 9, 0, Qt::AlignTop); gridLayout->addWidget(_crlFileLabel, 10, 0); gridLayout->addWidget(_crlFilePathLineEdit, 10, 1); gridLayout->addWidget(_crlFileBrowseButton, 10, 2); gridLayout->addWidget(_allowInvalidHostnamesLabel, 11, 0); gridLayout->addWidget(_allowInvalidHostnamesComboBox, 11, 1, Qt::AlignLeft); auto mainLayout = new QVBoxLayout; mainLayout->setAlignment(Qt::AlignTop); mainLayout->addWidget(_useSslCheckBox); mainLayout->addLayout(gridLayout); setLayout(mainLayout); // Load SSL settings to update UI states _useSslCheckBox->setChecked(sslSettings->sslEnabled()); _authMethodComboBox->setCurrentIndex(!sslSettings->allowInvalidCertificates()); _caFilePathLineEdit->setText(QString::fromStdString(sslSettings->caFile())); _usePemFileCheckBox->setChecked(sslSettings->usePemFile()); _pemFilePathLineEdit->setText(QString::fromStdString(sslSettings->pemKeyFile())); _askPemPassCheckBox->setChecked(sslSettings->askPassphrase()); // Load passphrase only if askPassphrase is false if (!sslSettings->askPassphrase()) { _pemPassLineEdit->setText(QString::fromStdString(sslSettings->pemPassPhrase())); } _useAdvancedOptionsCheckBox->setChecked(sslSettings->useAdvancedOptions()); _allowInvalidHostnamesComboBox->setCurrentIndex(sslSettings->allowInvalidHostnames()); _crlFilePathLineEdit->setText(QString::fromStdString(sslSettings->crlFile())); // Update UI inter-connected (signal-slot) widget states on_authModeComboBox_change(_authMethodComboBox->currentIndex()); on_usePemFileCheckBox_toggle(_usePemFileCheckBox->isChecked()); on_askPemPassCheckBox_toggle(_askPemPassCheckBox->isChecked()); on_useAdvancedOptionsCheckBox_toggle(_useAdvancedOptionsCheckBox->isChecked()); // Enable/disable all SSL tab widgets useSslCheckBoxStateChange(_useSslCheckBox->checkState()); // Attempt to fix issue for Windows High DPI button height is slightly taller than other widgets #ifdef Q_OS_WIN _caFileBrowseButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); _pemFileBrowseButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); _pemPassShowButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); _crlFileBrowseButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); #endif } bool SSLTab::accept() { saveSslSettings(); return validate(); } bool SSLTab::sslEnabled() const { return _useSslCheckBox->isChecked(); } void SSLTab::clearTab() { _authMethodComboBox->setCurrentIndex(1); _caFilePathLineEdit->clear(); _usePemFileCheckBox->setChecked(false); _pemFilePathLineEdit->clear(); _pemPassLineEdit->clear(); _useAdvancedOptionsCheckBox->setChecked(false); _allowInvalidHostnamesComboBox->setCurrentIndex(0); } void SSLTab::setSslOptions( int index, bool allowInvalidHostnames, std::string_view caFile, std::string_view certPemFile, std::string_view certPemFilePwd ) { _useSslCheckBox->setChecked(true); _authMethodComboBox->setCurrentIndex(index); _caFilePathLineEdit->setText(QString::fromStdString(std::string(caFile))); if(!certPemFile.empty()) _usePemFileCheckBox->setChecked(true); _pemFilePathLineEdit->setText(QString::fromStdString(std::string(certPemFile))); _pemPassLineEdit->setText(QString::fromStdString(std::string(certPemFilePwd))); if (allowInvalidHostnames) _useAdvancedOptionsCheckBox->setChecked(true); _allowInvalidHostnamesComboBox->setCurrentIndex(allowInvalidHostnames); } void SSLTab::useSslCheckBoxStateChange(int state) { bool isChecked = static_cast<bool>(state); _authMethodLabel->setDisabled(!isChecked); _authMethodComboBox->setDisabled(!isChecked); _selfSignedInfoStr->setDisabled(!isChecked); _caFileLabel->setDisabled(!isChecked); _caFilePathLineEdit->setDisabled(!isChecked); _caFileBrowseButton->setDisabled(!isChecked); _usePemFileCheckBox->setDisabled(!isChecked); _pemFileInfoStr->setDisabled(!isChecked); _pemFileLabel->setDisabled(!isChecked); _pemFilePathLineEdit->setDisabled(!isChecked); _pemFileBrowseButton->setDisabled(!isChecked); _pemPassLabel->setDisabled(!isChecked); _pemPassLineEdit->setDisabled(!isChecked); _pemPassShowButton->setDisabled(!isChecked); _askPemPassCheckBox->setDisabled(!isChecked); _useAdvancedOptionsCheckBox->setDisabled(!isChecked); _crlFileLabel->setDisabled(!isChecked); _crlFilePathLineEdit->setDisabled(!isChecked); _crlFileBrowseButton->setDisabled(!isChecked); _allowInvalidHostnamesLabel->setDisabled(!isChecked); _allowInvalidHostnamesComboBox->setDisabled(!isChecked); if (isChecked) // Update some widgets only if SSL enabled { on_usePemFileCheckBox_toggle(_usePemFileCheckBox->isChecked()); on_askPemPassCheckBox_toggle(_askPemPassCheckBox->isChecked()); } } void SSLTab::on_authModeComboBox_change(int index) { bool const isCaSigned = static_cast<bool>(index); _selfSignedInfoStr->setVisible(!isCaSigned); _caFileLabel->setVisible(isCaSigned); _caFilePathLineEdit->setVisible(isCaSigned); _caFileBrowseButton->setVisible(isCaSigned); } void SSLTab::on_usePemFileCheckBox_toggle(bool isChecked) { _pemFileInfoStr->setVisible(!isChecked); _pemFileLabel->setVisible(isChecked); _pemFilePathLineEdit->setVisible(isChecked); _pemFileBrowseButton->setVisible(isChecked); _pemPassLabel->setVisible(isChecked); _pemPassLineEdit->setVisible(isChecked); _pemPassShowButton->setVisible(isChecked); _askPemPassCheckBox->setVisible(isChecked); } void SSLTab::on_useAdvancedOptionsCheckBox_toggle(bool isChecked) { _crlFileLabel->setVisible(isChecked); _crlFilePathLineEdit->setVisible(isChecked); _crlFileBrowseButton->setVisible(isChecked); _allowInvalidHostnamesLabel->setVisible(isChecked); _allowInvalidHostnamesComboBox->setVisible(isChecked); } void SSLTab::on_caFileBrowseButton_clicked() { QString const& fileName = openFileBrowseDialog(_caFilePathLineEdit->text()); if (!fileName.isEmpty()) { _caFilePathLineEdit->setText(fileName); } } void SSLTab::on_pemKeyFileBrowseButton_clicked() { QString const& fileName = openFileBrowseDialog(_pemFilePathLineEdit->text()); if (!fileName.isEmpty()) { _pemFilePathLineEdit->setText(fileName); } } void SSLTab::on_crlFileBrowseButton_clicked() { QString const& fileName = openFileBrowseDialog(_crlFilePathLineEdit->text()); if (!fileName.isEmpty()) { _crlFilePathLineEdit->setText(fileName); } } void SSLTab::togglePassphraseShowMode() { bool isPassword = _pemPassLineEdit->echoMode() == QLineEdit::Password; _pemPassLineEdit->setEchoMode(isPassword ? QLineEdit::Normal : QLineEdit::Password); _pemPassShowButton->setIcon(isPassword ? GuiRegistry::instance().showIcon() : GuiRegistry::instance().hideIcon()); } void SSLTab::on_askPemPassCheckBox_toggle(bool checked) { //if (_usePemFileCheckBox->isChecked()) //{ _pemPassLabel->setDisabled(checked); _pemPassLineEdit->setDisabled(checked); _pemPassShowButton->setDisabled(checked); if (checked) { _pemPassLineEdit->setText(""); // clear passphrase on UI } //} } bool SSLTab::validate() { // Validate existence of files auto const& resultAndFileName = checkExistenseOfFiles(); if (!resultAndFileName.first) { QString const& nonExistingFile = resultAndFileName.second; QMessageBox errorBox; errorBox.critical(this, "Error", ("Error: " + nonExistingFile + " file does not exist")); errorBox.adjustSize(); return false; } return true; } std::pair<bool,QString> SSLTab::checkExistenseOfFiles() const { if (_caFilePathLineEdit->isEnabled() && _caFilePathLineEdit->isVisible()) { if (!fileExists(_caFilePathLineEdit->text())) { return {false, "CA-signed certificate"}; } } if (_pemFilePathLineEdit->isVisible() && _pemFilePathLineEdit->isEnabled()) { if (!fileExists(_pemFilePathLineEdit->text())) { return {false, "PEM Certificate/Key"}; } } if (!_crlFilePathLineEdit->text().isEmpty()) { if (!fileExists(_crlFilePathLineEdit->text())) { return {false, "CRL (Revocation List)"}; } } return {true, ""}; } void SSLTab::saveSslSettings() const { SslSettings* sslSettings = _connSettings->sslSettings(); sslSettings->enableSSL(_useSslCheckBox->isChecked()); sslSettings->setAllowInvalidCertificates(!static_cast<bool>(_authMethodComboBox->currentIndex())); sslSettings->setCaFile(QtUtils::toStdString(_caFilePathLineEdit->text())); sslSettings->setUsePemFile(_usePemFileCheckBox->isChecked()); sslSettings->setPemKeyFile(QtUtils::toStdString(_pemFilePathLineEdit->text())); sslSettings->setAskPassphrase(_askPemPassCheckBox->isChecked()); // save passphrase only if _askPemPassCheckBox is not checked; otherwise don't save and clear saved passphrase if (!_askPemPassCheckBox->isChecked()) { sslSettings->setPemPassPhrase(QtUtils::toStdString(_pemPassLineEdit->text())); } else { sslSettings->setPemPassPhrase(""); } sslSettings->setUseAdvancedOptions(_useAdvancedOptionsCheckBox->isChecked()); sslSettings->setCrlFile(QtUtils::toStdString(_crlFilePathLineEdit->text())); sslSettings->setAllowInvalidHostnames(static_cast<bool>(_allowInvalidHostnamesComboBox->currentIndex())); } QString SSLTab::openFileBrowseDialog(const QString& initialPath) { QString filePath = initialPath; // If user has previously selected a file, initialize file dialog with that file's // path and name; otherwise, use user's home directory. if (filePath.isEmpty()) { filePath = QDir::homePath(); } QString fileName = QFileDialog::getOpenFileName(this, tr("Choose File"), filePath); // Some strange behaviour at least on Mac happens when you close QFileDialog. Focus switched to a different modal // dialog, not the one that was active before openning QFileDialog. // http://stackoverflow.com/questions/17998811/window-modal-qfiledialog-pushing-parent-to-background-after-exec QApplication::activeModalWidget()->raise(); QApplication::activeModalWidget()->activateWindow(); return QDir::toNativeSeparators(fileName); } }
19,726
C++
.cpp
385
42.846753
132
0.678151
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
14,713
ConnectionBasicTab.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/ConnectionBasicTab.cpp
#include "robomongo/gui/dialogs/ConnectionBasicTab.h" #include <QLabel> #include <QLineEdit> #include <QGridLayout> #include <QRegExpValidator> #include <QCheckBox> #include <QPushButton> #include <QFileDialog> #include <QComboBox> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QMessageBox> #include <QDialogButtonBox> #include <QApplication> #include <QDesktopWidget> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/ReplicaSetSettings.h" #include "robomongo/gui/dialogs/ConnectionDialog.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/GuiConstants.h" #include "mongo/client/mongo_uri.h" namespace Robomongo { ConnectionBasicTab::ConnectionBasicTab(ConnectionSettings *settings, ConnectionDialog *connectionDialog) : _settings(settings), _connectionDialog(connectionDialog) { _typeLabel = new QLabel("Type:"); _connectionType = new QComboBox; _connectionType->addItem(tr("Direct Connection")); _connectionType->addItem(tr("Replica Set")); _connectionType->setCurrentIndex(static_cast<int>(_settings->isReplicaSet())); VERIFY(connect(_connectionType, SIGNAL(currentIndexChanged(int)), this, SLOT(on_ConnectionTypeChange(int))) ); _nameLabel = new QLabel("Name:"); _connectionName = new QLineEdit(QtUtils::toQString(_settings->connectionName())); _connInfoLabel = new QLabel("Choose any connection name that will help you to identify this connection."); _connInfoLabel->setWordWrap(true); _addressLabel = new QLabel("Address:"); _serverAddress = new QLineEdit(QtUtils::toQString(_settings->serverHost())); _colon = new QLabel(":"); _serverPort = new QLineEdit(QString::number(_settings->serverPort())); _serverPort->setFixedWidth(80); QRegExp rx("\\d+"); //(0-65554) _serverPort->setValidator(new QRegExpValidator(rx, this)); _addInfoLabel = new QLabel("Specify host and port of MongoDB server. Host can be either IPv4, IPv6 or domain name."); _addInfoLabel->setWordWrap(true); _membersLabel = new QLabel("Members:"); _membersLabel->setFixedWidth(_membersLabel->sizeHint().width()); _members = new QTreeWidget; _members->setHeaderHidden(true); _members->setIndentation(0); #ifdef _WIN32 auto lineHeight = _members->fontMetrics().height(); _members->setFixedHeight(lineHeight * 8); #endif VERIFY(connect(_members, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(on_replicaMemberItemEdit(QTreeWidgetItem*, int)))); if (_settings->isReplicaSet() && _settings->replicaSetSettings()->members().size() > 0) { for (const std::string& str : _settings->replicaSetSettings()->members()) { if (!str.empty()) { auto item = new QTreeWidgetItem; item->setText(0, QString::fromStdString(str)); item->setFlags(item->flags() | Qt::ItemIsEditable); _members->addTopLevelItem(item); } } // To fix strange MAC alignment issue #ifdef __APPLE__ auto lineHeight = _members->fontMetrics().height(); _members->setFixedHeight(lineHeight * 8); #endif } else { // No members auto item = new QTreeWidgetItem; item->setText(0, "localhost:27017"); item->setFlags(item->flags() | Qt::ItemIsEditable); _members->addTopLevelItem(item); } int const BUTTON_SIZE = 60; _addButton = new QPushButton; _addButton->setIcon(GuiRegistry::instance().plusIcon()); _removeButton = new QPushButton; _removeButton->setIcon(GuiRegistry::instance().minusIcon()); VERIFY(connect(_addButton, SIGNAL(clicked()), this, SLOT(on_addButton_clicked()))); VERIFY(connect(_removeButton, SIGNAL(clicked()), this, SLOT(on_removeButton_clicked()))); _minusPlusButtonBox = new QDialogButtonBox(this); _minusPlusButtonBox->setOrientation(Qt::Horizontal); #ifdef _WIN32 _minusPlusButtonBox->addButton(_addButton, QDialogButtonBox::NoRole); _minusPlusButtonBox->addButton(_removeButton, QDialogButtonBox::NoRole); #else _minusPlusButtonBox->addButton(_removeButton, QDialogButtonBox::NoRole); _minusPlusButtonBox->addButton(_addButton, QDialogButtonBox::NoRole); #endif _setNameLabel = new QLabel("Set Name:"); _setNameEdit = new QLineEdit(QString::fromStdString(_settings->replicaSetSettings()->setNameUserEntered())); auto fakeSpacer = new QLabel(""); auto hline = new QFrame(); hline->setFrameShape(QFrame::HLine); hline->setFrameShadow(QFrame::Sunken); _uriEdit = new QLineEdit(); _uriEdit->setPlaceholderText("Import connection details from MongoDB URI connection string"); _uriButton = new QPushButton("From URI"); #ifdef _WIN32 _uriButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT); _uriButton->setMinimumWidth(60); #else // MacOS _uriButton->setMaximumHeight(HighDpiConstants::MACOS_HIGH_DPI_BUTTON_HEIGHT); _uriButton->setMaximumWidth(90); #endif VERIFY(connect(_uriButton, SIGNAL(clicked()), this, SLOT(on_uriButton_clicked()))); auto connLayout = new QGridLayout; connLayout->setVerticalSpacing(8); connLayout->setAlignment(Qt::AlignTop); connLayout->addWidget(_typeLabel, 1, 0); connLayout->addWidget(_connectionType, 1, 1, 1, 3); connLayout->addWidget(_nameLabel, 3, 0); connLayout->addWidget(_connectionName, 3, 1, 1, 3); connLayout->addWidget(_addressLabel, 5, 0); connLayout->addWidget(_serverAddress, 5, 1); connLayout->addWidget(_colon, 5, 2); connLayout->addWidget(_serverPort, 5, 3); connLayout->addWidget(_addInfoLabel, 6, 1, 1, 3); connLayout->addWidget(_membersLabel, 7, 0, Qt::AlignTop); connLayout->addWidget(_members, 7, 1, 1, 3); connLayout->addWidget(_minusPlusButtonBox, 8, 3, Qt::AlignRight | Qt::AlignTop); connLayout->addWidget(_setNameLabel, 9, 0); connLayout->addWidget(_setNameEdit, 9, 1, 1, 3, Qt::AlignTop); connLayout->addWidget(fakeSpacer, 10, 0); connLayout->addWidget(hline, 11, 0, 1, 4); connLayout->addWidget(_uriButton, 13, 0); connLayout->addWidget(_uriEdit, 13, 1, 1, 3); connLayout->setRowStretch(10, 1); #ifdef __APPLE__ connLayout->setRowMinimumHeight(11, 20); #endif auto mainLayout = new QVBoxLayout; mainLayout->addLayout(connLayout); setLayout(mainLayout); #ifdef __APPLE__ mainLayout->setContentsMargins(-1, -1, -1, 10); #endif _connectionName->setFocus(); on_ConnectionTypeChange(_connectionType->currentIndex()); } bool ConnectionBasicTab::accept() { _settings->setReplicaSet(static_cast<bool>(_connectionType->currentIndex())); _settings->setConnectionName(QtUtils::toStdString(_connectionName->text())); if (_settings->isReplicaSet() && _members->topLevelItemCount() == 0) { QMessageBox::critical(this, "Error", "Replica set members cannot be empty. " "Please enter at least one member."); return false; } // Check and warn if there is duplicate member or // if any of the replica set member items does not contain ":" character between hostname and port. if (_settings->isReplicaSet() && _members->topLevelItemCount() > 1) { QStringList members; for (int i = 0; i < _members->topLevelItemCount(); ++i) { QTreeWidgetItem const* item = _members->topLevelItem(i); QStringList const hostAndPort = item->text(0).split(":"); if (hostAndPort.size() < 2) { QMessageBox::critical(this, "Error", "Replica set member items must all contain ':' between" " hostname and port."); return false; } if (!item->text(0).isEmpty()) members.push_back(item->text(0)); } if (members.size() > 1) { if (members.removeDuplicates() > 0) { QMessageBox::critical(this, "Error", "Please remove duplicate member, two replica" " set members cannot have the same hostname and port."); return false; } } } // Save to settings if (_settings->isReplicaSet() && _members->topLevelItemCount() > 0) { QStringList const hostAndPort = _members->topLevelItem(0)->text(0).split(":"); _settings->setServerHost(hostAndPort[0].toStdString()); _settings->setServerPort(hostAndPort[1].toInt()); } else { // Single server _settings->setServerHost(QtUtils::toStdString(_serverAddress->text())); _settings->setServerPort(_serverPort->text().toInt()); } if (_settings->isReplicaSet()) { // Save replica members std::vector<std::string> members; for (int i = 0; i < _members->topLevelItemCount(); ++i) { QTreeWidgetItem const* item = _members->topLevelItem(i); if (!item->text(0).isEmpty()) members.push_back(item->text(0).toStdString()); } _settings->replicaSetSettings()->setMembers(members); _settings->replicaSetSettings()->setSetNameUserEntered(_setNameEdit->text().toStdString()); // Clear cached set name _settings->replicaSetSettings()->setCachedSetName(""); } return true; } void ConnectionBasicTab::clearTab() { _connectionType->setCurrentIndex(0); _connectionName->setText("New Connection"); _serverAddress->clear(); _serverPort->clear(); _members->clear(); _setNameEdit->clear(); } void ConnectionBasicTab::on_ConnectionTypeChange(int index) { bool const isReplica = static_cast<bool>(index); _connectionDialog->toggleSshSupport(isReplica); // Replica set _membersLabel->setVisible(isReplica); _members->setVisible(isReplica); _minusPlusButtonBox->setVisible(isReplica); _setNameLabel->setVisible(isReplica); _setNameEdit->setVisible(isReplica); // Direct Connection _addressLabel->setVisible(!isReplica); _serverAddress->setVisible(!isReplica); _serverPort->setVisible(!isReplica); _colon->setVisible(!isReplica); _addInfoLabel->setVisible(!isReplica); } void ConnectionBasicTab::deleteItem() { delete _members->currentItem(); // todo: refactor } void ConnectionBasicTab::on_addButton_clicked() { auto item = new QTreeWidgetItem; // Make member addition little smarter than expected if (_members->topLevelItemCount() < 1) { item->setText(0, "localhost:27017"); } else { // Add the next member using last entered hostname and incremented port by one QString const& lastMember = _members->topLevelItem(_members->topLevelItemCount()-1)->text(0); QStringList const& hostAndPort = lastMember.split(':'); if (hostAndPort.size() == 2) { auto const& hostName = hostAndPort[0]; auto const& port = hostAndPort[1].toInt(); item->setText(0, hostName + ':' + QString::number(port + 1)); } else { item->setText(0, "localhost:" + QString::number(_members->topLevelItemCount() + 27017)); } } item->setFlags(item->flags() | Qt::ItemIsEditable); _members->addTopLevelItem(item); } void ConnectionBasicTab::on_removeButton_clicked() { if (_members->topLevelItemCount() <= 0) return; if (_members->currentItem()) delete _members->currentItem(); else delete _members->topLevelItem(_members->topLevelItemCount() - 1); } void ConnectionBasicTab::on_replicaMemberItemEdit(QTreeWidgetItem* item, int column) { if (!item) return; auto str = item->text(0); // Remove white spaces str = str.simplified(); str.remove(" "); // Remove item from tree widget if it has empty text if (str.isEmpty()) { delete item; return; } // Force port as integer QStringList const& hostAndPort = str.split(':'); if (hostAndPort.size() >= 2) { auto const& hostName = hostAndPort[0]; auto portStr = hostAndPort[1]; portStr.remove(QRegExp("[^\\d]")); str = hostName + ':' + QString::number(portStr.toInt()); } else str += ":27017"; item->setText(0, str); } void ConnectionBasicTab::on_uriButton_clicked() { // Parse Mongo URI QString uriStr = _uriEdit->text().simplified(); uriStr.replace(" ", ""); auto const statusWithURI = mongo::MongoURI::parse(uriStr.toStdString()); if (!statusWithURI.isOK()) { QMessageBox errorBox; errorBox.critical( this, "Error", ("MongoDB URI:\n" + statusWithURI.getStatus().toString()).c_str() ); errorBox.show(); return; } auto const mongoUri = statusWithURI.getValue(); // Clear tabs clearTab(); _connectionDialog->clearConnAuthTab(); _connectionDialog->clearSslTab(); // Set Basic (this) Tab auto const isReplicaSet = mongoUri.type() == mongo::ConnectionString::ConnectionType::SET; if(isReplicaSet) { _connectionType->setCurrentIndex(1); // Switch to Replica Set for (auto const& hostAndPort : mongoUri.getServers()) { auto host = QString::fromStdString(hostAndPort.host()); host.endsWith('.') ? host.remove(host.size()-1, 1) : "no-op"; auto const newHostAndPort = host + ':' + QString::number(hostAndPort.port()); auto item = new QTreeWidgetItem; item->setText(0, newHostAndPort); item->setFlags(item->flags() | Qt::ItemIsEditable); _members->addTopLevelItem(item); } _setNameEdit->setText(QString::fromStdString(mongoUri.getSetName())); } else { // Standalone _connectionType->setCurrentIndex(0); _serverAddress->setText(QString::fromStdString(mongoUri.getServers()[0].host())); _serverPort->setText(QString::number(mongoUri.getServers()[0].port())); } // Set Auth Tab auto const user = QString::fromStdString(mongoUri.getUser()); auto const pwd = QString::fromStdString(mongoUri.getPassword()); auto const authDb = QString::fromStdString(mongoUri.getAuthenticationDatabase()); auto const authMechanism = mongoUri.getOption("authMechanism").get_value_or(""); if(!user.isEmpty()) _connectionDialog->setAuthTab( authDb, user, pwd, authMechanismFromStr(authMechanism) ); // Set SSL Tab if(mongoUri.getSSLMode() == mongo::transport::ConnectSSLMode::kEnableSSL) { auto tlsAllowInvalidCertificates = mongoUri.getOption("tlsAllowInvalidCertificates"); int const authMethodIndex = tlsAllowInvalidCertificates.get_value_or("") == "true" ? 0 : 1; auto const caFile = mongoUri.getOption("tlsCAFile").get_value_or(""); auto const certKeyFile = mongoUri.getOption("tlsCertificateKeyFile").get_value_or(""); auto const certKeyFilePwd = mongoUri.getOption("tlsCertificateKeyFilePassword").get_value_or(""); auto const allowInvalidHostnames = mongoUri.getOption("tlsAllowInvalidHostnames").get_value_or("") == "true"; _connectionDialog->setSslTab( authMethodIndex, allowInvalidHostnames, caFile, certKeyFile, certKeyFilePwd ); } // Advanced Tab _connectionDialog->setDefaultDb(QString::fromStdString(mongoUri.getDatabase())); } }
17,148
C++
.cpp
356
37.873596
125
0.604117
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
14,714
CreateCollectionDialog.cpp
Studio3T_robomongo/src/robomongo/gui/dialogs/CreateCollectionDialog.cpp
#include "robomongo/gui/dialogs/CreateCollectionDialog.h" #include <mongo/bson/bsonobjbuilder.h> #include <QApplication> #include <QCheckBox> #include <QComboBox> #include <QDialogButtonBox> #include <QHBoxLayout> #include <QLineEdit> #include <QLabel> #include <QMessageBox> #include <QPushButton> #include <QSettings> #include <Qsci/qscilexerjavascript.h> #include <Qsci/qsciscintilla.h> #include <QVBoxLayout> #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/editors/FindFrame.h" #include "robomongo/gui/editors/JSLexer.h" #include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include "robomongo/shell/bson/json.h" namespace Robomongo { enum { OPTIONS_TAB = 0, STORAGE_ENGINE_TAB = 1, VALIDATOR_TAB = 2, INDEX_OPTION_DEFAULTS_TAB = 3, }; const QString CreateCollectionDialog::STORAGE_ENGINE_TAB_HINT = "Option available for WiredTiger storage engine only and database version 3.0 and higher."; const QString CreateCollectionDialog::VALIDATOR_TAB_HINT = "Option available for database version 3.2 and higher."; const QString CreateCollectionDialog::INDEX_OPTION_DEFAULTS_TAB_HINT = "Option available for database version 3.2 and higher."; const QString CreateCollectionDialog::NO_PADDING_HINT = "Option available for MMAPv1 storage engine only and database version 3.0 and higher."; const QString CreateCollectionDialog::USE_POWEROFTWO_HINT = "Option available for MMAPv1 storage engine only and deprecated since database version 3.0"; const QString CreateCollectionDialog::AUTO_INDEXID_HINT = "Option deprecated since database version 3.2"; CreateCollectionDialog::CreateCollectionDialog(const QString &serverName, const float dbVersion, const std::string& storageEngine, const QString &database, const QString &collection, QWidget *parent) : QDialog(parent), _dbVersion(dbVersion), _storageEngine(storageEngine), _activeFrame(nullptr), _activeObj(&_storageEngineObj) { setWindowTitle(tr("Create Collection")); setMinimumSize(300,150); Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), serverName); QFrame *hline = new QFrame(); hline->setFrameShape(QFrame::HLine); hline->setFrameShadow(QFrame::Sunken); _inputEdit = new QLineEdit(); _inputLabel = new QLabel(tr("Collection Name:")); _inputEdit->setMaxLength(60); _buttonBox = new QDialogButtonBox(this); _buttonBox->setOrientation(Qt::Horizontal); _buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); _buttonBox->button(QDialogButtonBox::Save)->setText(tr("C&reate")); _buttonBox->button(QDialogButtonBox::Save)->setEnabled(false); VERIFY(connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); VERIFY(connect(_inputEdit, SIGNAL(textChanged(const QString &)), this, SLOT(enableCreateButton(const QString &)))); _validateJsonButton = new QPushButton(tr("Validate JSON")); _validateJsonButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation)); _validateJsonButton->hide(); VERIFY(connect(_validateJsonButton, SIGNAL(clicked()), this, SLOT(onValidateButtonClicked()))); // Create advanced options tabs _advancedOptions = new QTabWidget(this); _advancedOptions->addTab(createOptionsTab(), tr("Options")); _advancedOptions->addTab(createStorageEngineTab(), tr("Storage Engine")); _advancedOptions->addTab(createValidatorTab(), tr("Validator")); _advancedOptions->addTab(createIndexOptionDefaultsTab(), tr("Index Option Defaults")); _advancedOptions->setTabsClosable(false); VERIFY(connect(_advancedOptions, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)))); // Create Advanced Button _advancedButton = new QPushButton(tr("Advanced")); _advancedButton->setCheckable(true); VERIFY(connect(_advancedButton, SIGNAL(toggled(bool)), this, SLOT(onAdvancedButtonToggled(bool)))); // Check mongodb version and storage engine type to enable/disable UI options disableUnsupportedOptions(); QHBoxLayout *buttomHlayout = new QHBoxLayout(); buttomHlayout->addWidget(_validateJsonButton); buttomHlayout->addStretch(1); buttomHlayout->addWidget(_buttonBox); buttomHlayout->addWidget(_advancedButton); QHBoxLayout *vlayout = new QHBoxLayout(); if (!serverName.isEmpty()) vlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); if (!database.isEmpty()) vlayout->addWidget(createDatabaseIndicator(database), 0, Qt::AlignLeft); if (!collection.isEmpty()) vlayout->addWidget(createCollectionIndicator(collection), 0, Qt::AlignLeft); vlayout->addStretch(1); QVBoxLayout *namelayout = new QVBoxLayout(); namelayout->setContentsMargins(0, 7, 0, 7); namelayout->addWidget(_inputLabel); namelayout->addWidget(_inputEdit); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->addLayout(vlayout); mainLayout->addWidget(hline); mainLayout->addLayout(namelayout); mainLayout->addWidget(_advancedOptions); mainLayout->addLayout(buttomHlayout); mainLayout->setSizeConstraint(QLayout::SetMaximumSize); setLayout(mainLayout); _advancedOptions->hide(); _inputEdit->setFocus(); } const mongo::BSONObj CreateCollectionDialog::getExtraOptions() const { return _extraOptionsObj; } QString CreateCollectionDialog::getCollectionName() const { return _inputEdit->text(); } bool CreateCollectionDialog::isCapped() const { return (_cappedCheckBox->checkState() == Qt::Checked); } long long CreateCollectionDialog::getSizeInputValue() const { return (_sizeInputEdit->text().toLongLong()); } int CreateCollectionDialog::getMaxDocNumberInputValue() const { return (_maxDocNumberInputEdit->text().toInt()); } bool CreateCollectionDialog::isCheckedAutoIndexid() const { return (_autoIndexCheckBox->checkState() == Qt::Checked); } bool CreateCollectionDialog::isCheckedUsePowerOfTwo() const { return (_usePowerOfTwoSizeCheckBox->checkState() == Qt::Checked); } bool CreateCollectionDialog::isCheckedNoPadding() const { return (_noPaddingCheckBox->checkState() == Qt::Checked); } void CreateCollectionDialog::accept() { if ( _inputEdit->text().isEmpty() || !validateOptionDependencies() || !validate(_storageEngineFrame, _storageEngineObj) || !validate(_validatorFrame, _validatorObj) || !validate(_indexOptionDefaultsFrame, _indexOptionDefaultsObj)) { return; } makeExtraOptionsObj(); saveWindowSettings(); QDialog::accept(); } void CreateCollectionDialog::reject() { saveWindowSettings(); QDialog::reject(); } void CreateCollectionDialog::closeEvent(QCloseEvent *event) { if (_advancedOptions->isVisible()) { saveWindowSettings(); } QWidget::closeEvent(event); } void CreateCollectionDialog::onFrameTextChanged() { _activeFrame->sciScintilla()->clearIndicatorRange(0, 0, _activeFrame->sciScintilla()->lines(), 40, 0); } void CreateCollectionDialog::onValidateButtonClicked() { validate(_activeFrame, *_activeObj, false); } void CreateCollectionDialog::enableCreateButton(const QString &text) { _buttonBox->button(QDialogButtonBox::Save)->setEnabled(!text.isEmpty()); } void CreateCollectionDialog::onCappedCheckBoxChanged(int newState) { _sizeInputEdit->setEnabled((Qt::Checked == static_cast<Qt::CheckState>(newState))); _maxDocNumberInputEdit->setEnabled((Qt::Checked == static_cast<Qt::CheckState>(newState))); } void CreateCollectionDialog::onTabChanged(int index) { if (OPTIONS_TAB == index) { _validateJsonButton->hide(); } else { _validateJsonButton->show(); if (STORAGE_ENGINE_TAB == index) { _activeFrame = _storageEngineFrame; _activeObj = &_storageEngineObj; } else if (VALIDATOR_TAB == index) { _activeFrame = _validatorFrame; _activeObj = &_validatorObj; } else if (INDEX_OPTION_DEFAULTS_TAB == index) { _activeFrame = _indexOptionDefaultsFrame; _activeObj = &_indexOptionDefaultsObj; } } }; void CreateCollectionDialog::onAdvancedButtonToggled(bool state) { _advancedOptions->setVisible(state); if (state) // resize, dialog is expanding { setMinimumSize(560, 440); _validateJsonButton->setHidden(_advancedOptions->currentIndex() == OPTIONS_TAB); QSettings settings("3T", "Robomongo"); if (settings.contains("CreateCollectionDialog/size")) { restoreWindowSettings(); } else { resize(560, 440); adjustSize(); } } else // resize, dialog is shrinking { saveWindowSettings(); // save expanded geometry first _validateJsonButton->hide(); setFixedSize(300, 150); adjustSize(); } } Indicator *CreateCollectionDialog::createDatabaseIndicator(const QString &database) { return new Indicator(GuiRegistry::instance().databaseIcon(), database); } Indicator *CreateCollectionDialog::createCollectionIndicator(const QString &collection) { return new Indicator(GuiRegistry::instance().collectionIcon(), collection); } QWidget* CreateCollectionDialog::createOptionsTab() { QWidget *optionsTab = new QWidget(this); _cappedCheckBox = new QCheckBox(tr("Create capped collection"), optionsTab); _sizeInputLabel = new QLabel(tr("Maximum size in bytes: ")); _sizeInputLabel->setContentsMargins(22, 0, 0, 0); _sizeInputEdit = new QLineEdit(); _sizeInputEdit->setEnabled(false); _maxDocNumberInputLabel = new QLabel(tr("Maximum number of documents: ")); _maxDocNumberInputLabel->setContentsMargins(22, 0, 0, 0); _maxDocNumberInputEdit = new QLineEdit(); _maxDocNumberInputEdit->setEnabled(false); _autoIndexCheckBox = new QCheckBox(tr("Auto index _id"), optionsTab); _autoIndexCheckBox->setChecked(true); _usePowerOfTwoSizeCheckBox = new QCheckBox(tr("Use power-of-2 sizes"), optionsTab); // Note: For mongodb 2.6 does not have storageEngine string due to the fact that it uses MMAPV1 only. if (MongoDatabase::StorageEngineType::MMAPV1 == _storageEngine || "" == _storageEngine) { _usePowerOfTwoSizeCheckBox->setChecked(true); } _noPaddingCheckBox = new QCheckBox(tr("No Padding"), optionsTab); VERIFY(connect(_cappedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(onCappedCheckBoxChanged(int)))); QGridLayout *layout = new QGridLayout; layout->addWidget(_cappedCheckBox, 0, 0, 1, 2); layout->addWidget(_sizeInputLabel, 1, 0); layout->addWidget(_sizeInputEdit, 1, 1); layout->addWidget(_maxDocNumberInputLabel, 2, 0); layout->addWidget(_maxDocNumberInputEdit, 2, 1); layout->addWidget(_autoIndexCheckBox, 3, 0); layout->addWidget(_usePowerOfTwoSizeCheckBox, 4, 0); layout->addWidget(_noPaddingCheckBox, 5, 0); layout->setAlignment(Qt::AlignTop); optionsTab->setLayout(layout); return optionsTab; } QWidget* CreateCollectionDialog::createStorageEngineTab() { QWidget *storageEngineTab = new QWidget(this); _storageEngineFrameLabel = new QLabel(tr("Enter the configuration for the storage engine: ")); _storageEngineFrame = new JSONFrame(this); configureFrameText(_storageEngineFrame); _storageEngineFrame->sciScintilla()->setText("{\n \n}"); // clear modification state after setting the content _storageEngineFrame->sciScintilla()->setModified(false); VERIFY(connect(_storageEngineFrame->sciScintilla(), SIGNAL(textChanged()), this, SLOT(onFrameTextChanged()))); QGridLayout *layout = new QGridLayout; layout->addWidget(_storageEngineFrameLabel, 0, 0); layout->addWidget(_storageEngineFrame, 1, 0); layout->setAlignment(Qt::AlignTop); storageEngineTab->setLayout(layout); return storageEngineTab; } QWidget* CreateCollectionDialog::createValidatorTab() { QWidget *validatorEngineTab = new QWidget(this); _validatorLevelLabel = new QLabel(tr("Validation Level: ")); _validatorLevelComboBox = new QComboBox(); _validatorLevelComboBox->addItem(tr("off")); _validatorLevelComboBox->addItem(tr("strict")); _validatorLevelComboBox->addItem(tr("moderate")); _validatorLevelComboBox->setCurrentIndex(1); _validatorActionLabel = new QLabel(tr("Validation Action: ")); _validatorActionComboBox = new QComboBox(); _validatorActionComboBox->addItem(tr("error")); _validatorActionComboBox->addItem(tr("warn")); _validatorActionComboBox->setCurrentIndex(0); _validatorFrameLabel = new QLabel(tr("Enter the validator document for this collection: ")); _validatorFrame = new JSONFrame(this); configureFrameText(_validatorFrame); _validatorFrame->sciScintilla()->setText("{\n \n}"); // clear modification state after setting the content _validatorFrame->sciScintilla()->setModified(false); VERIFY(connect(_validatorFrame->sciScintilla(), SIGNAL(textChanged()), this, SLOT(onFrameTextChanged()))); QHBoxLayout *validationOptionslayout = new QHBoxLayout(); validationOptionslayout->addWidget(_validatorLevelLabel); validationOptionslayout->addWidget(_validatorLevelComboBox, Qt::AlignLeft); validationOptionslayout->addWidget(_validatorActionLabel); validationOptionslayout->addWidget(_validatorActionComboBox, Qt::AlignLeft); QVBoxLayout *vlayout = new QVBoxLayout(); vlayout->addWidget(_validatorFrameLabel); vlayout->addWidget(_validatorFrame); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(validationOptionslayout); layout->addLayout(vlayout); validatorEngineTab->setLayout(layout); return validatorEngineTab; } QWidget* CreateCollectionDialog::createIndexOptionDefaultsTab() { QWidget *indexOptionDefaultsTab = new QWidget(this); _indexOptionDefaultsFrameLabel = new QLabel(tr("Enter a default configuration for indexes when creating a collection: ")); _indexOptionDefaultsFrame = new JSONFrame(this); configureFrameText(_indexOptionDefaultsFrame); _indexOptionDefaultsFrame->sciScintilla()->setText("{\n \n}"); // clear modification state after setting the content _indexOptionDefaultsFrame->sciScintilla()->setModified(false); VERIFY(connect(_indexOptionDefaultsFrame->sciScintilla(), SIGNAL(textChanged()), this, SLOT(onFrameTextChanged()))); QGridLayout *layout = new QGridLayout; layout->addWidget(_indexOptionDefaultsFrameLabel, 0, 0); layout->addWidget(_indexOptionDefaultsFrame, 1, 0); layout->setAlignment(Qt::AlignTop); indexOptionDefaultsTab->setLayout(layout); return indexOptionDefaultsTab; } void CreateCollectionDialog::saveWindowSettings() const { QSettings settings("3T", "Robomongo"); settings.setValue("CreateCollectionDialog/size", size()); } void CreateCollectionDialog::restoreWindowSettings() { QSettings settings("3T", "Robomongo"); resize(settings.value("CreateCollectionDialog/size").toSize()); } void CreateCollectionDialog::configureFrameText(JSONFrame* frame) { QsciLexerJavaScript *javaScriptLexer = new JSLexer(this); QFont font = GuiRegistry::instance().font(); javaScriptLexer->setFont(font); frame->sciScintilla()->setBraceMatching(QsciScintilla::StrictBraceMatch); frame->sciScintilla()->setFont(font); frame->sciScintilla()->setPaper(QColor(255, 0, 0, 127)); frame->sciScintilla()->setLexer(javaScriptLexer); frame->sciScintilla()->setWrapMode((QsciScintilla::WrapMode)QsciScintilla::SC_WRAP_WORD); frame->sciScintilla()->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); frame->sciScintilla()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); frame->sciScintilla()->setStyleSheet("QFrame { background-color: rgb(73, 76, 78); border: 1px solid #c7c5c4; border-radius: 4px; margin: 0px; padding: 0px;}"); } bool CreateCollectionDialog::validate(JSONFrame* frame, mongo::BSONObj& bsonObj, bool silentOnSuccess /* = true */) { try { bsonObj = mongo::Robomongo::fromjson(jsonText(frame).toStdString()); } catch (const mongo::Robomongo::ParseMsgAssertionException &ex) { // v0.9 QString message = QtUtils::toQString(ex.reason()); int offset = ex.offset(); int line = 0, pos = 0; frame->sciScintilla()->lineIndexFromPosition(offset, &line, &pos); frame->sciScintilla()->setCursorPosition(line, pos); int lineHeight = frame->sciScintilla()->lineLength(line); frame->sciScintilla()->fillIndicatorRange(line, pos, line, lineHeight, 0); message = QString(tr("Unable to parse JSON:<br /> <b>%1</b>, at (%2, %3).")) .arg(message).arg(line + 1).arg(pos + 1); QMessageBox::critical(NULL, tr("Parsing error"), message); frame->setFocus(); activateWindow(); return false; } if (!silentOnSuccess) { QMessageBox::information(NULL, tr("Validation"), tr("JSON is valid!")); frame->setFocus(); activateWindow(); } return true; } void CreateCollectionDialog::makeExtraOptionsObj() { mongo::BSONObjBuilder builder; if (_autoIndexCheckBox->isEnabled()) builder.append("autoIndexId", isCheckedAutoIndexid()); if (_noPaddingCheckBox->isEnabled() && _usePowerOfTwoSizeCheckBox->isEnabled()) { builder.append("flags", (isCheckedNoPadding()*2 + isCheckedUsePowerOfTwo()*1)); } else if (_noPaddingCheckBox->isEnabled()) { builder.append("flags", (isCheckedNoPadding()*2)); } else if (_usePowerOfTwoSizeCheckBox->isEnabled()) { builder.append("flags", (isCheckedUsePowerOfTwo()*1)); } if (_advancedOptions->isTabEnabled(STORAGE_ENGINE_TAB) ) { validate(_storageEngineFrame, _storageEngineObj); if(!_storageEngineObj.isEmpty()) builder.append("storageEngine", _storageEngineObj); } if (_advancedOptions->isTabEnabled(VALIDATOR_TAB)) { validate(_validatorFrame, _validatorObj); if (!_validatorObj.isEmpty()) { builder.append("validator", _validatorObj); builder.append("validationLevel", _validatorLevelComboBox->currentText().toStdString()); builder.append("validationAction", _validatorActionComboBox->currentText().toStdString()); } } if (_advancedOptions->isTabEnabled(INDEX_OPTION_DEFAULTS_TAB)) { validate(_indexOptionDefaultsFrame, _indexOptionDefaultsObj); if (!_indexOptionDefaultsObj.isEmpty()) builder.append("indexOptionDefaults", _indexOptionDefaultsObj); } // Complete and get resulting BSONObj _extraOptionsObj = builder.obj(); } bool CreateCollectionDialog::validateOptionDependencies() const { bool result(false); // Validate capped options if (isCapped()) { if (!(getSizeInputValue() > 0)) { QMessageBox::critical(NULL, tr("Error"), tr("Maximum size is required for capped collections")); return false; } result = true; } else { result = true; } // Completed checking all dependendencies. return result; } void CreateCollectionDialog::disableUnsupportedOptions() const { // Handle WIRED_TIGER engine type if (MongoDatabase::StorageEngineType::WIRED_TIGER == _storageEngine) { disableOption(_usePowerOfTwoSizeCheckBox, USE_POWEROFTWO_HINT); disableOption(_noPaddingCheckBox, NO_PADDING_HINT); if (MongoDatabase::DBVersion::MONGODB_3_0 > _dbVersion) { disableTab(STORAGE_ENGINE_TAB, STORAGE_ENGINE_TAB_HINT); } } else { disableTab(STORAGE_ENGINE_TAB, STORAGE_ENGINE_TAB_HINT); } // Handle MMAPV1 engine type // Note: For mongodb 2.6 does not have storageEngine string due to the fact that it uses MMAPV1 only. if (MongoDatabase::StorageEngineType::MMAPV1 == _storageEngine || "" == _storageEngine) { if (MongoDatabase::DBVersion::MONGODB_3_0 < _dbVersion) { _usePowerOfTwoSizeCheckBox->hide(); } if (MongoDatabase::DBVersion::MONGODB_3_0 > _dbVersion) { disableOption(_noPaddingCheckBox, NO_PADDING_HINT); } } if (MongoDatabase::DBVersion::MONGODB_3_2 < _dbVersion) { disableOption(_autoIndexCheckBox, AUTO_INDEXID_HINT); } if (MongoDatabase::DBVersion::MONGODB_3_0 > _dbVersion) { disableTab(STORAGE_ENGINE_TAB, STORAGE_ENGINE_TAB_HINT); } if (MongoDatabase::DBVersion::MONGODB_3_2 > _dbVersion) { disableTab(VALIDATOR_TAB, VALIDATOR_TAB_HINT); disableTab(INDEX_OPTION_DEFAULTS_TAB, INDEX_OPTION_DEFAULTS_TAB_HINT); } } void CreateCollectionDialog::disableOption(QWidget* option, const QString& hint) const { option->setDisabled(true); option->setToolTip(hint); } void CreateCollectionDialog::disableTab(int index, const QString& hint) const { _advancedOptions->setTabEnabled(index, false); _advancedOptions->setTabToolTip(index, hint); } void CreateCollectionDialog::setCursorPosition(int line, int column) { _activeFrame->sciScintilla()->setCursorPosition(line, column); } QString CreateCollectionDialog::jsonText(JSONFrame* frame) const { return frame->sciScintilla()->text().trimmed(); } }
23,526
C++
.cpp
500
38.232
167
0.663904
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,715
LogWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/LogWidget.cpp
#include "robomongo/gui/widgets/LogWidget.h" #include <QHBoxLayout> #include <QScrollBar> #include <QMenu> #include <QTime> #include <QAction> #include <QPlainTextEdit> #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { LogWidget::LogWidget(QWidget* parent) : BaseClass(parent), _logTextEdit(new QTextEdit(this)) { _logTextEdit->setReadOnly(true); _logTextEdit->setContextMenuPolicy(Qt::CustomContextMenu); VERIFY(connect(_logTextEdit, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint &)))); QHBoxLayout *hlayout = new QHBoxLayout; hlayout->setContentsMargins(0, 0, 0, 0); hlayout->addWidget(_logTextEdit); _clear = new QAction("Clear All", this); VERIFY(connect(_clear, SIGNAL(triggered()), _logTextEdit, SLOT(clear()))); setLayout(hlayout); } void LogWidget::showContextMenu(const QPoint &pt) { QMenu *menu = _logTextEdit->createStandardContextMenu(); menu->addAction(_clear); _clear->setEnabled(!_logTextEdit->toPlainText().isEmpty()); menu->exec(_logTextEdit->mapToGlobal(pt)); delete menu; } void LogWidget::addMessage(const QString &message, mongo::logger::LogSeverity level) { // Print time QTime time = QTime::currentTime(); _logTextEdit->moveCursor (QTextCursor::End); _logTextEdit->setTextColor(QColor("#aaaaaa")); _logTextEdit->insertPlainText(time.toString("h:mm:ss AP") + "\t"); // Print message _logTextEdit->moveCursor (QTextCursor::End); // Nice color for the future: "#CD9800" :) QColor textColor = QColor(Qt::black); if (level == mongo::logger::LogSeverity::Error()) textColor = QColor("#CD0000"); else if (level == mongo::logger::LogSeverity::Log()) textColor = QColor("#777777"); else if (level == mongo::logger::LogSeverity::Warning()) textColor = QColor("#CD9800"); _logTextEdit->setTextColor(textColor); const int maxLength = 500; if (message.length() <= maxLength) { _logTextEdit->insertPlainText(message.trimmed() + "\n"); } else { _logTextEdit->insertPlainText(QString("(truncated) ") + message.left(maxLength).trimmed() + "...\n"); } // Scroll to the bottom QScrollBar *sb = _logTextEdit->verticalScrollBar(); sb->setValue(sb->maximum()); } }
2,520
C++
.cpp
60
34.416667
134
0.639706
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,716
ExplorerServerTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerServerTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerServerTreeItem.h" #include <QAction> #include <QMenu> #include <QMessageBox> #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/ReplicaSetSettings.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/EventBus.h" #include "robomongo/core/utils/Logger.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerReplicaSetFolderItem.h" #include "robomongo/gui/widgets/explorer/ExplorerReplicaSetTreeItem.h" #include "robomongo/gui/dialogs/CreateDatabaseDialog.h" #include "robomongo/gui/GuiRegistry.h" namespace { void openCurrentServerShell(Robomongo::MongoServer *const server, const QString &script, bool execute = true, const Robomongo::CursorPosition &cursor = Robomongo::CursorPosition()) { QString const connName = Robomongo::QtUtils::toQString(server->connectionRecord()->getReadableName()); Robomongo::AppRegistry::instance().app()->openShell(server, script, std::string(), execute, connName, cursor); } } namespace Robomongo { ExplorerServerTreeItem::ExplorerServerTreeItem(QTreeWidget *view, MongoServer *const server, ConnectionInfo connInfo) : BaseClass(view), _server(server), _bus(AppRegistry::instance().bus()), _replicaSetFolder(nullptr), _primaryWasUnreachable(false), _systemFolder(nullptr) { auto openShellAction = new QAction("Open Shell", this); #ifdef __APPLE__ openShellAction->setIcon(GuiRegistry::instance().mongodbIconForMAC()); #else openShellAction->setIcon(GuiRegistry::instance().mongodbIcon()); #endif VERIFY(connect(openShellAction, SIGNAL(triggered()), SLOT(ui_openShell()))); QAction *refreshServer = new QAction("Refresh", this); VERIFY(connect(refreshServer, SIGNAL(triggered()), SLOT(ui_refreshServer()))); QAction *createDatabase = new QAction("Create Database", this); VERIFY(connect(createDatabase, SIGNAL(triggered()), SLOT(ui_createDatabase()))); QAction *serverStatus = new QAction("Server Status", this); VERIFY(connect(serverStatus, SIGNAL(triggered()), SLOT(ui_serverStatus()))); QAction *serverVersion = new QAction("MongoDB Version", this); VERIFY(connect(serverVersion, SIGNAL(triggered()), SLOT(ui_serverVersion()))); QAction *serverHostInfo = new QAction("Host Info", this); VERIFY(connect(serverHostInfo, SIGNAL(triggered()), SLOT(ui_serverHostInfo()))); QAction *showLog = new QAction("Show Log", this); VERIFY(connect(showLog, SIGNAL(triggered()), SLOT(ui_showLog()))); QAction *disconnectAction = new QAction("Disconnect", this); disconnectAction->setIconText("Disconnect"); VERIFY(connect(disconnectAction, SIGNAL(triggered()), SLOT(ui_disconnectServer()))); BaseClass::_contextMenu->addAction(openShellAction); BaseClass::_contextMenu->addAction(refreshServer); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(createDatabase); BaseClass::_contextMenu->addAction(serverStatus); BaseClass::_contextMenu->addAction(serverHostInfo); BaseClass::_contextMenu->addAction(serverVersion); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(showLog); BaseClass::_contextMenu->addAction(disconnectAction); _bus->subscribe(this, DatabaseListLoadedEvent::Type, _server); _bus->subscribe(this, MongoServerLoadingDatabasesEvent::Type, _server); _bus->subscribe(this, ReplicaSetFolderRefreshed::Type, _server); _bus->subscribe(this, ConnectionEstablishedEvent::Type, _server); _bus->subscribe(this, ConnectionFailedEvent::Type, _server); setText(0, buildServerName()); setIcon(0, _server->connectionRecord()->isReplicaSet() ? GuiRegistry::instance().replicaSetIcon() : GuiRegistry::instance().serverIcon()); setExpanded(true); setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); if (_server->connectionRecord()->isReplicaSet()) { buildReplicaSetFolder(false); buildDatabaseItems(); } } void ExplorerServerTreeItem::expand() { if (_server->connectionRecord()->isReplicaSet()) { // do nothing since replica set refresh/reload can take very long times. } else { // single server _server->loadDatabases(); } } void ExplorerServerTreeItem::disableSomeContextMenuActions(bool disable) { if (BaseClass::_contextMenu->actions().size() < 10 || !_server->connectionRecord()->isReplicaSet()) return; // [1]:Refresh and [9]:Disconnect are always enabled BaseClass::_contextMenu->actions().at(0)->setDisabled(disable); BaseClass::_contextMenu->actions().at(2)->setDisabled(disable); BaseClass::_contextMenu->actions().at(3)->setDisabled(disable); BaseClass::_contextMenu->actions().at(4)->setDisabled(disable); BaseClass::_contextMenu->actions().at(5)->setDisabled(disable); BaseClass::_contextMenu->actions().at(6)->setDisabled(disable); BaseClass::_contextMenu->actions().at(8)->setDisabled(disable); } void ExplorerServerTreeItem::databaseRefreshed(const QList<MongoDatabase *> &dbs) { int count = dbs.count(); setText(0, buildServerName(&count)); // Delete system folder and database items QtUtils::clearChildItems(this); // Add 'System' folder QIcon folderIcon = GuiRegistry::instance().folderIcon(); _systemFolder = new ExplorerTreeItem(this); _systemFolder->setIcon(0, folderIcon); _systemFolder->setText(0, "System"); addChild(_systemFolder); for (int i = 0; i < dbs.size(); i++) { MongoDatabase *database = dbs.at(i); if (database->isSystem()) { auto dbItem = new ExplorerDatabaseTreeItem(_systemFolder, database); _systemFolder->addChild(dbItem); continue; } auto dbItem = new ExplorerDatabaseTreeItem(this, database); addChild(dbItem); } // Show 'System' folder only if it has items _systemFolder->setHidden(_systemFolder->childCount() == 0); } void ExplorerServerTreeItem::handle(DatabaseListLoadedEvent *event) { if (event->isError()) { setText(0, buildServerName(0)); // Restore normal name (without "...") if (!_server->connectionRecord()->isReplicaSet()) setExpanded(false); // Collapse // We should clear all child items, but we are not // doing this, because of incorrect "senders" for messages // that are going to Worker thread. Yes, some guy specified UI objects // as senders. If we delete these UI objects, response will crash the app // (because QObject::thread() is used to get thread of the QObject) // QtUtils::clearChildItems(this); std::stringstream ss; ss << "Cannot load list of databases.\n\nError:\n" << event->error().errorMessage(); QMessageBox::information(NULL, "Error", QtUtils::toQString(ss.str())); return; } databaseRefreshed(event->list); } void ExplorerServerTreeItem::handle(MongoServerLoadingDatabasesEvent *event) { int count = -1; setText(0, buildServerName(&count)); } void ExplorerServerTreeItem::handle(ReplicaSetFolderRefreshed *event) { buildReplicaSetFolder(event->expanded); // Rebuild replica set folder in any case // ---Primary is unreachable if (event->isError()) { replicaSetPrimaryUnreachable(); disableSomeContextMenuActions(true); if (event->error().showErrorWindow()) { std::string const errorStr = "Replica set's primary is unreachable.\n\nReason:\n" "Connection failure. " + event->error().errorMessage(); QMessageBox::critical(nullptr, "Error", QString::fromStdString(errorStr)); } return; } // --- Primary is reachable if (_primaryWasUnreachable) // Rebuild db items only when primary was unreachable previously. _server->loadDatabases(); replicaSetPrimaryReachable(); } void ExplorerServerTreeItem::handle(ConnectionEstablishedEvent *event) { if (!_server->connectionRecord()->isReplicaSet() || ConnectionType::ConnectionRefresh != event->connectionType) return; if (_primaryWasUnreachable) replicaSetPrimaryReachable(); setIcon(0, GuiRegistry::instance().replicaSetIcon()); buildReplicaSetServerItem(); } void ExplorerServerTreeItem::handle(ConnectionFailedEvent *event) { if (!_server->connectionRecord()->isReplicaSet() || ConnectionType::ConnectionRefresh != event->connectionType) return; buildReplicaSetFolder(true); replicaSetPrimaryUnreachable(); QMessageBox::critical(nullptr, "Error", QString::fromStdString(event->message)); } QString ExplorerServerTreeItem::buildServerName(int *count /* = NULL */, bool online /* = true*/) { QString name = QtUtils::toQString(_server->connectionRecord()->getReadableName()); if (!count) return name; if (*count == -1) return name + " ..."; return online ? QString("%1 (%2)").arg(name).arg(*count) : QString("%1").arg(name) + " [Offline]"; } void ExplorerServerTreeItem::ui_serverHostInfo() { openCurrentServerShell(_server, "db.hostInfo()"); } void ExplorerServerTreeItem::ui_serverStatus() { openCurrentServerShell(_server, "db.serverStatus()"); } void ExplorerServerTreeItem::ui_serverVersion() { openCurrentServerShell(_server, "db.version()"); } void ExplorerServerTreeItem::ui_showLog() { openCurrentServerShell(_server, "show log"); } void ExplorerServerTreeItem::ui_openShell() { openCurrentServerShell(_server, ""); } void ExplorerServerTreeItem::ui_disconnectServer() { auto *view = dynamic_cast<QTreeWidget *>(BaseClass::treeWidget()); if (!view) return; int index = view->indexOfTopLevelItem(this); if (index == -1) return; QTreeWidgetItem *removedItem = view->takeTopLevelItem(index); if (!removedItem) return; AppRegistry::instance().app()->closeServer(_server); delete removedItem; } void ExplorerServerTreeItem::ui_refreshServer() { if (_server->connectionRecord()->isReplicaSet()) { int count = -1; setText(0, buildServerName(&count)); // Append "..." into root item text _server->tryRefreshReplicaSetConnection(); } else { // single server expand(); } } void ExplorerServerTreeItem::ui_createDatabase() { CreateDatabaseDialog dlg(QString::fromStdString(_server->connectionRecord()->getFullAddress()), QString(), QString(), treeWidget()); dlg.setOkButtonText("&Create"); dlg.setInputLabelText("Database Name:"); if (dlg.exec() == QDialog::Accepted) { if (_server->connectionRecord()->isReplicaSet()) { // Replica Set auto newDb = new MongoDatabase(_server, dlg.databaseName().toStdString()); _server->addDatabase(newDb); int dbCount = _server->databases().count(); setText(0, buildServerName(&dbCount)); auto dbItem = new ExplorerDatabaseTreeItem(this, newDb); addChild(dbItem); LOG_MSG("Database \'" + newDb->name() + "\' created.", mongo::logger::LogSeverity::Info()); } else { // single server _server->createDatabase(QtUtils::toStdStringSafe(dlg.databaseName())); } } } void ExplorerServerTreeItem::buildReplicaSetServerItem() { // Delete all children (replica set folder, system folder and database items) QtUtils::clearChildItems(this); _replicaSetFolder = nullptr; buildReplicaSetFolder(false); buildDatabaseItems(); } void ExplorerServerTreeItem::buildReplicaSetFolder(bool expanded) { if (_replicaSetFolder) { // delete and rebuild existing folder child items if (_replicaSetFolder->childCount() > 0) QtUtils::clearChildItems(_replicaSetFolder); _replicaSetFolder->updateText(); } else { // build folder from scratch _replicaSetFolder = new ExplorerReplicaSetFolderItem(this, _server); addChild(_replicaSetFolder); } // Add replica set members bool isPrimary; for (auto const& memberAndHealth : _server->replicaSetInfo()->membersAndHealths) { isPrimary = _server->replicaSetInfo()->primary.toString() == memberAndHealth.first; auto const& hostAndPort = mongo::HostAndPort(mongo::StringData(memberAndHealth.first)); _replicaSetFolder->addChild(new ExplorerReplicaSetTreeItem(_replicaSetFolder, _server, hostAndPort, isPrimary, memberAndHealth.second)); } _replicaSetFolder->setRefreshFlag(false); _replicaSetFolder->setExpanded(expanded); _replicaSetFolder->setRefreshFlag(true); } void ExplorerServerTreeItem::buildDatabaseItems() { int dbCount = _server->databases().count(); setText(0, buildServerName(&dbCount)); // Add 'System' folder _systemFolder = new ExplorerTreeItem(this); _systemFolder->setIcon(0, GuiRegistry::instance().folderIcon()); _systemFolder->setText(0, "System"); addChild(_systemFolder); for (auto const& database : _server->databases()) { if (database->isSystem()) { auto dbItem = new ExplorerDatabaseTreeItem(_systemFolder, database); _systemFolder->addChild(dbItem); continue; } auto dbItem = new ExplorerDatabaseTreeItem(this, database); addChild(dbItem); } // Show 'System' folder only if it has items _systemFolder->setHidden(_systemFolder->childCount() == 0); } void ExplorerServerTreeItem::replicaSetPrimaryReachable() { _primaryWasUnreachable = false; disableSomeContextMenuActions(false); _replicaSetFolder->disableSomeContextMenuActions(); } void ExplorerServerTreeItem::replicaSetPrimaryUnreachable() { _primaryWasUnreachable = true; disableSomeContextMenuActions(true); _replicaSetFolder->disableSomeContextMenuActions(); int dbCount = 0; setText(0, buildServerName(&dbCount, false)); setIcon(0, GuiRegistry::instance().replicaSetOfflineIcon()); // For system folder and database items - delete children then set disable QtUtils::clearChildItems(_systemFolder); _systemFolder->setDisabled(true); for (int i = 0; i < childCount(); ++i) { auto dbItem = dynamic_cast<ExplorerDatabaseTreeItem*>(child(i)); if (dbItem) { QtUtils::clearChildItems(dbItem); dbItem->setDisabled(true); } } } }
16,249
C++
.cpp
347
37.164265
121
0.639737
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,717
ExplorerCollectionIndexItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerCollectionIndexItem.cpp
#include "ExplorerCollectionIndexItem.h" #include <QAction> #include <QMenu> #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/DialogUtils.h" #include "robomongo/gui/widgets/explorer/AddEditIndexDialog.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionIndexesDir.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" namespace Robomongo { ExplorerCollectionIndexItem::ExplorerCollectionIndexItem( ExplorerCollectionIndexesDir *parent, const IndexInfo &info) : BaseClass(parent), _info(info) { auto dropIndex = new QAction("Drop Index...", this); connect(dropIndex, SIGNAL(triggered()), SLOT(ui_dropIndex())); auto editIndex = new QAction("Edit Index...", this); connect(editIndex, SIGNAL(triggered()), SLOT(ui_edit())); BaseClass::_contextMenu->addAction(editIndex); BaseClass::_contextMenu->addAction(dropIndex); setText(0, QtUtils::toQString(_info._name)); setIcon(0, Robomongo::GuiRegistry::instance().indexIcon()); } void ExplorerCollectionIndexItem::ui_dropIndex() { // Ask user auto const answer = utils::questionDialog(treeWidget(), "Drop", "Index", text(0)); if (answer != QMessageBox::Yes) return; auto const par = dynamic_cast<ExplorerCollectionIndexesDir *>(parent()); if (!par) return; auto const grandParent = dynamic_cast<ExplorerCollectionTreeItem *>(par->parent()); if (!grandParent) return; grandParent->dropIndex(this); } void ExplorerCollectionIndexItem::ui_edit() { auto const par = dynamic_cast<ExplorerCollectionIndexesDir *>(parent()); if (par) { auto const grPar = dynamic_cast<ExplorerCollectionTreeItem *const>(par->parent()); if (!grPar) return; auto const& db { grPar->databaseItem()->database() }; AddEditIndexDialog dlg { _info, QtUtils::toQString(db->name()), QtUtils::toQString(db->server()->connectionRecord()->getFullAddress()), false, treeWidget() }; auto const result = dlg.exec(); if (result != QDialog::Accepted) return; auto const databaseTreeItem = dynamic_cast<ExplorerDatabaseTreeItem *>(grPar->databaseItem()); if (!databaseTreeItem) return; databaseTreeItem->addEditIndex(grPar, _info, dlg.info()); } } }
2,770
C++
.cpp
65
33.738462
106
0.645173
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,718
ExplorerUserTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerUserTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerUserTreeItem.h" #include <QAction> #include <QMenu> #include "robomongo/gui/dialogs/CreateUserDialog.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/DialogUtils.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { ExplorerUserTreeItem::ExplorerUserTreeItem( QTreeWidgetItem *parent, MongoDatabase *const database, const MongoUser &user) : BaseClass(parent), _user(user), _database(database) { auto const dropUser { new QAction("Drop User", this) }; VERIFY(connect(dropUser, SIGNAL(triggered()), SLOT(ui_dropUser()))); auto const viewUser { new QAction("View User", this) }; VERIFY(connect(viewUser, SIGNAL(triggered()), SLOT(ui_viewUser()))); BaseClass::_contextMenu->addAction(viewUser); BaseClass::_contextMenu->addAction(dropUser); setText(0, QtUtils::toQString(_user.name())); setIcon(0, GuiRegistry::instance().userIcon()); setExpanded(false); } void ExplorerUserTreeItem::ui_dropUser() { // Ask user int const answer { utils::questionDialog( treeWidget(), "Drop", "User", QtUtils::toQString(_user.name()) ) }; if (answer == QMessageBox::Yes) _database->dropUser(_user.name()); } void ExplorerUserTreeItem::ui_viewUser() { auto const& app { Robomongo::AppRegistry::instance().app() }; app->openShell( _database, QString::fromStdString("db.getUser(\"" + _user.name() + "\")"), true, QtUtils::toQString(_database->name()), CursorPosition() ); } }
1,935
C++
.cpp
48
33.75
92
0.665956
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,719
ExplorerTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerTreeItem.h" #include <QMenu> #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { ExplorerTreeItem::ExplorerTreeItem(QTreeWidgetItem *parent) :QObject(), BaseClass(parent), _contextMenu(new QMenu(treeWidget()) ) { } ExplorerTreeItem::ExplorerTreeItem(QTreeWidget *view) :QObject(view), BaseClass(view), _contextMenu(new QMenu(view) ) { } void ExplorerTreeItem::showContextMenuAtPos(const QPoint &pos) { _contextMenu->exec(pos); } ExplorerTreeItem::~ExplorerTreeItem() { _contextMenu->deleteLater(); QtUtils::clearChildItems(this); } }
691
C++
.cpp
23
24.869565
77
0.70303
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,720
ExplorerCollectionIndexesDir.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerCollectionIndexesDir.cpp
#include "ExplorerCollectionIndexesDir.h" #include <QAction> #include <QMenu> #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/widgets/explorer/AddEditIndexDialog.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" namespace Robomongo { ExplorerCollectionIndexesDir::ExplorerCollectionIndexesDir(QTreeWidgetItem *parent) :BaseClass(parent) { QAction *addIndex = new QAction("Add Index...", this); VERIFY(connect(addIndex, SIGNAL(triggered()), SLOT(ui_addIndex()))); QAction *reIndex = new QAction("Rebuild Indexes...", this); VERIFY(connect(reIndex, SIGNAL(triggered()), SLOT(ui_reIndex()))); QAction *viewIndex = new QAction("View Indexes", this); VERIFY(connect(viewIndex, SIGNAL(triggered()), SLOT(ui_viewIndex()))); QAction *refreshIndex = new QAction("Refresh", this); VERIFY(connect(refreshIndex, SIGNAL(triggered()), SLOT(ui_refreshIndex()))); BaseClass::_contextMenu->addAction(viewIndex); BaseClass::_contextMenu->addAction(addIndex); BaseClass::_contextMenu->addAction(reIndex); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(refreshIndex); setText(0, "Indexes"); setIcon(0, Robomongo::GuiRegistry::instance().folderIcon()); setExpanded(false); setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } void ExplorerCollectionIndexesDir::expand() { auto const par = dynamic_cast<ExplorerCollectionTreeItem *>(parent()); if (!par) return; par->expand(); } void ExplorerCollectionIndexesDir::ui_viewIndex() { auto const par = dynamic_cast<ExplorerCollectionTreeItem *>(parent()); if (par) par->openCurrentCollectionShell("getIndexes()"); } void ExplorerCollectionIndexesDir::ui_refreshIndex() { auto const par = dynamic_cast<ExplorerCollectionTreeItem *>(parent()); if (par) par->expand(); } void ExplorerCollectionIndexesDir::ui_addIndex() { auto par = dynamic_cast<ExplorerCollectionTreeItem *const>(parent()); if (!par) return; IndexInfo const fakeInfo(par->collection()->info(), ""); auto const& db { par->databaseItem()->database() }; AddEditIndexDialog dlg { fakeInfo, QtUtils::toQString(db->name()), QtUtils::toQString(db->server()->connectionRecord()->getFullAddress()), true, treeWidget() }; auto const result = dlg.exec(); if (result != QDialog::Accepted) return; auto const databaseTreeItem = dynamic_cast<ExplorerDatabaseTreeItem *>(par->databaseItem()); if (!databaseTreeItem) return; databaseTreeItem->addEditIndex(par, fakeInfo, dlg.info()); } void ExplorerCollectionIndexesDir::ui_reIndex() { auto const par = dynamic_cast<ExplorerCollectionTreeItem *>(parent()); if (par) par->openCurrentCollectionShell("reIndex()", false); } }
3,324
C++
.cpp
80
33.725
100
0.66181
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,721
ExplorerFunctionTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerFunctionTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerFunctionTreeItem.h" #include <QAction> #include <QMenu> #include "robomongo/gui/dialogs/FunctionTextEditor.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/DialogUtils.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { ExplorerFunctionTreeItem::ExplorerFunctionTreeItem(QTreeWidgetItem *parent, MongoDatabase *database, const MongoFunction &function) : BaseClass(parent), _function(function), _database(database) { QAction *dropFunction = new QAction("Remove Function", this); VERIFY(connect(dropFunction, SIGNAL(triggered()), SLOT(ui_dropFunction()))); QAction *editFunction = new QAction("Edit Function", this); VERIFY(connect(editFunction, SIGNAL(triggered()), SLOT(ui_editFunction()))); BaseClass::_contextMenu->addAction(editFunction); BaseClass::_contextMenu->addAction(dropFunction); setText(0, QtUtils::toQString(_function.name())); setIcon(0, GuiRegistry::instance().functionIcon()); setToolTip(0, buildToolTip(_function)); setExpanded(false); } QString ExplorerFunctionTreeItem::buildToolTip(const MongoFunction &function) { return QString("%0").arg(QtUtils::toQString(function.name())); } void ExplorerFunctionTreeItem::ui_editFunction() { std::string name = _function.name(); FunctionTextEditor dlg(QString::fromStdString(_database->server()->connectionRecord()->getFullAddress()), QString::fromStdString(_database->name()), _function); dlg.setWindowTitle("Edit Function"); if (dlg.exec() == QDialog::Accepted) { MongoFunction editedFunction = dlg.function(); _database->updateFunction(name, editedFunction); } } void ExplorerFunctionTreeItem::ui_dropFunction() { // Ask user int answer = utils::questionDialog(treeWidget(), "Drop", "Function", QtUtils::toQString(_function.name())); if (answer != QMessageBox::Yes) return; _database->dropFunction(_function.name()); } }
2,393
C++
.cpp
53
37.169811
115
0.676129
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,722
ExplorerReplicaSetTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerReplicaSetTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerReplicaSetTreeItem.h" #include <QAction> #include <QMenu> #include <QMessageBox> #include <QString> #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/ReplicaSetSettings.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/EventBus.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/dialogs/CreateDatabaseDialog.h" #include "robomongo/gui/GuiRegistry.h" namespace { void openCurrentServerShell(Robomongo::MongoServer* server, Robomongo::ConnectionSettings* connSettings, const QString &script) { auto const scriptStr = Robomongo::ScriptInfo(script, true); Robomongo::AppRegistry::instance().app()->openShell(server, connSettings, scriptStr); } } namespace Robomongo { ExplorerReplicaSetTreeItem::ExplorerReplicaSetTreeItem(QTreeWidgetItem *parent, MongoServer *const server, const mongo::HostAndPort& repMemberHostAndPort, const bool isPrimary, const bool isUp) : BaseClass(parent), _repMemberHostAndPort(repMemberHostAndPort), _isPrimary(isPrimary), _isUp(isUp), _server(server), _connSettings(server->connectionRecord()->clone()), _bus(AppRegistry::instance().bus()) { // Set connection settings of this replica member _connSettings->setConnectionName(_repMemberHostAndPort.toString() + " [member of " + _connSettings->connectionName() + "]"); _connSettings->setServerHost(_repMemberHostAndPort.host()); _connSettings->setServerPort(_repMemberHostAndPort.port()); _connSettings->setReplicaSet(false); _connSettings->replicaSetSettings()->deleteAllMembers(); // Add Actions auto openShellAction = new QAction("Open Shell", this); #ifdef __APPLE__ openShellAction->setIcon(GuiRegistry::instance().mongodbIconForMAC()); #else openShellAction->setIcon(GuiRegistry::instance().mongodbIcon()); #endif VERIFY(connect(openShellAction, SIGNAL(triggered()), SLOT(ui_openShell()))); auto openDirectConnection = new QAction("Open Direct Connection", this); VERIFY(connect(openDirectConnection, SIGNAL(triggered()), SLOT(ui_openDirectConnection()))); auto serverStatus = new QAction("Server Status", this); VERIFY(connect(serverStatus, SIGNAL(triggered()), SLOT(ui_serverStatus()))); auto serverVersion = new QAction("MongoDB Version", this); VERIFY(connect(serverVersion, SIGNAL(triggered()), SLOT(ui_serverVersion()))); auto serverHostInfo = new QAction("Host Info", this); VERIFY(connect(serverHostInfo, SIGNAL(triggered()), SLOT(ui_serverHostInfo()))); auto showLog = new QAction("Show Log", this); VERIFY(connect(showLog, SIGNAL(triggered()), SLOT(ui_showLog()))); BaseClass::_contextMenu->addAction(openShellAction); BaseClass::_contextMenu->addAction(openDirectConnection); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(serverStatus); BaseClass::_contextMenu->addAction(serverHostInfo); BaseClass::_contextMenu->addAction(serverVersion); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(showLog); updateTextAndIcon(_isUp, _isPrimary); setExpanded(true); setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator); } void ExplorerReplicaSetTreeItem::updateTextAndIcon(bool isUp, bool isPrimary) { _isUp = isUp; _isPrimary = isPrimary; QString stateStr("[Unknown]"); if (_isUp) stateStr = _isPrimary ? "[Primary]" : "[Secondary]"; else stateStr = "[Not Reachable]"; setDisabled(_isUp ? false : true); setText(0, QString::fromStdString(_repMemberHostAndPort.toString()) + " " + stateStr); setIcon(0, _isPrimary ? GuiRegistry::instance().serverPrimaryIcon() : GuiRegistry::instance().serverSecondaryIcon()); } void ExplorerReplicaSetTreeItem::ui_serverHostInfo() { openCurrentServerShell(_server, _connSettings.get(), "db.hostInfo()"); } void ExplorerReplicaSetTreeItem::ui_serverStatus() { openCurrentServerShell(_server, _connSettings.get(), "db.serverStatus()"); } void ExplorerReplicaSetTreeItem::ui_serverVersion() { openCurrentServerShell(_server, _connSettings.get(), "db.version()"); } void ExplorerReplicaSetTreeItem::ui_showLog() { openCurrentServerShell(_server, _connSettings.get(), "show log"); } void ExplorerReplicaSetTreeItem::ui_openShell() { openCurrentServerShell(_server, _connSettings.get(), ""); } void ExplorerReplicaSetTreeItem::ui_openDirectConnection() { AppRegistry::instance().app()->openServer(_connSettings.get(), ConnectionPrimary); } }
5,268
C++
.cpp
113
39.20354
132
0.692128
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,723
ExplorerDatabaseTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include <QMessageBox> #include <QAction> #include <QMenu> #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/MongoCollection.h" #include "robomongo/core/domain/MongoUser.h" #include "robomongo/core/domain/MongoFunction.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/mongodb/MongoWorker.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/EventBus.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseCategoryTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerUserTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerFunctionTreeItem.h" #include "robomongo/gui/GuiRegistry.h" namespace { void openCurrentDatabaseShell(Robomongo::MongoDatabase *database, const QString &script, bool execute = true, const Robomongo::CursorPosition &cursor = Robomongo::CursorPosition()) { Robomongo::AppRegistry::instance().app()->openShell(database, script, execute, Robomongo::QtUtils::toQString(database->name()), cursor); } } namespace Robomongo { namespace detail { QString buildName(const QString& text, int count) { if (count == -1) return QString("%1 ...").arg(text); return QString("%1 (%2)").arg(text).arg(count); } } ExplorerDatabaseTreeItem::ExplorerDatabaseTreeItem(QTreeWidgetItem *parent, MongoDatabase *const database) : BaseClass(parent), _database(database), _bus(AppRegistry::instance().bus()), _collectionSystemFolderItem(NULL) { auto openDbShellAction = new QAction("Open Shell", this); #ifdef __APPLE__ openDbShellAction->setIcon(GuiRegistry::instance().mongodbIconForMAC()); #else openDbShellAction->setIcon(GuiRegistry::instance().mongodbIcon()); #endif VERIFY(connect(openDbShellAction, SIGNAL(triggered()), SLOT(ui_dbOpenShell()))); QAction *dbStats = new QAction("Database Statistics", this); VERIFY(connect(dbStats, SIGNAL(triggered()), SLOT(ui_dbStatistics()))); QAction *dbCurrOps = new QAction("Current Operations", this); VERIFY(connect(dbCurrOps, SIGNAL(triggered()), SLOT(ui_dbCurrentOps()))); QAction *dbKillOp = new QAction("Kill Operation...", this); VERIFY(connect(dbKillOp, SIGNAL(triggered()), SLOT(ui_dbKillOp()))); QAction *dbDrop = new QAction("Drop Database...", this); VERIFY(connect(dbDrop, SIGNAL(triggered()), SLOT(ui_dbDrop()))); QAction *dbRepair = new QAction("Repair Database...", this); VERIFY(connect(dbRepair, SIGNAL(triggered()), SLOT(ui_dbRepair()))); QAction *refreshDatabase = new QAction("Refresh", this); VERIFY(connect(refreshDatabase, SIGNAL(triggered()), SLOT(ui_refreshDatabase()))); BaseClass::_contextMenu->addAction(openDbShellAction); BaseClass::_contextMenu->addAction(refreshDatabase); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(dbStats); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(dbCurrOps); BaseClass::_contextMenu->addAction(dbKillOp); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(dbRepair); BaseClass::_contextMenu->addAction(dbDrop); _bus->subscribe(this, MongoDatabaseCollectionListLoadedEvent::Type, _database); _bus->subscribe(this, MongoDatabaseUsersLoadedEvent::Type, _database); _bus->subscribe(this, MongoDatabaseFunctionsLoadedEvent::Type, _database); _bus->subscribe(this, MongoDatabaseCollectionsLoadingEvent::Type, _database); _bus->subscribe(this, MongoDatabaseFunctionsLoadingEvent::Type, _database); _bus->subscribe(this, MongoDatabaseUsersLoadingEvent::Type, _database); setText(0, QtUtils::toQString(_database->name())); setIcon(0, GuiRegistry::instance().databaseIcon()); setExpanded(false); setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); _collectionFolderItem = new ExplorerDatabaseCategoryTreeItem(this, Collections); _collectionFolderItem->setText(0, "Collections"); _collectionFolderItem->setIcon(0, GuiRegistry::instance().folderIcon()); addChild(_collectionFolderItem); _functionsFolderItem = new ExplorerDatabaseCategoryTreeItem(this, Functions); _functionsFolderItem->setText(0, "Functions"); _functionsFolderItem->setIcon(0, GuiRegistry::instance().folderIcon()); addChild(_functionsFolderItem); _usersFolderItem = new ExplorerDatabaseCategoryTreeItem(this, Users); _usersFolderItem->setText(0, "Users"); _usersFolderItem->setIcon(0, GuiRegistry::instance().folderIcon()); addChild(_usersFolderItem); setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicatorWhenChildless); } void ExplorerDatabaseTreeItem::expandCollections() { _database->loadCollections(); } void ExplorerDatabaseTreeItem::expandUsers() { _database->loadUsers(); } void ExplorerDatabaseTreeItem::expandColection(ExplorerCollectionTreeItem *const item) { _bus->send(_database->server()->worker(), new LoadCollectionIndexesRequest(item, item->collection()->info())); } void ExplorerDatabaseTreeItem::dropIndexFromCollection(ExplorerCollectionTreeItem *const item, const std::string &indexName) { _bus->send(_database->server()->worker(), new DropCollectionIndexRequest(item, item->collection()->info(), indexName)); } void ExplorerDatabaseTreeItem::addEditIndex( ExplorerCollectionTreeItem *const item, const IndexInfo &oldInfo, const IndexInfo &newInfo) const { _bus->send(_database->server()->worker(), new AddEditIndexRequest(item, oldInfo, newInfo)); } void ExplorerDatabaseTreeItem::expandFunctions() { _database->loadFunctions(); } void ExplorerDatabaseTreeItem::handle(MongoDatabaseCollectionListLoadedEvent *event) { if (event->isError()) { _collectionFolderItem->setText(0, "Collections"); _collectionFolderItem->setExpanded(false); return; } std::vector<MongoCollection *> collections = event->collections; int count = collections.size(); _collectionFolderItem->setText(0, detail::buildName("Collections", count)); QtUtils::clearChildItems(_collectionFolderItem); // Do not expand, when we do not have collections if (count == 0) { _collectionFolderItem->setExpanded(false); return; } _collectionSystemFolderItem = new ExplorerTreeItem(_collectionFolderItem); _collectionSystemFolderItem->setIcon(0, GuiRegistry::instance().folderIcon()); _collectionSystemFolderItem->setText(0, "System"); _collectionFolderItem->addChild(_collectionSystemFolderItem); for (int i = 0; i < collections.size(); ++i) { MongoCollection *collection = collections[i]; if (collection->isSystem()) { addSystemCollectionItem(collection); } else { addCollectionItem(collection); } } showCollectionSystemFolderIfNeeded(); } void ExplorerDatabaseTreeItem::handle(MongoDatabaseUsersLoadedEvent *event) { if (event->isError()) { _usersFolderItem->setText(0, "Users"); _usersFolderItem->setExpanded(false); return; } auto const& users = event->users(); _usersFolderItem->setText(0, detail::buildName("Users", users.size())); // Do not expand, when we do not have any users if (users.size() == 0) _usersFolderItem->setExpanded(false); QtUtils::clearChildItems(_usersFolderItem); for(auto const& user : users) addUserItem(event->database(), user); } void ExplorerDatabaseTreeItem::handle(MongoDatabaseFunctionsLoadedEvent *event) { if (event->isError()) { _functionsFolderItem->setText(0, "Functions"); _functionsFolderItem->setExpanded(false); return; } std::vector<MongoFunction> functions = event->functions(); int count = functions.size(); _functionsFolderItem->setText(0, detail::buildName("Functions", count)); // Do not expand, when we do not have functions if (count == 0) _functionsFolderItem->setExpanded(false); QtUtils::clearChildItems(_functionsFolderItem); for (int i = 0; i < functions.size(); ++i) { MongoFunction fun = functions[i]; addFunctionItem(event->database(), fun); } } void ExplorerDatabaseTreeItem::handle(MongoDatabaseCollectionsLoadingEvent *event) { _collectionFolderItem->setText(0, detail::buildName("Collections", -1)); } void ExplorerDatabaseTreeItem::handle(MongoDatabaseFunctionsLoadingEvent *event) { _functionsFolderItem->setText(0, detail::buildName("Functions", -1)); } void ExplorerDatabaseTreeItem::handle(MongoDatabaseUsersLoadingEvent *event) { _usersFolderItem->setText(0, detail::buildName("Users", -1)); } void ExplorerDatabaseTreeItem::addCollectionItem(MongoCollection *collection) { auto collectionItem = new ExplorerCollectionTreeItem(_collectionFolderItem, this, collection); collectionItem->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicatorWhenChildless); _collectionFolderItem->addChild(collectionItem); } void ExplorerDatabaseTreeItem::addSystemCollectionItem(MongoCollection *collection) { auto collectionItem = new ExplorerCollectionTreeItem(_collectionSystemFolderItem, this, collection); collectionItem->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicatorWhenChildless); _collectionSystemFolderItem->addChild(collectionItem); } void ExplorerDatabaseTreeItem::showCollectionSystemFolderIfNeeded() { _collectionSystemFolderItem->setHidden(_collectionSystemFolderItem->childCount() == 0); } void ExplorerDatabaseTreeItem::addUserItem(MongoDatabase *database, const MongoUser &user) { ExplorerUserTreeItem *userItem = new ExplorerUserTreeItem(_usersFolderItem, database, user); _usersFolderItem->addChild(userItem); } void ExplorerDatabaseTreeItem::addFunctionItem(MongoDatabase *database, const MongoFunction &function) { ExplorerFunctionTreeItem *functionItem = new ExplorerFunctionTreeItem(_functionsFolderItem, database, function); _functionsFolderItem->addChild(functionItem); } void ExplorerDatabaseTreeItem::ui_refreshDatabase() { expandCollections(); } void ExplorerDatabaseTreeItem::ui_dbStatistics() { openCurrentDatabaseShell(_database, "db.stats()"); } void ExplorerDatabaseTreeItem::ui_dbCurrentOps() { openCurrentDatabaseShell(_database, "db.currentOp()"); } void ExplorerDatabaseTreeItem::ui_dbKillOp() { openCurrentDatabaseShell(_database, "db.killOp()", false, CursorPosition(0, -1)); } void ExplorerDatabaseTreeItem::ui_dbDrop() { auto const& buff = QString("Drop <b>%1</b> database?").arg(QtUtils::toQString(_database->name())); int const answer = QMessageBox::question(treeWidget(), "Drop Database", buff, QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton); if (answer != QMessageBox::Yes) return; _database->server()->dropDatabase(_database->name()); } void ExplorerDatabaseTreeItem::ui_dbRepair() { auto const& buff = QString("Repair <b>%1</b> database?").arg(QtUtils::toQString(_database->name())); int const answer = QMessageBox::question(treeWidget(), "Repair Database", buff, QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton); if (answer != QMessageBox::Yes) return; openCurrentDatabaseShell(_database, "db.repairDatabase()", false); } void ExplorerDatabaseTreeItem::ui_dbOpenShell() { openCurrentDatabaseShell(_database, ""); } }
12,700
C++
.cpp
259
40.698842
128
0.687222
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,724
ExplorerDatabaseCategoryTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerDatabaseCategoryTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerDatabaseCategoryTreeItem.h" #include <QAction> #include <QMenu> #include "robomongo/gui/dialogs/FunctionTextEditor.h" #include "robomongo/gui/dialogs/CreateUserDialog.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/dialogs/CreateCollectionDialog.h" #include "robomongo/gui/dialogs/CreateDatabaseDialog.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { void openDatabaseShell(MongoDatabase *database, const QString &script, bool execute = true, const CursorPosition &cursor = CursorPosition()) { AppRegistry::instance().app()->openShell(database, script, execute, QtUtils::toQString(database->name()), cursor); } ExplorerDatabaseCategoryTreeItem::ExplorerDatabaseCategoryTreeItem( ExplorerDatabaseTreeItem *databaseItem, ExplorerDatabaseCategory category) : BaseClass(databaseItem), _category(category) { if (_category == Collections) { QAction *createCollection = new QAction("Create Collection...", this); VERIFY(connect(createCollection, SIGNAL(triggered()), SLOT(ui_createCollection()))); QAction *dbCollectionsStats = new QAction("Collections Statistics", this); VERIFY(connect(dbCollectionsStats, SIGNAL(triggered()), SLOT(ui_dbCollectionsStatistics()))); QAction *refreshCollections = new QAction("Refresh", this); VERIFY(connect(refreshCollections, SIGNAL(triggered()), SLOT(ui_refreshCollections()))); BaseClass::_contextMenu->addAction(dbCollectionsStats); BaseClass::_contextMenu->addAction(createCollection); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(refreshCollections); } else if (_category == Users) { QAction *refreshUsers = new QAction("Refresh", this); VERIFY(connect(refreshUsers, SIGNAL(triggered()), SLOT(ui_refreshUsers()))); QAction *viewUsers = new QAction("View Users", this); VERIFY(connect(viewUsers, SIGNAL(triggered()), SLOT(ui_viewUsers()))); QAction *addUser = new QAction("Add User...", this); VERIFY(connect(addUser, SIGNAL(triggered()), SLOT(ui_addUser()))); BaseClass::_contextMenu->addAction(viewUsers); BaseClass::_contextMenu->addAction(addUser); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(refreshUsers); } else if (_category == Functions) { QAction *refreshFunctions = new QAction("Refresh", this); VERIFY(connect(refreshFunctions, SIGNAL(triggered()), SLOT(ui_refreshFunctions()))); QAction *viewFunctions = new QAction("View Functions", this); VERIFY(connect(viewFunctions, SIGNAL(triggered()), SLOT(ui_viewFunctions()))); QAction *addFunction = new QAction("Add Function...", this); VERIFY(connect(addFunction, SIGNAL(triggered()), SLOT(ui_addFunction()))); BaseClass::_contextMenu->addAction(viewFunctions); BaseClass::_contextMenu->addAction(addFunction); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(refreshFunctions); } setExpanded(false); setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } void ExplorerDatabaseCategoryTreeItem::expand() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (!databaseItem) return; switch(_category) { case Collections: databaseItem->expandCollections(); break; case Files: break; case Functions: databaseItem->expandFunctions(); break; case Users: databaseItem->expandUsers(); break; } } ExplorerDatabaseTreeItem *ExplorerDatabaseCategoryTreeItem::databaseItem() const { return static_cast<ExplorerDatabaseTreeItem*>(parent()); } void ExplorerDatabaseCategoryTreeItem::ui_dbCollectionsStatistics() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (databaseItem) { openDatabaseShell(databaseItem->database(), "db.printCollectionStats()"); } } void ExplorerDatabaseCategoryTreeItem::ui_refreshUsers() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (databaseItem) { databaseItem->expandUsers(); } } void ExplorerDatabaseCategoryTreeItem::ui_refreshFunctions() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (databaseItem) { databaseItem->expandFunctions(); } } void ExplorerDatabaseCategoryTreeItem::ui_viewUsers() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (databaseItem) { openDatabaseShell(databaseItem->database(), "db.getUsers()"); } } void ExplorerDatabaseCategoryTreeItem::ui_viewFunctions() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (databaseItem) { openDatabaseShell(databaseItem->database(), "db.system.js.find()"); } } void ExplorerDatabaseCategoryTreeItem::ui_createCollection() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (!databaseItem) return; const float dbVersion = databaseItem->database()->server()->version(); const std::string& engineName = databaseItem->database()->server()->getStorageEngineType(); const QString& serverName = QtUtils::toQString(databaseItem->database()->server()->connectionRecord()->getFullAddress()); const QString& dbName = QtUtils::toQString(databaseItem->database()->name()); CreateCollectionDialog dlg(serverName, dbVersion, engineName, dbName, QString(), treeWidget()); int result = dlg.exec(); if (result != QDialog::Accepted) return; std::string collectionName = QtUtils::toStdString(dlg.getCollectionName()); databaseItem->database()->createCollection(collectionName, dlg.getSizeInputValue(), dlg.isCapped(), dlg.getMaxDocNumberInputValue(), dlg.getExtraOptions()); } void ExplorerDatabaseCategoryTreeItem::ui_addUser() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (!databaseItem) return; std::unique_ptr<CreateUserDialog> dlg = nullptr; float const version = databaseItem->database()->server()->version(); if (version < MongoUser::minimumSupportedVersion) { dlg.reset(new CreateUserDialog( QtUtils::toQString(databaseItem->database()->server()->connectionRecord()->getFullAddress()), QtUtils::toQString(databaseItem->database()->name()), MongoUser(version), treeWidget())); } else { dlg.reset(new CreateUserDialog(databaseItem->database()->server()->getDatabasesNames(), QtUtils::toQString(databaseItem->database()->server()->connectionRecord()->getFullAddress()), QtUtils::toQString(databaseItem->database()->name()), MongoUser(version), treeWidget())); } if (dlg->exec() != QDialog::Accepted) return; MongoUser user = dlg->user(); databaseItem->database()->createUser(user); } void ExplorerDatabaseCategoryTreeItem::ui_addFunction() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (!databaseItem) return; FunctionTextEditor dlg( QtUtils::toQString(databaseItem->database()->server()->connectionRecord()->getFullAddress()), QtUtils::toQString(databaseItem->database()->name()), MongoFunction()); dlg.setWindowTitle("Create Function"); dlg.setCode( "function() {\n" " // write your code here\n" "}"); if (dlg.exec() != QDialog::Accepted) return; MongoFunction function = dlg.function(); databaseItem->database()->createFunction(function); } void ExplorerDatabaseCategoryTreeItem::ui_refreshCollections() { ExplorerDatabaseTreeItem *databaseItem = ExplorerDatabaseCategoryTreeItem::databaseItem(); if (databaseItem) databaseItem->expandCollections(); } }
9,139
C++
.cpp
187
39.550802
129
0.672772
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,725
ExplorerCollectionTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include <QAction> #include <QMenu> #include "robomongo/gui/widgets/explorer/AddEditIndexDialog.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionIndexesDir.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionIndexItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/dialogs/CreateDatabaseDialog.h" #include "robomongo/gui/dialogs/CopyCollectionDialog.h" #include "robomongo/gui/dialogs/DocumentTextEditor.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/utils/DialogUtils.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/domain/MongoCollection.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/utils/Logger.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/EventBus.h" namespace { const char *tooltipTemplate = "%s " "<table>" "<tr><td>Count:</td> <td><b>&nbsp;&nbsp;%lld</b></td></tr>" "<tr><td>Size:</td><td><b>&nbsp;&nbsp;%s</b></td></tr>" "</table>" ; } namespace Robomongo { R_REGISTER_EVENT(CollectionIndexesLoadingEvent) ExplorerCollectionTreeItem::ExplorerCollectionTreeItem( QTreeWidgetItem *parent, ExplorerDatabaseTreeItem *databaseItem, MongoCollection *collection) : BaseClass(parent), _collection(collection), _databaseItem(databaseItem) { QAction *addDocument = new QAction("Insert Document...", this); VERIFY(connect(addDocument, SIGNAL(triggered()), SLOT(ui_addDocument()))); QAction *updateDocument = new QAction("Update Documents...", this); VERIFY(connect(updateDocument, SIGNAL(triggered()), SLOT(ui_updateDocument()))); QAction *removeDocument = new QAction("Remove Documents...", this); VERIFY(connect(removeDocument, SIGNAL(triggered()), SLOT(ui_removeDocument()))); QAction *removeAllDocuments = new QAction("Remove All Documents...", this); VERIFY(connect(removeAllDocuments, SIGNAL(triggered()), SLOT(ui_removeAllDocuments()))); QAction *collectionStats = new QAction("Statistics", this); VERIFY(connect(collectionStats, SIGNAL(triggered()), SLOT(ui_collectionStatistics()))); QAction *storageSize = new QAction("Storage Size", this); VERIFY(connect(storageSize, SIGNAL(triggered()), SLOT(ui_storageSize()))); QAction *totalIndexSize = new QAction("Total Index Size", this); VERIFY(connect(totalIndexSize, SIGNAL(triggered()), SLOT(ui_totalIndexSize()))); QAction *totalSize = new QAction("Total Size", this); VERIFY(connect(totalSize, SIGNAL(triggered()), SLOT(ui_totalSize()))); QAction *shardVersion = new QAction("Shard Version", this); VERIFY(connect(shardVersion, SIGNAL(triggered()), SLOT(ui_shardVersion()))); QAction *shardDistribution = new QAction("Shard Distribution", this); VERIFY(connect(shardDistribution, SIGNAL(triggered()), SLOT(ui_shardDistribution()))); QAction *dropCollection = new QAction("Drop Collection...", this); VERIFY(connect(dropCollection, SIGNAL(triggered()), SLOT(ui_dropCollection()))); QAction *renameCollection = new QAction("Rename Collection...", this); VERIFY(connect(renameCollection, SIGNAL(triggered()), SLOT(ui_renameCollection()))); QAction *duplicateCollection = new QAction("Duplicate Collection...", this); VERIFY(connect(duplicateCollection, SIGNAL(triggered()), SLOT(ui_duplicateCollection()))); // Disabling for 0.8.5 release as this is currently a broken misfeature (see discussion on issue #398) // QAction *copyCollectionToDiffrentServer = new QAction("Copy Collection to Database...", this); // VERIFY(connect(copyCollectionToDiffrentServer, SIGNAL(triggered()), SLOT(ui_copyToCollectionToDiffrentServer()))); QAction *viewCollection = new QAction("View Documents", this); VERIFY(connect(viewCollection, SIGNAL(triggered()), SLOT(ui_viewCollection()))); BaseClass::_contextMenu->addAction(viewCollection); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(addDocument); BaseClass::_contextMenu->addAction(updateDocument); BaseClass::_contextMenu->addAction(removeDocument); BaseClass::_contextMenu->addAction(removeAllDocuments); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(renameCollection); BaseClass::_contextMenu->addAction(duplicateCollection); // Disabling for 0.8.5 release as this is currently a broken misfeature (see discussion on issue #398) // BaseClass::_contextMenu->addAction(copyCollectionToDiffrentServer); BaseClass::_contextMenu->addAction(dropCollection); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(collectionStats); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(shardVersion); BaseClass::_contextMenu->addAction(shardDistribution); AppRegistry::instance().bus()->subscribe(_databaseItem, LoadCollectionIndexesResponse::Type, this); AppRegistry::instance().bus()->subscribe(_databaseItem, AddEditIndexResponse::Type, this); AppRegistry::instance().bus()->subscribe(_databaseItem, DropCollectionIndexResponse::Type, this); AppRegistry::instance().bus()->subscribe(this, CollectionIndexesLoadingEvent::Type, this); setText(0, QtUtils::toQString(_collection->name())); setIcon(0, GuiRegistry::instance().collectionIcon()); _indexDir = new ExplorerCollectionIndexesDir(this); addChild(_indexDir); setExpanded(false); setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } void ExplorerCollectionTreeItem::handle(LoadCollectionIndexesResponse *event) { if (event->isError()) { _indexDir->setText(0, "Indexes"); _indexDir->setExpanded(false); QtUtils::clearChildItems(_indexDir); std::stringstream ss; ss << "Cannot load list of indexes.\n\nError:\n" << event->error().errorMessage(); QMessageBox::information(NULL, "Error", QtUtils::toQString(ss.str())); return; } QtUtils::clearChildItems(_indexDir); const std::vector<IndexInfo> &indexes = event->indexes(); // Do not expand, when we do not have functions if (indexes.size() == 0) _indexDir->setExpanded(false); for (std::vector<IndexInfo>::const_iterator it = indexes.begin(); it != indexes.end(); ++it) { _indexDir->addChild(new ExplorerCollectionIndexItem(_indexDir, *it)); } _indexDir->setText(0, detail::buildName("Indexes", _indexDir->childCount())); } void ExplorerCollectionTreeItem::handle(AddEditIndexResponse *event) { bool const isAddIndex{ event->oldIndex_._name.empty() }; QString const action{ isAddIndex ? "add" : "edit" }; auto const index{ QString::fromStdString( isAddIndex ? event->newIndex_._name : event->oldIndex_._name )}; if (event->isError()) { QString const header{ "Operation failed" }; QString const msg{ "Failed to " + action + " index \"" + index + '\"'}; auto const err{ QString::fromStdString(event->error().errorMessage()) }; LOG_MSG((msg + ". " + err).toStdString(), mongo::logger::LogSeverity::Error()); QMessageBox::critical(nullptr, "Error: " + header, msg + "\n\n" + err); return; } LOG_MSG(("Succeeded to " + action + " index \"" + index + '\"').toStdString(), mongo::logger::LogSeverity::Info()); } void ExplorerCollectionTreeItem::handle(DropCollectionIndexResponse *event) { if (event->isError()) { QString const header{"Operation failed"}; QString const msg{ "Failed to drop index \"" + QString::fromStdString(event->index()) + '\"' }; auto const err{ "Reason: " + QString::fromStdString(event->error().errorMessage()) }; LOG_MSG((msg + ". " + err).toStdString(), mongo::logger::LogSeverity::Error()); QMessageBox::critical(nullptr, "Error: " + header, msg + "\n\n" + err); return; } for (int i = 0; i < _indexDir->childCount(); ++i) { QTreeWidgetItem *item = _indexDir->child(i); if (item->text(0) == QString::fromStdString(event->index())) { removeChild(item); delete item; break; } } LOG_MSG("Succeeded to drop index \"" + event->index() + '\"', mongo::logger::LogSeverity::Info()); _indexDir->setText(0, detail::buildName("Indexes", _indexDir->childCount())); } void ExplorerCollectionTreeItem::handle(CollectionIndexesLoadingEvent *event) { _indexDir->setText(0, detail::buildName("Indexes", -1)); } void ExplorerCollectionTreeItem::expand() { AppRegistry::instance().bus()->publish(new CollectionIndexesLoadingEvent(this)); if (_databaseItem) { _databaseItem->expandColection(this); } } void ExplorerCollectionTreeItem::dropIndex(const QTreeWidgetItem * const ind) { if (!_databaseItem) return; _databaseItem->dropIndexFromCollection(this, QtUtils::toStdString(ind->text(0))); } QString ExplorerCollectionTreeItem::buildToolTip(MongoCollection *collection) { // This function does not used now char buff[2048] = {0}; // sprintf(buff,tooltipTemplate,collection->name().c_str(),collection->info().count(),collection->sizeString().c_str()); return buff; } void ExplorerCollectionTreeItem::ui_addDocument() { MongoDatabase *database = _collection->database(); MongoServer *server = database->server(); ConnectionSettings *settings = server->connectionRecord(); DocumentTextEditor editor(CollectionInfo(settings->getFullAddress(), database->name(), _collection->name()), "{\n \n}"); editor.setCursorPosition(1, 4); editor.setWindowTitle("Insert Document"); int result = editor.exec(); treeWidget()->activateWindow(); if (result == QDialog::Accepted) { server->insertDocuments(editor.bsonObj(), MongoNamespace(database->name(), _collection->name()) ); } } void ExplorerCollectionTreeItem::ui_removeDocument() { openCurrentCollectionShell( "remove({ '' : '' });" , false, CursorPosition(0, -10)); } void ExplorerCollectionTreeItem::ui_removeAllDocuments() { MongoDatabase *database = _collection->database(); // Ask user int answer = QMessageBox::question(treeWidget(), "Remove All Documents", QString("Remove all documents from <b>%1</b> collection?").arg(QtUtils::toQString(_collection->name())), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton); if (answer == QMessageBox::Yes) { MongoServer *server = database->server(); mongo::BSONObjBuilder builder; mongo::BSONObj bsonQuery = builder.obj(); mongo::Query query(bsonQuery); server->removeDocuments(query, MongoNamespace(database->name(), _collection->name()), RemoveDocumentCount::ALL); } } void ExplorerCollectionTreeItem::ui_updateDocument() { openCurrentCollectionShell( "update(\n" " // query \n" " {\n" " \"key\" : \"value\"\n" " },\n" " \n" " // update \n" " {\n" " },\n" " \n" " // options \n" " {\n" " \"multi\" : false, // update only one document \n" " \"upsert\" : false // insert a new document, if no existing document match the query \n" " }\n" ");", false); } void ExplorerCollectionTreeItem::ui_collectionStatistics() { openCurrentCollectionShell("stats()"); } void ExplorerCollectionTreeItem::ui_dropCollection() { // Ask user int answer = utils::questionDialog(treeWidget(), "Drop", "collection", QtUtils::toQString(_collection->name())); if (answer == QMessageBox::Yes) { MongoDatabase *database = _collection->database(); database->dropCollection(_collection->name()); } } void ExplorerCollectionTreeItem::ui_duplicateCollection() { MongoDatabase *database = _collection->database(); MongoServer *server = database->server(); ConnectionSettings *settings = server->connectionRecord(); CreateDatabaseDialog dlg(QtUtils::toQString(settings->getFullAddress()), QtUtils::toQString(database->name()), QtUtils::toQString(_collection->name()), treeWidget()); dlg.setWindowTitle("Duplicate Collection"); dlg.setOkButtonText("&Duplicate"); dlg.setInputLabelText("New Collection Name:"); dlg.setInputText(QtUtils::toQString(_collection->name() + "_copy")); int result = dlg.exec(); if (result == QDialog::Accepted) { database->duplicateCollection(_collection->name(), QtUtils::toStdString(dlg.databaseName())); } } void ExplorerCollectionTreeItem::ui_copyToCollectionToDiffrentServer() { MongoDatabase *databaseFrom = _collection->database(); MongoServer *server = databaseFrom->server(); ConnectionSettings *settings = server->connectionRecord(); CopyCollection dlg(QtUtils::toQString(settings->getFullAddress()), QtUtils::toQString(databaseFrom->name()), QtUtils::toQString(_collection->name()) ); int result = dlg.exec(); if (result == QDialog::Accepted) { MongoDatabase *databaseTo = dlg.selectedDatabase(); databaseTo->copyCollection(server, databaseFrom->name(), _collection->name()); databaseTo->loadCollections(); } } void ExplorerCollectionTreeItem::ui_renameCollection() { MongoDatabase *database = _collection->database(); MongoServer *server = database->server(); ConnectionSettings *connSettings = server->connectionRecord(); CreateDatabaseDialog dlg(QtUtils::toQString(connSettings->getFullAddress()), QtUtils::toQString(database->name()), QtUtils::toQString(_collection->name()), treeWidget()); dlg.setWindowTitle("Rename Collection"); dlg.setOkButtonText("&Rename"); dlg.setInputLabelText("New Collection Name:"); dlg.setInputText(QtUtils::toQString(_collection->name())); int result = dlg.exec(); if (result == QDialog::Accepted) { database->renameCollection(_collection->name(), QtUtils::toStdString(dlg.databaseName())); } } void ExplorerCollectionTreeItem::ui_viewCollection() { CursorPosition cp(0, -2); openCurrentCollectionShell("find({})", true, cp); } void ExplorerCollectionTreeItem::ui_storageSize() { openCurrentCollectionShell("storageSize()"); } void ExplorerCollectionTreeItem::ui_totalIndexSize() { openCurrentCollectionShell("totalIndexSize()"); } void ExplorerCollectionTreeItem::ui_totalSize() { openCurrentCollectionShell("totalSize()"); } void ExplorerCollectionTreeItem::ui_shardVersion() { openCurrentCollectionShell("getShardVersion()"); } void ExplorerCollectionTreeItem::ui_shardDistribution() { openCurrentCollectionShell("getShardDistribution()"); } void ExplorerCollectionTreeItem::openCurrentCollectionShell(const QString &script, bool execute, const CursorPosition &cursor) { QString query = detail::buildCollectionQuery(_collection->name(), script); AppRegistry::instance().app()->openShell(_collection->database(), query, execute, QtUtils::toQString(_collection->name()), cursor); } }
16,567
C++
.cpp
331
41.326284
159
0.650773
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,726
ExplorerTreeWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerTreeWidget.cpp
#include "robomongo/gui/widgets/explorer/ExplorerTreeWidget.h" #include "robomongo/gui/widgets/explorer/ExplorerTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerReplicaSetTreeItem.h" #include <QContextMenuEvent> #include <robomongo/gui/GuiRegistry.h> namespace Robomongo { ExplorerTreeWidget::ExplorerTreeWidget(QWidget *parent) : QTreeWidget(parent) { #if defined(Q_OS_MAC) setAttribute(Qt::WA_MacShowFocusRect, false); QPalette palet = palette(); palet.setColor(QPalette::Active, QPalette::Highlight, QColor(16, 108, 214)); setPalette(palet); #endif setContextMenuPolicy(Qt::DefaultContextMenu); setObjectName("explorerTree"); setIndentation(15); setHeaderHidden(true); setSelectionMode(QAbstractItemView::SingleSelection); setExpandsOnDoubleClick(false); } void ExplorerTreeWidget::contextMenuEvent(QContextMenuEvent *event) { QTreeWidgetItem *item = itemAt(event->pos()); // If the replica set item is not reachable, do not show context menu auto replicaSetItem = dynamic_cast<ExplorerReplicaSetTreeItem*>(item); if (replicaSetItem && !replicaSetItem->isUp()) return; // If the database set item is disabled, do not show context menu auto dbItem = dynamic_cast<ExplorerDatabaseTreeItem*>(item); if (dbItem && dbItem->isDisabled()) return; if (item) { auto explorerItem = dynamic_cast<ExplorerTreeItem *>(item); if (explorerItem) explorerItem->showContextMenuAtPos(mapToGlobal(event->pos())); } } }
1,746
C++
.cpp
41
35.170732
84
0.697991
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,727
ExplorerWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerWidget.cpp
#include "robomongo/gui/widgets/explorer/ExplorerWidget.h" #include <QHBoxLayout> #include <QLabel> #include <QMovie> #include <QKeyEvent> #include "robomongo/core/AppRegistry.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/MainWindow.h" #include "robomongo/gui/widgets/explorer/ExplorerTreeWidget.h" #include "robomongo/gui/widgets/explorer/ExplorerServerTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionIndexesDir.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseCategoryTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerReplicaSetTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerReplicaSetFolderItem.h" #include "robomongo/gui/widgets/explorer/ExplorerUserTreeItem.h" #include "robomongo/utils/common.h" namespace Robomongo { ExplorerWidget::ExplorerWidget(MainWindow *parentMainWindow) : BaseClass(parentMainWindow), _progress(0) { _treeWidget = new ExplorerTreeWidget(this); QHBoxLayout *vlaout = new QHBoxLayout(); vlaout->setMargin(0); vlaout->addWidget(_treeWidget, Qt::AlignJustify); VERIFY(connect(_treeWidget, SIGNAL(itemExpanded(QTreeWidgetItem *)), this, SLOT(ui_itemExpanded(QTreeWidgetItem *)))); VERIFY(connect(_treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(ui_itemDoubleClicked(QTreeWidgetItem *, int)))); setLayout(vlaout); QMovie *movie = new QMovie(":robomongo/icons/loading.gif", QByteArray(), this); _progressLabel = new QLabel(this); _progressLabel->setMovie(movie); _progressLabel->hide(); movie->start(); } ExplorerWidget::~ExplorerWidget() { saveSetting("ExplorerWidget/size", size()); } QTreeWidgetItem* ExplorerWidget::getSelectedTreeItem() const { return _treeWidget->currentItem(); } void ExplorerWidget::keyPressEvent(QKeyEvent *event) { if ((event->key() == Qt::Key_Return) || (event->key() == Qt::Key_Enter)) { QList<QTreeWidgetItem*> items = _treeWidget->selectedItems(); if (items.count() != 1) { BaseClass::keyPressEvent(event); return; } QTreeWidgetItem *item = items[0]; if (!item) { BaseClass::keyPressEvent(event); return; } ui_itemDoubleClicked(item, 0); return; } BaseClass::keyPressEvent(event); } QSize ExplorerWidget::sizeHint() const { auto size { getSetting("ExplorerWidget/size").toSize() }; if(QSize(-1, -1) == size) size = QSize(180, -1); return(size); } void ExplorerWidget::increaseProgress() { ++_progress; _progressLabel->move(width() / 2 - 8, height() / 2 - 8); _progressLabel->show(); } void ExplorerWidget::decreaseProgress() { --_progress; if (_progress < 0) _progress = 0; if (!_progress) _progressLabel->hide(); } void ExplorerWidget::handle(ConnectingEvent *event) { increaseProgress(); } void ExplorerWidget::handle(ConnectionEstablishedEvent *event) { // Do not make UI changes for non PRIMARY connections if (event->connectionType != ConnectionPrimary) return; decreaseProgress(); auto item = new ExplorerServerTreeItem(_treeWidget, event->server, event->connInfo); _treeWidget->addTopLevelItem(item); _treeWidget->setCurrentItem(item); _treeWidget->setFocus(); } void ExplorerWidget::handle(ConnectionFailedEvent *event) { decreaseProgress(); } void ExplorerWidget::ui_itemExpanded(QTreeWidgetItem *item) { auto categoryItem = dynamic_cast<ExplorerDatabaseCategoryTreeItem *>(item); if (categoryItem) { categoryItem->expand(); return; } auto serverItem = dynamic_cast<ExplorerServerTreeItem *>(item); if (serverItem) { serverItem->expand(); return; } auto replicaSetFolder = dynamic_cast<ExplorerReplicaSetFolderItem *>(item); if (replicaSetFolder) { replicaSetFolder->expand(); return; } auto dirItem = dynamic_cast<ExplorerCollectionIndexesDir *>(item); if (dirItem) { dirItem->expand(); } } void ExplorerWidget::ui_itemDoubleClicked(QTreeWidgetItem *item, int column) { if (auto collectionItem = dynamic_cast<ExplorerCollectionTreeItem *>(item)) { AppRegistry::instance().app()->openShell(collectionItem->collection()); return; } if (auto userItem = dynamic_cast<ExplorerUserTreeItem *>(item)) { userItem->ui_viewUser(); return; } auto replicaMemberItem = dynamic_cast<ExplorerReplicaSetTreeItem*>(item); if (replicaMemberItem && replicaMemberItem->isUp()) { AppRegistry::instance().app()->openShell(replicaMemberItem->server(), replicaMemberItem->connectionSettings(), ScriptInfo("", true)); return; } // Toggle expanded state item->setExpanded(!item->isExpanded()); } }
5,534
C++
.cpp
146
29.513699
126
0.639663
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,728
AddEditIndexDialog.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/AddEditIndexDialog.cpp
#include "robomongo/gui/widgets/explorer/AddEditIndexDialog.h" #include <QTabWidget> #include <QTabBar> #include <QVBoxLayout> #include <QHBoxLayout> #include <QDialogButtonBox> #include <QLineEdit> #include <QTextEdit> #include <QLabel> #include <QCheckBox> #include <QMessageBox> #include <Qsci/qsciscintilla.h> #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h" #include "robomongo/gui/widgets/explorer/ExplorerDatabaseTreeItem.h" #include "robomongo/gui/editors/JSLexer.h" #include "robomongo/gui/editors/FindFrame.h" #include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/domain/MongoCollection.h" #include "robomongo/core/utils/QtUtils.h" #include <robomongo/shell/bson/json.h> namespace { bool isValidJson(const QString &text) { bool result = false; if (!text.isEmpty()) { try { mongo::Robomongo::fromjson(text.toUtf8()); result = true; } catch (const std::exception &) { } } return result; } QLabel *createHelpLabel(const QString &text, int marginLeft = 0, int marginTop = 0, int marginRight = 0, int marginBottom = 0) { QLabel *helpLabel = new QLabel(text); helpLabel->setWordWrap(true); helpLabel->setContentsMargins(marginLeft, marginTop, marginRight, marginBottom); QPalette palette = helpLabel->palette(); palette.setColor(QPalette::WindowText, QColor(110, 110, 110)); helpLabel->setPalette(palette); return helpLabel; } Robomongo::FindFrame *createFindFrame(QWidget *parent = NULL, const QString &text = QString()) { const QFont &textFont = Robomongo::GuiRegistry::instance().font(); QsciLexerJavaScript *javaScriptLexer = new Robomongo::JSLexer(parent); javaScriptLexer->setFont(textFont); Robomongo::FindFrame *findFrame = new Robomongo::FindFrame(parent); findFrame->sciScintilla()->setLexer(javaScriptLexer); findFrame->sciScintilla()->setTabWidth(4); findFrame->sciScintilla()->setAppropriateBraceMatching(); findFrame->sciScintilla()->setFont(textFont); findFrame->sciScintilla()->setStyleSheet("QFrame {background-color: rgb(73, 76, 78); border: 1px solid #c7c5c4; border-radius: 4px; margin: 0px; padding: 0px;}"); findFrame->sciScintilla()->setText(text); findFrame->setMaximumHeight(120); return findFrame; } } namespace Robomongo { AddEditIndexDialog::AddEditIndexDialog( const IndexInfo &info, const QString &databaseName, const QString &serverAdress, bool const isAddIndex, QWidget *parent) : BaseClass(parent), _info(info), _isAddIndex(isAddIndex) { setWindowTitle("Index Properties"); Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), serverAdress); Indicator *collectionIndicator = new Indicator(GuiRegistry::instance().collectionIcon(), QtUtils::toQString(_info._collection.name())); Indicator *databaseIndicator = new Indicator(GuiRegistry::instance().databaseIcon(), databaseName); QHBoxLayout *hlayout = new QHBoxLayout; hlayout->setContentsMargins(2, 0, 5, 1); hlayout->setSpacing(0); hlayout->addWidget(serverIndicator, 0, Qt::AlignLeft); hlayout->addWidget(databaseIndicator, 0, Qt::AlignLeft); hlayout->addWidget(collectionIndicator, 0, Qt::AlignLeft); hlayout->addStretch(1); QTabWidget *mainTab = new QTabWidget(this); mainTab->addTab(createBasicTab(), tr("Basic")); mainTab->addTab(createAdvancedTab(), tr("Advanced")); mainTab->addTab(createTextSearchTab(), tr("Text Search")); mainTab->setTabsClosable(false); QDialogButtonBox *buttonBox = new QDialogButtonBox (this); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save); VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()))); VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()))); QVBoxLayout *vlayout = new QVBoxLayout; vlayout->addLayout(hlayout); vlayout->addSpacing(5); vlayout->addWidget(mainTab); vlayout->addWidget(buttonBox); setLayout(vlayout); _nameLineEdit->setFocus(); } QWidget* AddEditIndexDialog::createBasicTab() { QWidget *basicTab = new QWidget(this); _nameLineEdit = new QLineEdit(QtUtils::toQString(_info._name), basicTab); _nameLineEdit->setFocus(); _jsonText = createFindFrame(basicTab, QtUtils::toQString(_info._keys)); _uniqueCheckBox = new QCheckBox(tr("Unique")); _uniqueCheckBox->setChecked(_info._unique); QLabel *nameHelpLabel = createHelpLabel( "Choose any name that will help you to identify this index.", 0, -2, 0, 15); QLabel *keyHelpLabel = createHelpLabel( "Document that contains pairs with the name of the field or fields to index " "and order of the index. A 1 specifies ascending and a -1 specifies descending.", 0, -2, 0, 20); QLabel *uniqueHelpLabel = createHelpLabel( "If set, creates a unique index so that the collection will not accept insertion " "of documents where the index key or keys match an existing value in the index.", 20, -2, 0, 20); QGridLayout *layout = new QGridLayout; layout->addWidget(new QLabel("Name: "), 0, 0); layout->addWidget(_nameLineEdit, 0, 1); layout->addWidget(nameHelpLabel, 1, 1, Qt::AlignTop); layout->addWidget(new QLabel("Keys: "), 2, 0, Qt::AlignTop); layout->addWidget(_jsonText, 2, 1, Qt::AlignTop); layout->addWidget(keyHelpLabel, 3, 1, Qt::AlignTop); layout->addWidget(_uniqueCheckBox, 4, 0, 1, 2); layout->addWidget(uniqueHelpLabel, 5, 0, 1, 2, Qt::AlignTop); layout->setAlignment(Qt::AlignTop); basicTab->setLayout(layout); return basicTab; } void AddEditIndexDialog::expireStateChanged(int value) { _expireAfterLineEdit->setEnabled(value); if (!value) { _expireAfterLineEdit->setText(""); } } QWidget* AddEditIndexDialog::createAdvancedTab() { QWidget *advanced = new QWidget(this); _sparceCheckBox = new QCheckBox(tr("Sparse"), advanced); _sparceCheckBox->setChecked(_info._sparse); _backGroundCheckBox = new QCheckBox(tr("Create index in background"), advanced); _backGroundCheckBox->setChecked(_info._backGround); QHBoxLayout *expireLayout = new QHBoxLayout; _expireAfterLineEdit = new QLineEdit(advanced); _expireAfterLineEdit->setMaximumWidth(150); QRegExp rx("\\d+"); _expireAfterLineEdit->setValidator(new QRegExpValidator(rx, this)); QLabel *secLabel = new QLabel(tr("seconds"), advanced); expireLayout->addWidget(_expireAfterLineEdit); expireLayout->addWidget(secLabel); expireLayout->addStretch(1); QCheckBox *expireCheckBox = new QCheckBox(tr("Expire after")); expireCheckBox->setChecked(false); if (_info._ttl >= 0) { expireCheckBox->setChecked(true); _expireAfterLineEdit->setText(QString("%1").arg(_info._ttl)); } expireStateChanged(expireCheckBox->checkState()); VERIFY(connect(expireCheckBox, SIGNAL(stateChanged(int)), this, SLOT(expireStateChanged(int)))); QLabel *sparseHelpLabel = createHelpLabel( "If set, the index only references documents with the specified field. " "These indexes use less space but behave differently in some situations (particularly sorts).", 20, -2, 0, 20); QLabel *backgroundHelpLabel = createHelpLabel( "Builds the index in the background so that building an index does not block other database activities.", 20, -2, 0, 20); QLabel *expireHelpLabel = createHelpLabel( "Specifies a <i>time to live</i>, in seconds, to control how long MongoDB retains documents in this collection", 20, -2, 0, 20); QGridLayout *layout = new QGridLayout; layout->addWidget(_sparceCheckBox, 0, 0, 1, 2); layout->addWidget(sparseHelpLabel, 1, 0, 1, 2); layout->addWidget(_backGroundCheckBox, 2, 0, 1, 2); layout->addWidget(backgroundHelpLabel, 3, 0, 1, 2); layout->addWidget(expireCheckBox, 4, 0); layout->addLayout(expireLayout, 4, 1); layout->addWidget(expireHelpLabel, 5, 0, 1, 2); layout->setAlignment(Qt::AlignTop); advanced->setLayout(layout); return advanced; } QWidget* AddEditIndexDialog::createTextSearchTab() { QWidget *textSearch = new QWidget(this); _defaultLanguageLineEdit = new QLineEdit(QtUtils::toQString(_info._defaultLanguage), textSearch); _languageOverrideLineEdit = new QLineEdit(QtUtils::toQString(_info._languageOverride), textSearch); _textWeightsLineEdit = createFindFrame(textSearch, QtUtils::toQString(_info._textWeights)); QLabel *defaultLanguageHelpLabel = createHelpLabel( "For a <i>text</i> index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is <b>english</b>", 0, -2, 0, 20); QLabel *languageOverrideHelpLabel = createHelpLabel( "For a <i>text</i> index, specify the name of the field in the document that contains, for that document, the language to override the default language. The default value is <b>language</b>", 0, -2, 0, 20); QLabel *textWeightsHelpLabel = createHelpLabel( "Document that contains field and weight pairs. The weight is a number ranging from 1 to 99,999 " "and denotes the significance of the field relative to the other indexed fields. ", 0, -2, 0, 20); QGridLayout *layout = new QGridLayout; layout->addWidget(new QLabel(tr("Default language:")), 0, 0); layout->addWidget(_defaultLanguageLineEdit, 0, 1); layout->addWidget(defaultLanguageHelpLabel, 1, 1); layout->addWidget(new QLabel(tr("Language override:")), 2, 0, Qt::AlignTop); layout->addWidget(_languageOverrideLineEdit, 2, 1); layout->addWidget(languageOverrideHelpLabel, 3, 1); layout->addWidget(new QLabel(tr("Text weights")), 4, 0, Qt::AlignTop); layout->addWidget(_textWeightsLineEdit, 4, 1, Qt::AlignTop); layout->addWidget(textWeightsHelpLabel, 5, 1); layout->setAlignment(Qt::AlignTop); textSearch->setLayout(layout); return textSearch; } IndexInfo AddEditIndexDialog::info() const { const QString &expAft = _expireAfterLineEdit->text(); int expAftInt = _info._ttl; if (!expAft.isEmpty()) { expAftInt = _expireAfterLineEdit->text().toInt(); } return IndexInfo( _info._collection, _nameLineEdit->text().toStdString(), _jsonText->sciScintilla()->text().toStdString(), _uniqueCheckBox->checkState() == Qt::Checked, _backGroundCheckBox->checkState() == Qt::Checked, _sparceCheckBox->checkState() == Qt::Checked, expAftInt, QtUtils::toStdString(_defaultLanguageLineEdit->text()), QtUtils::toStdString(_languageOverrideLineEdit->text()), QtUtils::toStdString(_textWeightsLineEdit->sciScintilla()->text())); } void AddEditIndexDialog::accept() { if (isValidJson(_jsonText->sciScintilla()->text())) { const QString &weightText = _textWeightsLineEdit->sciScintilla()->text(); if (!weightText.isEmpty() && !isValidJson(weightText)) { QMessageBox::warning(this, "Invalid json", "Please check json text.\n"); _textWeightsLineEdit->setFocus(); return ; } if (!_isAddIndex) { // Ask user int const answer = QMessageBox::question(this, "Warning", QString("MongoDB does not support direct (one step) edit index. " "\nTo edit an existing index, the index must be dropped and recreated. " "This means if the recreate step fails, the index being edited might " "have already been dropped. " "In this case, Robo 3T will try to recover (recreate) the index being edited. " "Please consider backing up your index first. " "\n\nAre you sure you want to proceed?" ), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton ); if (answer == QMessageBox::No) return; } return BaseClass::accept(); } else { QMessageBox::warning(this, "Invalid json", "Please check json text.\n"); _jsonText->setFocus(); } } }
13,782
C++
.cpp
267
42.05618
203
0.631856
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,729
ExplorerReplicaSetFolderItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/explorer/ExplorerReplicaSetFolderItem.cpp
#include "robomongo/gui/widgets/explorer/ExplorerReplicaSetFolderItem.h" #include <QAction> #include <QMenu> #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/ReplicaSetSettings.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/EventBus.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/utils/Logger.h" #include "robomongo/gui/GuiRegistry.h" namespace { void openCurrentServerShell(Robomongo::MongoServer *const server, const QString &script, bool execute = true, const Robomongo::CursorPosition &cursor = Robomongo::CursorPosition()) { Robomongo::AppRegistry::instance().app()->openShell(server, script, std::string(), execute, Robomongo::QtUtils::toQString(server->connectionRecord()->getReadableName()), cursor); } void openCurrentServerShell(Robomongo::MongoServer* server, Robomongo::ConnectionSettings* connSettings, const QString &script) { Robomongo::AppRegistry::instance().app()->openShell(server, connSettings, Robomongo::ScriptInfo(script, true)); } } namespace Robomongo { ExplorerReplicaSetFolderItem::ExplorerReplicaSetFolderItem(ExplorerTreeItem *parent, MongoServer *const server) : BaseClass(parent), _server(server) { auto repSetStatus = new QAction("Status of Replica Set", this); VERIFY(connect(repSetStatus, SIGNAL(triggered()), SLOT(on_repSetStatus()))); auto refresh = new QAction("Refresh", this); VERIFY(connect(refresh, SIGNAL(triggered()), SLOT(on_refresh()))); BaseClass::_contextMenu->addAction(repSetStatus); BaseClass::_contextMenu->addSeparator(); BaseClass::_contextMenu->addAction(refresh); AppRegistry::instance().bus()->subscribe(this, ReplicaSetFolderLoading::Type, _server); setIcon(0, GuiRegistry::instance().folderIcon()); setText(0, "Replica Set (" + QString::number(_server->replicaSetInfo()->membersAndHealths.size()) + " nodes)"); setExpanded(false); setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } void ExplorerReplicaSetFolderItem::updateText() { setText(0, "Replica Set (" + QString::number(_server->replicaSetInfo()->membersAndHealths.size()) + " nodes)"); } void ExplorerReplicaSetFolderItem::disableSomeContextMenuActions() { if (BaseClass::_contextMenu->actions().size() < 1) return; // Find out if there is at least one reachable member mongo::HostAndPort onlineMember; for (auto const& member : _server->replicaSetInfo()->membersAndHealths) { if (member.second) { onlineMember = mongo::HostAndPort(member.first); break; } } // Show menu item "Status of Replica Set" only if there is at least one reachable member // If there is no reachable member, disable it. BaseClass::_contextMenu->actions().at(0)->setDisabled(onlineMember.empty()); } void ExplorerReplicaSetFolderItem::expand() { if (!_refreshFlag) { _refreshFlag = true; return; } _server->tryRefreshReplicaSetFolder(true); } void ExplorerReplicaSetFolderItem::on_repSetStatus() { if (!_server->replicaSetInfo()->primary.empty()) { openCurrentServerShell(_server, "rs.status()"); } else // Primary is unreachable, try to find and run rs.status on a reachable secondary { mongo::HostAndPort onlineMember; for (auto const& member : _server->replicaSetInfo()->membersAndHealths) { if (member.second) { onlineMember = mongo::HostAndPort(member.first); break; } } if (onlineMember.empty()) { LOG_MSG("Unable to find a reachable replica set member to run rs.status().", mongo::logger::LogSeverity::Error()); return; } auto connSetting = std::unique_ptr<ConnectionSettings>(_server->connectionRecord()->clone()); // Set connection settings of this replica member connSetting->setConnectionName(onlineMember.toString() + " [member of " + connSetting->connectionName() + "]"); connSetting->setServerHost(onlineMember.host()); connSetting->setServerPort(onlineMember.port()); connSetting->setReplicaSet(false); connSetting->replicaSetSettings()->setMembers(std::vector<std::string>()); openCurrentServerShell(_server, connSetting.get(), "rs.status()"); } } void ExplorerReplicaSetFolderItem::handle(ReplicaSetFolderLoading *event) { setText(0, "Replica Set ..."); } void ExplorerReplicaSetFolderItem::on_refresh() { _server->tryRefreshReplicaSetFolder(true); } }
5,157
C++
.cpp
111
37.189189
119
0.649144
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,730
CollectionStatsTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/CollectionStatsTreeItem.cpp
#include "robomongo/gui/widgets/workarea/CollectionStatsTreeItem.h" #include <mongo/db/jsobj.h> #include <mongo/bson/bsonobj.h> #include "robomongo/core/domain/MongoUtils.h" #include "robomongo/core/domain/MongoDocument.h" #include "robomongo/core/domain/MongoNamespace.h" #include "robomongo/core/utils/BsonUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/utils/QtUtils.h" namespace { QString prepareValue(const QString &data) { return data + " "; // ugly yet simple way to extend size of columns } } namespace Robomongo { CollectionStatsTreeItem::CollectionStatsTreeItem(MongoDocumentPtr document) { mongo::BSONObj _obj = document->bsonObj(); MongoNamespace ns(BsonUtils::getField<mongo::String>(_obj, "ns")); setText(0, prepareValue(QtUtils::toQString(ns.collectionName()))); setIcon(0, GuiRegistry::instance().collectionIcon()); setText(1, prepareValue(QString::number(BsonUtils::getField<mongo::NumberLong>(_obj, "count")))); setText(2, prepareValue(MongoUtils::buildNiceSizeString(BsonUtils::getField<mongo::NumberDouble>(_obj, "size")))); setText(3, prepareValue(MongoUtils::buildNiceSizeString(BsonUtils::getField<mongo::NumberDouble>(_obj, "storageSize")))); setText(4, prepareValue(MongoUtils::buildNiceSizeString(BsonUtils::getField<mongo::NumberDouble>(_obj, "totalIndexSize")))); setText(5, prepareValue(MongoUtils::buildNiceSizeString(BsonUtils::getField<mongo::NumberDouble>(_obj, "avgObjSize")))); setText(6, prepareValue(QString::number(BsonUtils::getField<mongo::NumberDouble>(_obj, "paddingFactor")))); } }
1,674
C++
.cpp
32
47.5625
132
0.73945
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,731
WelcomeTab.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/WelcomeTab.cpp
#include "robomongo/gui/widgets/workarea/WelcomeTab.h" #ifndef __linux__ // --------------------- Windows, macOS impl --------------------------// #include <QtWebEngineWidgets> #include <QDesktopServices> namespace Robomongo { // ------------------ WelcomeTab WelcomeTab::WelcomeTab(QScrollArea *parent) : QWidget(parent), _parent(parent) { auto webView = new QWebEngineView(this); QUrl const URL { "http://files.studio3t.com/rm-feed_3t_io/1.4.3/index.html" }; webView->setPage(new MyWebPage(this)); webView->page()->setUrl(URL); webView->setContextMenuPolicy(Qt::NoContextMenu); webView->page()->triggerAction(QWebEnginePage::WebAction::ReloadAndBypassCache); webView->page()->profile()->setHttpCacheType(QWebEngineProfile::HttpCacheType::NoCache); auto mainLayout = new QHBoxLayout; mainLayout->setContentsMargins(-10, -10, -1, -1); mainLayout->setSizeConstraint(QLayout::SetMinimumSize); mainLayout->addWidget(webView); setLayout(mainLayout); } // ------------------ MyWebPage bool MyWebPage::acceptNavigationRequest( QUrl const& url, NavigationType type, bool /*isMainFrame*/) { if (NavigationTypeLinkClicked == type) { QDesktopServices::openUrl(url); return false; } return true; } } #else // -------------------------------- Linux impl. ------------------------------------// #include <QObject> #include <QPushButton> #include <QApplication> #include <QLabel> #include <QVBoxLayout> #include <QPixmap> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QDir> #include <QFile> #include <QFileInfo> #include <QDesktopServices> #include <QScrollArea> #include <QScrollBar> #include <QEvent> #include <QXmlStreamReader> #include <QMessageBox> #include <QToolButton> #include <QMenu> #include "robomongo/core/AppRegistry.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/MainWindow.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/EventBus.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/utils/Logger.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/utils/common.h" namespace Robomongo { bool deleteOldCacheFile(QString const& absFilePath); bool saveIntoCache(QString const& fileName, QString const& fileData, QString const& lastModifiedKey, QString const& lastModifiedDate); bool saveIntoCache(QString const& fileName, QPixmap const& pixMap, QString const& lastModifiedKey, QString const& lastModifiedDate); bool saveIntoCache(QString const& fileName, QByteArray* data, QString const& lastModifiedKey, QString const& lastModifiedDate); /** * @brief Container structure to hold data of a blog link */ struct BlogInfo { BlogInfo(QString const& title, QString const& link, QString const& publishDate) : title(title), link(link), publishDate(publishDate) {} QString const title; QString const link; QString const publishDate; }; /** * @brief Custom label for identifying a blog link label */ struct BlogLinkLabel : public QLabel { BlogLinkLabel(QString const& args) : QLabel(args) {} }; QString const WhatsNew = "<p><h1><font color=\"#2d862d\">%1</h1></p>"; QString const BlogsHeader = "<p><h1><font color=\"#2d862d\">Blog Posts</h1></p>"; QString const BlogLinkTemplate = "<a style = 'color: #106CD6; text-decoration: none;'" "href='%1'>%2</a>"; // For info only. Starting from 1.2.1, PROJECT_VERSION is used. // URL Folder number for Pic1 and Text1 enum { URL_FOLDER_1_0_0 = 1, URL_FOLDER_1_1_0_BETA = 2, URL_FOLDER_1_1_1 = 3, URL_FOLDER_1_2_0_BETA = 4, // Starting from 1.2.1, PROJECT_VERSION is used. }; QString const IMAGE_PATH = QString(PROJECT_VERSION) + "/image.png"; QString const CONTENTS_PATH = QString(PROJECT_VERSION) + "/contents.txt"; QString const RssFileName = "rss.xml"; QString const Text1_LastModifiedDateKey("wtText1LastModifiedDate"); QString const Image1_LastModifiedDateKey("wtImage1LastModifiedDate"); QString const Rss_LastModifiedDateKey("wtRssLastModifiedDate"); auto const TEXT_TO_TAB_RATIO = 0.6; auto const IMAGE_TO_TAB_RATIO = 0.25; auto const BLOG_TO_TAB_RATIO = 0.28; /* ------------------------------------- Welcome Tab --------------------------------------- */ WelcomeTab::WelcomeTab(QScrollArea *parent) : QWidget(parent), _parent(parent) { _pic1_URL = "https://files.studio3t.com/rm-feed_3t_io/" + IMAGE_PATH; _text1_URL = "https://files.studio3t.com/rm-feed_3t_io/" + CONTENTS_PATH; _rss_URL = "https://blog.robomongo.org/rss/"; #ifdef __APPLE__ constexpr int HEADER_POINT_SIZE = 10; #else constexpr int HEADER_POINT_SIZE = 7; #endif //// What's new section _whatsNewHeader = new QLabel; _whatsNewHeader->setHidden(true); QFont headerFont { _whatsNewHeader->font() }; headerFont.setPointSize(HEADER_POINT_SIZE); _whatsNewHeader->setFont(headerFont); // _whatsNewHeader->setFont _whatsNewText = new QLabel; _whatsNewText->setTextInteractionFlags(Qt::TextSelectableByMouse); _whatsNewText->setTextFormat(Qt::RichText); _whatsNewText->setTextInteractionFlags(Qt::TextBrowserInteraction); _whatsNewText->setOpenExternalLinks(true); _whatsNewText->setWordWrap(true); _whatsNewText->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); _pic1 = new QLabel; _pic1->setTextInteractionFlags(Qt::TextSelectableByMouse); _pic1->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); _pic1->setScaledContents(true); _blogsHeader = new QLabel(BlogsHeader); _blogsHeader->setHidden(true); _blogsHeader->setFont(headerFont); //// --- Network Access Managers if (!AppRegistry::instance().settingsManager()->disableHttpsFeatures()) { auto text1Downloader = new QNetworkAccessManager; VERIFY(connect(text1Downloader, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_downloadTextReply(QNetworkReply*)))); text1Downloader->head(QNetworkRequest(_text1_URL)); auto pic1Downloader = new QNetworkAccessManager; VERIFY(connect(pic1Downloader, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_downloadPictureReply(QNetworkReply*)))); pic1Downloader->head(QNetworkRequest(_pic1_URL)); auto rssDownloader = new QNetworkAccessManager; VERIFY(connect(rssDownloader, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_downloadRssReply(QNetworkReply*)))); rssDownloader->get(QNetworkRequest(_rss_URL)); } //// --- Layouts _allBlogsButton = new QPushButton("All Blog Posts"); _allBlogsButton->setHidden(true); _allBlogsButton->setStyleSheet("color: #106CD6"); VERIFY(connect(_allBlogsButton, SIGNAL(clicked()), this, SLOT(on_allBlogsButton_clicked()))); _allBlogsButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); _blogLinksLay = new QVBoxLayout; _blogLinksLay->setAlignment(Qt::AlignLeft); auto rightLayout = new QVBoxLayout; rightLayout->setContentsMargins(20, -1, -1, -1); rightLayout->addWidget(_blogsHeader, 0, Qt::AlignTop); rightLayout->addLayout(_blogLinksLay); rightLayout->addSpacing(15); rightLayout->addWidget(_allBlogsButton, 0, Qt::AlignLeft); rightLayout->addStretch(); auto leftLayout = new QVBoxLayout; leftLayout->addWidget(_whatsNewHeader, 0, Qt::AlignTop); leftLayout->addWidget(_pic1, 0, Qt::AlignTop); leftLayout->addWidget(_whatsNewText, 0, Qt::AlignTop); leftLayout->addStretch(); leftLayout->setSizeConstraint(QLayout::SetMinimumSize); auto mainLayout = new QHBoxLayout; mainLayout->setContentsMargins(20, 20, -1, -1); mainLayout->addLayout(leftLayout); mainLayout->addSpacing(20); mainLayout->addLayout(rightLayout); mainLayout->setSizeConstraint(QLayout::SetMinimumSize); setLayout(mainLayout); } WelcomeTab::~WelcomeTab() { } void WelcomeTab::on_downloadTextReply(QNetworkReply* reply) { auto hideOrShowWhatsNewHeader = [this]() { if ((!_pic1->pixmap() || _pic1->pixmap()->isNull()) && _whatsNewText->text().isEmpty()) _whatsNewHeader->setHidden(true); else _whatsNewHeader->setVisible(true); }; if (reply->operation() == QNetworkAccessManager::HeadOperation) { if (reply->error() == QNetworkReply::NoError) { // No network error QString const& createDate = reply->header(QNetworkRequest::LastModifiedHeader).toString(); if (createDate == AppRegistry::instance().settingsManager()->cacheData(Text1_LastModifiedDateKey) && fileExists(CacheDir + _text1_URL.fileName())) { // Load from cache QFile file(CacheDir + _text1_URL.fileName()); if (!file.open(QFile::ReadOnly | QFile::Text)) return; QTextStream in(&file); QString str(in.readAll()); setWhatsNewHeaderAndText(str); hideOrShowWhatsNewHeader(); return; } else { // Get from internet reply->manager()->get(QNetworkRequest(_text1_URL)); } } else { // There is a network error // Load from cache QFile file(CacheDir + _text1_URL.fileName()); if (!file.open(QFile::ReadOnly | QFile::Text)) return; QTextStream in(&file); QString str(in.readAll()); setWhatsNewHeaderAndText(str); hideOrShowWhatsNewHeader(); return; } } else if (reply->operation() == QNetworkAccessManager::GetOperation) { // todo: handle get operation fails QString str(QUrl::fromPercentEncoding(reply->readAll())); if (str.isEmpty()) { LOG_MSG("WelcomeTab: Failed to download text file from URL. Reason: " + reply->errorString(), mongo::logger::LogSeverity::Warning()); hideOrShowWhatsNewHeader(); return; } setWhatsNewHeaderAndText(str); hideOrShowWhatsNewHeader(); saveIntoCache(_text1_URL.fileName(), str, Text1_LastModifiedDateKey, reply->header(QNetworkRequest::LastModifiedHeader).toString()); } } void WelcomeTab::on_downloadPictureReply(QNetworkReply* reply) { auto const FIFTY_PERCENT_OF_TAB = _parent->width() * IMAGE_TO_TAB_RATIO; QPixmap image; auto hideOrShowWhatsNewHeader = [this]() { if ((!_pic1->pixmap() || _pic1->pixmap()->isNull()) && _whatsNewText->text().isEmpty()) _whatsNewHeader->setHidden(true); else _whatsNewHeader->setVisible(true); }; // Network error, load from cache if (reply->error() != QNetworkReply::NoError) { image = QPixmap(CacheDir + _pic1_URL.fileName()); if (image.isNull()) return; _image = image; _pic1->setPixmap(_image); if (0 == _image.size().width()) return; _pic1->setFixedSize(FIFTY_PERCENT_OF_TAB, (FIFTY_PERCENT_OF_TAB / _image.size().width()) * _image.size().height()); adjustSize(); hideOrShowWhatsNewHeader(); return; } // No network error if (reply->operation() == QNetworkAccessManager::HeadOperation) { QString const& createDate = reply->header(QNetworkRequest::LastModifiedHeader).toString(); // If the file in URL is not newer load from cache, otherwise get from internet if (createDate == AppRegistry::instance().settingsManager()->cacheData(Image1_LastModifiedDateKey) && fileExists(CacheDir + _pic1_URL.fileName())) { image = QPixmap(CacheDir + _pic1_URL.fileName()); // Load from cache } else { // Get from internet reply->manager()->get(QNetworkRequest(_pic1_URL)); return; } } else if (reply->operation() == QNetworkAccessManager::GetOperation) { image.loadFromData(reply->readAll()); if (image.isNull()) { LOG_MSG("WelcomeTab: Failed to download image file from internet. Reason: " + reply->errorString(), mongo::logger::LogSeverity::Warning()); image = QPixmap(CacheDir + _pic1_URL.fileName()); } else { saveIntoCache(_pic1_URL.fileName(), image, Image1_LastModifiedDateKey, reply->header(QNetworkRequest::LastModifiedHeader).toString()); } } // Set the image if (image.isNull()) return; _image = image; if (0 == _image.size().width()) return hideOrShowWhatsNewHeader(); resize(); } void WelcomeTab::on_downloadRssReply(QNetworkReply* reply) { auto const THIRTY_PERCENT_OF_TAB = _parent->width() * BLOG_TO_TAB_RATIO; QByteArray data = reply->readAll(); if (data.isEmpty() || reply->error() != QNetworkReply::NoError) { // Load from cache QFile file(CacheDir + RssFileName); if (!file.open(QFile::ReadOnly | QFile::Text)) return; data = file.readAll(); } QXmlStreamReader xmlReader(data); int count = 0; int const MaxBlogCountShown = 10; QString title, link, pubDate; while (!xmlReader.atEnd()) { xmlReader.readNext(); if (xmlReader.isStartElement()) { if (xmlReader.name() == "title") title = xmlReader.readElementText(); else if (xmlReader.name() == "link") link = xmlReader.readElementText(); else if (xmlReader.name() == "pubDate") pubDate = xmlReader.readElementText().left(16); if (!pubDate.isEmpty()) { auto blogLink = new BlogLinkLabel(BlogLinkTemplate.arg(link, title)); blogLink->setMouseTracking(true); blogLink->setAttribute(Qt::WA_Hover); blogLink->installEventFilter(this); blogLink->setTextInteractionFlags(Qt::TextBrowserInteraction); blogLink->setOpenExternalLinks(true); blogLink->setWordWrap(true); blogLink->setMinimumWidth(THIRTY_PERCENT_OF_TAB); _blogLinksLay->addWidget(blogLink); _blogLinksLay->addWidget(new QLabel("<font color='gray'>" + pubDate + "</font>")); _blogLinksLay->addSpacing(_blogLinksLay->spacing()); pubDate.clear(); ++count; if (MaxBlogCountShown == count) break; } } } _blogsHeader->setVisible(true); _allBlogsButton->setVisible(true); adjustSize(); // Save into cache saveIntoCache(RssFileName, data, Rss_LastModifiedDateKey, "NotImplemented"); // todo } void WelcomeTab::on_allBlogsButton_clicked() { QDesktopServices::openUrl(QUrl("https://blog.robomongo.org/")); } void WelcomeTab::setWhatsNewHeaderAndText(QString const& str) { if (!str.contains("\n") || str.size() == 0) return; auto const firstNewLineIndex = str.indexOf("\n"); auto const leftOfStr = str.left(firstNewLineIndex); auto const rightOfStr = str.right(str.size() - firstNewLineIndex - 7); _whatsNewHeader->setText(WhatsNew.arg(leftOfStr)); _whatsNewText->setText(rightOfStr); auto const SIXTY_PERCENT_OF_TAB = _parent->width() * TEXT_TO_TAB_RATIO; _whatsNewText->setMaximumWidth(SIXTY_PERCENT_OF_TAB); adjustSize(); } void WelcomeTab::resize() { auto const tabWidth = _parent->width(); auto const FIFTY_PERCENT_OF_TAB = _parent->width() * IMAGE_TO_TAB_RATIO; _whatsNewText->setFixedWidth(tabWidth * TEXT_TO_TAB_RATIO); _pic1->setPixmap(_image); if (0 == _image.size().width()) return; _pic1->setFixedSize(FIFTY_PERCENT_OF_TAB, (FIFTY_PERCENT_OF_TAB / _image.size().width())*_image.size().height()); _blogsHeader->setFixedWidth(tabWidth * BLOG_TO_TAB_RATIO); for (int i = 0; i < _blogLinksLay->count(); ++i) { if(auto wid = _blogLinksLay->itemAt(i)->widget()) wid->setFixedWidth(tabWidth * BLOG_TO_TAB_RATIO); } adjustSize(); } bool WelcomeTab::eventFilter(QObject *target, QEvent *event) { auto blogLinkLabel = dynamic_cast<BlogLinkLabel*>(target); // Make blog link underlined on mouse hover if (blogLinkLabel) { if (event->type() == QEvent::HoverEnter) { blogLinkLabel->setText(blogLinkLabel->text().replace("text-decoration: none;", "text-decoration: ;")); setCursor(Qt::PointingHandCursor); return true; } else if (event->type() == QEvent::HoverLeave) { blogLinkLabel->setText(blogLinkLabel->text().replace("text-decoration: ;", "text-decoration: none;")); setCursor(Qt::ArrowCursor); return true; } } return QWidget::eventFilter(target, event); } bool deleteOldCacheFile(QString const& absFilePath) { if (!fileExists(absFilePath)) return true; if (!QFile::remove(absFilePath)) { LOG_MSG("WelcomeTab: Failed to delete cached file at: " + absFilePath, mongo::logger::LogSeverity::Warning()); return false; } return true; } bool saveIntoCache(QString const& fileName, QString const& fileData, QString const& lastModifiedKey, QString const& lastModifiedDate) { if (!QDir(CacheDir).exists()) QDir().mkdir(CacheDir); else deleteOldCacheFile(CacheDir + fileName); QFile file(CacheDir + fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; QTextStream out(&file); out << fileData; // Save file's last modified date into settings AppRegistry::instance().settingsManager()->addCacheData(lastModifiedKey, lastModifiedDate); AppRegistry::instance().settingsManager()->save(); return true; } bool saveIntoCache(QString const& fileName, QPixmap const& pixMap, QString const& lastModifiedKey, QString const& lastModifiedDate) { if (!QDir(CacheDir).exists()) QDir().mkdir(CacheDir); else deleteOldCacheFile(CacheDir + fileName); QFile file(CacheDir + fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; pixMap.save(CacheDir + fileName); // Save file's last modified date into settings AppRegistry::instance().settingsManager()->addCacheData(lastModifiedKey, lastModifiedDate); AppRegistry::instance().settingsManager()->save(); return true; } bool saveIntoCache(QString const& fileName, QByteArray* data, QString const& lastModifiedKey, QString const& lastModifiedDate) { if (!QDir(CacheDir).exists()) QDir().mkdir(CacheDir); else deleteOldCacheFile(CacheDir + fileName); QFile file(CacheDir + fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; file.write(*data); // Save file's last modified date into settings AppRegistry::instance().settingsManager()->addCacheData(lastModifiedKey, lastModifiedDate); AppRegistry::instance().settingsManager()->save(); return true; } } #endif // -------------------------------- end of Linux impl. ------------------------------------//
21,329
C++
.cpp
472
34.603814
127
0.599103
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,732
BsonTreeModel.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/BsonTreeModel.cpp
#include "robomongo/gui/widgets/workarea/BsonTreeModel.h" #include <mongo/client/dbclient_base.h> #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/utils/BsonUtils.h" #include "robomongo/core/domain/MongoDocument.h" #include "robomongo/gui/widgets/workarea/BsonTreeItem.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" namespace { using namespace Robomongo; QString arrayValue(int itemsCount) { QString elements = itemsCount == 1 ? "element" : "elements"; return QString("[ %1 %2 ]").arg(itemsCount).arg(elements); } QString objectValue(int itemsCount) { QString fields = itemsCount == 1 ? "field" : "fields"; return QString("{ %1 %2 }").arg(itemsCount).arg(fields); } void parseDocument(BsonTreeItem *root, const mongo::BSONObj &doc, bool isArray) { mongo::BSONObjIterator iterator(doc); while (iterator.more()) { mongo::BSONElement element = iterator.next(); BsonTreeItem *childItemInner = new BsonTreeItem(doc, root); std::string fieldName = std::string(element.fieldName()); childItemInner->setFieldName(fieldName); QString uiFieldName = QtUtils::toQString(fieldName); childItemInner->setKey(uiFieldName); if (isArray) { // When we iterate array, show field names in square brackets // In this case field names are numeric, starting from 0. childItemInner->setKey("[" + uiFieldName + "]"); } if (BsonUtils::isArray(element)) { int itemsCount = element.Array().size(); childItemInner->setValue(arrayValue(itemsCount)); } else if (BsonUtils::isDocument(element)) { int count = BsonUtils::elementsCount(element.Obj()); childItemInner->setValue(objectValue(count)); } else { std::string result; BsonUtils::buildJsonString(element, result, AppRegistry::instance().settingsManager()->uuidEncoding(), AppRegistry::instance().settingsManager()->timeZone()); childItemInner->setValue(QtUtils::toQString(result)); } childItemInner->setType(element.type()); if (element.type() == mongo::BinData) { childItemInner->setBinType(element.binDataType()); } root->addChild(childItemInner); //root->setValue(QString("{ %1 fields }").arg(root->childrenCount())); } } } namespace Robomongo { BsonTreeModel::BsonTreeModel(const std::vector<MongoDocumentPtr> &documents, QObject *parent) : BaseClass(parent), _root(new BsonTreeItem(this)) { for (int i = 0; i < documents.size(); ++i) { MongoDocumentPtr doc = documents[i]; BsonTreeItem *child = new BsonTreeItem(doc->bsonObj(), _root); parseDocument(child, doc->bsonObj(), doc->bsonObj().isArray()); QString idValue; BsonTreeItem *idItem = child->childByKey("_id"); if (idItem) { idValue = idItem->value(); } child->setKey(QString("(%1) %2").arg(i + 1).arg(idValue)); int count = BsonUtils::elementsCount(doc->bsonObj()); if (doc->bsonObj().isArray()) { child->setValue(arrayValue(count)); child->setType(mongo::Array); } else { child->setValue(objectValue(count)); child->setType(mongo::Object); } _root->addChild(child); } } void BsonTreeModel::fetchMore(const QModelIndex &parent) { BsonTreeItem *node = QtUtils::item<BsonTreeItem*>(parent); if (node) { mongo::BSONElement elem = BsonUtils::indexOf(node->root(), parent.row()); if (!elem.isNull() && elem.isABSONObj()) { parseDocument(node, elem.Obj(), elem.type() == mongo::Array); } } return BaseClass::fetchMore(parent); } bool BsonTreeModel::canFetchMore(const QModelIndex &parent) const { BsonTreeItem *node = QtUtils::item<BsonTreeItem*>(parent); if (node && !node->childrenCount()) { return BsonUtils::isDocument(node->type()); } return false; } bool BsonTreeModel::hasChildren(const QModelIndex &parent) const { BsonTreeItem *node = QtUtils::item<BsonTreeItem*>(parent); if (node) { return BsonUtils::isDocument(node->type()); } return true; } const QIcon &BsonTreeModel::getIcon(BsonTreeItem *item) { switch(item->type()) { case mongo::NumberDouble: return GuiRegistry::instance().bsonDoubleIcon(); case mongo::NumberDecimal: return GuiRegistry::instance().bsonNumberDecimalIcon(); case mongo::String: return GuiRegistry::instance().bsonStringIcon(); case mongo::Object: return GuiRegistry::instance().bsonObjectIcon(); case mongo::Array: return GuiRegistry::instance().bsonArrayIcon(); case mongo::BinData: return GuiRegistry::instance().bsonBinaryIcon(); case mongo::Undefined: return GuiRegistry::instance().circleIcon(); case mongo::jstOID: return GuiRegistry::instance().circleIcon(); case mongo::Bool: return GuiRegistry::instance().bsonBooleanIcon(); case mongo::Date: return GuiRegistry::instance().bsonDateTimeIcon(); case mongo::jstNULL: return GuiRegistry::instance().bsonNullIcon(); case mongo::RegEx: return GuiRegistry::instance().circleIcon(); case mongo::DBRef: return GuiRegistry::instance().circleIcon(); case mongo::Code: case mongo::CodeWScope: return GuiRegistry::instance().circleIcon(); case mongo::NumberInt: return GuiRegistry::instance().bsonIntegerIcon(); case mongo::bsonTimestamp: return GuiRegistry::instance().bsonDateTimeIcon(); case mongo::NumberLong: return GuiRegistry::instance().bsonIntegerIcon(); default: return GuiRegistry::instance().circleIcon(); } } QVariant BsonTreeModel::data(const QModelIndex &index, int role) const { QVariant result; if (!index.isValid()) return result; BsonTreeItem *node = QtUtils::item<BsonTreeItem*>(index); if (!node) return result; int col = index.column(); if (role == Qt::DecorationRole && col == BsonTreeItem::eKey ) { return getIcon(node); } if (role == Qt::TextColorRole && col == BsonTreeItem::eType) { return QColor(Qt::gray); } if (role == Qt::DisplayRole || role == Qt::ToolTipRole) { if (col == BsonTreeItem::eKey) { if (role == Qt::DisplayRole) { result = node->key(); } } else if (col == BsonTreeItem::eValue) { bool isCut = node->type() == mongo::String || node->type() == mongo::Code || node->type() == mongo::CodeWScope; if (role == Qt::ToolTipRole) { result = isCut ? node->value().left(500) : node->value(); } else{ result = isCut ? node->value().simplified().left(300) : node->value(); } } else if (col == BsonTreeItem::eType) { result = BsonUtils::BSONTypeToString(node->type(), node->binType(), AppRegistry::instance().settingsManager()->uuidEncoding()); } } return result; } Qt::ItemFlags BsonTreeModel::flags(const QModelIndex &index) const { Qt::ItemFlags result = 0; if (index.isValid()) { result = Qt::ItemIsSelectable | Qt::ItemIsEnabled; } return result; } int BsonTreeModel::rowCount(const QModelIndex &parent) const { const BsonTreeItem *parentItem = NULL; if (parent.isValid()) parentItem = QtUtils::item<BsonTreeItem*>(parent); else parentItem = _root; return parentItem->childrenCount(); } int BsonTreeModel::columnCount(const QModelIndex &parent) const { return BsonTreeItem::eCountColumns; } QVariant BsonTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { if (section == BsonTreeItem::eKey) { return "Key"; } else if (section == BsonTreeItem::eValue) { return "Value"; } else { return "Type"; } } return BaseClass::headerData(section, orientation, role); } QModelIndex BsonTreeModel::parent(const QModelIndex& index) const { QModelIndex result; if (index.isValid()) { BsonTreeItem *const childItem = QtUtils::item<BsonTreeItem*const>(index); BsonTreeItem *const parentItem = static_cast<BsonTreeItem*const>(childItem->parent()); if (parentItem && parentItem != _root) { BsonTreeItem *const grandParent = static_cast<BsonTreeItem*const>(parentItem->parent()); int row = grandParent->indexOf(parentItem); result = createIndex(row, 0, parentItem); } } return result; } QModelIndex BsonTreeModel::index(int row, int column, const QModelIndex &parent) const { QModelIndex index; if (hasIndex(row, column, parent)) { const BsonTreeItem * parentItem = NULL; if (!parent.isValid()) { parentItem = _root; } else { parentItem = QtUtils::item<BsonTreeItem*>(parent); } BsonTreeItem *childItem = parentItem->child(row); if (childItem) { index = createIndex(row, column, childItem); } } return index; } void BsonTreeModel::insertItem(BsonTreeItem *parent, BsonTreeItem *children) { QModelIndex index = createIndex(0, 0, parent); unsigned child_count = parent->childrenCount(); beginInsertRows(index, child_count, child_count); parent->addChild(children); endInsertRows(); } void BsonTreeModel::removeitem(BsonTreeItem *children) { BsonTreeItem *parent = static_cast<BsonTreeItem *>(children->parent()); if (parent) { QModelIndex index = createIndex(0, 0, parent); int row = parent->indexOf(children); beginRemoveRows(index, row, row); parent->removeChild(children); endRemoveRows(); } } }
11,230
C++
.cpp
260
32.161538
178
0.583242
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,733
JsonPrepareThread.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/JsonPrepareThread.cpp
#include "robomongo/gui/widgets/workarea/JsonPrepareThread.h" #include <QHBoxLayout> #include "robomongo/core/domain/MongoDocument.h" #include "robomongo/core/utils/BsonUtils.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { JsonPrepareThread::JsonPrepareThread(const std::vector<MongoDocumentPtr> &bsonObjects, UUIDEncoding uuidEncoding, SupportedTimes timeZone) :_bsonObjects(bsonObjects), _uuidEncoding(uuidEncoding), _timeZone(timeZone), _stop(false) { } void JsonPrepareThread::stop() { _stop = true; } void JsonPrepareThread::run() { int position = 1; // 1-based numbering to match tree & table views for (std::vector<MongoDocumentPtr>::const_iterator it = _bsonObjects.begin(); it != _bsonObjects.end(); ++it) { MongoDocumentPtr doc = *it; mongo::StringBuilder sb; if (position == 1) sb << "/* 1 */\n"; else sb << "\n\n/* " << position << " */\n"; mongo::BSONObj obj = doc->bsonObj(); std::string stdJson = BsonUtils::jsonString(obj, mongo::TenGen, 1, _uuidEncoding, _timeZone); if (_stop) break; sb << stdJson; QString json = QtUtils::toQString(sb.str()); if (_stop) break; emit partReady(json); position++; } emit done(); } }
1,488
C++
.cpp
43
25.790698
142
0.581996
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,734
WorkAreaTabWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/WorkAreaTabWidget.cpp
#include "robomongo/gui/widgets/workarea/WorkAreaTabWidget.h" #include <QKeyEvent> #include <QScrollArea> #include "robomongo/core/AppRegistry.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/KeyboardManager.h" #include "robomongo/core/domain/MongoShell.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/gui/widgets/workarea/WorkAreaTabBar.h" #include "robomongo/gui/widgets/workarea/QueryWidget.h" #include "robomongo/gui/widgets/workarea/WelcomeTab.h" #include "robomongo/gui/GuiRegistry.h" namespace Robomongo { /** * @brief Creates WorkAreaTabWidget. * @param workAreaWidget: WorkAreaWidget this tab belongs to. */ WorkAreaTabWidget::WorkAreaTabWidget(QWidget *parent) : QTabWidget(parent) { auto tab = new WorkAreaTabBar(this); // This line (setTabBar()) should go before setTabsClosable(true) setTabBar(tab); setTabsClosable(true); setElideMode(Qt::ElideRight); setMovable(true); setDocumentMode(true); #ifdef Q_OS_MAC setDocumentMode(false); QFont font = tab->font(); font.setPixelSize(12); tab->setFont(font); QString styles = QString( "QTabWidget::pane { background-color: white; }" // This style disables default styling under Mac "QTabWidget::tab-bar {" "alignment: left;" "}" "QTabBar::tab:selected { " "background: white; /*#E1E1E1*/; " "color: #282828;" "} " "QTabBar::tab {" "color: #505050;" "font-size: 11px;" "background: %1;" "border-right: 1px solid #aaaaaa;" "padding: 4px 5px 7px 5px;" "}" ).arg(QWidget::palette().color(QWidget::backgroundRole()).darker(114).name()); setStyleSheet(styles); #endif VERIFY(connect(this, SIGNAL(tabCloseRequested(int)), SLOT(tabBar_tabCloseRequested(int)))); VERIFY(connect(this, SIGNAL(currentChanged(int)), SLOT(ui_currentChanged(int)))); VERIFY(connect(tab, SIGNAL(newTabRequested(int)), SLOT(ui_newTabRequested(int)))); VERIFY(connect(tab, SIGNAL(reloadTabRequested(int)), SLOT(ui_reloadTabRequested(int)))); VERIFY(connect(tab, SIGNAL(duplicateTabRequested(int)), SLOT(ui_duplicateTabRequested(int)))); VERIFY(connect(tab, SIGNAL(closeOtherTabsRequested(int)), SLOT(ui_closeOtherTabsRequested(int)))); VERIFY(connect(tab, SIGNAL(closeTabsToTheRightRequested(int)), SLOT(ui_closeTabsToTheRightRequested(int)))); auto scrollArea = new QScrollArea; _welcomeTab = new WelcomeTab(scrollArea); scrollArea->setWidget(_welcomeTab); scrollArea->setBackgroundRole(QPalette::Base); scrollArea->setWidgetResizable(true); if (!AppRegistry::instance().settingsManager()->disableHttpsFeatures()) { #ifdef __APPLE__ addTab(scrollArea, QIcon(), "Welcome"); #else addTab(scrollArea, GuiRegistry::instance().welcomeTabIcon(), "Welcome"); #endif } scrollArea->setFrameShape(QFrame::NoFrame); } void WorkAreaTabWidget::closeTab(int index) { if (index >= 0) { QueryWidget *tabWidget = queryWidget(index); removeTab(index); delete tabWidget; } } void WorkAreaTabWidget::nextTab() { int index = currentIndex(); int tabsCount = count(); if (index == tabsCount - 1) { setCurrentIndex(0); return; } if (index >= 0 && index < tabsCount - 1) { setCurrentIndex(index + 1); return; } } void WorkAreaTabWidget::previousTab() { int index = currentIndex(); if (index == 0) { setCurrentIndex(count() - 1); return; } if (index > 0) { setCurrentIndex(index - 1); return; } } QueryWidget *WorkAreaTabWidget::currentQueryWidget() { return qobject_cast<QueryWidget *>(currentWidget()); } QueryWidget *WorkAreaTabWidget::queryWidget(int index) { return qobject_cast<QueryWidget*>(widget(index)); } WelcomeTab* WorkAreaTabWidget::getWelcomeTab() { return _welcomeTab; } void WorkAreaTabWidget::openWelcomeTab() { auto scrollArea = qobject_cast<QScrollArea*>(_welcomeTab->getParent()); if (!scrollArea) return; _welcomeTab = new WelcomeTab(scrollArea); scrollArea->setWidget(_welcomeTab); scrollArea->setBackgroundRole(QPalette::Base); #ifdef __APPLE__ QIcon icon; #else QIcon const& icon = GuiRegistry::instance().welcomeTabIcon(); #endif // If welcome tab is closed open it as first tab otherwise refresh on // it's current place. if (indexOf(scrollArea) == -1) // Welcome Tab is closed insertTab(0, scrollArea, icon, "Welcome"); else insertTab(indexOf(scrollArea), scrollArea, icon, "Welcome"); scrollArea->setFrameShape(QFrame::NoFrame); setCurrentIndex(indexOf(scrollArea)); } /** * @brief Overrides QTabWidget::keyPressEvent() in order to intercept * tab close key shortcuts (Ctrl+F4 and Ctrl+W) */ void WorkAreaTabWidget::keyPressEvent(QKeyEvent *keyEvent) { if ((keyEvent->modifiers() & Qt::ControlModifier) && (keyEvent->key() == Qt::Key_F4 || keyEvent->key() == Qt::Key_W)) { int index = currentIndex(); closeTab(index); return; } QueryWidget *widget = currentQueryWidget(); if (KeyboardManager::isPreviousTabShortcut(keyEvent)) { previousTab(); return; } else if (KeyboardManager::isNextTabShortcut(keyEvent)) { nextTab(); return; } else if (KeyboardManager::isNewTabShortcut(keyEvent) && widget) { widget->openNewTab(); return; } else if (KeyboardManager::isDuplicateTabShortcut(keyEvent) && widget) { widget->duplicate(); return; } else if (KeyboardManager::isSetFocusOnQueryLineShortcut(keyEvent) && widget) { widget->setScriptFocus(); return; } else if (KeyboardManager::isExecuteScriptShortcut(keyEvent) && widget) { widget->execute(); return; } else if (KeyboardManager::isAutoCompleteShortcut(keyEvent) && widget) { widget->showAutocompletion(); return; } else if (KeyboardManager::isHideAutoCompleteShortcut(keyEvent) && widget) { widget->hideAutocompletion(); return; } QTabWidget::keyPressEvent(keyEvent); } void WorkAreaTabWidget::resizeEvent(QResizeEvent* event) { QTabWidget::resizeEvent(event); if (_welcomeTab && _welcomeTab->isVisible()) _welcomeTab->resize(); } void WorkAreaTabWidget::tabBar_tabCloseRequested(int index) { closeTab(index); } void WorkAreaTabWidget::ui_newTabRequested(int index) { if (QueryWidget *query = queryWidget(index)) query->openNewTab(); } void WorkAreaTabWidget::ui_reloadTabRequested(int index) { QueryWidget *query = queryWidget(index); if (query) query->reload(); } void WorkAreaTabWidget::ui_duplicateTabRequested(int index) { QueryWidget *query = queryWidget(index); if (query) query->duplicate(); } void WorkAreaTabWidget::ui_closeOtherTabsRequested(int index) { tabBar()->moveTab(index, 0); while (count() > 1) { closeTab(1); // close second tab } } void WorkAreaTabWidget::ui_closeTabsToTheRightRequested(int index) { while (count() > index + 1) { closeTab(index + 1); // close nearest tab } } void WorkAreaTabWidget::ui_currentChanged(int index) { if (index < 0) return; QueryWidget *tabWidget = queryWidget(index); if (tabWidget) tabWidget->activateTabContent(); } void WorkAreaTabWidget::tabTextChange(const QString &text) { QWidget *send = qobject_cast<QWidget*>(sender()); if (!send) return; setTabText(indexOf(send), text); } void WorkAreaTabWidget::tooltipTextChange(const QString &text) { QWidget *send = qobject_cast<QWidget*>(sender()); if (!send) return; setTabToolTip(indexOf(send), text); } void WorkAreaTabWidget::handle(OpeningShellEvent *event) { const QString &title = event->shell->title(); QString shellName; if (event->shell->isExecutable()) shellName = title.isEmpty() ? " Loading..." : title; else shellName = "New Shell"; auto queryWidget = new QueryWidget(event->shell, this); VERIFY(connect(queryWidget, SIGNAL(titleChanged(const QString &)), this, SLOT(tabTextChange(const QString &)))); VERIFY(connect(queryWidget, SIGNAL(toolTipChanged(const QString &)), this, SLOT(tooltipTextChange(const QString &)))); addTab(queryWidget, shellName); setCurrentIndex(count() - 1); #if !defined(Q_OS_MAC) setTabIcon(count() - 1, GuiRegistry::instance().mongodbIcon()); #endif if (!event->shell->isExecutable()) { queryWidget->hideProgress(); queryWidget->setCurrentDatabase(event->shell->dbname()); return; } queryWidget->showProgress(); } }
9,910
C++
.cpp
274
27.412409
116
0.611291
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,735
ProgressBarPopup.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/ProgressBarPopup.cpp
#include "ProgressBarPopup.h" #include <QLabel> #include <QMovie> #include <QVBoxLayout> namespace Robomongo { ProgressBarPopup::ProgressBarPopup(QWidget *parent) : QFrame(parent) { setStyleSheet("QFrame {background-color: #e1e1e1; border: 0px solid #c7c5c4; border-radius: 6px;}"); QMovie *movie = new QMovie(":robomongo/icons/progress_bar.gif", QByteArray(), this); _progressLabel = new QLabel(); _progressLabel->setMovie(movie); _progressLabel->setFixedWidth(widthProgress); _progressLabel->setFixedHeight(heightProgress); movie->start(); setFixedSize(width, height); QVBoxLayout *layout = new QVBoxLayout(); layout->setContentsMargins((width-widthProgress)/2, (height-heightProgress)/2, (height-heightProgress)/2, (width-widthProgress)/2); layout->setSpacing(0); layout->addWidget(_progressLabel); setLayout(layout); } }
955
C++
.cpp
24
33.375
139
0.687568
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,736
OutputItemContentWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/OutputItemContentWidget.cpp
#include "robomongo/gui/widgets/workarea/OutputItemContentWidget.h" #include <QVBoxLayout> #include <Qsci/qscilexerjavascript.h> #include "robomongo/core/AppRegistry.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/domain/MongoShell.h" #include "robomongo/core/domain/MongoAggregateInfo.h" #include "robomongo/gui/widgets/workarea/OutputWidget.h" #include "robomongo/gui/widgets/workarea/OutputItemHeaderWidget.h" #include "robomongo/gui/widgets/workarea/JsonPrepareThread.h" #include "robomongo/gui/widgets/workarea/BsonTreeView.h" #include "robomongo/gui/widgets/workarea/BsonTreeModel.h" #include "robomongo/gui/widgets/workarea/BsonTableView.h" #include "robomongo/gui/widgets/workarea/BsonTableModel.h" #include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include "robomongo/gui/widgets/workarea/CollectionStatsTreeWidget.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/editors/JSLexer.h" #include "robomongo/gui/editors/FindFrame.h" namespace Robomongo { OutputItemContentWidget::OutputItemContentWidget(ViewMode viewMode, MongoShell *shell, const QString &text, double secs, bool multipleResults, bool tabbedResults, bool firstItem, bool lastItem, AggrInfo aggrInfo, QWidget *parent) : BaseClass(parent), _textView(NULL), _bsonTreeview(NULL), _thread(NULL), _bsonTable(NULL), _isTextModeSupported(true), _isTreeModeSupported(false), _isTableModeSupported(false), _isCustomModeSupported(false), _isTextModeInitialized(false), _isTreeModeInitialized(false), _isCustomModeInitialized(false), _isTableModeInitialized(false), _isFirstPartRendered(false), _text(text), _shell(shell), _outputWidget(dynamic_cast<OutputWidget*>(parentWidget())), _initialSkip(0), _initialLimit(0), _mod(NULL), _viewMode(viewMode), _aggrInfo(aggrInfo) { setup(secs, multipleResults, tabbedResults, firstItem, lastItem); } OutputItemContentWidget::OutputItemContentWidget(ViewMode viewMode, MongoShell *shell, const QString &type, const std::vector<MongoDocumentPtr> &documents, const MongoQueryInfo &queryInfo, double secs, bool multipleResults, bool tabbedResults, bool firstItem, bool lastItem, AggrInfo aggrInfo, QWidget *parent) : BaseClass(parent), _textView(NULL), _bsonTreeview(NULL), _thread(NULL), _bsonTable(NULL), _isTextModeSupported(true), _isTreeModeSupported(true), _isTableModeSupported(true), _isCustomModeSupported(!type.isEmpty()), _isTextModeInitialized(false), _isTreeModeInitialized(false), _isCustomModeInitialized(false), _isTableModeInitialized(false), _isFirstPartRendered(false), _documents(documents), _queryInfo(queryInfo), _type(type), _shell(shell), _initialSkip(queryInfo._skip), _initialLimit(queryInfo._limit), _outputWidget(dynamic_cast<OutputWidget*>(parentWidget())), _mod(NULL), _viewMode(viewMode), _aggrInfo(aggrInfo) { setup(secs, multipleResults, tabbedResults, firstItem, lastItem); } void OutputItemContentWidget::setup(double secs, bool multipleResults, bool tabbedResults, bool firstItem, bool lastItem) { setContentsMargins(0, 0, 0, 0); _header = new OutputItemHeaderWidget(this, multipleResults, tabbedResults, firstItem, lastItem); if (_queryInfo._info.isValid()) { _header->setCollection(QtUtils::toQString(_queryInfo._info._ns.collectionName())); _header->paging()->setBatchSize(_queryInfo._batchSize); _header->paging()->setSkip(_queryInfo._skip); if (!_queryInfo._limit) _queryInfo._limit = 50; } else if (_aggrInfo.isValid) { _initialLimit = 0; _initialSkip = 0; _header->setCollection(QtUtils::toQString(_aggrInfo.collectionName)); _header->paging()->setBatchSize(_aggrInfo.batchSize); _header->paging()->setSkip(_aggrInfo.skip); } _header->setTime(QString("%1 sec.").arg(secs, 0, 'g', 3)); QVBoxLayout *layout = new QVBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(_header); _stack = new QStackedWidget; layout->addWidget(_stack); setLayout(layout); configureModel(); VERIFY(connect(_header->paging(), SIGNAL(refreshed(int, int)), this, SLOT(refresh(int, int)))); VERIFY(connect(_header->paging(), SIGNAL(leftClicked(int, int)), this, SLOT(paging_leftClicked(int, int)))); VERIFY(connect(_header->paging(), SIGNAL(rightClicked(int, int)), this, SLOT(paging_rightClicked(int, int)))); VERIFY(connect(_header, SIGNAL(maximizedPart()), this, SIGNAL(maximizedPart()))); VERIFY(connect(_header, SIGNAL(restoredSize()), this, SIGNAL(restoredSize()))); refreshOutputItem(); } void OutputItemContentWidget::paging_leftClicked(int skip, int limit) { int s = skip - limit; if (s < 0) s = 0; refresh(s, limit); } void OutputItemContentWidget::refreshOutputItem() { switch(_viewMode) { case Text: showText(); break; case Tree: showTree(); break; case Table: showTable(); break; case Custom: showCustom(); break; default: showTree(); } } void OutputItemContentWidget::paging_rightClicked(int skip, int limit) { skip += limit; refresh(skip, limit); } void OutputItemContentWidget::refresh(int skip, int batchSize) { // Cannot set skip lower than in the text query if (skip < _initialSkip) { _header->paging()->setSkip(_initialSkip); skip = _initialSkip; } int skipDelta = skip - _initialSkip; int limit = batchSize; // If limit is set to 0 it means UNLIMITED number of documents (limited only by batch size) // This is according to MongoDB documentation. if (_initialLimit != 0) { limit = _initialLimit - skipDelta; if (limit <= 0) limit = -1; // It means that we do not need to load documents if (limit > batchSize) limit = batchSize; } MongoQueryInfo info(_queryInfo); info._limit = limit; info._skip = skip; info._batchSize = batchSize; _outputWidget->showProgress(); _shell->setScriptExecutable(true); if (_aggrInfo.isValid) { // Build original pipeline object, and append extra skip and limit for paging std::string pipelineModified = "["; for (int i = 0; ; i++) { auto const obj = mongo::tojson(_aggrInfo.pipeline.getObjectField(std::to_string(i))); if (obj.empty() || "{}" == obj) break; pipelineModified.append(obj + ","); } pipelineModified.append("{$skip:" + std::to_string(skip) + "}, " + "{$limit:" + std::to_string(batchSize) + "}" + "]"); std::string const query = "db.getCollection('" + _aggrInfo.collectionName + "').aggregate(" + pipelineModified + ", " + _aggrInfo.options.toString() + ")"; // Create aggr. info with new skip and batchsize AggrInfo const aggrInfo { _aggrInfo.collectionName, skip, batchSize, _aggrInfo.pipeline, _aggrInfo.options, _outputWidget->resultIndex(this) }; _shell->setAggrInfo(aggrInfo); _shell->execute(query); } else _shell->query(_outputWidget->resultIndex(this), info); } void OutputItemContentWidget::updateWithInfo(const MongoQueryInfo &inf, const std::vector<MongoDocumentPtr> &documents) { update(documents, inf._skip, inf._batchSize); } void OutputItemContentWidget::updateWithInfo(const AggrInfo &aggrInfo, const std::vector<MongoDocumentPtr> &documents) { update(documents, aggrInfo.skip, aggrInfo.batchSize); } void OutputItemContentWidget::update(const std::vector<MongoDocumentPtr> &documents, int skip, int batchSize) { _documents = documents; _header->paging()->setSkip(skip); _header->paging()->setBatchSize(batchSize); _text.clear(); _isFirstPartRendered = false; markUninitialized(); if (_bsonTable) { _stack->removeWidget(_bsonTable); delete _bsonTable; _bsonTable = NULL; } if (_bsonTreeview) { _stack->removeWidget(_bsonTreeview); delete _bsonTreeview; _bsonTreeview = NULL; } if (_textView) { _stack->removeWidget(_textView); delete _textView; _textView = NULL; } configureModel(); } void OutputItemContentWidget::showText() { _viewMode = Text; _header->showText(); if (!_isTextModeSupported) return; if (!_isTextModeInitialized) { _textView = configureLogText(); if (!_text.isEmpty()) { _textView->sciScintilla()->setText(_text); } else { if (_documents.size() > 0) { _textView->sciScintilla()->setText("Loading..."); _thread = new JsonPrepareThread(_documents, AppRegistry::instance().settingsManager()->uuidEncoding(), AppRegistry::instance().settingsManager()->timeZone()); VERIFY(connect(_thread, SIGNAL(partReady(const QString&)), this, SLOT(jsonPartReady(const QString&)))); VERIFY(connect(_thread, SIGNAL(finished()), _thread, SLOT(deleteLater()))); _thread->start(); } } _stack->addWidget(_textView); _isTextModeInitialized = true; } _stack->setCurrentWidget(_textView); } void OutputItemContentWidget::showTree() { _viewMode = Tree; _header->showTree(); if (!_isTreeModeSupported) { // try to downgrade to text mode showText(); _viewMode = Tree; return; } if (!_isTreeModeInitialized) { _bsonTreeview = new BsonTreeView(_shell, _queryInfo, this); _bsonTreeview->setModel(_mod); _stack->addWidget(_bsonTreeview); if (true == AppRegistry::instance().settingsManager()->autoExpand()) // Expanding only one level, because on large // documents it can take much time _bsonTreeview->expand(_mod->index(0, 0, QModelIndex())); _isTreeModeInitialized = true; } _stack->setCurrentWidget(_bsonTreeview); } void OutputItemContentWidget::showCustom() { _viewMode = Custom; _header->showCustom(); if (!_isCustomModeSupported) { // try to downgrade to tree mode showTree(); _viewMode = Custom; return; } if (!_isCustomModeInitialized) { if (_type == "collectionStats") { _collectionStats = new CollectionStatsTreeWidget(_documents, NULL); _stack->addWidget(_collectionStats); } _isCustomModeInitialized = true; } if (_collectionStats) _stack->setCurrentWidget(_collectionStats); } void OutputItemContentWidget::showTable() { _viewMode = Table; _header->showTable(); if (!_isTableModeSupported) { // try to downgrade to text mode showText(); _viewMode = Table; return; } if (!_isTableModeInitialized) { _bsonTable = new BsonTableView(_shell, _queryInfo); BsonTableModelProxy *modp = new BsonTableModelProxy(_bsonTable); modp->setSourceModel(_mod); _bsonTable->setModel(modp); _stack->addWidget(_bsonTable); _isTableModeInitialized = true; } _stack->setCurrentWidget(_bsonTable); } void OutputItemContentWidget::markUninitialized() { _isTextModeInitialized = false; _isTreeModeInitialized = false; _isCustomModeInitialized = false; _isTableModeInitialized = false; } void OutputItemContentWidget::applyDockUndockSettings(bool isDocking) const { _header->applyDockUndockSettings(isDocking); } void OutputItemContentWidget::toggleOrientation(Qt::Orientation orientation) const { _header->toggleOrientation(orientation); } void OutputItemContentWidget::jsonPartReady(const QString &json) { // check that this is our current thread JsonPrepareThread *thread = qobject_cast<JsonPrepareThread *>(sender()); if (thread && thread != _thread) { // close previous thread thread->stop(); thread->wait(); } else { if (_textView) { if (_isFirstPartRendered) _textView->sciScintilla()->append(json); else _textView->sciScintilla()->setText(json); _isFirstPartRendered = true; } } } BsonTreeModel *OutputItemContentWidget::configureModel() { delete _mod; _mod = new BsonTreeModel(_documents, this); return _mod; } FindFrame *Robomongo::OutputItemContentWidget::configureLogText() { const QFont &textFont = GuiRegistry::instance().font(); QsciLexerJavaScript *javaScriptLexer = new JSLexer(this); javaScriptLexer->setFont(textFont); FindFrame *_logText = new FindFrame(this); _logText->sciScintilla()->setLexer(javaScriptLexer); _logText->sciScintilla()->setTabWidth(4); _logText->sciScintilla()->setAppropriateBraceMatching(); _logText->sciScintilla()->setFont(textFont); _logText->sciScintilla()->setReadOnly(true); _logText->sciScintilla()->setWrapMode((QsciScintilla::WrapMode) QsciScintilla::SC_WRAP_NONE); _logText->sciScintilla()->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); _logText->sciScintilla()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // Wrap mode turned off because it introduces huge performance problems // even for medium size documents. _logText->sciScintilla()->setStyleSheet("QFrame {background-color: rgb(73, 76, 78); border: 1px solid #c7c5c4; border-radius: 0px; margin: 0px; padding: 0px;}"); return _logText; } }
15,871
C++
.cpp
375
30.922667
178
0.589343
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,737
PagingWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/PagingWidget.cpp
#include "robomongo/gui/widgets/workarea/PagingWidget.h" #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/gui/GuiRegistry.h" namespace { QPushButton *createButtonWithIcon(const QIcon &icon) { QPushButton *button = new QPushButton; button->setIcon(icon); button->setFixedSize(24, 24); button->setFlat(true); return button; } } namespace Robomongo { PagingWidget::PagingWidget(QWidget *parent) :BaseClass(parent) { _skipEdit = new QLineEdit; _batchSizeEdit = new QLineEdit; _skipEdit->setAlignment(Qt::AlignHCenter); _skipEdit->setToolTip("Skip"); _batchSizeEdit->setAlignment(Qt::AlignHCenter); _batchSizeEdit->setToolTip("Batch Size (number of documents shown at once)"); QFontMetrics metrics = _skipEdit->fontMetrics(); int width = metrics.boundingRect("00000000").width(); QRegExp rx("\\d+"); _skipEdit->setValidator(new QRegExpValidator(rx, this)); _batchSizeEdit->setValidator(new QRegExpValidator(rx, this)); _skipEdit->setFixedWidth(width); _batchSizeEdit->setFixedWidth(width); QPushButton *leftButton = createButtonWithIcon(GuiRegistry::instance().leftIcon()); QPushButton *rightButton = createButtonWithIcon(GuiRegistry::instance().rightIcon()); VERIFY(connect(leftButton, SIGNAL(clicked()), this, SLOT(leftButton_clicked()))); VERIFY(connect(rightButton, SIGNAL(clicked()), this, SLOT(rightButton_clicked()))); VERIFY(connect(_batchSizeEdit, SIGNAL(returnPressed()), this, SLOT(refresh()))); VERIFY(connect(_skipEdit, SIGNAL(returnPressed()), this, SLOT(refresh()))); QHBoxLayout *layout = new QHBoxLayout(); layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(leftButton); layout->addSpacing(0); layout->addWidget(_skipEdit); layout->addSpacing(1); layout->addWidget(_batchSizeEdit); layout->addSpacing(0); layout->addWidget(rightButton); setLayout(layout); } void PagingWidget::setSkip(int skip) { _skipEdit->setText(QString::number(skip)); show(); } void PagingWidget::setBatchSize(int batchSize) { if (batchSize <= 0) batchSize = AppRegistry::instance().settingsManager()->batchSize(); _batchSizeEdit->setText(QString::number(batchSize)); show(); } void PagingWidget::refresh() { int limit = _batchSizeEdit->text().toInt(); int skip = _skipEdit->text().toInt(); emit refreshed(skip, limit); } void PagingWidget::leftButton_clicked() { int limit = _batchSizeEdit->text().toInt(); int skip = _skipEdit->text().toInt(); emit leftClicked(skip, limit); } void PagingWidget::rightButton_clicked() { int limit = _batchSizeEdit->text().toInt(); int skip = _skipEdit->text().toInt(); emit rightClicked(skip, limit); } }
3,238
C++
.cpp
86
30.709302
93
0.657316
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,738
BsonTableView.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/BsonTableView.cpp
#include "robomongo/gui/widgets/workarea/BsonTableView.h" #include <QHeaderView> #include <QAction> #include <QMenu> #include <QKeyEvent> #include "robomongo/gui/widgets/workarea/BsonTreeItem.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { BsonTableView::BsonTableView(MongoShell *shell, const MongoQueryInfo &queryInfo, QWidget *parent) :BaseClass(parent), _notifier(this, shell, queryInfo) { #if defined(Q_OS_MAC) setAttribute(Qt::WA_MacShowFocusRect, false); #endif GuiRegistry::instance().setAlternatingColor(this); verticalHeader()->setDefaultAlignment(Qt::AlignLeft); horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); setStyleSheet("QTableView { border-left: 1px solid #c7c5c4; border-top: 1px solid #c7c5c4; gridline-color: #edebea;}"); setSelectionMode(QAbstractItemView::ExtendedSelection); setSelectionBehavior(QAbstractItemView::SelectItems); setContextMenuPolicy(Qt::CustomContextMenu); VERIFY(connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)))); } void BsonTableView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Delete) { _notifier.onDeleteDocuments(); } return BaseClass::keyPressEvent(event); } QModelIndex BsonTableView::selectedIndex() const { QModelIndexList indexes = detail::uniqueRows(selectionModel()->selectedIndexes()); if (indexes.count() != 1) return QModelIndex(); return indexes[0]; } QModelIndexList BsonTableView::selectedIndexes() const { return detail::uniqueRows(selectionModel()->selectedIndexes()); } void BsonTableView::showContextMenu( const QPoint &point ) { QPoint menuPoint = mapToGlobal(point); menuPoint.setY(menuPoint.y() + horizontalHeader()->height()); menuPoint.setX(menuPoint.x() + verticalHeader()->width()); QModelIndexList indexes = selectedIndexes(); if (detail::isMultiSelection(indexes)) { QMenu menu(this); _notifier.initMultiSelectionMenu(&menu); menu.exec(menuPoint); } else{ QModelIndex selectedInd = selectedIndex(); BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd); QMenu menu(this); _notifier.initMenu(&menu, documentItem); menu.exec(menuPoint); } } }
2,568
C++
.cpp
63
33.507937
127
0.683387
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,739
BsonTreeView.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/BsonTreeView.cpp
#include "robomongo/gui/widgets/workarea/BsonTreeView.h" #include <QHeaderView> #include <QAction> #include <QMenu> #include <QKeyEvent> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/widgets/workarea/BsonTreeItem.h" #include "robomongo/gui/widgets/workarea/OutputWidget.h" namespace Robomongo { BsonTreeView::BsonTreeView(MongoShell *shell, const MongoQueryInfo &queryInfo, QWidget *parent) : BaseClass(parent), _notifier(this, shell, queryInfo), _outputItemContentWidget(dynamic_cast<const OutputItemContentWidget*>(parent)) { #if defined(Q_OS_MAC) setAttribute(Qt::WA_MacShowFocusRect, false); #endif GuiRegistry::instance().setAlternatingColor(this); setSelectionMode(QAbstractItemView::ExtendedSelection); setSelectionBehavior(QAbstractItemView::SelectRows); setContextMenuPolicy(Qt::CustomContextMenu); VERIFY(connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)))); _expandRecursive = new QAction("Expand Recursively", this); _expandRecursive->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Right)); VERIFY(connect(_expandRecursive, SIGNAL(triggered()), SLOT(onExpandRecursive()))); _collapseRecursive = new QAction(tr("Collapse Recursively"), this); _collapseRecursive->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Left)); VERIFY(connect(_collapseRecursive, SIGNAL(triggered()), SLOT(onCollapseRecursive()))); setStyleSheet("QTreeView { border-left: 1px solid #c7c5c4; border-top: 1px solid #c7c5c4; }"); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) header()->setSectionResizeMode(QHeaderView::Interactive); #endif } void BsonTreeView::showContextMenu(const QPoint &point) { if (_outputItemContentWidget->outputWidget()->progressBarActive()) return; QPoint menuPoint = mapToGlobal(point); menuPoint.setY(menuPoint.y() + header()->height()); QModelIndexList indexes = selectedIndexes(); if (detail::isMultiSelection(indexes)) { QMenu menu(this); menu.addAction(_expandRecursive); menu.addAction(_collapseRecursive); menu.addSeparator(); _notifier.initMultiSelectionMenu(&menu); menu.exec(menuPoint); } else { QModelIndex selectedInd = selectedIndex(); BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd); QMenu menu(this); bool isSimple = false; if (documentItem) { isSimple = detail::isSimpleType(documentItem); if (detail::isDocumentType(documentItem)) { menu.addAction(_expandRecursive); menu.addAction(_collapseRecursive); menu.addSeparator(); } } _notifier.initMenu(&menu, documentItem); menu.exec(menuPoint); } } void BsonTreeView::resizeEvent(QResizeEvent *event) { BaseClass::resizeEvent(event); header()->resizeSections(QHeaderView::Stretch); } void BsonTreeView::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Delete: _notifier.handleDeleteCommand(); break; case Qt::Key_Backspace: // Cmd/Ctrl + Backspace if (event->modifiers() & Qt::ControlModifier) _notifier.handleDeleteCommand(); break; case Qt::Key_Right: if (event->modifiers() & Qt::AltModifier) this->onExpandRecursive(); break; case Qt::Key_Left: if (event->modifiers() & Qt::AltModifier) this->onCollapseRecursive(); break; } return BaseClass::keyPressEvent(event); } void BsonTreeView::expandNode(const QModelIndex &index) { if (index.isValid()) { BaseClass::expand(index); BsonTreeItem *item = QtUtils::item<BsonTreeItem*>(index); for (unsigned i = 0; i < item->childrenCount(); ++i) { BsonTreeItem *tritem = item->child(i); if (tritem && detail::isDocumentType(tritem)) { expandNode(model()->index(i, 0, index)); } } } } void BsonTreeView::collapseNode(const QModelIndex &index) { if (index.isValid()) { BaseClass::collapse(index); BsonTreeItem *item = QtUtils::item<BsonTreeItem*>(index); for (unsigned i = 0; i < item->childrenCount(); ++i) { BsonTreeItem *tritem = item->child(i); if (tritem && detail::isDocumentType(tritem)) { collapseNode(model()->index(i, 0, index)); } } } } void BsonTreeView::onExpandRecursive() { QModelIndexList indexes = selectedIndexes(); if (detail::isMultiSelection(indexes)) { for (int i = 0; i<indexes.count(); ++i) expandNode(indexes[i]); } else { expandNode(selectedIndex()); } } void BsonTreeView::onCollapseRecursive() { QModelIndexList indexes = selectedIndexes(); if (detail::isMultiSelection(indexes)) { for (int i = 0; i<indexes.count(); ++i) collapseNode(indexes[i]); } else { collapseNode(selectedIndex()); } } /** * @returns selected BsonTreeItem, or NULL otherwise */ QModelIndex BsonTreeView::selectedIndex() const { QModelIndexList indexes = detail::uniqueRows(selectionModel()->selectedRows()); int count = indexes.count(); if (indexes.count() != 1) return QModelIndex(); return indexes[0]; } QModelIndexList BsonTreeView::selectedIndexes() const { return detail::uniqueRows(selectionModel()->selectedRows(), true); } }
6,238
C++
.cpp
155
29.967742
125
0.603952
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,740
ScriptWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/ScriptWidget.cpp
#include "robomongo/gui/widgets/workarea/ScriptWidget.h" #include <QVBoxLayout> #include <QKeyEvent> #include <QCompleter> #include <QStringListModel> #include <Qsci/qscilexerjavascript.h> #include <Qsci/qsciscintilla.h> #include "robomongo/core/domain/MongoShell.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/gui/widgets/workarea/QueryWidget.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/editors/JSLexer.h" #include "robomongo/gui/editors/FindFrame.h" #include "robomongo/gui/editors/PlainJavaScriptEditor.h" namespace { bool isStopChar(const QChar &ch, bool direction) { if (ch == '=' || ch == ';' || ch == '(' || ch == ')' || ch == '{' || ch == '}' || ch == '-' || ch == '/' || ch == '+' || ch == '*' || ch == '\r' || ch == '\n' || ch == ' ' ) { return true; } if (direction) { // right direction if (ch == '.') return true; } return false; } bool isForbiddenChar(const QChar &ch) { return ch == '\"' || ch == '\''; } } namespace Robomongo { ScriptWidget::ScriptWidget(MongoShell *shell, QueryWidget *parent) : _shell(shell), _parent(parent), _textChanged(false), _disableTextAndCursorNotifications(false) { setStyleSheet("QFrame {background-color: rgb(255, 255, 255); border: 0px solid #c7c5c4;" "border-radius: 0px; margin: 0px; padding: 0px;}"); _queryText = new FindFrame(this); _topStatusBar = new TopStatusBar(_shell->server()->connectionRecord()->connectionName(), _shell->server()->connectionRecord()->getFullAddress(), "loading..."); QVBoxLayout *layout = new QVBoxLayout; layout->setSpacing(0); layout->setContentsMargins(5, 1, 5, 5); layout->addWidget(_topStatusBar, 0, Qt::AlignTop); layout->addWidget(_queryText); setLayout(layout); // Query text widget configureQueryText(); _queryText->sciScintilla()->setFocus(); _queryText->sciScintilla()->installEventFilter(this); _completer = new QCompleter(this); _completer->setWidget(_queryText->sciScintilla()); _completer->setCompletionMode(QCompleter::PopupCompletion); _completer->setCaseSensitivity(Qt::CaseInsensitive); _completer->setMaxVisibleItems(20); _completer->setWrapAround(false); _completer->popup()->setFont(GuiRegistry::instance().font()); VERIFY(connect(_completer, SIGNAL(activated(const QString &)), this, SLOT(onCompletionActivated(const QString&)))); QStringListModel *model = new QStringListModel(_completer); _completer->setModel(model); setText(QtUtils::toQString(shell->query())); setTextCursor(shell->cursor()); } bool ScriptWidget::eventFilter(QObject *obj, QEvent *event) { if (obj == _queryText->sciScintilla()) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Tab) { hideAutocompletion(); return false; } } } return QFrame::eventFilter(obj, event); } void ScriptWidget::setup(const MongoShellExecResult &execResult) { setCurrentDatabase(execResult.currentDatabase(), execResult.isCurrentDatabaseValid()); setCurrentServer(execResult.currentServer(), execResult.isCurrentServerValid()); } void ScriptWidget::setText(const QString &text) { _queryText->sciScintilla()->setText(text); } void ScriptWidget::setTextCursor(const CursorPosition &cursor) { if (cursor.isNull()) { _queryText->sciScintilla()->setCursorPosition(15, 1000); return; } int column = cursor.column(); if (column < 0) { column = _queryText->sciScintilla()->text(cursor.line()).length() + column; } _queryText->sciScintilla()->setCursorPosition(cursor.line(), column); } QString ScriptWidget::text() const { return _queryText->sciScintilla()->text(); } QString ScriptWidget::selectedText() const { return _queryText->sciScintilla()->selectedText(); } void ScriptWidget::selectAll() { _queryText->sciScintilla()->selectAll(); } void ScriptWidget::setScriptFocus() { _queryText->sciScintilla()->setFocus(); } void ScriptWidget::setCurrentDatabase(const std::string &database, bool isValid) { _topStatusBar->setCurrentDatabase(database, isValid); } void ScriptWidget::setCurrentServer(const std::string &address, bool isValid) { _topStatusBar->setCurrentServer(address, isValid); } void ScriptWidget::showAutocompletion(const QStringList &list, const QString &prefix) { // do not show single autocompletion which is identical to existing prefix // or if it identical to prefix + '('. if (list.count() == 1) { if (list.at(0) == prefix || list.at(0) == (prefix + "(")) { return; } } // update list of completions QStringListModel * model = static_cast<QStringListModel *>(_completer->model()); model->setStringList(list); int currentLine = 0; int currentIndex = 0; _queryText->sciScintilla()->getCursorPosition(&currentLine, &currentIndex); int physicalLine = currentLine - _queryText->sciScintilla()->firstVisibleLine(); // "physical" line number in text editor (not logical) int lineIndexLeft = _currentAutoCompletionInfo.lineIndexLeft(); QRect rect = _queryText->sciScintilla()->rect(); rect.setWidth(550); rect.setHeight(editorHeight(physicalLine + 1)); rect.moveLeft(charWidth() * lineIndexLeft + autocompletionBoxLeftPosition() + _queryText->sciScintilla()->lineNumberMarginWidth()); _completer->complete(rect); _completer->popup()->setCurrentIndex(_completer->completionModel()->index(0, 0)); RoboScintilla* scin = static_cast<RoboScintilla*>(_queryText->sciScintilla()); scin->setIgnoreEnterKey(true); scin->setIgnoreTabKey(true); } void ScriptWidget::showAutocompletion() { _currentAutoCompletionInfo = sanitizeForAutocompletion(); if (_currentAutoCompletionInfo.isEmpty()) { hideAutocompletion(); return; } _shell->autocomplete(QtUtils::toStdString(_currentAutoCompletionInfo.text())); } void ScriptWidget::hideAutocompletion() { _completer->popup()->hide(); RoboScintilla *scin = static_cast<RoboScintilla*>(_queryText->sciScintilla()); scin->setIgnoreEnterKey(false); scin->setIgnoreTabKey(false); } void ScriptWidget::disableFixedHeight() const { _queryText->setMinimumSize(0, 0); _queryText->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); _queryText->sciScintilla()->setMinimumSize(0, 0); _queryText->sciScintilla()->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); _queryText->sciScintilla()->setFocus(); } void ScriptWidget::ui_queryLinesCountChanged() { // Set fixed size only if output widget is docked if (_parent->outputWindowDocked()) { int lines = _queryText->sciScintilla()->lines(); int editorTotalHeight = editorHeight(lines); int maxHeight = editorHeight(18); if (editorTotalHeight > maxHeight) { editorTotalHeight = maxHeight; } // Hide & Show solves problem of UI blinking _queryText->hide(); _queryText->setFixedHeight(editorTotalHeight); _queryText->sciScintilla()->setFixedHeight(editorTotalHeight); _queryText->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); _queryText->setMaximumHeight(editorTotalHeight + FindFrame::HeightFindPanel); _queryText->sciScintilla()->setFocus(); _queryText->show(); } } void ScriptWidget::onTextChanged() { emit textChanged(); if (!_disableTextAndCursorNotifications) _textChanged = true; } void ScriptWidget::onCursorPositionChanged(int line, int index) { if (!_disableTextAndCursorNotifications && _textChanged) { showAutocompletion(); _textChanged = false; } } void ScriptWidget::onCompletionActivated(const QString &text) { int row = _currentAutoCompletionInfo.line(); int colLeft = _currentAutoCompletionInfo.lineIndexLeft(); int colRight = _currentAutoCompletionInfo.lineIndexRight(); QString line = _queryText->sciScintilla()->text(row); int selectionIndexRight = colRight + 1; // overwrite open parenthesis, if it already exists in text if (text.endsWith('(')) { if (line.length() > colRight + 1) { if (line.at(colRight + 1) == '(') { ++selectionIndexRight; } } } _disableTextAndCursorNotifications = true; _queryText->sciScintilla()->setSelection(row, colLeft, row, selectionIndexRight); _queryText->sciScintilla()->replaceSelectedText(text); _disableTextAndCursorNotifications = false; } /* ** Configure QsciScintilla query widget */ void ScriptWidget::configureQueryText() { QsciLexerJavaScript *javaScriptLexer = new JSLexer(this); javaScriptLexer->setFont(GuiRegistry::instance().font()); int height = editorHeight(1); _queryText->sciScintilla()->setMinimumHeight(height); _queryText->sciScintilla()->setFixedHeight(height); _queryText->sciScintilla()->setAppropriateBraceMatching(); _queryText->sciScintilla()->setFont(GuiRegistry::instance().font()); _queryText->sciScintilla()->setPaper(QColor(255, 0, 0, 127)); _queryText->sciScintilla()->setLexer(javaScriptLexer); _queryText->sciScintilla()->setStyleSheet("QFrame { background-color: rgb(73, 76, 78); border: 1px solid #c7c5c4; border-radius: 4px; margin: 0px; padding: 0px;}"); VERIFY(connect(_queryText->sciScintilla(), SIGNAL(linesChanged()), SLOT(ui_queryLinesCountChanged()))); VERIFY(connect(_queryText->sciScintilla(), SIGNAL(textChanged()), SLOT(onTextChanged()))); VERIFY(connect(_queryText->sciScintilla(), SIGNAL(cursorPositionChanged(int, int)), SLOT(onCursorPositionChanged(int, int)))); } /** * @brief Calculates line height of text editor */ int ScriptWidget::lineHeight() const { return _queryText->sciScintilla()->textHeight(-1); } /** * @brief Calculates char width of text editor */ int ScriptWidget::charWidth() { QFontMetrics m(_queryText->sciScintilla()->font()); return m.averageCharWidth(); } int ScriptWidget::autocompletionBoxLeftPosition() { #if defined(Q_OS_MAC) return -1; #endif // for Linux and Windows it is the same for now return 1; } /** * @brief Calculates preferable editor height for specified number of lines */ int ScriptWidget::editorHeight(int lines) const { return lines * lineHeight() + 8; } AutoCompletionInfo ScriptWidget::sanitizeForAutocompletion() { int row = 0; int col = 0; _queryText->sciScintilla()->getCursorPosition(&row, &col); QString line = _queryText->sciScintilla()->text(row); int leftStop = -1; for (int i = col - 1; i >= 0; --i) { const QChar ch = line.at(i); if (isForbiddenChar(ch)) return AutoCompletionInfo(); if (isStopChar(ch, false)) { leftStop = i; break; } } int rightStop = line.length() + 1; for (int i = col; i < line.length(); ++i) { const QChar ch = line.at(i); if (isForbiddenChar(ch)) return AutoCompletionInfo(); if (isStopChar(ch, true)) { rightStop = i; break; } } leftStop = leftStop + 1; rightStop = rightStop - 1; //int len = ondemand ? col - leftStop : rightStop - leftStop + 1; int len = col - leftStop; QString final = line.mid(leftStop, len); return AutoCompletionInfo(final, row, leftStop, rightStop); } TopStatusBar::TopStatusBar(const std::string &connectionName, const std::string &serverName, const std::string &dbName) { setContentsMargins(0, 0, 0, 0); _textColor = palette().text().color().lighter(200); _currentConnectionLabel = new Indicator(GuiRegistry::instance().connectIcon(), QString("<font color='%1'>%2</font>").arg(_textColor.name()).arg(connectionName.c_str())); _currentConnectionLabel->setDisabled(true); _currentServerLabel = new Indicator(GuiRegistry::instance().serverIcon(), QString("<font color='%1'>%2</font>").arg(_textColor.name()).arg(serverName.c_str())); _currentServerLabel->setDisabled(true); _currentDatabaseLabel = new Indicator(GuiRegistry::instance().databaseIcon(), QString("<font color='%1'>%2</font>").arg(_textColor.name()).arg(dbName.c_str())); _currentDatabaseLabel->setDisabled(true); QHBoxLayout *topLayout = new QHBoxLayout; topLayout->setSpacing(0); #if defined(Q_OS_MAC) topLayout->setContentsMargins(2, 3, 2, 3); #else topLayout->setContentsMargins(2, 7, 2, 3); #endif topLayout->addWidget(_currentConnectionLabel, 0, Qt::AlignLeft); topLayout->addWidget(_currentServerLabel, 0, Qt::AlignLeft); topLayout->addWidget(_currentDatabaseLabel, 0, Qt::AlignLeft); topLayout->addStretch(1); setLayout(topLayout); } void TopStatusBar::setCurrentDatabase(const std::string &database, bool isValid) { QString color = isValid ? _textColor.name() : "red"; QString text = QString("<font color='%1'>%2</font>") .arg(color) .arg(database.c_str()); _currentDatabaseLabel->setText(text); } void TopStatusBar::setCurrentServer(const std::string &address, bool isValid) { QString color = isValid ? _textColor.name() : "red"; QString text = QString("<font color='%1'>%2</font>") .arg(color) .arg(detail::prepareServerAddress(address).c_str()); _currentServerLabel->setText(text); } }
15,378
C++
.cpp
369
32.842818
172
0.620526
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,741
CollectionStatsTreeWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/CollectionStatsTreeWidget.cpp
#include "robomongo/gui/widgets/workarea/CollectionStatsTreeWidget.h" #include <QHeaderView> #include "robomongo/gui/widgets/workarea/CollectionStatsTreeItem.h" namespace Robomongo { CollectionStatsTreeWidget::CollectionStatsTreeWidget(const std::vector<MongoDocumentPtr> &documents, QWidget *parent) : QTreeWidget(parent) { QStringList colums; colums << "Name" << "Count" << "Size" << "Storage" << "Index" << "Average Object" << "Padding"; setHeaderLabels(colums); setStyleSheet( "QTreeWidget { border-left: 1px solid #c7c5c4; border-top: 1px solid #c7c5c4; }" ); QList<QTreeWidgetItem *> items; size_t documentsCount = documents.size(); for (int i = 0; i < documentsCount; i++) { MongoDocumentPtr document = documents[i]; CollectionStatsTreeItem *item = new CollectionStatsTreeItem(document); items.append(item); } addTopLevelItems(items); header()->resizeSections(QHeaderView::ResizeToContents); } }
1,068
C++
.cpp
25
35.12
122
0.668599
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,743
BsonTableModel.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/BsonTableModel.cpp
#include "robomongo/gui/widgets/workarea/BsonTableModel.h" #include <QBrush> #include <QIcon> #include "robomongo/gui/widgets/workarea/BsonTreeItem.h" #include "robomongo/gui/widgets/workarea/BsonTreeModel.h" #include "robomongo/core/utils/QtUtils.h" namespace Robomongo { BsonTableModelProxy::BsonTableModelProxy(QObject *parent) : BaseClass(parent) { } int BsonTableModelProxy::rowCount(const QModelIndex &parent) const { int count = sourceModel()->rowCount(parent); return count; } QModelIndex BsonTableModelProxy::parent( const QModelIndex& index ) const { QModelIndex sourceParent = sourceModel()->parent( mapToSource(index) ); return sourceParent; } int BsonTableModelProxy::columnCount(const QModelIndex &parent) const { return _columns.size(); } QModelIndex BsonTableModelProxy::mapFromSource( const QModelIndex & sourceIndex ) const { int row = sourceIndex.row(); int col = sourceIndex.column(); BsonTreeItem *node = QtUtils::item<BsonTreeItem *>(sourceIndex); if (!node || _columns.size() <= col) return QModelIndex(); BsonTreeItem *child = node->childByKey(_columns[col]); return createIndex( row, col, child ); } QModelIndex BsonTableModelProxy::sibling(int row, int column, const QModelIndex &idx) const { return BaseClass::sibling(row, 0, idx); } QModelIndex BsonTableModelProxy::index( int row, int col, const QModelIndex& parent ) const { BsonTreeItem *node = QtUtils::item<BsonTreeItem *>(sourceModel()->index(row, 0, parent)); if (!node || _columns.size() <= col) return QModelIndex(); BsonTreeItem *child = node->childByKey(_columns[col]); return createIndex( row, col, child ); } QModelIndex BsonTableModelProxy::mapToSource( const QModelIndex &proxyIndex ) const { if ( !proxyIndex.isValid() ) return QModelIndex(); Q_ASSERT( proxyIndex.model() == this ); QModelIndex sourceIndex; BsonTreeItem *child = static_cast<BsonTreeItem *>(proxyIndex.internalPointer()); if (child) { QtUtils::HackQModelIndex* hack = reinterpret_cast<QtUtils::HackQModelIndex*>(&sourceIndex); BsonTreeItem *parent = static_cast<BsonTreeItem *>(child->parent()); hack->r = proxyIndex.row(); hack->c = proxyIndex.column(); hack->i = parent; hack->m = sourceModel(); } return sourceIndex; } void BsonTableModelProxy::setSourceModel( QAbstractItemModel* model ) { if (model) { BsonTreeItem *child = QtUtils::item<BsonTreeItem *>(model->index(0, 0)); if (child) { _root = qobject_cast<BsonTreeItem *>(child->parent()); if (_root) { int count = _root->childrenCount(); for (int i = 0; i < count; ++i) { BsonTreeItem *child = _root->child(i); int countc = child->childrenCount(); for (int j = 0; j < countc; ++j) { addColumn(child->child(j)->key()); } } } } } return BaseClass::setSourceModel(model); } QVariant BsonTableModelProxy::data(const QModelIndex &index, int role) const { QVariant result; if (!index.isValid()) return result; BsonTreeItem *node = QtUtils::item<BsonTreeItem *>(index); if (!node) { if (role == Qt::BackgroundRole) { return QBrush("#f5f3f2"); } return result; } if (role == Qt::DisplayRole || role == Qt::ToolTipRole) { bool isCut = node->type() == mongo::String || node->type() == mongo::Code || node->type() == mongo::CodeWScope; if (role == Qt::ToolTipRole) { result = isCut ? node->value() : node->value().left(500); } else{ result = isCut ? node->value() : node->value().simplified().left(300); } } else if (role == Qt::DecorationRole) { return BsonTreeModel::getIcon(node); } return result; } QVariant BsonTableModelProxy::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { return column(section); } else { return QString("%1").arg(section + 1); } } QString BsonTableModelProxy::column(int col) const { return _columns[col]; } size_t BsonTableModelProxy::findIndexColumn(const QString &col) const { for (int i = 0; i < _columns.size(); ++i) { if (_columns[i] == col) { return i; } } return _columns.size(); } size_t BsonTableModelProxy::addColumn(const QString &col) { size_t column = findIndexColumn(col); if (column == _columns.size()) { _columns.push_back(col); } return column; } }
5,373
C++
.cpp
143
27.937063
126
0.575197
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,744
QueryWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/QueryWidget.cpp
#include "robomongo/gui/widgets/workarea/QueryWidget.h" #include <QObject> #include <QPushButton> #include <QApplication> #include <QLabel> #include <QFileInfo> #include <QVBoxLayout> #include <QMessageBox> #include <QMainWindow> #include <QDockWidget> #include <Qsci/qsciscintilla.h> #include <Qsci/qscilexerjavascript.h> #include <mongo/client/dbclient_base.h> #include "robomongo/core/AppRegistry.h" #include "robomongo/core/EventBus.h" #include "robomongo/core/domain/App.h" #include "robomongo/core/domain/MongoCollection.h" #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/MongoServer.h" #include "robomongo/core/domain/MongoShell.h" #include "robomongo/core/domain/MongoAggregateInfo.h" #include "robomongo/core/events/MongoEvents.h" #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/utils/Logger.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/widgets/workarea/OutputWidget.h" #include "robomongo/gui/widgets/workarea/ScriptWidget.h" #include "robomongo/gui/widgets/workarea/OutputItemContentWidget.h" #include "robomongo/gui/widgets/workarea/OutputItemHeaderWidget.h" #include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include "robomongo/gui/editors/JSLexer.h" #include "robomongo/gui/dialogs/ChangeShellTimeoutDialog.h" using namespace mongo; namespace Robomongo { QueryWidget::QueryWidget(MongoShell *shell, QWidget *parent) : QWidget(parent), _shell(shell), _viewer(nullptr), _dock(nullptr), _isTextChanged(false) { AppRegistry::instance().bus()->subscribe(this, DocumentListLoadedEvent::Type, shell); AppRegistry::instance().bus()->subscribe(this, ScriptExecutedEvent::Type, shell); AppRegistry::instance().bus()->subscribe(this, AutocompleteResponse::Type, shell); // Make QMessageBox text selectable // setStyleSheet("QMessageBox { messagebox-text-interaction-flags: 5; }"); _scriptWidget = new ScriptWidget(_shell, this); VERIFY(connect(_scriptWidget, SIGNAL(textChanged()), this, SLOT(textChange()))); // Need to use QMainWindow in order to make use of all features of docking. // (Note: Qt full support for dock windows implemented only for QMainWindow) _viewer = new OutputWidget(this); _outputWindow = new QMainWindow; _dock = new CustomDockWidget(this); _dock->setAllowedAreas(Qt::NoDockWidgetArea); _dock->setFeatures(QDockWidget::DockWidgetFloatable); _dock->setWidget(_viewer); _dock->setTitleBarWidget(new QWidget); VERIFY(connect(_dock, SIGNAL(topLevelChanged(bool)), this, SLOT(on_dock_undock()))); _outputWindow->addDockWidget(Qt::BottomDockWidgetArea, _dock); _outputLabel = new QLabel(this); _outputLabel->setContentsMargins(0, 5, 0, 0); _outputLabel->setVisible(false); _line = new QFrame(this); _line->setFrameShape(QFrame::HLine); _line->setFrameShadow(QFrame::Raised); _mainLayout = new QVBoxLayout; _mainLayout->setSpacing(0); _mainLayout->setContentsMargins(0, 0, 0, 0); _mainLayout->addWidget(_scriptWidget); _mainLayout->addWidget(_line); _mainLayout->addWidget(_outputLabel, 0, Qt::AlignTop); _mainLayout->addWidget(_outputWindow, 1); setLayout(_mainLayout); } void QueryWidget::setScriptFocus() { _scriptWidget->setScriptFocus(); } void QueryWidget::showAutocompletion() { _scriptWidget->showAutocompletion(); } void QueryWidget::hideAutocompletion() { _scriptWidget->hideAutocompletion(); } void QueryWidget::setCurrentDatabase(const std::string & dbname) { _scriptWidget->setCurrentDatabase(dbname); } void QueryWidget::bringDockToFront() { _dock->raise(); // required for MAC only; possible Qt bug _dock->activateWindow(); } bool QueryWidget::outputWindowDocked() const { if (_dock) { return !_dock->isFloating(); } else { // _dock is not initialized yet, but it will be docked when initialized return true; } } void QueryWidget::execute() { QString query = _scriptWidget->selectedText(); if (query.isEmpty()) query = _scriptWidget->text(); showProgress(); _shell->open(QtUtils::toStdString(query)); } void QueryWidget::stop() { _shell->stop(); } void QueryWidget::toggleOrientation() { _viewer->toggleOrientation(); } void QueryWidget::openNewTab() { if (_shell) { MongoServer *server = _shell->server(); QString query = _scriptWidget->selectedText(); AppRegistry::instance().app()->openShell(server, query, _currentResult.currentDatabase(), AppRegistry::instance().settingsManager()->autoExec()); } } void QueryWidget::saveToFile() { if (_shell) { _shell->setScript(_scriptWidget->text()); if (_shell->saveToFile()) { _isTextChanged = false; updateCurrentTab(); } } } void QueryWidget::savebToFileAs() { if (_shell) { _shell->setScript(_scriptWidget->text()); if (_shell->saveToFileAs()) { _isTextChanged = false; updateCurrentTab(); } } } void QueryWidget::openFile() { if (_shell && _shell->loadFromFile()) { _scriptWidget->setText(QtUtils::toQString(_shell->query())); _isTextChanged = false; updateCurrentTab(); } } void QueryWidget::textChange() { _isTextChanged = true; updateCurrentTab(); } QueryWidget::~QueryWidget() { AppRegistry::instance().app()->closeShell(_shell); } void QueryWidget::reload() { execute(); } void QueryWidget::duplicate() { _scriptWidget->selectAll(); openNewTab(); } void QueryWidget::enterTreeMode() { _viewer->enterTreeMode(); } void QueryWidget::enterTextMode() { _viewer->enterTextMode(); } void QueryWidget::enterTableMode() { _viewer->enterTableMode(); } void QueryWidget::enterCustomMode() { _viewer->enterCustomMode(); } void QueryWidget::showProgress() { _viewer->showProgress(); } void QueryWidget::dockUndock() { // Toggle between dock/undock _dock->setFloating(!_dock->isFloating()); }; void QueryWidget::changeShellTimeout() { changeShellTimeoutDialog(); } void QueryWidget::hideProgress() { _viewer->hideProgress(); } void QueryWidget::handle(DocumentListLoadedEvent *event) { hideProgress(); if (event->isError()) { QString message = QString("Failed to load documents.\n\nError:\n%1") .arg(QtUtils::toQString(event->error().errorMessage())); QMessageBox::information(this, "Error", message); return; } // this should be in viewer, subscribed to ScriptExecutedEvent _viewer->updatePart(event->resultIndex(), event->queryInfo(), event->documents()); } void QueryWidget::handle(ScriptExecutedEvent *event) { hideProgress(); _currentResult = event->result(); if (_currentResult.results().size() == 1) { MongoShellResult const& result = _currentResult.results().front(); AggrInfo const& aggrInfo = result.aggrInfo(); if (aggrInfo.isValid && aggrInfo.resultIndex > -1) { _viewer->updatePart(aggrInfo.resultIndex, aggrInfo, _currentResult.results().front().documents()); return; } } updateCurrentTab(); displayData(event->result().results(), event->empty()); // this should be in ScriptWidget, which is subscribed to ScriptExecutedEvent _scriptWidget->setup(event->result()); activateTabContent(); if (event->isError()) { // For some cases, event error message already contains string "Error:" QString const& subStr = QString::fromStdString(event->error().errorMessage()).startsWith("Error", Qt::CaseInsensitive) ? "" : "Error:\n"; QString const& message = "Failed to execute script.\n\n" + subStr + QString::fromStdString((event->error().errorMessage())); QMessageBox::critical(this, "Error", message); } if (event->timeoutReached()) { auto const shellTimeoutSec = AppRegistry::instance().settingsManager()->shellTimeoutSec(); QString const subStr = _currentResult.results().size() > 1 ? "At least one of the scripts has reached shell timeout" : "The script has reached shell timeout"; QString const secondStr = (shellTimeoutSec > 1) ? " seconds)" : " second)"; QString messageShort = "Failed to execute all of the script. " + subStr + " (" + QString::number(shellTimeoutSec) + secondStr + " limit. "; QString messageLong = messageShort + "\n\nPlease increase the value of shell timeout using button below " "or from the main window menu \"Options->Change Shell Timeout\"."; LOG_MSG(messageShort, mongo::logger::LogSeverity::Error()); auto errorDia = new QMessageBox(QMessageBox::Icon::Critical, "Error", messageLong); auto but = new QPushButton("Change Shell Timeout"); VERIFY(connect(but, SIGNAL(clicked()), this, SLOT(changeShellTimeout()))); errorDia->addButton(but, QMessageBox::NoRole); errorDia->exec(); } } void QueryWidget::activateTabContent() { AppRegistry::instance().bus()->publish(new QueryWidgetUpdatedEvent(this, _currentResult.results().size())); _scriptWidget->setScriptFocus(); } void QueryWidget::handle(AutocompleteResponse *event) { if (event->isError()) { // Do not show error message (error should be already logged) return; } _scriptWidget->showAutocompletion(event->list, QtUtils::toQString(event->prefix) ); } void QueryWidget::on_dock_undock() { if (!_dock->isFloating()) { // If output window docked // Settings to revert to docked mode _scriptWidget->ui_queryLinesCountChanged(); _mainLayout->addWidget(_scriptWidget); _mainLayout->addWidget(_line); _mainLayout->addWidget(_outputWindow, 1); _dock->setFeatures(QDockWidget::DockWidgetFloatable); _dock->setTitleBarWidget(new QWidget); _viewer->applyDockUndockSettings(true); } else { // output window undocked(floating) // Settings for query window in order to use maximum space _scriptWidget->disableFixedHeight(); _mainLayout->addWidget(_scriptWidget, 1); _mainLayout->addWidget(_line); _mainLayout->addWidget(_outputWindow); _dock->setFeatures(QDockWidget::DockWidgetClosable); _dock->setTitleBarWidget(nullptr); _viewer->applyDockUndockSettings(false); } } void QueryWidget::updateCurrentTab() { const QString &shellQuery = QtUtils::toQString(_shell->query()); QString toolTipQuery = shellQuery.left(700); QString tabTitle, toolTipText; if (_shell) { QFileInfo fileInfo(_shell->filePath()); if (fileInfo.isFile()) { tabTitle = fileInfo.fileName(); toolTipText = fileInfo.filePath(); } } if (tabTitle.isEmpty() && shellQuery.isEmpty()) { tabTitle = "New Shell"; } else { if (tabTitle.isEmpty()) { tabTitle = shellQuery.left(41).replace(QRegExp("[\n\r\t]"), " "); toolTipText = QString("<pre>%1</pre>").arg(toolTipQuery); } else { //tabTitle = QString("%1 %2").arg(tabTitle).arg(shellQuery); toolTipText = QString("<b>%1</b><br/><pre>%2</pre>").arg(toolTipText).arg(toolTipQuery); } } if (_isTextChanged) { tabTitle = "* " + tabTitle; } emit titleChanged(tabTitle); emit toolTipChanged(toolTipText); } void QueryWidget::displayData(const std::vector<MongoShellResult> &results, bool empty) { if (!empty) { bool isOutVisible = results.size() == 0 && !_scriptWidget->text().isEmpty(); if (isOutVisible) { _outputLabel->setText(" Script executed successfully, but there are no results to show."); } _outputLabel->setVisible(isOutVisible); } _viewer->present(_shell, results); } }
13,474
C++
.cpp
347
29.9683
115
0.614425
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,745
BsonTreeItem.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/BsonTreeItem.cpp
#include "robomongo/gui/widgets/workarea/BsonTreeItem.h" #include <mongo/client/dbclient_base.h> using namespace mongo; namespace { struct removeIfFound { removeIfFound(Robomongo::BsonTreeItem *item) :_whatSearch(item) {} bool operator()(const Robomongo::BsonTreeItem* item) const { if (item == _whatSearch) { delete _whatSearch; return true; } return false; } const Robomongo::BsonTreeItem *const _whatSearch; }; const Robomongo::BsonTreeItem *findSuperRoot(const Robomongo::BsonTreeItem *const item) { Robomongo::BsonTreeItem *parent = qobject_cast<Robomongo::BsonTreeItem *>(item->parent()); if (parent) { Robomongo::BsonTreeItem *grParent = qobject_cast<Robomongo::BsonTreeItem *>(parent->parent()); if (grParent) { return findSuperRoot(parent); } } return item; } } namespace Robomongo { BsonTreeItem::BsonTreeItem(QObject *parent) :BaseClass(parent) { } BsonTreeItem::BsonTreeItem(const mongo::BSONObj &bsonObjRoot, QObject *parent) :BaseClass(parent), _root(bsonObjRoot) { } unsigned BsonTreeItem::childrenCount() const { return _items.size(); } void BsonTreeItem::clear() { _items.clear(); } void BsonTreeItem::addChild(BsonTreeItem *item) { _items.push_back(item); } BsonTreeItem* BsonTreeItem::child(unsigned pos) const { return _items[pos]; } BsonTreeItem* BsonTreeItem::childSafe(unsigned pos) const { if (childrenCount() > pos) { return _items[pos]; } else { return NULL; } } BsonTreeItem* BsonTreeItem::childByKey(const QString &val) { for (unsigned i = 0; i < _items.size(); ++i) { if (_items[i]->key() == val) { return _items[i]; } } return NULL; } const BsonTreeItem *BsonTreeItem::superParent() const { return findSuperRoot(this); } mongo::BSONObj BsonTreeItem::superRoot() const { return superParent()->root(); } mongo::BSONObj BsonTreeItem::root() const { return _root; } int BsonTreeItem::indexOf(BsonTreeItem *item) const { for (unsigned i = 0; i < _items.size(); ++i) { if (item == _items[i]) { return i; } } return -1; } QString BsonTreeItem::key() const { return _fields._key; } QString BsonTreeItem::value() const { return _fields._value; } mongo::BSONType BsonTreeItem::type() const { return _fields._type; } void BsonTreeItem::setKey(const QString &key) { _fields._key = key; } void BsonTreeItem::setValue(const QString &value) { _fields._value = value; } void BsonTreeItem::setType(mongo::BSONType type) { _fields._type = type; } mongo::BinDataType BsonTreeItem::binType() const { return _fields._binType; } void BsonTreeItem::setBinType(mongo::BinDataType type) { _fields._binType = type; } void BsonTreeItem::removeChild(BsonTreeItem *item) { _items.erase(std::remove_if(_items.begin(), _items.end(), removeIfFound(item)), _items.end()); } }
3,507
C++
.cpp
133
19.097744
106
0.582112
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,746
OutputWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/OutputWidget.cpp
#include "robomongo/gui/widgets/workarea/OutputWidget.h" #include <QHBoxLayout> #include <QSplitter> #include <QWidget> #include <QMouseEvent> #include "robomongo/core/AppRegistry.h" #include "robomongo/core/domain/MongoShell.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/widgets/workarea/OutputItemContentWidget.h" #include "robomongo/gui/widgets/workarea/ProgressBarPopup.h" #include "robomongo/gui/widgets/workarea/WorkAreaTabBar.h" namespace Robomongo { OutputWidget::OutputWidget(QWidget *parent) : QTabWidget(parent), _splitter(new QSplitter), _tabbedResults(false) { _splitter->setOrientation(Qt::Vertical); _splitter->setHandleWidth(1); _splitter->setContentsMargins(0, 0, 0, 0); QVBoxLayout *layout = new QVBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(_splitter); setLayout(layout); setTabsClosable(true); setElideMode(Qt::ElideRight); setMovable(true); #ifdef __APPLE__ setDocumentMode(false); #else setDocumentMode(true); #endif setStyleSheet(buildStyleSheet()); VERIFY(connect(this, SIGNAL(tabCloseRequested(int)), SLOT(tabCloseRequested(int)))); _progressBarPopup = new ProgressBarPopup(this); } void OutputWidget::present(MongoShell *shell, const std::vector<MongoShellResult> &results) { if (_prevResultsCount > 0) clearAllParts(); int const RESULTS_SIZE = _prevResultsCount = results.size(); bool const multipleResults = (RESULTS_SIZE > 1); _tabbedResults = (RESULTS_SIZE > 2); _splitter->setHidden(_tabbedResults ? true : false); _outputItemContentWidgets.clear(); while (count() > 0) removeTab(count()-1); for (int i = 0; i < RESULTS_SIZE; ++i) { MongoShellResult shellResult = results[i]; double secs = shellResult.elapsedMs() / 1000.f; ViewMode viewMode = AppRegistry::instance().settingsManager()->viewMode(); if (_prevViewModes.size()) { viewMode = _prevViewModes.back(); _prevViewModes.pop_back(); } bool const firstItem = (0 == i); bool const lastItem = (RESULTS_SIZE-1 == i); OutputItemContentWidget* item = nullptr; if (shellResult.documents().size() > 0) { item = new OutputItemContentWidget(viewMode, shell, QtUtils::toQString(shellResult.type()), shellResult.documents(), shellResult.queryInfo(), secs, multipleResults, _tabbedResults, firstItem, lastItem, shellResult.aggrInfo(), this); } else { item = new OutputItemContentWidget(viewMode, shell, QtUtils::toQString(shellResult.response()), secs, multipleResults, _tabbedResults, firstItem, lastItem, shellResult.aggrInfo(), this); } VERIFY(connect(item, SIGNAL(maximizedPart()), this, SLOT(maximizePart()))); VERIFY(connect(item, SIGNAL(restoredSize()), this, SLOT(restoreSize()))); if (_tabbedResults) { addTab(item, QString::fromStdString(shellResult.statementShort())); setTabToolTip(i, QString::fromStdString(shellResult.statement())); } else _splitter->addWidget(item); _outputItemContentWidgets.push_back(item); } tryToMakeAllPartsEqualInSize(); } void OutputWidget::updatePart(int partIndex, const MongoQueryInfo &queryInfo, const std::vector<MongoDocumentPtr> &documents) { if (!_tabbedResults && partIndex >= _splitter->count()) return; OutputItemContentWidget* outputItemContentWidget = nullptr; if(_tabbedResults) outputItemContentWidget = qobject_cast<OutputItemContentWidget*>(currentWidget()); else outputItemContentWidget = qobject_cast<OutputItemContentWidget*>(_splitter->widget(partIndex)); outputItemContentWidget->updateWithInfo(queryInfo, documents); outputItemContentWidget->refreshOutputItem(); } void OutputWidget::updatePart(int partIndex, const AggrInfo &agrrInfo, const std::vector<MongoDocumentPtr> &documents) { if (partIndex >= _splitter->count()) return; auto outputItemContentWidget = qobject_cast<OutputItemContentWidget*>(_splitter->widget(partIndex)); outputItemContentWidget->updateWithInfo(agrrInfo, documents); outputItemContentWidget->refreshOutputItem(); } void OutputWidget::toggleOrientation() { bool const horizontal = _splitter->orientation() == Qt::Horizontal; _splitter->setOrientation(horizontal ? Qt::Vertical : Qt::Horizontal); int const COUNT = _splitter->count(); if (COUNT > 1) { auto const* firstItem = qobject_cast<OutputItemContentWidget*>(_splitter->widget(0)); auto const* lastItem = qobject_cast<OutputItemContentWidget*>(_splitter->widget(COUNT-1)); firstItem->toggleOrientation(_splitter->orientation()); lastItem->toggleOrientation(_splitter->orientation()); } } void OutputWidget::switchMode( std::function<void(OutputItemContentWidget*)> modeFunc ) { if (_tabbedResults) { QWidget* currentTab { widget(currentIndex()) }; modeFunc(qobject_cast<OutputItemContentWidget*>(currentTab)); } else { for (int i = 0; i < _splitter->count(); i++) { QWidget* widget { _splitter->widget(i) }; modeFunc(qobject_cast<OutputItemContentWidget*>(widget)); } } } void OutputWidget::enterTreeMode() { switchMode(&OutputItemContentWidget::showTree); } void OutputWidget::enterTextMode() { switchMode(&OutputItemContentWidget::showText); } void OutputWidget::enterTableMode() { switchMode(&OutputItemContentWidget::showTable); } void OutputWidget::enterCustomMode() { switchMode(&OutputItemContentWidget::showCustom); } void OutputWidget::maximizePart() { OutputItemContentWidget *result = qobject_cast<OutputItemContentWidget *>(sender()); int count = _splitter->count(); for (int i = 0; i < count; i++) { OutputItemContentWidget *widget = (OutputItemContentWidget *) _splitter->widget(i); if (widget != result) widget->hide(); } } void OutputWidget::tabCloseRequested(int index) { removeTab(index); } void OutputWidget::restoreSize() { int count = _splitter->count(); for (int i = 0; i < count; i++) { OutputItemContentWidget *widget = (OutputItemContentWidget *) _splitter->widget(i); widget->show(); } } int OutputWidget::resultIndex(OutputItemContentWidget *result) { return _splitter->indexOf(result); } void OutputWidget::showProgress() { QSize siz = size(); QPoint point(siz.width() / 2 - ProgressBarPopup::width/2, siz.height() / 2 - ProgressBarPopup::height/2); _progressBarPopup->move(point); _progressBarPopup->show(); } void OutputWidget::hideProgress() { _progressBarPopup->hide(); } bool OutputWidget::progressBarActive() const { return _progressBarPopup->isVisible(); } void OutputWidget::applyDockUndockSettings(bool isDocking) const { for (auto const& item : _outputItemContentWidgets) { item->applyDockUndockSettings(isDocking); } } Qt::Orientation OutputWidget::getOrientation() const { return _splitter->orientation(); } void OutputWidget::mouseReleaseEvent(QMouseEvent * event) { if (event->button() != Qt::MidButton) return; int const tabIndex = tabBar()->tabAt(event->pos()); removeTab(tabIndex); QTabWidget::mouseReleaseEvent(event); } void OutputWidget::clearAllParts() { _prevViewModes.clear(); while (_splitter->count() > 0) { OutputItemContentWidget *widget = (OutputItemContentWidget *)_splitter->widget(_splitter->count()-1); _prevViewModes.push_back(widget->viewMode()); widget->hide(); delete widget; } } QString OutputWidget::buildStyleSheet() { QColor background = palette().window().color(); QColor gradientZero = QColor("#ffffff"); //Qt::white;//.lighter(103); QColor gradientOne = background.lighter(104); //Qt::white;//.lighter(103); QColor gradientTwo = background.lighter(108); //.lighter(103); QColor selectedBorder = background.darker(103); QString aga1 = gradientOne.name(); QString aga2 = gradientTwo.name(); QString aga3 = background.name(); #ifdef __APPLE__ QString styles = QString( "QTabWidget::pane { background-color: white; }" // This style disables default styling under Mac "QTabWidget::tab-bar {" "alignment: left;" "border-top-left-radius: 2px;" "border-top-right-radius: 2px;" "}" "QTabBar::close-button { " "margin-top: 2px;" "image: url(:/robomongo/icons/close_2_Mac_16x16.png);" "width: 10px;" "height: 10px;" "}" "QTabBar::close-button:hover { " "image: url(:/robomongo/icons/close_hover_16x16.png);" "width: 15px;" "height: 15px;" "}" "QTabBar::tab:selected { " "background: white; /*#E1E1E1*/; " "color: #282828;" "} " "QTabBar::tab {" "color: #505050;" "font-size: 11px;" "background: %1;" "border-top-left-radius: 2px;" "border-top-right-radius: 2px;" "border-right: 1px solid #aaaaaa;" "padding: 8px 0px 5px 0px;" // top r b l "}" ).arg(QWidget::palette().color(QWidget::backgroundRole()).darker(114).name()); #else // Wind and Linux QString styles = QString( "QTabBar::close-button { " "image: url(:/robomongo/icons/close_2_16x16.png);" "width: 10px;" "height: 10px;" "}" "QTabBar::close-button:hover { " "image: url(:/robomongo/icons/close_hover_16x16.png);" "width: 15px;" "height: 15px;" "}" "QTabBar::tab {" "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," "stop: 0 #F0F0F0, stop: 0.4 #DEDEDE," "stop: 0.5 #E6E6E6, stop: 1.0 #E1E1E1);" "border: 1px solid #C4C4C3;" "border-bottom-color: #B8B7B6;" // #C2C7CB same as the pane color "border-top-left-radius: 6px;" "border-top-right-radius: 6px;" "padding: 4px 4px 5px 8px;" "max-width: 200px;" "margin: 0px;" "margin-left: 1px;" "margin-right: -3px;" // it should be -(tab:first:margin-left + tab:last:margin-left) to fix incorrect text elidement "}" "QTabBar::tab:selected, QTabBar::tab:hover {" "/* background: qlineargradient(x1: 0, y1: 1, x2: 0, y2: 0," "stop: 0 %1, stop: 0.3 %2," //#fafafa, #f4f4f4 "stop: 0.6 %3, stop: 1.0 %4); */" //#e7e7e7, #fafafa "background-color: white;" "}" "QTabBar::tab:selected {" "margin-top: 1px;" "border-color: #9B9B9B;" // "border-bottom-color: %4;" //#fafafa "}" "QTabBar::tab:!selected {" "margin-top: 2px;" // make non-selected tabs look smaller "}" ).arg(gradientZero.name(), gradientOne.name(), gradientTwo.name(), "#ffffff"); #endif return styles; } void OutputWidget::tryToMakeAllPartsEqualInSize() { int resultsCount = _splitter->count(); if (resultsCount <= 1) return; int dimension = _splitter->orientation() == Qt::Vertical ? _splitter->height() : _splitter->width(); int step = dimension / resultsCount; QList<int> partSizes; for (int i = 0; i < resultsCount; ++i) { partSizes << step; } _splitter->setSizes(partSizes); } }
13,399
C++
.cpp
316
30.832278
150
0.571099
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,747
IndicatorLabel.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/IndicatorLabel.cpp
#include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include <QLabel> #include <QHBoxLayout> #include <QIcon> namespace Robomongo { Indicator::Indicator(const QIcon &icon, const QString &text) { QLabel *iconLabel = createLabelWithIcon(icon); _label = new QLabel(); QHBoxLayout *layout = new QHBoxLayout(); layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(iconLabel); layout->addSpacing(7); layout->addWidget(_label); layout->addSpacing(14); setLayout(layout); setText(text); } void Indicator::setText(const QString &text) { _label->setText(text); } QLabel *Indicator::createLabelWithIcon(const QIcon &icon) { QPixmap pixmap = icon.pixmap(16, 16); QLabel *label = new QLabel; label->setPixmap(pixmap); return label; } }
929
C++
.cpp
32
22.6875
64
0.639326
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,748
OutputItemHeaderWidget.cpp
Studio3T_robomongo/src/robomongo/gui/widgets/workarea/OutputItemHeaderWidget.cpp
#include "robomongo/gui/widgets/workarea/OutputItemHeaderWidget.h" #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QSplitter> #include "robomongo/core/utils/QtUtils.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/gui/widgets/workarea/QueryWidget.h" #include "robomongo/gui/widgets/workarea/OutputWidget.h" #include "robomongo/gui/widgets/workarea/OutputItemContentWidget.h" #include "robomongo/gui/widgets/workarea/IndicatorLabel.h" #include "robomongo/core/AppRegistry.h" #include "robomongo/core/settings/SettingsManager.h" namespace { QFrame *createVerticalLine() { QFrame *vline = new QFrame(); vline->setFrameShape(QFrame::VLine); vline->setFrameShadow(QFrame::Sunken); vline->setFixedWidth(5); return vline; } } namespace Robomongo { OutputItemHeaderWidget::OutputItemHeaderWidget( OutputItemContentWidget *outputItemContentWidget, bool multipleResults, bool tabbedResults, bool firstItem, bool lastItem, QWidget *parent) : QFrame(parent), _maxButton(nullptr), _dockUndockButton(nullptr), _maximized(false), _multipleResults(multipleResults), _firstItem(firstItem), _lastItem(lastItem), _orientation(Qt::Vertical) { setContentsMargins(5, 0, 0, 0); auto const* outputWidget = qobject_cast<OutputWidget*>(outputItemContentWidget->parentWidget()); _orientation = outputWidget->getOrientation(); // Text mode button _textButton = new QPushButton(this); _textButton->setIcon(GuiRegistry::instance().textIcon()); _textButton->setToolTip("View results in text mode"); _textButton->setFixedSize(24, 24); _textButton->setFlat(true); _textButton->setCheckable(true); // Tree mode button _treeButton = new QPushButton(this); _treeButton->hide(); _treeButton->setIcon(GuiRegistry::instance().treeIcon()); _treeButton->setToolTip("View results in tree mode"); _treeButton->setFixedSize(24, 24); _treeButton->setFlat(true); _treeButton->setCheckable(true); _treeButton->setChecked(true); // Table mode button _tableButton = new QPushButton(this); _tableButton->hide(); _tableButton->setIcon(GuiRegistry::instance().tableIcon()); _tableButton->setToolTip("View results in table mode"); _tableButton->setFixedSize(24, 24); _tableButton->setFlat(true); _tableButton->setCheckable(true); _tableButton->setChecked(true); // Custom mode button _customButton = new QPushButton(this); _customButton->hide(); _customButton->setIcon(GuiRegistry::instance().customIcon()); _customButton->setToolTip("View results in custom UI"); _customButton->setFixedSize(24, 24); _customButton->setFlat(true); _customButton->setCheckable(true); // Create maximize button only if there are multiple results if (_multipleResults && !tabbedResults) { _maxButton = new QPushButton; _maxButton->setIcon(GuiRegistry::instance().maximizeIcon()); _maxButton->setToolTip("Maximize this output result (double-click on result's header)"); _maxButton->setFixedSize(18, 18); _maxButton->setFlat(true); VERIFY(connect(_maxButton, SIGNAL(clicked()), this, SLOT(maximizeMinimizePart()))); } auto dockWidget = qobject_cast<QueryWidget::CustomDockWidget*>(outputItemContentWidget->parentWidget()->parentWidget()); auto queryWidget = dockWidget->getParentQueryWidget(); _dockUndockButton = new QPushButton; _dockUndockButton->setFixedSize(18, 18); _dockUndockButton->setFlat(true); _dockUndockButton->setHidden(true); applyDockUndockSettings(!dockWidget->isFloating()); VERIFY(connect(_dockUndockButton, SIGNAL(clicked()), queryWidget, SLOT(dockUndock()))); VERIFY(connect(_textButton, SIGNAL(clicked()), outputItemContentWidget, SLOT(showText()))); VERIFY(connect(_treeButton, SIGNAL(clicked()), outputItemContentWidget, SLOT(showTree()))); VERIFY(connect(_tableButton, SIGNAL(clicked()), outputItemContentWidget, SLOT(showTable()))); VERIFY(connect(_customButton, SIGNAL(clicked()), outputItemContentWidget, SLOT(showCustom()))); _collectionIndicator = new Indicator(GuiRegistry::instance().collectionIcon()); _timeIndicator = new Indicator(GuiRegistry::instance().timeIcon()); _paging = new PagingWidget(); _collectionIndicator->hide(); _timeIndicator->hide(); _paging->hide(); QHBoxLayout *layout = new QHBoxLayout(); #ifdef __APPLE__ layout->setContentsMargins(2, 8, 5, 1); #else layout->setContentsMargins(2, 0, 5, 1); #endif layout->setSpacing(0); layout->addWidget(_collectionIndicator); layout->addWidget(_timeIndicator); QSpacerItem *hSpacer = new QSpacerItem(2000, 24, QSizePolicy::Preferred, QSizePolicy::Minimum); layout->addSpacerItem(hSpacer); layout->addWidget(_paging); layout->addWidget(createVerticalLine()); layout->addSpacing(2); if (outputItemContentWidget->isCustomModeSupported()) { layout->addWidget(_customButton, 0, Qt::AlignRight); _customButton->show(); } if (outputItemContentWidget->isTreeModeSupported()) { layout->addWidget(_treeButton, 0, Qt::AlignRight); _treeButton->show(); } if (outputItemContentWidget->isTableModeSupported()) { layout->addWidget(_tableButton, 0, Qt::AlignRight); _tableButton->show(); } if (outputItemContentWidget->isTextModeSupported()) layout->addWidget(_textButton, 0, Qt::AlignRight); if (_multipleResults) layout->addWidget(_maxButton, 0, Qt::AlignRight); layout->addSpacing(3); _verticalLine = createVerticalLine(); _verticalLine->setHidden(true); layout->addWidget(_verticalLine); layout->addWidget(_dockUndockButton); setLayout(layout); // Update dock/undock button visibility if (_multipleResults) updateDockButtonOnToggleOrientation(); else { _verticalLine->setVisible(true); _dockUndockButton->setVisible(true); } if(tabbedResults) setStyleSheet("background-color: white"); } void OutputItemHeaderWidget::mouseDoubleClickEvent(QMouseEvent *) { maximizeMinimizePart(); } void OutputItemHeaderWidget::showText() { _textButton->setIcon(GuiRegistry::instance().textHighlightedIcon()); _textButton->setChecked(true); _treeButton->setIcon(GuiRegistry::instance().treeIcon()); _treeButton->setChecked(false); _tableButton->setIcon(GuiRegistry::instance().tableIcon()); _tableButton->setChecked(false); _customButton->setIcon(GuiRegistry::instance().customIcon()); _customButton->setChecked(false); } void OutputItemHeaderWidget::showTree() { _textButton->setIcon(GuiRegistry::instance().textIcon()); _textButton->setChecked(false); _treeButton->setIcon(GuiRegistry::instance().treeHighlightedIcon()); _treeButton->setChecked(true); _tableButton->setIcon(GuiRegistry::instance().tableIcon()); _tableButton->setChecked(false); _customButton->setIcon(GuiRegistry::instance().customIcon()); _customButton->setChecked(false); } void OutputItemHeaderWidget::showTable() { _textButton->setIcon(GuiRegistry::instance().textIcon()); _textButton->setChecked(false); _treeButton->setIcon(GuiRegistry::instance().treeIcon()); _treeButton->setChecked(false); _tableButton->setIcon(GuiRegistry::instance().tableHighlightedIcon()); _tableButton->setChecked(true); _customButton->setIcon(GuiRegistry::instance().customIcon()); _customButton->setChecked(false); } void OutputItemHeaderWidget::showCustom() { _textButton->setIcon(GuiRegistry::instance().textIcon()); _textButton->setChecked(false); _treeButton->setIcon(GuiRegistry::instance().treeIcon()); _treeButton->setChecked(false); _tableButton->setIcon(GuiRegistry::instance().tableIcon()); _tableButton->setChecked(false); _customButton->setIcon(GuiRegistry::instance().customHighlightedIcon()); _customButton->setChecked(true); } void OutputItemHeaderWidget::applyDockUndockSettings(bool isDocking) { if (isDocking) { _dockUndockButton->setIcon(GuiRegistry::instance().undockIcon()); _dockUndockButton->setToolTip("Undock into separate window"); } else { _dockUndockButton->setIcon(GuiRegistry::instance().dockIcon()); _dockUndockButton->setToolTip("Dock into main window"); } } void OutputItemHeaderWidget::toggleOrientation(Qt::Orientation orientation) { if (!_firstItem && !_lastItem) return; _orientation = orientation; updateDockButtonOnToggleOrientation(); } void OutputItemHeaderWidget::setTime(const QString &time) { _timeIndicator->setVisible(!time.isEmpty()); _timeIndicator->setText(time); } void OutputItemHeaderWidget::setCollection(const QString &collection) { _collectionIndicator->setVisible(!collection.isEmpty()); _collectionIndicator->setText(collection); } void OutputItemHeaderWidget::maximizeMinimizePart() { // No maximize/minimize behaviour if there is only one query result if (!_multipleResults) return; if (_maximized) { // restoring original size emit restoredSize(); _maxButton->setIcon(GuiRegistry::instance().maximizeIcon()); _maxButton->setToolTip("Maximize this output result (double-click on result header)"); updateDockButtonOnToggleOrientation(); } else { // maximizing emit maximizedPart(); _maxButton->setIcon(GuiRegistry::instance().minimizeIcon()); _maxButton->setToolTip("Restore back to original size (double-click on result header)"); _verticalLine->setVisible(true); _dockUndockButton->setVisible(true); } _maximized = !_maximized; } void OutputItemHeaderWidget::updateDockButtonOnToggleOrientation() const { if (!_multipleResults) return; if (_firstItem) { _verticalLine->setVisible(Qt::Vertical == _orientation); _dockUndockButton->setVisible(Qt::Vertical == _orientation); } else if (_lastItem) { _verticalLine->setVisible(Qt::Horizontal == _orientation); _dockUndockButton->setVisible(Qt::Horizontal == _orientation); } else { _verticalLine->setVisible(false); _dockUndockButton->setVisible(false); } } }
11,330
C++
.cpp
257
35.420233
128
0.659947
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,749
ComboBoxUtils.cpp
Studio3T_robomongo/src/robomongo/gui/utils/ComboBoxUtils.cpp
#include "robomongo/gui/utils/ComboBoxUtils.h" namespace Robomongo { namespace utils { /** * @brief This function behaves identically to Qt5 QComboBox::setCurrentText(). * We are using this function in order to support Qt4 */ void setCurrentText(QComboBox *comboBox, const QString &text) { if (comboBox->isEditable()) { comboBox->setEditText(text); } else { const int i = comboBox->findText(text); if (i > -1) comboBox->setCurrentIndex(i); } } } }
624
C++
.cpp
21
20.333333
87
0.546512
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,750
DialogUtils.cpp
Studio3T_robomongo/src/robomongo/gui/utils/DialogUtils.cpp
#include "robomongo/gui/utils/DialogUtils.h" namespace Robomongo { namespace utils { namespace { const QString titleTemaple = QString("%1 %2"); const QString textTemaple = QString("%1 <b>%3</b> %2?"); } int questionDialog(QWidget *parent, const QString &actionText, const QString &itemText, const QString& valueText) { return questionDialog(parent, actionText, itemText, textTemaple, valueText); } int questionDialog(QWidget *parent, const QString &actionText, const QString &itemText, const QString &templateText, const QString &valueText) { return QMessageBox::question(parent, titleTemaple.arg(actionText).arg(itemText), templateText.arg(actionText).arg(itemText.toLower()).arg(valueText), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton); } } }
892
C++
.cpp
20
36.9
220
0.674713
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,751
FindFrame.cpp
Studio3T_robomongo/src/robomongo/gui/editors/FindFrame.cpp
#include "robomongo/gui/editors/FindFrame.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include <QCheckBox> #include <QToolButton> #include <Qsci/qsciscintilla.h> #include <QMessageBox> #include <QKeyEvent> #include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include "robomongo/core/utils/QtUtils.h" #include "robomongo/core/KeyboardManager.h" #include "robomongo/gui/widgets/workarea/ScriptWidget.h" namespace Robomongo { FindFrame::FindFrame(QWidget *parent) : BaseClass(parent), _parent(parent), _scin(new RoboScintilla()), _findPanel(new QFrame(this)), _close(new QToolButton(this)), _findLine(new QLineEdit(this)), _next(new QPushButton("Next", this)), _prev(new QPushButton("Previous", this)), _caseSensitive(new QCheckBox("Match case", this)), _commentSign("// "), _commentSignLength(3) { _close->setIcon(QIcon(":/robomongo/icons/close_2_16x16.png")); _close->setToolButtonStyle(Qt::ToolButtonIconOnly); _close->setIconSize(QSize(16, 16)); _close->hide(); // We do not need close button because ESC works _findLine->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); QHBoxLayout *layout = new QHBoxLayout(); layout->setContentsMargins(2, 0, 6, 0); layout->setSpacing(7); layout->addWidget(_findLine); layout->addWidget(_next); layout->addWidget(_prev); layout->addWidget(_caseSensitive); _findPanel->setFixedHeight(HeightFindPanel); _findPanel->setLayout(layout); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setSpacing(0); mainLayout->addWidget(_scin, 1); mainLayout->addWidget(_findPanel, 0, Qt::AlignBottom); setLayout(mainLayout); _findPanel->hide(); VERIFY(connect(_close, SIGNAL(clicked()), _findPanel, SLOT(hide()))); VERIFY(connect(_next, SIGNAL(clicked()), this, SLOT(goToNextElement()))); VERIFY(connect(_prev, SIGNAL(clicked()), this, SLOT(goToPrevElement()))); } void FindFrame::wheelEvent(QWheelEvent *e) { return BaseClass::wheelEvent(e); } void FindFrame::keyPressEvent(QKeyEvent *keyEvent) { bool isFocusScin = _scin->isActiveWindow(); bool isShowFind = _findPanel->isVisible(); if (Qt::Key_Escape == keyEvent->key() && isFocusScin && isShowFind) { // Hide & Show of Scintilla widget solves problem of UI blinking _scin->hide(); _findPanel->hide(); _scin->setFocus(); _scin->show(); return keyEvent->accept(); } else if (Qt::Key_Return == keyEvent->key() && (keyEvent->modifiers() & Qt::ShiftModifier) && isFocusScin && isShowFind) { goToPrevElement(); } else if (Qt::Key_Return == keyEvent->key() && isFocusScin && isShowFind) { goToNextElement(); } else if (((keyEvent->modifiers() & Qt::ControlModifier) && keyEvent->key() == Qt::Key_F) && isFocusScin) { _findPanel->show(); _findLine->setFocus(); _findLine->selectAll(); return keyEvent->accept(); } else if (KeyboardManager::isToggleCommentsShortcut(keyEvent)) { toggleComments(); return keyEvent->accept(); } else { return BaseClass::keyPressEvent(keyEvent); } } void FindFrame::goToNextElement() { findElement(true); } void FindFrame::goToPrevElement() { findElement(false); } void FindFrame::findElement(bool forward) { const QString &text = _findLine->text(); if (!text.isEmpty()) { bool re = false; bool wo = false; bool looped = true; int index = 0; int line = 0; _scin->getCursorPosition(&line, &index); if (!forward) index -= _scin->selectedText().length(); _scin->setCursorPosition(line, 0); bool isFounded = _scin->findFirst(text, re, _caseSensitive->checkState() == Qt::Checked, wo, looped, forward, line, index); if (isFounded) { _scin->ensureCursorVisible(); } else { QMessageBox::warning(this, tr("Search"), tr("The specified text was not found.")); } } } void FindFrame::toggleComments() { int lineFrom, indexFrom, lineTo, indexTo; QString line; ScriptWidget *container; bool commentOut, is_textAndCursorNotificationsDisabled; _scin->getSelection(&lineFrom, &indexFrom, &lineTo, &indexTo); if (-1 == indexTo) { // There is no selection. Get cursor position _scin->getCursorPosition(&lineFrom, &indexFrom); lineTo = lineFrom; } // Define what action should be done for each selected line line = _scin->text(lineFrom); if (line.startsWith(_commentSign)) { // Remove comment sign commentOut = false; } else { // Add comment sign commentOut = true; } // To prevent displaying of autocomplete menu container = dynamic_cast<ScriptWidget*>(_parent); if (NULL != container) { is_textAndCursorNotificationsDisabled = container->getDisableTextAndCursorNotifications(); container->setDisableTextAndCursorNotifications(true); } for (int lineIndex = lineFrom; lineIndex <= lineTo; ++lineIndex) { setLineComment(lineIndex, commentOut); } /** * Changing cursor position cancels the selection, so restoring original position of the cursor is done * only if there was no selection at the beginning of the operation */ if (-1 == indexTo) { // No selection, set original cursor position if (commentOut) { _scin->setCursorPosition(lineFrom, indexFrom + _commentSignLength); } else { _scin->setCursorPosition(lineFrom, indexFrom - _commentSignLength); } } else { // Restore original selection if (commentOut) { _scin->setSelection(lineFrom, indexFrom + _commentSignLength, lineTo, indexTo + _commentSignLength); } else { _scin->setSelection(lineFrom, indexFrom - _commentSignLength, lineTo, indexTo - _commentSignLength); } } if (NULL != container) { container->setDisableTextAndCursorNotifications(is_textAndCursorNotificationsDisabled); } } void FindFrame::setLineComment(const int lineIndex, const bool commentOut) { QString line; line = _scin->text(lineIndex); if (commentOut) { // Add comment sign _scin->insertAt(_commentSign, lineIndex, 0); } else if (line.startsWith(_commentSign)) { // Remove comment sign _scin->setSelection(lineIndex, 0, lineIndex, _commentSignLength); _scin->removeSelectedText(); } } FindFrame::~FindFrame() { delete _scin; } }
7,445
C++
.cpp
186
30.387097
135
0.60103
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,752
PlainJavaScriptEditor.cpp
Studio3T_robomongo/src/robomongo/gui/editors/PlainJavaScriptEditor.cpp
#include "robomongo/gui/editors/PlainJavaScriptEditor.h" #include <QPainter> #include <QApplication> #include <QKeyEvent> #include "robomongo/core/AppRegistry.h" #include "robomongo/core/settings/SettingsManager.h" #include "robomongo/gui/GuiRegistry.h" #include "robomongo/core/utils/QtUtils.h" namespace { /** * @brief Returns the number of digits in an 32-bit integer * http://stackoverflow.com/questions/1489830/efficient-way-to-determine-number-of-digits-in-an-integer */ int getNumberOfDigits(int x) { if (x < 0) return getNumberOfDigits(-x) + 1; if (x >= 10000) { if (x >= 10000000) { if (x >= 100000000) { if (x >= 1000000000) return 10; return 9; } return 8; } if (x >= 100000) { if (x >= 1000000) return 7; return 6; } return 5; } if (x >= 100) { if (x >= 1000) return 4; return 3; } if (x >= 10) return 2; return 1; } } namespace Robomongo { const QColor RoboScintilla::marginsBackgroundColor = QColor(73, 76, 78); const QColor RoboScintilla::caretForegroundColor = QColor("#FFFFFF"); const QColor RoboScintilla::matchedBraceForegroundColor = QColor("#FF8861"); RoboScintilla::RoboScintilla(QWidget *parent) : QsciScintilla(parent), _ignoreEnterKey(false), _ignoreTabKey(false), _lineNumberDigitWidth(0), _lineNumberMarginWidth(0) { setAutoIndent(true); setIndentationsUseTabs(false); setIndentationWidth(indentationWidth); setUtf8(true); setMarginWidth(1, 0); setCaretForegroundColor(caretForegroundColor); setMatchedBraceForegroundColor(matchedBraceForegroundColor); //1AB0A6 setMatchedBraceBackgroundColor(marginsBackgroundColor); setContentsMargins(0, 0, 0, 0); setViewportMargins(3, 3, 3, 3); QFont ourFont = GuiRegistry::instance().font(); setMarginsFont(ourFont); setMarginLineNumbers(0, true); setMarginsBackgroundColor(QColor(53, 56, 58)); setMarginsForegroundColor(QColor(173, 176, 178)); SendScintilla(QsciScintilla::SCI_STYLESETFONT, 1, ourFont.family().data()); SendScintilla(QsciScintilla::SCI_SETHSCROLLBAR, 0); setWrapMode((QsciScintilla::WrapMode)QsciScintilla::SC_WRAP_NONE); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // Cache width of one digit #ifdef Q_OS_WIN _lineNumberDigitWidth = rowNumberWidth; #else _lineNumberDigitWidth = textWidth(STYLE_LINENUMBER, "0"); #endif updateLineNumbersMarginWidth(); setLineNumbers(AppRegistry::instance().settingsManager()->lineNumbers()); setUtf8(true); VERIFY(connect(this, SIGNAL(linesChanged()), this, SLOT(updateLineNumbersMarginWidth()))); } int RoboScintilla::lineNumberMarginWidth() const { return marginWidth(0); } int RoboScintilla::textWidth(int style, const QString &text) { const char *byteArray = (text.toUtf8()).constData(); return SendScintilla(SCI_TEXTWIDTH, style, byteArray); } void RoboScintilla::wheelEvent(QWheelEvent *e) { if (this->isActiveWindow()) { QsciScintilla::wheelEvent(e); } else { qApp->sendEvent(parentWidget(), e); e->accept(); } } void RoboScintilla::setLineNumbers(bool displayNumbers) { if (displayNumbers) { setMarginWidth(0, _lineNumberMarginWidth); } else { setMarginWidth(0, 0); } } void RoboScintilla::toggleLineNumbers() { setLineNumbers(!lineNumberMarginWidth()); } void RoboScintilla::keyPressEvent(QKeyEvent *keyEvent) { if (_ignoreEnterKey) { if (keyEvent->key() == Qt::Key_Return) { keyEvent->ignore(); _ignoreEnterKey = false; return; } } if (_ignoreTabKey) { if (keyEvent->key() == Qt::Key_Tab) { keyEvent->ignore(); _ignoreTabKey = false; return; } } if (keyEvent->key() == Qt::Key_F11) { keyEvent->ignore(); toggleLineNumbers(); return; } if (((keyEvent->modifiers() & Qt::ControlModifier) && (keyEvent->key() == Qt::Key_F4 || keyEvent->key() == Qt::Key_W || keyEvent->key() == Qt::Key_T || keyEvent->key() == Qt::Key_Space || keyEvent->key() == Qt::Key_F || keyEvent->key() == Qt::Key_Slash)) || keyEvent->key() == Qt::Key_Escape /*|| keyEvent->key() == Qt::Key_Return*/ || ((keyEvent->modifiers() & Qt::ControlModifier) && (keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Left) || ((keyEvent->modifiers() & Qt::ControlModifier) && (keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Right) || ((keyEvent->modifiers() & Qt::ControlModifier) && (keyEvent->modifiers() & Qt::ShiftModifier) && keyEvent->key() == Qt::Key_C) ) { keyEvent->ignore(); } else { BaseClass::keyPressEvent(keyEvent); } } void RoboScintilla::updateLineNumbersMarginWidth() { int numberOfDigits = getNumberOfDigits(lines()); _lineNumberMarginWidth = numberOfDigits * _lineNumberDigitWidth + rowNumberWidth; // If line numbers margin already displayed, update its width if (lineNumberMarginWidth()) { setMarginWidth(0, _lineNumberMarginWidth); } } void RoboScintilla::setAppropriateBraceMatching() { #ifdef Q_OS_MAC // On Mac OS when brace matching is enabled, text // will blink when you move cursor to some brace or // when inside braces. This behaviour is not fully fixed // in QScintilla 2.9.1 and 2.8.4 setBraceMatching(QsciScintilla::NoBraceMatch); #else setBraceMatching(QsciScintilla::StrictBraceMatch); #endif } }
6,424
C++
.cpp
176
27.534091
143
0.597108
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,888
InputMethod.cpp
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/Qt4Qt5/InputMethod.cpp
// Copyright (c) 2014 Riverbank Computing Limited // Copyright (c) 2011 Archaeopteryx Software, Inc. // Copyright (c) 1990-2011, Scientific Toolworks, Inc. // // The License.txt file describes the conditions under which this software may // be distributed. #include <qglobal.h> #include "Qsci/qsciscintillabase.h" #include <QColor> #include <QFont> #include <QInputMethodEvent> #include <QRect> #include <QTextCharFormat> #include <QTextFormat> #include <QVariant> #include <QVarLengthArray> #include "ScintillaQt.h" #define INDIC_INPUTMETHOD 24 void QsciScintillaBase::inputMethodEvent(QInputMethodEvent *event) { // Do nothing if it appears to be a non-event. This can sometimes happen // (but why?) on losing focus. if (event->commitString().isEmpty() && event->preeditString().isEmpty() && event->replacementLength() == 0) return; ScintillaBytes bytes; // Clear the current selection. sci->ClearSelection(); if (preeditPos >= 0) sci->SetSelection(preeditPos, preeditPos); // Insert the commit string. if (!event->commitString().isEmpty() || event->replacementLength()) { // Select the text to be removed. int commitPos = SendScintilla(SCI_GETCURRENTPOS); int start = commitPos + event->replacementStart(); int end = start + event->replacementLength(); sci->SetSelection(start, end); // Replace the selection with the commit string. bytes = textAsBytes(event->commitString()); sci->AddCharUTF(bytes.data(), bytes.length()); } // Select the previous preedit string. int pos = SendScintilla(SCI_GETCURRENTPOS); sci->SetSelection(pos, pos + preeditNrBytes); // Replace the selection with the new preedit string. bool recording = sci->recordingMacro; sci->recordingMacro = false; SendScintilla(SCI_SETUNDOCOLLECTION, false); bytes = textAsBytes(event->preeditString()); sci->AddCharUTF(bytes.data(), bytes.length()); SendScintilla(SCI_SETUNDOCOLLECTION, true); sci->recordingMacro = recording; sci->SetSelection(pos, pos); // Store the state of the current preedit string. preeditString = event->preeditString(); preeditNrBytes = bytes.length(); preeditPos = preeditNrBytes ? SendScintilla(SCI_GETCURRENTPOS) : -1; if (preeditNrBytes) { // Apply attributes to the preedit string. int indicNum = 0; sci->ShowCaretAtCurrentPosition(); foreach (QInputMethodEvent::Attribute a, event->attributes()) { QString prefix = preeditString.left(a.start); int prefixLength = textAsBytes(prefix).length(); int caretPos = preeditPos + prefixLength; if (a.type == QInputMethodEvent::Cursor) { sci->SetSelection(caretPos, caretPos); if (!a.length) sci->DropCaret(); } else if (a.type == QInputMethodEvent::TextFormat) { Q_ASSERT(a.value.canConvert(QVariant::TextFormat)); QTextFormat format = a.value.value<QTextFormat>(); Q_ASSERT(format.isCharFormat()); QTextCharFormat charFormat = format.toCharFormat(); if (charFormat.underlineStyle() != QTextCharFormat::NoUnderline) { QString sub = preeditString.mid(a.start, a.length); int subLength = textAsBytes(sub).length(); // Set temporary indicator for underline style. QColor uc = charFormat.underlineColor(); int style = INDIC_COMPOSITIONTHICK; if (charFormat.underlineStyle() == QTextCharFormat::DashUnderline) style = INDIC_DASH; SendScintilla(SCI_INDICSETSTYLE, INDIC_INPUTMETHOD + indicNum, style); SendScintilla(SCI_INDICSETFORE, INDIC_INPUTMETHOD + indicNum, uc.rgb()); SendScintilla(SCI_SETINDICATORCURRENT, INDIC_INPUTMETHOD + indicNum); SendScintilla(SCI_INDICATORFILLRANGE, caretPos, subLength); indicNum++; } } } } } QVariant QsciScintillaBase::inputMethodQuery(Qt::InputMethodQuery query) const { int pos = SendScintilla(SCI_GETCURRENTPOS); int line = SendScintilla(SCI_LINEFROMPOSITION, pos); switch (query) { #if QT_VERSION >= 0x050000 case Qt::ImHints: return QWidget::inputMethodQuery(query); #endif case Qt::ImMicroFocus: { int startPos = (preeditPos >= 0) ? preeditPos : pos; Point pt = sci->LocationFromPosition(startPos); int width = SendScintilla(SCI_GETCARETWIDTH); int height = SendScintilla(SCI_TEXTHEIGHT, line); return QRect(pt.x, pt.y, width, height); } case Qt::ImFont: { char fontName[64]; int style = SendScintilla(SCI_GETSTYLEAT, pos); int len = SendScintilla(SCI_STYLEGETFONT, style, (sptr_t)fontName); int size = SendScintilla(SCI_STYLEGETSIZE, style); bool italic = SendScintilla(SCI_STYLEGETITALIC, style); int weight = SendScintilla(SCI_STYLEGETBOLD, style) ? QFont::Bold : -1; return QFont(QString::fromUtf8(fontName, len), size, weight, italic); } case Qt::ImCursorPosition: { int paraStart = sci->pdoc->ParaUp(pos); return pos - paraStart; } case Qt::ImSurroundingText: { int paraStart = sci->pdoc->ParaUp(pos); int paraEnd = sci->pdoc->ParaDown(pos); QVarLengthArray<char,1024> buffer(paraEnd - paraStart + 1); Sci_CharacterRange charRange; charRange.cpMin = paraStart; charRange.cpMax = paraEnd; Sci_TextRange textRange; textRange.chrg = charRange; textRange.lpstrText = buffer.data(); SendScintilla(SCI_GETTEXTRANGE, 0, (sptr_t)&textRange); return bytesAsText(buffer.constData()); } case Qt::ImCurrentSelection: { QVarLengthArray<char,1024> buffer(SendScintilla(SCI_GETSELTEXT)); SendScintilla(SCI_GETSELTEXT, 0, (sptr_t)buffer.data()); return bytesAsText(buffer.constData()); } default: return QVariant(); } }
6,431
C++
.cpp
147
34.278912
111
0.632464
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
true
false
true
true
true
false
14,941
qscintillaplugin.cpp
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/designer-Qt3/qscintillaplugin.cpp
// This implements the QScintilla plugin for Qt Designer. #include <qwidgetplugin.h> #include <Qsci/qsciscintilla.h> static const char *qscintilla_pixmap[] = { "22 22 35 1", "m c #000000", "n c #000033", "p c #003300", "r c #003333", "v c #330000", "o c #330033", "l c #333300", "h c #333333", "c c #333366", "d c #336666", "u c #336699", "E c #3366cc", "k c #663333", "i c #663366", "b c #666666", "e c #666699", "A c #6666cc", "G c #669966", "f c #669999", "j c #6699cc", "y c #6699ff", "t c #996666", "a c #999999", "g c #9999cc", "s c #9999ff", "C c #99cc99", "x c #99cccc", "w c #99ccff", "F c #cc99ff", "q c #cccccc", "# c #ccccff", "B c #ccffcc", "z c #ccffff", "D c #ffffcc", ". c none", "........#abcda........", "......abefghdidcf.....", ".....cadhfaehjheck....", "....leh.m.ncbehjddo...", "...depn.hqhqhr#mccch..", "..bb.hcaeh.hqersjhjcd.", ".tcm.uqn.hc.uvwxhuygha", ".feh.n.hb.hhzemcwhmuAm", "Bgehghqqme.eo#wlnysbnj", "awhdAzn.engjepswhmuyuj", "bCh#m.de.jpqwbmcwemlcz", "hcb#xh.nd#qrbswfehwzbm", "bd#d.A#zor#qmgbzwgjgws", "ajbcuqhqzchwwbemewchmr", "Dcn#cwmhgwehgsxbmhEjAc", ".uanauFrhbgeahAAbcbuhh", ".bohdAegcccfbbebuucmhe", "..briuauAediddeclchhh.", "...hcbhjccdecbceccch..", "....nhcmeccdccephcp...", ".....crbhchhhrhhck....", "......tcmdhohhcnG....." }; class QScintillaPlugin : public QWidgetPlugin { public: QScintillaPlugin() {}; QStringList keys() const; QWidget *create(const QString &classname, QWidget *parent = 0, const char *name = 0); QString group(const QString &) const; QIconSet iconSet(const QString &) const; QString includeFile(const QString &) const; QString toolTip(const QString &) const; QString whatsThis(const QString &) const; bool isContainer(const QString &) const; }; QStringList QScintillaPlugin::keys() const { QStringList list; list << "QsciScintilla"; return list; } QWidget *QScintillaPlugin::create(const QString &key, QWidget *parent, const char *name) { if (key == "QsciScintilla") return new QsciScintilla(parent, name); return 0; } QString QScintillaPlugin::group(const QString &feature) const { if (feature == "QsciScintilla") return "Input"; return QString::null; } QIconSet QScintillaPlugin::iconSet(const QString &) const { return QIconSet(QPixmap(qscintilla_pixmap)); } QString QScintillaPlugin::includeFile(const QString &feature) const { if (feature == "QsciScintilla") return "qsciscintilla.h"; return QString::null; } QString QScintillaPlugin::toolTip(const QString &feature) const { if (feature == "QsciScintilla") return "QScintilla Programmer's Editor"; return QString::null; } QString QScintillaPlugin::whatsThis(const QString &feature) const { if (feature == "QsciScintilla") return "A port to Qt of the Scintilla programmer's editor"; return QString::null; } bool QScintillaPlugin::isContainer(const QString &) const { return FALSE; } Q_EXPORT_PLUGIN(QScintillaPlugin)
2,961
C++
.cpp
121
22.438017
88
0.702886
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,959
SciClasses.cpp
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/Qt3/SciClasses.cpp
// The implementation of various Qt version independent classes used by the // rest of the port. // // Copyright (c) 2014 Riverbank Computing Limited <info@riverbankcomputing.com> // // This file is part of QScintilla. // // This file may be used under the terms of the GNU General Public // License versions 2.0 or 3.0 as published by the Free Software // Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 // included in the packaging of this file. Alternatively you may (at // your option) use any later version of the GNU General Public // License if such license has been publicly approved by Riverbank // Computing Limited (or its successors, if any) and the KDE Free Qt // Foundation. In addition, as a special exception, Riverbank gives you // certain additional rights. These rights are described in the Riverbank // GPL Exception version 1.1, which can be found in the file // GPL_EXCEPTION.txt in this package. // // If you are unsure which license is appropriate for your use, please // contact the sales department at sales@riverbankcomputing.com. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #include "SciNamespace.h" #include "SciClasses.h" #include <qevent.h> #include <qpainter.h> #include "ScintillaQt.h" #include "ListBoxQt.h" // Create a call tip. QsciSciCallTip::QsciSciCallTip(QWidget *parent, QsciScintillaQt *sci_) : QWidget(parent, 0, Qt::WType_Popup|Qt::WStyle_Customize|Qt::WStyle_NoBorder), sci(sci_) { // Ensure that the main window keeps the focus (and the caret flashing) // when this is displayed. setFocusProxy(parent); } // Destroy a call tip. QsciSciCallTip::~QsciSciCallTip() { // Ensure that the main window doesn't receive a focus out event when // this is destroyed. setFocusProxy(0); } // Paint a call tip. void QsciSciCallTip::paintEvent(QPaintEvent *) { QSCI_SCI_NAMESPACE(Surface) *surfaceWindow = QSCI_SCI_NAMESPACE(Surface)::Allocate(SC_TECHNOLOGY_DEFAULT); if (!surfaceWindow) return; QPainter p(this); surfaceWindow->Init(&p); surfaceWindow->SetUnicodeMode(sci->CodePage() == SC_CP_UTF8); sci->ct.PaintCT(surfaceWindow); delete surfaceWindow; } // Handle a mouse press in a call tip. void QsciSciCallTip::mousePressEvent(QMouseEvent *e) { QSCI_SCI_NAMESPACE(Point) pt; pt.x = e->x(); pt.y = e->y(); sci->ct.MouseClick(pt); sci->CallTipClick(); update(); } // Add an item and associated command to the popup and enable it if required. void QsciSciPopup::addItem(const QString &label, int cmd, bool enabled, QsciScintillaQt *sci_) { insertItem(label, this, SLOT(on_triggered(int)), 0, cmd); setItemEnabled(cmd, enabled); sci = sci_; } // Add a separator to the popup. void QsciSciPopup::addSeparator() { insertSeparator(); } // A slot to handle a menu action being triggered. void QsciSciPopup::on_triggered(int cmd) { sci->Command(cmd); } QsciSciListBox::QsciSciListBox(QWidget *parent, QsciListBoxQt *lbx_) : QListBox(parent,0,Qt::WType_Popup|Qt::WStyle_Customize|Qt::WStyle_NoBorder|Qt::WStaticContents), lbx(lbx_) { setFocusProxy(parent); setFrameShape(StyledPanel); setFrameShadow(Plain); connect(this,SIGNAL(doubleClicked(QListBoxItem *)), SLOT(handleSelection())); connect(this,SIGNAL(highlighted(QListBoxItem *)), SLOT(ensureCurrentVisible())); } int QsciSciListBox::find(const QString &prefix) { return index(findItem(prefix, Qt::CaseSensitive|Qt::BeginsWith)); } QsciSciListBox::~QsciSciListBox() { // Ensure that the main widget doesn't get a focus out event when this is // destroyed. setFocusProxy(0); } void QsciSciListBox::handleSelection() { if (lbx && lbx->cb_action) lbx->cb_action(lbx->cb_data); }
3,923
C++
.cpp
112
31.946429
112
0.736744
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,971
InputMethod.cpp
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/Qt3/InputMethod.cpp
// Copyright (c) 2014 Riverbank Computing Limited // Copyright (c) 2011 Archaeopteryx Software, Inc. // Copyright (c) 1990-2011, Scientific Toolworks, Inc. // // The License.txt file describes the conditions under which this software may // be distributed. #include <qglobal.h>
281
C++
.cpp
7
38.714286
78
0.771218
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,987
qsciscintillabase.cpp
Studio3T_robomongo/src/third-party/qscintilla-2.8.4/sources/Qt3/qsciscintillabase.cpp
// This module implements the "official" low-level API. // // Copyright (c) 2014 Riverbank Computing Limited <info@riverbankcomputing.com> // // This file is part of QScintilla. // // This file may be used under the terms of the GNU General Public // License versions 2.0 or 3.0 as published by the Free Software // Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 // included in the packaging of this file. Alternatively you may (at // your option) use any later version of the GNU General Public // License if such license has been publicly approved by Riverbank // Computing Limited (or its successors, if any) and the KDE Free Qt // Foundation. In addition, as a special exception, Riverbank gives you // certain additional rights. These rights are described in the Riverbank // GPL Exception version 1.1, which can be found in the file // GPL_EXCEPTION.txt in this package. // // If you are unsure which license is appropriate for your use, please // contact the sales department at sales@riverbankcomputing.com. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #include "Qsci/qsciscintillabase.h" #include <qapplication.h> #include <qclipboard.h> #include <qcolor.h> #include <qscrollbar.h> #include <qtextcodec.h> #include <qdragobject.h> #include <qevent.h> #include <qlayout.h> #include <qpainter.h> #include <qptrlist.h> #include "ScintillaQt.h" // The #defines in Scintilla.h and the enums in qsciscintillabase.h conflict // (because we want to use the same names) so we have to undefine those we use // in this file. #undef SCI_SETCARETPERIOD #undef SCK_DOWN #undef SCK_UP #undef SCK_LEFT #undef SCK_RIGHT #undef SCK_HOME #undef SCK_END #undef SCK_PRIOR #undef SCK_NEXT #undef SCK_DELETE #undef SCK_INSERT #undef SCK_ESCAPE #undef SCK_BACK #undef SCK_TAB #undef SCK_RETURN #undef SCK_ADD #undef SCK_SUBTRACT #undef SCK_DIVIDE #undef SCK_WIN #undef SCK_RWIN #undef SCK_MENU // Remember if we have linked the lexers. static bool lexersLinked = false; // The list of instances. static QPtrList<QsciScintillaBase> poolList; // The ctor. QsciScintillaBase::QsciScintillaBase(QWidget *parent, const char *name, WFlags f) : QWidget(parent, name, f) { QGridLayout *layout = new QGridLayout(this, 2, 2); txtarea = new QWidget(this, 0, WRepaintNoErase|WResizeNoErase); txtarea->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); txtarea->setMouseTracking(true); txtarea->setAcceptDrops(true); txtarea->setFocusPolicy(WheelFocus); txtarea->setFocusProxy(this); layout->addWidget(txtarea, 0, 0); vsb = new QScrollBar(Vertical, this); layout->addWidget(vsb, 0, 1); connect(vsb, SIGNAL(valueChanged(int)), SLOT(handleVSb(int))); hsb = new QScrollBar(Horizontal, this); layout->addWidget(hsb, 1, 0); connect(hsb, SIGNAL(valueChanged(int)), SLOT(handleHSb(int))); txtarea->installEventFilter(this); setFocusPolicy(WheelFocus); #if (QT_VERSION >= 0x040200 && QT_VERSION < 0x050000 && defined(Q_OS_MAC)) || (QT_VERSION >= 0x050200 && defined(Q_OS_OSX)) initialiseRectangularPasteboardMime(); #endif sci = new QsciScintillaQt(this); SendScintilla(SCI_SETCARETPERIOD, QApplication::cursorFlashTime() / 2); // Make sure the lexers are linked in. if (!lexersLinked) { Scintilla_LinkLexers(); lexersLinked = true; } QClipboard *cb = QApplication::clipboard(); if (cb->supportsSelection()) connect(cb, SIGNAL(selectionChanged()), SLOT(handleSelection())); // Add it to the pool. poolList.append(this); } // The dtor. QsciScintillaBase::~QsciScintillaBase() { // Remove it from the pool. poolList.remove(this); delete sci; } // Return an instance from the pool. QsciScintillaBase *QsciScintillaBase::pool() { return poolList.first(); } // Tell Scintilla to update the scroll bars. Scintilla should be doing this // itself. void QsciScintillaBase::setScrollBars() { sci->SetScrollBars(); } // Return the horizontal scrollbar widget. QScrollBar *QsciScintillaBase::horizontalScrollBar() const { return hsb; } // Return the vertical scrollbar widget. QScrollBar *QsciScintillaBase::verticalScrollBar() const { return vsb; } // Return the viewport widget. QWidget *QsciScintillaBase::viewport() const { return txtarea; } // Handle events on behalf of the text area. bool QsciScintillaBase::eventFilter(QObject *o, QEvent *e) { if (o != txtarea) return QWidget::eventFilter(o, e); bool used = true; switch (e->type()) { case QEvent::ContextMenu: contextMenuEvent(static_cast<QContextMenuEvent *>(e)); break; case QEvent::DragEnter: dragEnterEvent(static_cast<QDragEnterEvent *>(e)); break; case QEvent::DragLeave: dragLeaveEvent(static_cast<QDragLeaveEvent *>(e)); break; case QEvent::DragMove: dragMoveEvent(static_cast<QDragMoveEvent *>(e)); break; case QEvent::Drop: dropEvent(static_cast<QDropEvent *>(e)); break; case QEvent::MouseButtonDblClick: mouseDoubleClickEvent(static_cast<QMouseEvent *>(e)); break; case QEvent::MouseButtonPress: mousePressEvent(static_cast<QMouseEvent *>(e)); break; case QEvent::MouseButtonRelease: mouseReleaseEvent(static_cast<QMouseEvent *>(e)); break; case QEvent::MouseMove: mouseMoveEvent(static_cast<QMouseEvent *>(e)); break; case QEvent::Paint: paintEvent(static_cast<QPaintEvent *>(e)); break; case QEvent::Resize: resizeEvent(static_cast<QResizeEvent *>(e)); break; case QEvent::Wheel: { QWheelEvent *we = static_cast<QWheelEvent *>(e); setFocus(); if (we->orientation() == Horizontal || we->state() & ShiftButton) QApplication::sendEvent(hsb, we); else if (we->orientation() == Vertical) QApplication::sendEvent(vsb, we); break; } default: used = false; } return used; } // Send a message to the real Scintilla widget using the low level Scintilla // API. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, long lParam) const { return sci->WndProc(msg, wParam, lParam); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, void *lParam) const { return sci->WndProc(msg, wParam, reinterpret_cast<sptr_t>(lParam)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, const char *lParam) const { return sci->WndProc(msg, wParam, reinterpret_cast<sptr_t>(lParam)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, const char *lParam) const { return sci->WndProc(msg, static_cast<uptr_t>(0), reinterpret_cast<sptr_t>(lParam)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, const char *wParam, const char *lParam) const { return sci->WndProc(msg, reinterpret_cast<uptr_t>(wParam), reinterpret_cast<sptr_t>(lParam)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, long wParam) const { return sci->WndProc(msg, static_cast<uptr_t>(wParam), static_cast<sptr_t>(0)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, int wParam) const { return sci->WndProc(msg, static_cast<uptr_t>(wParam), static_cast<sptr_t>(0)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, long cpMin, long cpMax, char *lpstrText) const { QSCI_SCI_NAMESPACE(TextRange) tr; tr.chrg.cpMin = cpMin; tr.chrg.cpMax = cpMax; tr.lpstrText = lpstrText; return sci->WndProc(msg, static_cast<uptr_t>(0), reinterpret_cast<sptr_t>(&tr)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, const QColor &col) const { sptr_t lParam = (col.blue() << 16) | (col.green() << 8) | col.red(); return sci->WndProc(msg, wParam, lParam); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, const QColor &col) const { uptr_t wParam = (col.blue() << 16) | (col.green() << 8) | col.red(); return sci->WndProc(msg, wParam, static_cast<sptr_t>(0)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, QPainter *hdc, const QRect &rc, long cpMin, long cpMax) const { QSCI_SCI_NAMESPACE(RangeToFormat) rf; rf.hdc = rf.hdcTarget = reinterpret_cast<QSCI_SCI_NAMESPACE(SurfaceID)>(hdc); rf.rc.left = rc.left(); rf.rc.top = rc.top(); rf.rc.right = rc.right() + 1; rf.rc.bottom = rc.bottom() + 1; rf.chrg.cpMin = cpMin; rf.chrg.cpMax = cpMax; return sci->WndProc(msg, wParam, reinterpret_cast<sptr_t>(&rf)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, const QPixmap &lParam) const { return sci->WndProc(msg, wParam, reinterpret_cast<sptr_t>(&lParam)); } // Overloaded message send. long QsciScintillaBase::SendScintilla(unsigned int msg, unsigned long wParam, const QImage &lParam) const { return sci->WndProc(msg, wParam, reinterpret_cast<sptr_t>(&lParam)); } // Send a message to the real Scintilla widget using the low level Scintilla // API that returns a pointer result. void *QsciScintillaBase::SendScintillaPtrResult(unsigned int msg) const { return reinterpret_cast<void *>(sci->WndProc(msg, static_cast<uptr_t>(0), static_cast<sptr_t>(0))); } // Handle the timer on behalf of the QsciScintillaQt instance. void QsciScintillaBase::handleTimer() { sci->Tick(); } // Re-implemented to handle the context menu. void QsciScintillaBase::contextMenuEvent(QContextMenuEvent *e) { sci->ContextMenu(QSCI_SCI_NAMESPACE(Point)(e->globalX(), e->globalY())); } // Re-implemented to tell the widget it has the focus. void QsciScintillaBase::focusInEvent(QFocusEvent *e) { sci->SetFocusState(true); #if QT_VERSION >= 0x050000 clickCausedFocus = (e->reason() == Qt::MouseFocusReason); #endif QWidget::focusInEvent(e); } // Re-implemented to tell the widget it has lost the focus. void QsciScintillaBase::focusOutEvent(QFocusEvent *e) { // Only tell Scintilla we have lost focus if the new active window isn't // our auto-completion list. This is probably only an issue on Linux and // there are still problems because subsequent focus out events don't // always seem to get generated (at least with Qt5). { QWidget *aw = qApp->activeWindow(); if (!aw || aw->parent() != this || !aw->inherits("QsciSciListBox")) sci->SetFocusState(false); } QWidget::focusOutEvent(e); } // Re-implemented to make sure tabs are passed to the editor. bool QsciScintillaBase::focusNextPrevChild(bool next) { if (!sci->pdoc->IsReadOnly()) return false; return QWidget::focusNextPrevChild(next); } // Handle the selection changing. void QsciScintillaBase::handleSelection() { if (!QApplication::clipboard()->ownsSelection()) sci->UnclaimSelection(); } // Handle key presses. void QsciScintillaBase::keyPressEvent(QKeyEvent *e) { int modifiers = 0; if (e->state() & Qt::ShiftButton) modifiers |= SCMOD_SHIFT; if (e->state() & Qt::ControlButton) modifiers |= SCMOD_CTRL; if (e->state() & Qt::AltButton) modifiers |= SCMOD_ALT; if (e->state() & Qt::MetaButton) modifiers |= SCMOD_META; int key = commandKey(e->key(), modifiers); if (key) { bool consumed = false; sci->KeyDownWithModifiers(key, modifiers, &consumed); if (consumed) { e->accept(); return; } } QString text = e->text(); if (!text.isEmpty() && text[0].isPrint()) { ScintillaBytes bytes = textAsBytes(text); sci->AddCharUTF(bytes.data(), bytes.length()); e->accept(); } else { QWidget::keyPressEvent(e); } } // Map a Qt key to a valid Scintilla command key, or 0 if none. int QsciScintillaBase::commandKey(int qt_key, int &modifiers) { int key; switch (qt_key) { case Qt::Key_Down: key = SCK_DOWN; break; case Qt::Key_Up: key = SCK_UP; break; case Qt::Key_Left: key = SCK_LEFT; break; case Qt::Key_Right: key = SCK_RIGHT; break; case Qt::Key_Home: key = SCK_HOME; break; case Qt::Key_End: key = SCK_END; break; case Qt::Key_Prior: key = SCK_PRIOR; break; case Qt::Key_Next: key = SCK_NEXT; break; case Qt::Key_Delete: key = SCK_DELETE; break; case Qt::Key_Insert: key = SCK_INSERT; break; case Qt::Key_Escape: key = SCK_ESCAPE; break; case Qt::Key_Backspace: key = SCK_BACK; break; case Qt::Key_Tab: key = SCK_TAB; break; case Qt::Key_Backtab: // Scintilla assumes a backtab is shift-tab. key = SCK_TAB; modifiers |= SCMOD_SHIFT; break; case Qt::Key_Return: case Qt::Key_Enter: key = SCK_RETURN; break; case Qt::Key_Super_L: key = SCK_WIN; break; case Qt::Key_Super_R: key = SCK_RWIN; break; case Qt::Key_Menu: key = SCK_MENU; break; default: if ((key = qt_key) > 0x7f) key = 0; } return key; } // Encode a QString as bytes. QsciScintillaBase::ScintillaBytes QsciScintillaBase::textAsBytes(const QString &text) const { if (sci->IsUnicodeMode()) return text.utf8(); return QCString(text.latin1()); } // Decode bytes as a QString. QString QsciScintillaBase::bytesAsText(const char *bytes) const { if (sci->IsUnicodeMode()) return QString::fromUtf8(bytes); return QString::fromLatin1(bytes); } // Handle a mouse button double click. void QsciScintillaBase::mouseDoubleClickEvent(QMouseEvent *e) { if (e->button() != Qt::LeftButton) { e->ignore(); return; } setFocus(); // Make sure Scintilla will interpret this as a double-click. unsigned clickTime = sci->lastClickTime + QSCI_SCI_NAMESPACE(Platform)::DoubleClickTime() - 1; bool shift = e->state() & Qt::ShiftButton; bool ctrl = e->state() & Qt::ControlButton; bool alt = e->state() & Qt::AltButton; sci->ButtonDown(QSCI_SCI_NAMESPACE(Point)(e->x(), e->y()), clickTime, shift, ctrl, alt); // Remember the current position and time in case it turns into a triple // click. triple_click_at = e->globalPos(); triple_click.start(QApplication::doubleClickInterval()); } // Handle a mouse move. void QsciScintillaBase::mouseMoveEvent(QMouseEvent *e) { sci->ButtonMove(QSCI_SCI_NAMESPACE(Point)(e->x(), e->y())); } // Handle a mouse button press. void QsciScintillaBase::mousePressEvent(QMouseEvent *e) { setFocus(); QSCI_SCI_NAMESPACE(Point) pt(e->x(), e->y()); if (e->button() == Qt::LeftButton) { unsigned clickTime; // It is a triple click if the timer is running and the mouse hasn't // moved too much. if (triple_click.isActive() && (e->globalPos() - triple_click_at).manhattanLength() < QApplication::startDragDistance()) clickTime = sci->lastClickTime + QSCI_SCI_NAMESPACE(Platform)::DoubleClickTime() - 1; else clickTime = sci->lastClickTime + QSCI_SCI_NAMESPACE(Platform)::DoubleClickTime() + 1; triple_click.stop(); // Scintilla uses the Alt modifier to initiate rectangular selection. // However the GTK port (under X11, not Windows) uses the Control // modifier (by default, although it is configurable). It does this // because most X11 window managers hijack Alt-drag to move the window. // We do the same, except that (for the moment at least) we don't allow // the modifier to be configured. bool shift = e->state() & Qt::ShiftButton; bool ctrl = e->state() & Qt::ControlButton; #if !defined(Q_WS_X11) bool alt = e->modifiers() & Qt::AltButton; #else bool alt = ctrl; #endif sci->ButtonDown(pt, clickTime, shift, ctrl, alt); } else if (e->button() == Qt::MidButton) { QClipboard *cb = QApplication::clipboard(); if (cb->supportsSelection()) { int pos = sci->PositionFromLocation(pt); sci->sel.Clear(); sci->SetSelection(pos, pos); sci->pasteFromClipboard(QClipboard::Selection); } } } // Handle a mouse button releases. void QsciScintillaBase::mouseReleaseEvent(QMouseEvent *e) { if (e->button() != Qt::LeftButton) return; QSCI_SCI_NAMESPACE(Point) pt(e->x(), e->y()); if (sci->HaveMouseCapture()) { bool ctrl = e->state() & Qt::ControlButton; sci->ButtonUp(pt, 0, ctrl); } #if QT_VERSION >= 0x050000 if (!sci->pdoc->IsReadOnly() && !sci->PointInSelMargin(pt) && qApp->autoSipEnabled()) { QStyle::RequestSoftwareInputPanel rsip = QStyle::RequestSoftwareInputPanel(style()->styleHint(QStyle::SH_RequestSoftwareInputPanel)); if (!clickCausedFocus || rsip == QStyle::RSIP_OnMouseClick) qApp->inputMethod()->show(); } clickCausedFocus = false; #endif } // Handle paint events. void QsciScintillaBase::paintEvent(QPaintEvent *e) { sci->paintEvent(e); } // Handle resize events. void QsciScintillaBase::resizeEvent(QResizeEvent *) { sci->ChangeSize(); } // Handle the vertical scrollbar. void QsciScintillaBase::handleVSb(int value) { sci->ScrollTo(value); } // Handle the horizontal scrollbar. void QsciScintillaBase::handleHSb(int value) { sci->HorizontalScrollTo(value); } // Handle drag enters. void QsciScintillaBase::dragEnterEvent(QDragEnterEvent *e) { QsciScintillaBase::dragMoveEvent(e); } // Handle drag leaves. void QsciScintillaBase::dragLeaveEvent(QDragLeaveEvent *) { sci->SetDragPosition(QSCI_SCI_NAMESPACE(SelectionPosition)()); } // Handle drag moves. void QsciScintillaBase::dragMoveEvent(QDragMoveEvent *e) { sci->SetDragPosition( sci->SPositionFromLocation( QSCI_SCI_NAMESPACE(Point)(e->pos().x(), e->pos().y()), false, false, sci->UserVirtualSpace())); if (sci->pdoc->IsReadOnly() || !QTextDrag::canDecode(e)) { e->ignore(); return; } e->acceptAction(); } // Handle drops. void QsciScintillaBase::dropEvent(QDropEvent *e) { bool moving; int len; const char *s; bool rectangular; QString text; if (sci->pdoc->IsReadOnly() || !QTextDrag::decode(e, text)) { e->ignore(); return; } moving = (e->source() == txtarea && e->action() == QDropEvent::Move); e->acceptAction(); QCString bytes; if (sci->IsUnicodeMode()) { bytes = text.utf8(); len = bytes.length(); s = bytes.data(); } else { s = text.latin1(); len = (s ? qstrlen(s) : 0); } rectangular = false; std::string dest = QSCI_SCI_NAMESPACE(Document)::TransformLineEnds(s, len, sci->pdoc->eolMode); sci->DropAt(sci->posDrop, dest.c_str(), dest.length(), moving, rectangular); sci->Redraw(); }
20,040
C++
.cpp
624
27.064103
141
0.66986
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,993
testscanner.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/scanner/testscanner.cpp
/* This file is part of QJson * * Copyright (C) 2013 Silvio Moioli <silvio@moioli.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtCore/QVariant> #include <QtTest/QtTest> // cmath does #undef for isnan and isinf macroses what can be defined in math.h #if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) || defined(Q_OS_SOLARIS) # include <math.h> #else # include <cmath> #endif #include "json_scanner.h" #include "json_parser.hh" #include "location.hh" #define TOKEN(type) (int)yy::json_parser::token::type class TestScanner: public QObject { Q_OBJECT private slots: void scanClosedDevice(); void scanTokens(); void scanTokens_data(); void scanSpecialNumbers(); void scanSpecialNumbers_data(); }; Q_DECLARE_METATYPE(QVariant) Q_DECLARE_METATYPE(QVariant::Type) using namespace QJson; void TestScanner::scanClosedDevice() { QBuffer buffer; int expectedResult = -1; JSonScanner scanner(&buffer); QVariant yylval; yy::location location; int result = scanner.yylex(&yylval, &location); QCOMPARE(result, expectedResult); } void TestScanner::scanTokens() { QFETCH(QByteArray, input); QFETCH(bool, allowSpecialNumbers); QFETCH(bool, skipFirstToken); QFETCH(int, expectedResult); QFETCH(QVariant, expectedYylval); QFETCH(int, expectedLocationBeginLine); QFETCH(int, expectedLocationBeginColumn); QFETCH(int, expectedLocationEndLine); QFETCH(int, expectedLocationEndColumn); QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write(input); buffer.seek(0); JSonScanner scanner(&buffer); scanner.allowSpecialNumbers(allowSpecialNumbers); QVariant yylval; yy::position position(YY_NULL, 1, 0); yy::location location(position, position); int result = scanner.yylex(&yylval, &location); if (skipFirstToken) { result = scanner.yylex(&yylval, &location); } QCOMPARE(result, expectedResult); QCOMPARE(yylval, expectedYylval); QCOMPARE(location.begin.line, (uint)expectedLocationBeginLine); QCOMPARE(location.begin.column, (uint)expectedLocationBeginColumn); QCOMPARE(location.end.line, (uint)expectedLocationEndLine); QCOMPARE(location.end.column, (uint)expectedLocationEndColumn); } void TestScanner::scanTokens_data() { QTest::addColumn<QByteArray>("input"); QTest::addColumn<bool>("allowSpecialNumbers"); QTest::addColumn<bool>("skipFirstToken"); QTest::addColumn<int>("expectedResult"); QTest::addColumn<QVariant>("expectedYylval"); QTest::addColumn<int>("expectedLocationBeginLine"); QTest::addColumn<int>("expectedLocationBeginColumn"); QTest::addColumn<int>("expectedLocationEndLine"); QTest::addColumn<int>("expectedLocationEndColumn"); QTest::newRow("empty json") << QByteArray("") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 1 << 0; QTest::newRow("carriage return") << QByteArray("\r") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 2 << 1; QTest::newRow("new line") << QByteArray("\n") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 2 << 1; QTest::newRow("formfeed") << QByteArray("\f") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("vertical tab") << QByteArray("\v") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("space") << QByteArray(" ") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("tab") << QByteArray("\t") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("all spaces") << QByteArray("\r\n\f\v \t") << true << false << TOKEN(END) << QVariant() << 1 << 0 << 3 << 5; QTest::newRow("true") << QByteArray("true") << true << false << TOKEN(TRUE_VAL) << QVariant(true) << 1 << 0 << 1 << 4; QTest::newRow("false") << QByteArray("false") << true << false << TOKEN(FALSE_VAL) << QVariant(false) << 1 << 0 << 1 << 5; QTest::newRow("null") << QByteArray("null") << true << false << TOKEN(NULL_VAL) << QVariant() << 1 << 0 << 1 << 4; QTest::newRow("alphabetic string") << QByteArray("\"abcde\"") << true << false << TOKEN(STRING) << QVariant(QLatin1String("abcde")) << 1 << 0 << 1 << 2; QTest::newRow("ecaped string") << QByteArray("\"abcde\\b\\f\\n\\r\\t\"") << true << false << TOKEN(STRING) << QVariant(QLatin1String("abcde\b\f\n\r\t")) << 1 << 0 << 1 << 2; QTest::newRow("invalid ecaped string") << QByteArray("\"\\x\"") << true << false << TOKEN(STRING) << QVariant(QLatin1String("x")) << 1 << 0 << 1 << 2; QTest::newRow("escaped unicode sequence") << QByteArray("\"\\u005A\"") << true << false << TOKEN(STRING) << QVariant(QLatin1String("Z")) << 1 << 0 << 1 << 2; QTest::newRow("invalid unicode sequence") << QByteArray("\"\\u005Z\"") << true << false << TOKEN(INVALID) << QVariant(QLatin1String("")) << 1 << 0 << 1 << 2; QTest::newRow("empty string") << QByteArray("\"\"") << true << false << TOKEN(STRING) << QVariant(QLatin1String("")) << 1 << 0 << 1 << 2; QTest::newRow("unterminated empty string") << QByteArray("\"") << true << false << TOKEN(INVALID) << QVariant() << 1 << 0 << 1 << 2; QTest::newRow("unterminated string") << QByteArray("\"abcde") << true << false << TOKEN(INVALID) << QVariant() << 1 << 0 << 1 << 2; QTest::newRow("unterminated unicode sequence") << QByteArray("\"\\u005A") << true << false << TOKEN(INVALID) << QVariant() << 1 << 0 << 1 << 2; QTest::newRow("single digit") << QByteArray("0") << true << false << TOKEN(NUMBER) << QVariant(0u) << 1 << 0 << 1 << 1; QTest::newRow("multiple digits") << QByteArray("123456789") << true << false << TOKEN(NUMBER) << QVariant(123456789u) << 1 << 0 << 1 << 9; QTest::newRow("negative single digit") << QByteArray("-0") << true << false << TOKEN(NUMBER) << QVariant(0) << 1 << 0 << 1 << 2; QTest::newRow("negative multiple digits") << QByteArray("-123456789") << true << false << TOKEN(NUMBER) << QVariant(-123456789) << 1 << 0 << 1 << 10; QTest::newRow("fractional single digit") << QByteArray("0.1") << true << false << TOKEN(NUMBER) << QVariant(0.1) << 1 << 0 << 1 << 3; QTest::newRow("fractional multiple digits") << QByteArray("123456789.12") << true << false << TOKEN(NUMBER) << QVariant(123456789.12) << 1 << 0 << 1 << 12; QTest::newRow("fractional negative single digit") << QByteArray("-0.3") << true << false << TOKEN(NUMBER) << QVariant(-0.3) << 1 << 0 << 1 << 4; QTest::newRow("fractional negative multiple digits") << QByteArray("-123456789.23") << true << false << TOKEN(NUMBER) << QVariant(-123456789.23) << 1 << 0 << 1 << 13; QTest::newRow("exponential single digit") << QByteArray("10e2") << true << false << TOKEN(NUMBER) << QVariant(1000) << 1 << 0 << 1 << 4; QTest::newRow("exponential multiple digits") << QByteArray("10e23") << true << false << TOKEN(NUMBER) << QVariant(10e23) << 1 << 0 << 1 << 5; QTest::newRow("exponential zero") << QByteArray("0e23") << true << false << TOKEN(NUMBER) << QVariant(0) << 1 << 0 << 1 << 4; QTest::newRow("exponential fractional") << QByteArray("0.12354e23") << true << false << TOKEN(NUMBER) << QVariant(0.12354e23) << 1 << 0 << 1 << 10; QTest::newRow("exponential fractional multiple digits") << QByteArray("120.12354e23") << true << false << TOKEN(NUMBER) << QVariant(120.12354e23) << 1 << 0 << 1 << 12; QTest::newRow("uppercase exponential") << QByteArray("120.12354E23") << true << false << TOKEN(NUMBER) << QVariant(120.12354E23) << 1 << 0 << 1 << 12; QTest::newRow("negative exponential single digit") << QByteArray("-10e2") << true << false << TOKEN(NUMBER) << QVariant(-1000) << 1 << 0 << 1 << 5; QTest::newRow("negative exponential multiple digits") << QByteArray("-10e23") << true << false << TOKEN(NUMBER) << QVariant(-10e23) << 1 << 0 << 1 << 6; QTest::newRow("negative exponential zero") << QByteArray("-0e23") << true << false << TOKEN(NUMBER) << QVariant(0) << 1 << 0 << 1 << 5; QTest::newRow("negative exponential fractional") << QByteArray("-0.12354e23") << true << false << TOKEN(NUMBER) << QVariant(-0.12354e23) << 1 << 0 << 1 << 11; QTest::newRow("negative exponential fractional multiple digits") << QByteArray("-120.12354e23") << true << false << TOKEN(NUMBER) << QVariant(-120.12354e23) << 1 << 0 << 1 << 13; QTest::newRow("negative exponent") << QByteArray("10e-2") << true << false << TOKEN(NUMBER) << QVariant(10e-2) << 1 << 0 << 1 << 5; QTest::newRow("positive exponent with plus") << QByteArray("10e+2") << true << false << TOKEN(NUMBER) << QVariant(1000) << 1 << 0 << 1 << 5; QTest::newRow("invalid multiple digits") << QByteArray("001") << true << false << TOKEN(NUMBER) << QVariant(0) << 1 << 0 << 1 << 1; QTest::newRow("invalid negative multiple digits") << QByteArray("-001") << true << false << TOKEN(NUMBER) << QVariant(0) << 1 << 0 << 1 << 2; QTest::newRow("invalid fractional") << QByteArray("12.") << true << true << TOKEN(INVALID) << QVariant(12) << 1 << 2 << 1 << 3; QTest::newRow("invalid exponential 1") << QByteArray("-5e+") << true << true << TOKEN(INVALID) << QVariant(-5) << 1 << 2 << 1 << 3; QTest::newRow("invalid exponential 2") << QByteArray("2e") << true << true << TOKEN(INVALID) << QVariant(2) << 1 << 1 << 1 << 2; QTest::newRow("invalid exponential 3") << QByteArray("3e+") << true << true << TOKEN(INVALID) << QVariant(3) << 1 << 1 << 1 << 2; QTest::newRow("invalid exponential 4") << QByteArray("4.3E") << true << true << TOKEN(INVALID) << QVariant(4.3) << 1 << 3 << 1 << 4; QTest::newRow("invalid exponential 5") << QByteArray("5.4E-") << true << true << TOKEN(INVALID) << QVariant(5.4) << 1 << 3 << 1 << 4; QTest::newRow("colon") << QByteArray(":") << true << false << TOKEN(COLON) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("comma") << QByteArray(",") << true << false << TOKEN(COMMA) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("square bracket open") << QByteArray("[") << true << false << TOKEN(SQUARE_BRACKET_OPEN) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("square bracket close") << QByteArray("]") << true << false << TOKEN(SQUARE_BRACKET_CLOSE) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("curly bracket open") << QByteArray("{") << true << false << TOKEN(CURLY_BRACKET_OPEN) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("curly bracket close") << QByteArray("}") << true << false << TOKEN(CURLY_BRACKET_CLOSE) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("too large unsinged number") << QByteArray("18446744073709551616") << false << false << TOKEN(INVALID) << QVariant(ULLONG_MAX) << 1 << 0 << 1 << 20; QTest::newRow("too large signed number") << QByteArray("-9223372036854775808") << false << false << TOKEN(INVALID) << QVariant(LLONG_MIN) << 1 << 0 << 1 << 20; QTest::newRow("too large exponential") << QByteArray("1.7976931348623157e309") << false << false << TOKEN(INVALID) << QVariant(0) << 1 << 0 << 1 << 22; QTest::newRow("not allowed nan") << QByteArray("nan") << false << false << TOKEN(INVALID) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("not allowed infinity") << QByteArray("Infinity") << false << false << TOKEN(INVALID) << QVariant() << 1 << 0 << 1 << 1; QTest::newRow("unknown") << QByteArray("*") << true << false << TOKEN(INVALID) << QVariant() << 1 << 0 << 1 << 1; } void TestScanner::scanSpecialNumbers() { QFETCH(QByteArray, input); QFETCH(bool, isInfinity); QFETCH(bool, isNegative); QFETCH(bool, isNan); QFETCH(int, expectedLocationBeginLine); QFETCH(int, expectedLocationBeginColumn); QFETCH(int, expectedLocationEndLine); QFETCH(int, expectedLocationEndColumn); QBuffer buffer; buffer.open(QBuffer::ReadWrite); buffer.write(input); buffer.seek(0); JSonScanner scanner(&buffer); scanner.allowSpecialNumbers(true); QVariant yylval; yy::position position(YY_NULL, 1, 0); yy::location location(position, position); int result = scanner.yylex(&yylval, &location); QCOMPARE(result, TOKEN(NUMBER)); QVERIFY(yylval.type() == QVariant::Double); double doubleResult = yylval.toDouble(); #if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) QCOMPARE(bool(isinf(doubleResult)), isInfinity); #else // skip this test for MSVC, because there is no "isinf" function. #ifndef Q_CC_MSVC QCOMPARE(bool(std::isinf(doubleResult)), isInfinity); #endif #endif QCOMPARE(doubleResult<0, isNegative); #if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) QCOMPARE(bool(isnan(doubleResult)), isNan); #else // skip this test for MSVC, because there is no "isinf" function. #ifndef Q_CC_MSVC QCOMPARE(bool(std::isnan(doubleResult)), isNan); #endif #endif QCOMPARE(location.begin.line, (uint)expectedLocationBeginLine); QCOMPARE(location.begin.column, (uint)expectedLocationBeginColumn); QCOMPARE(location.end.line, (uint)expectedLocationEndLine); QCOMPARE(location.end.column, (uint)expectedLocationEndColumn); } void TestScanner::scanSpecialNumbers_data() { QTest::addColumn<QByteArray>("input"); QTest::addColumn<bool>("isInfinity"); QTest::addColumn<bool>("isNegative"); QTest::addColumn<bool>("isNan"); QTest::addColumn<int>("expectedLocationBeginLine"); QTest::addColumn<int>("expectedLocationBeginColumn"); QTest::addColumn<int>("expectedLocationEndLine"); QTest::addColumn<int>("expectedLocationEndColumn"); QTest::newRow("nan") << QByteArray("nan") << false << false << true << 1 << 0 << 1 << 3; QTest::newRow("NAN") << QByteArray("NAN") << false << false << true << 1 << 0 << 1 << 3; QTest::newRow("NaN") << QByteArray("NaN") << false << false << true << 1 << 0 << 1 << 3; QTest::newRow("infinity") << QByteArray("infinity") << true << false << false << 1 << 0 << 1 << 8; QTest::newRow("Infinity") << QByteArray("infinity") << true << false << false << 1 << 0 << 1 << 8; QTest::newRow("-infinity") << QByteArray("-infinity") << true << true << false << 1 << 0 << 1 << 9; QTest::newRow("-Infinity") << QByteArray("-Infinity") << true << true << false << 1 << 0 << 1 << 9; } #if QT_VERSION < QT_VERSION_CHECK(5,0,0) // using Qt4 rather then Qt5 QTEST_MAIN(TestScanner) #include "moc_testscanner.cxx" #else QTEST_GUILESS_MAIN(TestScanner) #include "testscanner.moc" #endif
14,933
C++
.cpp
224
63.558036
181
0.646653
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,994
testparser.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/parser/testparser.cpp
/* This file is part of QJson * * Copyright (C) 2008 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <cmath> #include <QtCore/QVariant> #include <QtTest/QtTest> #include <QJson/Parser> #include <QJson/Serializer> #include <QLocale> class TestParser: public QObject { Q_OBJECT private slots: void parseInvalidEmptyJson(); void parseInvalidEmptyJson_data(); void parseNonAsciiString(); void parseSimpleObject(); void parseEmptyObject(); void parseEmptyValue(); void parseUrl(); void parseMultipleObject(); void parseSimpleArray(); void parseInvalidObject(); void parseInvalidObject_data(); void parseMultipleArray(); void reuseSameParser(); void testTrueFalseNullValues(); void testEscapeChars(); void testNumbers(); void testNumbers_data(); void testDoubleParsingWithDifferentLocale(); void testTopLevelValues(); void testTopLevelValues_data(); void testReadWrite(); void testReadWrite_data(); }; Q_DECLARE_METATYPE(QVariant) Q_DECLARE_METATYPE(QVariant::Type) using namespace QJson; void TestParser::parseInvalidEmptyJson() { QFETCH(QByteArray, json); Parser parser; bool ok; QVariant result = parser.parse(json, &ok); QVERIFY(!ok); QVERIFY(!parser.errorString().isEmpty()); } void TestParser::parseInvalidEmptyJson_data() { QTest::addColumn<QByteArray>("json"); QTest::newRow("empty") << QByteArray(""); QTest::newRow("empty with spaces") << QByteArray(" \n"); } void TestParser::parseSimpleObject() { QByteArray json = "{\"foo\":\"bar\"}"; QVariantMap map; map.insert (QLatin1String("foo"), QLatin1String("bar")); QVariant expected(map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseEmptyObject() { QByteArray json = "{}"; QVariantMap map; QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseEmptyValue() { QByteArray json = "{\"value\": \"\"}"; QVariantMap map; map.insert (QLatin1String("value"), QString(QLatin1String(""))); QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVERIFY (result.toMap().value(QLatin1String("value")).type() == QVariant::String); QString value = result.toMap().value(QLatin1String("value")).toString(); QVERIFY (value.isEmpty()); } void TestParser::parseInvalidObject() { QFETCH(QByteArray, json); Parser parser; bool ok; parser.parse (json, &ok); QVERIFY (!ok); QVERIFY(!parser.errorString().isEmpty()); } void TestParser::parseInvalidObject_data() { QTest::addColumn<QByteArray>("json"); QTest::newRow("unclosed object") << QByteArray("{\"foo\":\"bar\""); QTest::newRow("infinum (disallow") << QByteArray("Infinum"); QTest::newRow("Nan (disallow") << QByteArray("NaN"); QTest::newRow("no data") << QByteArray(""); } void TestParser::parseNonAsciiString() { QByteArray json = "{\"artist\":\"Queensr\\u00ffche\"}"; QVariantMap map; QChar unicode_char (0x00ff); QString unicode_string; unicode_string.setUnicode(&unicode_char, 1); unicode_string = QLatin1String("Queensr") + unicode_string + QLatin1String("che"); map.insert (QLatin1String("artist"), unicode_string); QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseMultipleObject() { //put also some extra spaces inside the json string QByteArray json = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QVariantMap map; map.insert (QLatin1String("foo"), QLatin1String("bar")); map.insert (QLatin1String("number"), 51.3); QVariantList list; list.append (QLatin1String("item1")); list.append (QLatin1String("123")); map.insert (QLatin1String("array"), list); QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVERIFY (result.toMap().value(QLatin1String("number")).canConvert<float>()); QVERIFY (result.toMap().value(QLatin1String("array")).canConvert<QVariantList>()); } void TestParser::parseUrl(){ //"http:\/\/www.last.fm\/venue\/8926427" QByteArray json = "[\"http:\\/\\/www.last.fm\\/venue\\/8926427\"]"; QVariantList list; list.append (QVariant(QLatin1String("http://www.last.fm/venue/8926427"))); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseSimpleArray() { QByteArray json = "[\"foo\",\"bar\"]"; QVariantList list; list.append (QLatin1String("foo")); list.append (QLatin1String("bar")); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseMultipleArray() { //put also some extra spaces inside the json string QByteArray json = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QVariantMap map; map.insert (QLatin1String("foo"), QLatin1String("bar")); QVariantList array; array.append (QLatin1String("item1")); array.append (123); QVariantList list; list.append (map); list.append (QLatin1String("number")); list.append (QLatin1String("51.3")); list.append ((QVariant) array); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::testTrueFalseNullValues() { QByteArray json = "[true,false, null, {\"foo\" : true}]"; QVariantList list; list.append (QVariant(true)); list.append (QVariant(false)); list.append (QVariant()); QVariantMap map; map.insert (QLatin1String("foo"), true); list.append (map); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QCOMPARE (result.toList().at(0).toBool(), true); QCOMPARE (result.toList().at(1).toBool(), false); QVERIFY (result.toList().at(2).isNull()); } void TestParser::testEscapeChars() { QByteArray json = "[\"\\b \\f \\n \\r \\t \", \" \\\\ \\/ \\\\\", \"http:\\/\\/foo.com\"]"; QVariantList list; list.append (QLatin1String("\b \f \n \r \t ")); list.append (QLatin1String(" \\ / \\")); list.append (QLatin1String("http://foo.com")); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result.toList().size(), expected.toList().size() ); QCOMPARE(result, expected); } void TestParser::testNumbers() { QFETCH(QByteArray, input); QFETCH(QVariant, expected); QFETCH(QVariant::Type, type); Parser parser; bool ok; QVariant result = parser.parse ('[' + input + ']', &ok); QVERIFY (ok); QVariant value = result.toList().at(0); QCOMPARE(value, expected); QCOMPARE( value.type(), type); } void TestParser::testNumbers_data() { QTest::addColumn<QByteArray>( "input" ); QTest::addColumn<QVariant>( "expected" ); QTest::addColumn<QVariant::Type>( "type" ); QByteArray input; QVariant output; // simple ulonglong input = QByteArray("1"); output = QVariant(QVariant::ULongLong); output.setValue(1); QTest::newRow("simple ulonglong") << input << output << QVariant::ULongLong; // big number input = QByteArray("12345678901234567890"); output = QVariant(QVariant::ULongLong); output.setValue(12345678901234567890ull); QTest::newRow("big number") << input << output << QVariant::ULongLong; // simple double input = QByteArray("2.004"); output = QVariant(QVariant::Double); output.setValue(2.004); QTest::newRow("simple double") << input << output << QVariant::Double; // negative int input = QByteArray("-100"); output = QVariant(QVariant::LongLong); output.setValue(-100); QTest::newRow("negative int") << input << output << QVariant::LongLong; // negative double input = QByteArray("-3.4"); output = QVariant(QVariant::Double); output.setValue(-3.4); QTest::newRow("negative double") << input << output << QVariant::Double; } void TestParser::testTopLevelValues() { QFETCH(QByteArray, input); QFETCH(QVariant, expected); QFETCH(QVariant::Type, type); Parser parser; bool ok; QVariant result = parser.parse (input, &ok); QVERIFY (ok); QCOMPARE(result, expected); QCOMPARE(result.type(), type); } void TestParser::testTopLevelValues_data() { QTest::addColumn<QByteArray>( "input" ); QTest::addColumn<QVariant>( "expected" ); QTest::addColumn<QVariant::Type>( "type" ); QByteArray input; QVariant output; // string input = QByteArray("\"foo bar\""); output = QVariant(QLatin1String("foo bar")); QTest::newRow("string") << input << output << QVariant::String; // number input = QByteArray("2.4"); output = QVariant(QVariant::Double); output.setValue(2.4); QTest::newRow("simple double") << input << output << QVariant::Double; // boolean input = QByteArray("true"); output = QVariant(QVariant::Bool); output.setValue(true); QTest::newRow("bool") << input << output << QVariant::Bool; // null input = QByteArray("null"); output = QVariant(); QTest::newRow("null") << input << output << QVariant::Invalid; // array input = QByteArray("[1,2,3]"); QVariantList list; list << QVariant(1) << QVariant(2) << QVariant(3); output = QVariant(QVariant::List); output.setValue(list); QTest::newRow("array") << input << output << QVariant::List; // object input = QByteArray("{\"foo\" : \"bar\"}"); QVariantMap map; map.insert(QLatin1String("foo"), QLatin1String("bar")); output = QVariant(QVariant::Map); output.setValue(map); QTest::newRow("object") << input << output << QVariant::Map; } void TestParser::testDoubleParsingWithDifferentLocale() { QLocale oldLocale; QLocale itLocale(QLatin1String("it_IT.utf8")); QCOMPARE(itLocale.name(), QLatin1String("it_IT") ); // the Italian locale uses ',' as digit separator. QLocale::setDefault(itLocale); Parser parser; bool ok; QVariant result = parser.parse ("12.3", &ok); QVERIFY (ok); QCOMPARE(result.toDouble(), 12.3); QLocale::setDefault(oldLocale); } void TestParser::testReadWrite() { QFETCH( QVariant, variant ); Serializer serializer; bool ok; QByteArray json = serializer.serialize(variant, &ok); QVERIFY(ok); Parser parser; QVariant result = parser.parse( json, &ok ); QVERIFY(ok); QCOMPARE( result, variant ); } void TestParser::testReadWrite_data() { QTest::addColumn<QVariant>( "variant" ); // array tests QTest::newRow( "empty array" ) << QVariant(QVariantList()); // basic array QVariantList list; list << QString(QLatin1String("hello")); list << 12; QTest::newRow( "basic array" ) << QVariant(list); // simple map QVariantMap map; map[QString(QLatin1String("Name"))] = 32; QTest::newRow( "complicated array" ) << QVariant(map); } void TestParser::reuseSameParser() { Parser parser; bool ok; parser.parse ("12.3", &ok); QVERIFY (ok); parser.parse ("wrong entry", &ok); QVERIFY (!ok); parser.parse ("12.3", &ok); QVERIFY (ok); } #if QT_VERSION < QT_VERSION_CHECK(5,0,0) // using Qt4 rather then Qt5 QTEST_MAIN(TestParser) #include "moc_testparser.cxx" #else QTEST_GUILESS_MAIN(TestParser) #include "testparser.moc" #endif
12,366
C++
.cpp
384
29.138021
93
0.698545
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
14,995
person.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/qobjecthelper/person.cpp
#include "person.h" Person::Person(QObject* parent) : QObject(parent), m_name(), m_phoneNumber(0), m_gender(Female), m_luckyNumber(0) { } Person::~Person() { } QString Person::name() const { return m_name; } void Person::setName(const QString& name) { m_name = name; } int Person::phoneNumber() const { return m_phoneNumber; } void Person::setPhoneNumber(const int phoneNumber) { m_phoneNumber = phoneNumber; } void Person::setGender(Gender gender) { m_gender = gender; } Person::Gender Person::gender() const { return m_gender; } QDate Person::dob() const { return m_dob; } void Person::setDob(const QDate& dob) { m_dob = dob; } QVariant Person::customField() const { return m_customField; } void Person::setCustomField(const QVariant& customField) { m_customField = customField; } const quint16 Person::luckyNumber() const { return m_luckyNumber; } void Person::setLuckyNumber(const quint16 luckyNumber) { m_luckyNumber = luckyNumber; }
996
C++
.cpp
60
14.65
56
0.742671
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
14,996
testqobjecthelper.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/qobjecthelper/testqobjecthelper.cpp
/* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <limits> #include <QtCore/QVariant> #include <QtCore/QVariantList> #include <QtTest/QtTest> #include <QJson/Parser> #include <QJson/Serializer> #include <QJson/QObjectHelper> #include "person.h" class TestQObjectHelper: public QObject { Q_OBJECT private slots: void testQObject2QVariant(); void testQVariant2QObject(); }; using namespace QJson; void TestQObjectHelper::testQObject2QVariant() { QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); QVariantList nicknames; nicknames << QLatin1String("nickname1") << QLatin1String("nickname2"); quint16 luckyNumber = 123; Person person; person.setName(name); person.setPhoneNumber(phoneNumber); person.setGender(gender); person.setDob(dob); person.setCustomField(nicknames); person.setLuckyNumber(luckyNumber); QVariantMap expected; expected[QLatin1String("name")] = QVariant(name); expected[QLatin1String("phoneNumber")] = QVariant(phoneNumber); expected[QLatin1String("gender")] = QVariant(gender); expected[QLatin1String("dob")] = QVariant(dob); expected[QLatin1String("customField")] = nicknames; expected[QLatin1String("luckyNumber")] = luckyNumber; QVariantMap result = QObjectHelper::qobject2qvariant(&person); QCOMPARE(result, expected); } void TestQObjectHelper::testQVariant2QObject() { bool ok; QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); QVariantList nicknames; nicknames << QLatin1String("nickname1") << QLatin1String("nickname2"); quint16 luckyNumber = 123; Person expected_person; expected_person.setName(name); expected_person.setPhoneNumber(phoneNumber); expected_person.setGender(gender); expected_person.setDob(dob); expected_person.setCustomField(nicknames); expected_person.setLuckyNumber(luckyNumber); QVariantMap variant = QObjectHelper::qobject2qvariant(&expected_person); Serializer serializer; QByteArray json = serializer.serialize(variant, &ok); qDebug() << "json is" << json; QVERIFY(ok); Parser parser; QVariant parsedVariant = parser.parse(json,&ok); QVERIFY(ok); qDebug() << parsedVariant; QVERIFY(parsedVariant.canConvert(QVariant::Map)); Person person; QCOMPARE(Person::Female, person.gender()); QObjectHelper::qvariant2qobject(parsedVariant.toMap(), &person); QCOMPARE(person.name(), name); QCOMPARE(person.phoneNumber(), phoneNumber); QCOMPARE(person.gender(), gender); QCOMPARE(person.dob(), dob); QCOMPARE(person.customField(), QVariant(nicknames)); QCOMPARE(person.luckyNumber(), luckyNumber); } #if QT_VERSION < QT_VERSION_CHECK(5,0,0) // using Qt4 rather then Qt5 QTEST_MAIN(TestQObjectHelper) #include "moc_testqobjecthelper.cxx" #else QTEST_GUILESS_MAIN(TestQObjectHelper) #include "testqobjecthelper.moc" #endif
3,754
C++
.cpp
106
32.858491
75
0.769846
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
14,997
qlocalevsstrtod_l.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/benchmarks/qlocalevsstrtod_l.cpp
/* This file is part of QJson * * Copyright (C) 2014 Sune Vuorela <sune@ange.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QObject> #include <QtTest> #include <locale.h> class QLocaleVsStrtod_l : public QObject { Q_OBJECT private Q_SLOTS: void benchmark(); void benchmark_data(); }; void QLocaleVsStrtod_l::benchmark() { QFETCH(bool, useQLocale); QList<char*> l; l << strdup("0.123") << strdup("0.947834") << strdup("8.8373") << strdup("884.82921"); double result; if(useQLocale) { QLocale c(QLocale::C); QBENCHMARK { Q_FOREACH(const char* str, l) { result = c.toDouble(QString(str)); } } } else { locale_t c = newlocale(LC_NUMERIC_MASK, "C", NULL); QBENCHMARK { Q_FOREACH(const char* str, l) { result = strtod_l(str, NULL, c); } } } Q_FOREACH(char* str, l) { free(str); } } void QLocaleVsStrtod_l::benchmark_data() { QTest::addColumn<bool>("useQLocale"); QTest::newRow("using QLocale") << true; QTest::newRow("using strtod_l") << false; } QTEST_MAIN(QLocaleVsStrtod_l); #include "qlocalevsstrtod_l.moc"
1,911
C++
.cpp
59
27.355932
90
0.652363
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,998
parsingbenchmark.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/benchmarks/parsingbenchmark.cpp
/* This file is part of QJson * * Copyright (C) 2014 Sune Vuorela <sune@ange.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QJson/Parser> #include <QJson/Serializer> #include <QtTest/QTest> #include <QFile> class ParsingBenchmark: public QObject { Q_OBJECT private Q_SLOTS: void benchmark(); }; void ParsingBenchmark::benchmark() { QString path = QFINDTESTDATA("largefile.json"); QVERIFY(QFile::exists(path)); QFile f(path); QVERIFY(f.open(QIODevice::ReadOnly)); QByteArray data = f.readAll(); QVariant result; QJson::Parser parser; QBENCHMARK { result = parser.parse(data); } Q_UNUSED(result); } QTEST_MAIN(ParsingBenchmark) #include "parsingbenchmark.moc"
1,421
C++
.cpp
43
29.837209
75
0.734261
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,999
testserializer.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/serializer/testserializer.cpp
/* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <limits> #include <QtCore/QVariant> #include <QtTest/QtTest> #include <QJson/Parser> #include <QJson/Serializer> class TestSerializer: public QObject { Q_OBJECT private slots: void testReadWriteEmptyDocument(); void testReadWrite(); void testReadWrite_data(); void testValueNull(); void testValueString(); void testValueString_data(); void testValueStringList(); void testValueStringList_data(); void testValueHashMap(); void testValueInteger(); void testValueInteger_data(); void testValueDouble(); void testValueDouble_data(); void testSetDoublePrecision(); void testValueFloat(); void testValueFloat_data(); void testValueBoolean(); void testValueBoolean_data(); void testSpecialNumbers(); void testSpecialNumbers_data(); void testIndentation(); void testIndentation_data(); void testSerializetoQIODevice(); void testSerializeWithoutOkParam(); void testEscapeChars(); void testEscapeChars_data(); private: void valueTest( const QVariant& value, const QString& expectedRegExp, bool errorExpected = false ); void valueTest( const QObject* object, const QString& expectedRegExp ); }; Q_DECLARE_METATYPE(QVariant) using namespace QJson; void TestSerializer::testReadWriteEmptyDocument() { QByteArray json = ""; Parser parser; bool ok; QVariant result = parser.parse( json, &ok ); QVERIFY(!ok); QVERIFY( ! result.isValid() ); Serializer serializer; const QByteArray serialized = serializer.serialize( result, &ok); QVERIFY( ok ); QByteArray expected = "null"; QCOMPARE(expected, serialized); } void TestSerializer::testReadWrite() { QFETCH( QByteArray, json ); Parser parser; bool ok; QVariant result = parser.parse( json, &ok ); QVERIFY(ok); Serializer serializer; const QByteArray serialized = serializer.serialize( result, &ok); QVERIFY(ok); QVariant writtenThenRead = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( result, writtenThenRead ); } void TestSerializer::testReadWrite_data() { QTest::addColumn<QByteArray>( "json" ); // array tests QTest::newRow( "empty array" ) << QByteArray("[]"); QTest::newRow( "basic array" ) << QByteArray("[\"person\",\"bar\"]"); QTest::newRow( "single int array" ) << QByteArray("[6]"); QTest::newRow( "int array" ) << QByteArray("[6,5,6,7]"); const QByteArray json = "[1,2.4, -100, -3.4, -5e+0, 2e0,3e+0,4.3E0,5.4E-0]"; QTest::newRow( QByteArray("array of various numbers") ) << json; // document tests QTest::newRow( "empty object" ) << QByteArray("{}"); QTest::newRow( "basic document" ) << QByteArray("{\"person\":\"bar\"}"); QTest::newRow( "object with ints" ) << QByteArray("{\"person\":6}"); const QByteArray json2 = "{ \"person\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QTest::newRow( "complicated document" ) << json2; // more complex cases const QByteArray json3 = "[ {\"person\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QTest::newRow( "complicated array" ) << json3; } void TestSerializer::testIndentation() { QFETCH( QByteArray, json ); QFETCH( QByteArray, expected_compact ); QFETCH( QByteArray, expected_min ); QFETCH( QByteArray, expected_med ); QFETCH( QByteArray, expected_full ); // parse Parser parser; bool ok; QVariant parsed = parser.parse( json, &ok ); QVERIFY(ok); Serializer serializer; QVariant reparsed; QByteArray serialized; // serialize with indent compact and reparse serializer.setIndentMode(QJson::IndentCompact); serialized = serializer.serialize( parsed, &ok); QVERIFY(ok); QCOMPARE( serialized, expected_compact); reparsed = parser.parse( serialized, &ok); QVERIFY(ok); QCOMPARE( parsed, reparsed); // serialize with indent minimum and reparse serializer.setIndentMode(QJson::IndentMinimum); serialized = serializer.serialize( parsed, &ok); QVERIFY(ok); QCOMPARE( serialized, expected_min); reparsed = parser.parse( serialized, &ok); QVERIFY(ok); QCOMPARE( parsed, reparsed); // serialize with indent medium and reparse serializer.setIndentMode(QJson::IndentMedium); serialized = serializer.serialize( parsed, &ok); QVERIFY(ok); QCOMPARE( serialized, expected_med); reparsed = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( parsed, reparsed); // serialize with indent full and reparse serializer.setIndentMode(QJson::IndentFull); serialized = serializer.serialize( parsed, &ok); QVERIFY(ok); QCOMPARE( serialized, expected_full); reparsed = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( parsed, reparsed); } void TestSerializer::testIndentation_data() { QTest::addColumn<QByteArray>( "json" ); QTest::addColumn<QByteArray>( "expected_compact" ); QTest::addColumn<QByteArray>( "expected_min" ); QTest::addColumn<QByteArray>( "expected_med" ); QTest::addColumn<QByteArray>( "expected_full" ); const QByteArray json = " { \"foo\" : 0, \"foo1\" : 1, \"foo2\" : [ { \"bar\" : 1, \"foo\" : 0, \"foobar\" : 0 }, { \"bar\" : 1, \"foo\" : 1, \"foobar\" : 1 } ], \"foo3\" : [ 1, 2, 3, 4, 5, 6 ], \"foobaz\" : [ \"one\", \"two\", \"three\", \"four\" ] }"; const QByteArray ex_compact = "{\"foo\":0,\"foo1\":1,\"foo2\":[{\"bar\":1,\"foo\":0,\"foobar\":0},{\"bar\":1,\"foo\":1,\"foobar\":1}],\"foo3\":[1,2,3,4,5,6],\"foobaz\":[\"one\",\"two\",\"three\",\"four\"]}"; const QByteArray ex_min = "{ \"foo\" : 0, \"foo1\" : 1, \"foo2\" : [\n" " { \"bar\" : 1, \"foo\" : 0, \"foobar\" : 0 },\n" " { \"bar\" : 1, \"foo\" : 1, \"foobar\" : 1 }\n" " ], \"foo3\" : [\n" " 1,\n" " 2,\n" " 3,\n" " 4,\n" " 5,\n" " 6\n" " ], \"foobaz\" : [\n" " \"one\",\n" " \"two\",\n" " \"three\",\n" " \"four\"\n" " ] }"; const QByteArray ex_med = "{\n" " \"foo\" : 0, \"foo1\" : 1, \"foo2\" : [\n" " {\n" " \"bar\" : 1, \"foo\" : 0, \"foobar\" : 0\n" " },\n" " {\n" " \"bar\" : 1, \"foo\" : 1, \"foobar\" : 1\n" " }\n" " ], \"foo3\" : [\n" " 1,\n" " 2,\n" " 3,\n" " 4,\n" " 5,\n" " 6\n" " ], \"foobaz\" : [\n" " \"one\",\n" " \"two\",\n" " \"three\",\n" " \"four\"\n" " ]\n}"; const QByteArray ex_full = "{\n" " \"foo\" : 0,\n" " \"foo1\" : 1,\n" " \"foo2\" : [\n" " {\n" " \"bar\" : 1,\n" " \"foo\" : 0,\n" " \"foobar\" : 0\n" " },\n" " {\n" " \"bar\" : 1,\n" " \"foo\" : 1,\n" " \"foobar\" : 1\n" " }\n" " ],\n" " \"foo3\" : [\n" " 1,\n" " 2,\n" " 3,\n" " 4,\n" " 5,\n" " 6\n" " ],\n" " \"foobaz\" : [\n" " \"one\",\n" " \"two\",\n" " \"three\",\n" " \"four\"\n" " ]\n" "}"; QTest::newRow( "test indents" ) << json << ex_compact << ex_min << ex_med << ex_full; } void TestSerializer::valueTest( const QVariant& value, const QString& expectedRegExp, bool errorExpected ) { Serializer serializer; bool ok; const QByteArray serialized = serializer.serialize( value, &ok); QCOMPARE(ok, !errorExpected); QCOMPARE(serialized.isNull(), errorExpected); const QString serializedUnicode = QString::fromUtf8( serialized ); if (!errorExpected) { QRegExp expected( expectedRegExp ); QVERIFY( expected.isValid() ); QVERIFY2( expected.exactMatch( serializedUnicode ), qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) ) .arg( expectedRegExp ).arg( serializedUnicode ) ) ); } else { QVERIFY(!serializer.errorMessage().isEmpty()); } } void TestSerializer::valueTest( const QObject* object, const QString& expectedRegExp ) { Serializer serializer; bool ok; const QByteArray serialized = serializer.serialize( object, &ok); QVERIFY(ok); const QString serializedUnicode = QString::fromUtf8( serialized ); QRegExp expected( expectedRegExp ); QVERIFY( expected.isValid() ); QVERIFY2( expected.exactMatch( serializedUnicode ), qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) ) .arg( expectedRegExp ).arg( serializedUnicode ) ) ); } void TestSerializer::testValueNull() { valueTest( QVariant(), QLatin1String( "\\s*null\\s*" ) ); QVariantMap map; map[QLatin1String("value")] = QVariant(); valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:\\s*null\\s*\\}\\s*" ) ); } void TestSerializer::testValueString() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueString_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "null string" ) << QVariant( QString() ) << QString( QLatin1String( "\\s*\"\"\\s*" ) ); QTest::newRow( "empty string" ) << QVariant( QString( QLatin1String( "" ) ) ) << QString( QLatin1String( "\\s*\"\"\\s*" ) ); QTest::newRow( "Simple String" ) << QVariant( QString( QLatin1String( "simpleString" ) ) ) << QString( QLatin1String( "\\s*\"simpleString\"\\s*" ) ); QTest::newRow( "string with tab" ) << QVariant( QString( QLatin1String( "string\tstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\tstring\"\\s*" ) ); QTest::newRow( "string with newline" ) << QVariant( QString( QLatin1String( "string\nstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\nstring\"\\s*" ) ); QTest::newRow( "string with bell" ) << QVariant( QString( QLatin1String( "string\bstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\bstring\"\\s*" ) ); QTest::newRow( "string with return" ) << QVariant( QString( QLatin1String( "string\rstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\rstring\"\\s*" ) ); QTest::newRow( "string with double quote" ) << QVariant( QString( QLatin1String( "string\"string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\"string\"\\s*" ) ); QTest::newRow( "string with backslash" ) << QVariant( QString( QLatin1String( "string\\string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\\\\string\"\\s*" ) ); QString testStringWithUnicode = QString( QLatin1String( "string" ) ) + QChar( 0x2665 ) + QLatin1String( "string" ); QString testEscapedString = QString( QLatin1String( "string" ) ) + QLatin1String("\\\\u2665") + QLatin1String( "string" ); QTest::newRow( "string with unicode" ) << QVariant( testStringWithUnicode ) << QLatin1String( "\\s*\"" ) + testEscapedString + QLatin1String( "\"\\s*" ); } void TestSerializer::testValueStringList() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueStringList_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QStringList stringlist; QString expected; // simple QStringList stringlist << QLatin1String("hello") << QLatin1String("world"); expected = QLatin1String( "\\s*\\[\\s*\"hello\"\\s*,\\s*\"world\"\\s*\\]\\s*" ); QTest::newRow( "simple QStringList" ) << QVariant( stringlist) << expected; } void TestSerializer::testValueInteger() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueInteger_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "int 0" ) << QVariant( static_cast<int>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) ); QTest::newRow( "uint 0" ) << QVariant( static_cast<uint>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) ); QTest::newRow( "int -1" ) << QVariant( static_cast<int>( -1 ) ) << QString( QLatin1String( "\\s*-1\\s*" ) ); QTest::newRow( "int 2133149800" ) << QVariant( static_cast<int>(2133149800) ) << QString( QLatin1String( "\\s*2133149800\\s*" ) ); QTest::newRow( "uint 4133149800" ) << QVariant( static_cast<uint>(4133149800u) ) << QString( QLatin1String( "\\s*4133149800\\s*" ) ); QTest::newRow( "uint64 932838457459459" ) << QVariant( Q_UINT64_C(932838457459459) ) << QString( QLatin1String( "\\s*932838457459459\\s*" ) ); QTest::newRow( "max unsigned long long" ) << QVariant( std::numeric_limits<unsigned long long>::max() ) << QString( QLatin1String( "\\s*%1\\s*" ) ).arg(std::numeric_limits<unsigned long long>::max()); } void TestSerializer::testValueDouble() { QFETCH( QVariant, value ); QFETCH( QString, expected ); QFETCH( bool, errorExpected ); valueTest( value, expected, errorExpected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ), errorExpected ); } void TestSerializer::testValueDouble_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::addColumn<bool>( "errorExpected" ); QTest::newRow( "double 0" ) << QVariant( 0.0 ) << QString( QLatin1String( "\\s*0.0\\s*" ) ) << false; QTest::newRow( "double -1" ) << QVariant( -1.0 ) << QString( QLatin1String( "\\s*-1.0\\s*" ) ) << false; QTest::newRow( "double 1.5E-20" ) << QVariant( 1.5e-20 ) << QString( QLatin1String( "\\s*1.5[Ee]-20\\s*" ) ) << false; QTest::newRow( "double -1.5E-20" ) << QVariant( -1.5e-20 ) << QString( QLatin1String( "\\s*-1.5[Ee]-20\\s*" ) ) << false; QTest::newRow( "double 2.0E-20" ) << QVariant( 2.0e-20 ) << QString( QLatin1String( "\\s*2(?:.0)?[Ee]-20\\s*" ) ) << false; QTest::newRow( "double infinity" ) << QVariant( std::numeric_limits< double >::infinity() ) << QString( ) << true; QTest::newRow( "double -infinity" ) << QVariant( -std::numeric_limits< double >::infinity() ) << QString( ) << true; QTest::newRow( "double NaN" ) << QVariant( std::numeric_limits< double >::quiet_NaN() ) << QString( ) << true; } void TestSerializer::testSetDoublePrecision() { bool ok; Serializer serializer; QByteArray actual; QString expected, actualUnicode; double num = 0.12345678; // Set 1 as double precision serializer.setDoublePrecision(1); expected = QString(QLatin1String("0.1")); actual = serializer.serialize( QVariant(num), &ok); QVERIFY(ok); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); // Set 2 as double precision serializer.setDoublePrecision(2); expected = QString(QLatin1String("0.12")); actual = serializer.serialize( QVariant(num), &ok); QVERIFY(ok); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); // Set 4 as double precision serializer.setDoublePrecision(4); expected = QString(QLatin1String("0.1235")); actual = serializer.serialize( QVariant(num), &ok); QVERIFY(ok); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); // Set 14 as double precision serializer.setDoublePrecision(14); expected = QString(QLatin1String("0.12345678")); actual = serializer.serialize( QVariant(num), &ok); QVERIFY(ok); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); } void TestSerializer::testValueFloat() { QFETCH( QVariant, value ); QFETCH( QString, expected ); QFETCH( bool, errorExpected ); valueTest( value, expected, errorExpected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ), errorExpected ); } void TestSerializer::testValueFloat_data() { QVariant v; float value; QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::addColumn<bool>( "errorExpected" ); value = 0; v.setValue(value); QTest::newRow( "float 0" ) << v << QString( QLatin1String( "\\s*0.0\\s*" ) ) << false; value = -1; v.setValue(value); QTest::newRow( "float -1" ) << v << QString( QLatin1String( "\\s*-1.0\\s*" ) ) << false; value = 1.12f; v.setValue(value); QTest::newRow( "float 1.12" ) << v << QString( QLatin1String( "\\s*1.12\\s*" ) ) << false; } void TestSerializer::testValueBoolean() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueBoolean_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "bool false" ) << QVariant( false ) << QString( QLatin1String( "\\s*false\\s*" ) ); QTest::newRow( "bool true" ) << QVariant( true ) << QString( QLatin1String( "\\s*true\\s*" ) ); } void TestSerializer::testSpecialNumbers() { bool ok; QFETCH( QVariant, value ); QFETCH( QString, expected ); Serializer specialSerializer; QVERIFY(!specialSerializer.specialNumbersAllowed()); specialSerializer.allowSpecialNumbers(true); QVERIFY(specialSerializer.specialNumbersAllowed()); QByteArray serialized = specialSerializer.serialize(value, &ok); QVERIFY(ok); QCOMPARE(QString::fromLocal8Bit(serialized), expected); } void TestSerializer::testSpecialNumbers_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "Infinity" ) << QVariant( std::numeric_limits< double >::infinity() ) << QString::fromLocal8Bit("Infinity"); QTest::newRow( "-Infinity" ) << QVariant( -std::numeric_limits< double >::infinity() ) << QString::fromLocal8Bit("-Infinity"); QTest::newRow( "Infinity" ) << QVariant( std::numeric_limits< double >::quiet_NaN() ) << QString::fromLocal8Bit("NaN"); } void TestSerializer::testSerializetoQIODevice() { QBuffer buffer; QVariantList variant; variant << QVariant(QLatin1String("Hello")); variant << QVariant(QLatin1String("world!")); Serializer serializer; bool ok; serializer.serialize(variant, &buffer, &ok); QCOMPARE(QString(QLatin1String(buffer.data())), QString(QLatin1String("[ \"Hello\", \"world!\" ]"))); QVERIFY(ok); } void TestSerializer::testSerializeWithoutOkParam() { QBuffer buffer; QVariantList variant; variant << QVariant(QLatin1String("Hello")); variant << QVariant(QLatin1String("world!")); Serializer serializer; const QByteArray serialized = serializer.serialize(variant); const QByteArray expected = "[ \"Hello\", \"world!\" ]"; QCOMPARE(expected, serialized); // test a serialization which produces an error QVariant brokenVariant ( std::numeric_limits< double >::quiet_NaN() ); QVERIFY(serializer.serialize(brokenVariant).isEmpty()); } void TestSerializer::testValueHashMap() { Serializer serializer; bool ok; QVariantHash hash; hash[QLatin1String("one")] = 1; hash[QLatin1String("three")] = 3; hash[QLatin1String("seven")] = 7; QByteArray json = serializer.serialize(hash, &ok); QVERIFY(ok); Parser parser; QVariant var = parser.parse(json, &ok); QVERIFY(ok); QVariantMap vmap = var.toMap(); QHashIterator<QString, QVariant> hIt( hash ); while ( hIt.hasNext() ) { hIt.next(); QString key = hIt.key(); QVariant value = hIt.value(); QMap<QString, QVariant>::const_iterator mIt = vmap.constFind(key); QVERIFY(mIt != vmap.constEnd()); QCOMPARE(mIt.value(), value); } } void TestSerializer::testEscapeChars() { QFETCH(QString, input); QFETCH(QString, escaped); Serializer serializer; bool ok; QVariantHash hash; hash.insert(QLatin1String("key"), input); QByteArray json = serializer.serialize(hash, &ok); QVERIFY(ok); QString expected = QString(QLatin1String("{ \"key\" : \"%1\" }")).arg(escaped); QString actual = QString::fromUtf8(json.data(), json.length()); QCOMPARE(actual, expected); } void TestSerializer::testEscapeChars_data() { QTest::addColumn<QString>("input"); QTest::addColumn<QString>("escaped"); QTest::newRow("simple ASCII string") << "input" << "input"; QTest::newRow("ASCII new lines and tabs") << "line1\nline2\rline\t3" << "line1\\nline2\\rline\\t3"; QTest::newRow("backspace, backslash and quotes") << "one\\two\bthree\"four" << "one\\\\two\\bthree\\\"four"; QChar unicodeSnowman(0x2603); QTest::newRow("non-ASCII unicode char") << QString(unicodeSnowman) << "\\u2603"; QTest::newRow("control chars") << QString(QChar(0x06)) << "\\u0006"; } #if QT_VERSION < QT_VERSION_CHECK(5,0,0) // using Qt4 rather then Qt5 QTEST_MAIN(TestSerializer) #include "moc_testserializer.cxx" #else QTEST_GUILESS_MAIN(TestSerializer) #include "testserializer.moc" #endif
22,648
C++
.cpp
555
37.300901
257
0.650984
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
15,000
cmdlineparser.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/cmdline_tester/cmdlineparser.cpp
/* This file is part of qjson * * Copyright (C) 2010 Flavio Castelli <flavio@castelli.name> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <QtCore/QStringBuilder> #ifdef Q_OS_WIN //using Qt5 #ifdef QT_WIDGETS_LIB #include <QtWidgets/QMessageBox> #else //using Qt4 #include <QtGui/QMessageBox> #endif #endif #include "cmdlineparser.h" using namespace QJson; const QString CmdLineParser::m_helpMessage = QLatin1String( "Usage: cmdline_tester [options] file\n\n" "This program converts the json data read from 'file' to a QVariant object.\n" "--quiet Do not print output generated by parser and serializer.\n" "--serialize Parses the QVariant object back to json.\n" "--indent Sets the indentation level used by the 'serialize' option.\n" " Allowed values:\n" " - none [default]\n" " - compact\n" " - minimum\n" " - medium\n" " - full\n" "--help Displays this help.\n" ); CmdLineParser::CmdLineParser(const QStringList &arguments) : m_pos(0), m_indentationMode(IndentNone), m_serialize(false), m_quiet(false) { for (int i = 1; i < arguments.count(); ++i) { const QString &arg = arguments.at(i); m_arguments.append(arg); } } CmdLineParser::Result CmdLineParser::parse() { bool showHelp = false; while (m_error.isEmpty() && hasMoreArgs()) { const QString &arg = nextArg(); if (arg.toLower() == QLatin1String("--indent")) handleSetIndentationMode(); else if (arg.toLower() == QLatin1String("--help")) showHelp = true; else if (arg.toLower() == QLatin1String("--serialize")) m_serialize = true; else if (arg.toLower() == QLatin1String("--quiet")) m_quiet = true; else if (!arg.startsWith(QLatin1String("--"))) m_file = arg; else m_error = QString(QLatin1String("Unknown option: %1")).arg(arg); } if (m_file.isEmpty()) { m_error = QLatin1String("You have to specify the file containing the json data."); } if (!m_error.isEmpty()) { showMessage(m_error + QLatin1String("\n\n\n") + m_helpMessage, true); return Error; } else if (showHelp) { showMessage(m_helpMessage, false); return Help; } return Ok; } bool CmdLineParser::hasMoreArgs() const { return m_pos < m_arguments.count(); } const QString &CmdLineParser::nextArg() { Q_ASSERT(hasMoreArgs()); return m_arguments.at(m_pos++); } void CmdLineParser::handleSetIndentationMode() { if (hasMoreArgs()) { const QString &indentationMode = nextArg(); if (indentationMode.compare(QLatin1String("none"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentNone; else if (indentationMode.compare(QLatin1String("compact"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentCompact; else if (indentationMode.compare(QLatin1String("minimum"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentMinimum; else if (indentationMode.compare(QLatin1String("medium"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentMedium; else if (indentationMode.compare(QLatin1String("full"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentFull; else m_error = QString(QLatin1String("Unknown indentation mode '%1'.")). arg(indentationMode); } else { m_error = QLatin1String("Missing indentation level."); } } void CmdLineParser::showMessage(const QString &msg, bool error) { #ifdef Q_OS_WIN QString message = QLatin1String("<pre>") % msg % QLatin1String("</pre>"); if (error) QMessageBox::critical(0, QLatin1String("Error"), message); else QMessageBox::information(0, QLatin1String("Notice"), message); #else fprintf(error ? stderr : stdout, "%s\n", qPrintable(msg)); #endif } void CmdLineParser::setIndentationMode(const IndentMode &mode) { m_indentationMode = mode; } IndentMode CmdLineParser::indentationMode() const { return m_indentationMode; } QString CmdLineParser::file() const { return m_file; } bool CmdLineParser::serialize() { return m_serialize; } bool CmdLineParser::quiet() { return m_quiet; }
5,150
C++
.cpp
149
29.187919
93
0.652209
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
15,001
cmdline_tester.cpp
Studio3T_robomongo/src/third-party/qjson-0.8.1/sources/tests/cmdline_tester/cmdline_tester.cpp
/* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QStringList> #include <QtCore/QVariant> #include <QtCore/QTextCodec> #include <QtCore/QTime> #include <QJson/Parser> #include <QJson/Serializer> #include "cmdlineparser.h" using namespace QJson; int main(int argc, char *argv[]) { QCoreApplication app (argc, argv); #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForCStrings(codec); #endif QTime time; int duration; CmdLineParser cmd (app.arguments()); CmdLineParser::Result res = cmd.parse(); if (res == CmdLineParser::Help) return 0; else if (res == CmdLineParser::Error) return -1; QString filename = cmd.file(); if (!QFile::exists ( filename )) { qCritical ("The file you specified doesn't exist!"); exit (1); } Parser parser; bool ok; QFile file (filename); time.start(); QVariant data = parser.parse (&file, &ok); duration = time.elapsed(); if (!ok) { qCritical("%s:%i - Error: %s", filename.toLatin1().data(), parser.errorLine(), qPrintable(parser.errorString())); exit (1); } else { qDebug() << "Parsing of" << filename << "took" << duration << "ms"; if (!cmd.quiet()) qDebug() << data; } if (cmd.serialize()) { // serializer tests qDebug() << "Serializing... "; QJson::Serializer serializer; serializer.setIndentMode(cmd.indentationMode()); time.start(); QByteArray b = serializer.serialize(data, &ok); if (!ok) { qCritical() << "Serialization failed:" << serializer.errorMessage(); exit(1); } else { duration = time.elapsed(); qDebug() << "Serialization took:" << duration << "ms"; if (!cmd.quiet()) qDebug() << b; } } qDebug() << "JOB DONE, BYE"; return 0; }
2,691
C++
.cpp
84
28.630952
117
0.68545
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
15,113
Enums.h
Studio3T_robomongo/src/robomongo/core/Enums.h
#pragma once namespace Robomongo { enum UUIDEncoding { DefaultEncoding = 0, JavaLegacy = 1, CSharpLegacy = 2, PythonLegacy = 3 }; enum SupportedTimes { Utc = 0, LocalTime = 1 }; enum ViewMode { Text = 0, Tree = 1, Table = 2, Custom = 3 }; enum AutocompletionMode { AutocompleteNone = 0, AutocompleteAll = 1, AutocompleteNoCollectionNames = 2 }; const char *convertUUIDEncodingToString(UUIDEncoding uuidCode); UUIDEncoding convertStringToUUIDEncoding(const char *text); const char *convertTimesToString(SupportedTimes time); SupportedTimes convertStringToTimes(const char *text); const char *convertViewModeToString(ViewMode mode); ViewMode convertStringToViewMode(const char *text); }
886
C++
.h
35
19.057143
67
0.639383
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,117
EventWrapper.h
Studio3T_robomongo/src/robomongo/core/EventWrapper.h
#pragma once #include <boost/scoped_ptr.hpp> #include "robomongo/core/Event.h" namespace Robomongo { class EventWrapper : public QEvent { public: EventWrapper(Event *event, QList<QObject *> receivers); EventWrapper(Event *event, QObject * receiver); Event *event() const; const QList<QObject *> &receivers() const; private: const boost::scoped_ptr<Event> _event; const QList<QObject *> _receivers; }; }
473
C++
.h
17
22.705882
63
0.662996
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,118
AppRegistry.h
Studio3T_robomongo/src/robomongo/core/AppRegistry.h
#pragma once #include "robomongo/core/Core.h" #include "robomongo/core/utils/SingletonPattern.hpp" namespace Robomongo { class SettingsManager; class AppRegistry: public Patterns::LazySingleton<AppRegistry> { friend class Patterns::LazySingleton<AppRegistry>; public: SettingsManager *const settingsManager() const { return _settingsManager.get(); } App *const app() const { return _app.get(); } EventBus *const bus() const { return _bus.get(); } private: AppRegistry(); ~AppRegistry(); const EventBusScopedPtr _bus; const SettingsManagerScopedPtr _settingsManager; const AppScopedPtr _app; }; }
698
C++
.h
21
27.380952
89
0.690015
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,119
Core.h
Studio3T_robomongo/src/robomongo/core/Core.h
#pragma once #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> namespace mongo { class DBClientConnection; } /* ** Smart pointers for Mongo* staff */ namespace Robomongo { class AppRegistry; typedef boost::scoped_ptr<AppRegistry> AppRegistryScopedPtr; class SettingsManager; typedef boost::scoped_ptr<SettingsManager> SettingsManagerScopedPtr; class App; typedef boost::scoped_ptr<App> AppScopedPtr; class EventBus; typedef boost::scoped_ptr<EventBus> EventBusScopedPtr; class MongoCollection; typedef boost::shared_ptr<MongoCollection> MongoCollectionPtr; class MongoDocument; typedef boost::shared_ptr<MongoDocument> MongoDocumentPtr; // todo: Use enum class enum ConnectionType { // This type of connection is shown in Explorer and also opens SSH tunnel for secondary // connections (if needed) ConnectionPrimary = 0, // Never shown in Explorer and uses SSH tunnel from primary connection (if needed) ConnectionSecondary = 1, // The same as Primary, but is specifically for testing connections. ConnectionTest = 2, // Never shown in Explorer and can be used to refresh (via reconnecting) current connection view // (i.e. db version, storage engine, current replica set primary, status of replica set etc...) ConnectionRefresh = 3 }; }
1,431
C++
.h
38
32.5
105
0.717596
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,120
KeyboardManager.h
Studio3T_robomongo/src/robomongo/core/KeyboardManager.h
#pragma once #include <QKeyEvent> namespace Robomongo { namespace KeyboardManager { bool isNewTabShortcut(QKeyEvent *keyEvent); bool isDuplicateTabShortcut(QKeyEvent *keyEvent); bool isSetFocusOnQueryLineShortcut(QKeyEvent *keyEvent); bool isExecuteScriptShortcut(QKeyEvent *keyEvent); bool isAutoCompleteShortcut(QKeyEvent *keyEvent); bool isHideAutoCompleteShortcut(QKeyEvent *keyEvent); bool isNextTabShortcut(QKeyEvent *keyEvent); bool isPreviousTabShortcut(QKeyEvent *keyEvent); bool isToggleCommentsShortcut(QKeyEvent *keyEvent); } }
626
C++
.h
17
30.764706
64
0.752883
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,121
HexUtils.h
Studio3T_robomongo/src/robomongo/core/HexUtils.h
#pragma once #include "robomongo/core/Enums.h" #include <mongo/bson/bsonelement.h> namespace Robomongo { /** * @brief HexUtils * * Usage: * * std::string csuuid = HexUtils::hexToCSharpUuid(hex.toStdString()); * std::string cshex = HexUtils::csharpUuidToHex(csuuid); * * std::string juuid = HexUtils::hexToJavaUuid(hex.toStdString()); * std::string jhex = HexUtils::javaUuidToHex(juuid); * * std::string puuid = HexUtils::hexToPythonUuid(hex.toStdString()); * std::string phex = HexUtils::pythonUuidToHex(puuid);* * */ namespace HexUtils { bool isHexString(const std::string &hex); std::string toStdHexLower(const char *raw, int len); /** * @param str: data in hex format. * @param outBytes: out param - number of bytes in array. * @return array of bytes, with "outBytes" length. */ const char *fromHex(const std::string &str, int *outBytes); std::string hexToUuid(const std::string &hex, UUIDEncoding encoding); std::string hexToUuid(const std::string &hex); std::string hexToCSharpUuid(const std::string &hex); std::string hexToJavaUuid(const std::string &hex); std::string hexToPythonUuid(const std::string &hex); /** * @return empty string, if invalid UUID. */ std::string uuidToHex(const std::string &uuid, UUIDEncoding encoding); std::string uuidToHex(const std::string &uuid); std::string csharpUuidToHex(const std::string &uuid); std::string javaUuidToHex(const std::string &uuid); std::string pythonUuidToHex(const std::string &uuid); std::string formatUuid(const mongo::BSONElement &element, UUIDEncoding encoding); } }
1,809
C++
.h
46
32.456522
89
0.642817
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,123
EventError.h
Studio3T_robomongo/src/robomongo/core/EventError.h
#pragma once #include <string> #include "robomongo/core/mongodb/ReplicaSet.h" namespace Robomongo { /** * @brief Error object is a part of every Event in Robomongo. Before the * use of any event you should check whether error is detected by * calling Event::isError() method. */ class EventError { public: enum ErrorCode { Unknown, SetPrimaryUnreachable, ServerHasDifferentMembers }; /** * @brief Creates "null" (or, in other words, empty) error. * Subsequent call of isNull() on this object will return true. */ EventError(); /** * @brief Creates error object with specified error message. * Subsequent call of isNull() on this object will return false. */ explicit EventError(const std::string &errorMessage, ErrorCode errorCode = Unknown, bool showErrorWindow = true); /** * @brief Creates error object only for replica set connection failures */ explicit EventError(const std::string &errorMessage, ReplicaSet const& replicaSetInfo, bool showErrorWindow = true); /** * @brief Tests whether error is "null" (or, in other words, empty). * Because Error object should be created on stack, this is the only * way to support "null" semantic for value objects. * @return true, if null or false otherwise. */ bool isNull() const; /** * @brief Returns error message that describes this error. */ const std::string &errorMessage() const; ErrorCode errorCode() const { return _errorCode; } ReplicaSet replicaSetInfo() const { return _replicaSetInfo; } bool showErrorWindow() const { return _showErrorWindow; } private: /** * @brief Error message */ std::string const _errorMessage; ErrorCode const _errorCode = Unknown; ReplicaSet const _replicaSetInfo; bool const _showErrorWindow = true; bool const _isNull; }; }
2,149
C++
.h
55
30.072727
95
0.621674
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,124
ReplicaSet.h
Studio3T_robomongo/src/robomongo/core/mongodb/ReplicaSet.h
#pragma once #include <mongo/util/net/hostandport.h> #include <vector> namespace Robomongo { /** * @brief Struct to represent live information of a replica set. */ struct ReplicaSet { ReplicaSet(std::string const& setName, const mongo::HostAndPort primary, std::vector<std::pair<std::string, bool>> const& membersAndHealths, std::string const& errorStr = ""); ReplicaSet() {}; std::string const setName; mongo::HostAndPort const primary; std::string const errorStr; // pair: {HostNameAndPort, Health} std::vector<std::pair<std::string, bool>> const membersAndHealths; // todo: make first element of pair type HostnameAndPort }; }
764
C++
.h
21
29
121
0.645691
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,125
MongoWorker.h
Studio3T_robomongo/src/robomongo/core/mongodb/MongoWorker.h
#pragma once #include <QObject> #include <QMutex> #include <unordered_set> #include <mongo/client/dbclient_rs.h> #include "robomongo/core/events/MongoEvents.h" QT_BEGIN_NAMESPACE class QThread; class QTimer; QT_END_NAMESPACE namespace Robomongo { class MongoClient; class ScriptEngine; class ConnectionSettings; class MongoWorker : public QObject { Q_OBJECT public: explicit MongoWorker(ConnectionSettings *connection, bool isLoadMongoRcJs, int batchSize, double mongoTimeoutSec, int shellTimeoutSec, QObject *parent = nullptr); ~MongoWorker(); void interrupt(); void stopAndDelete(); void changeTimeout(int newTimeout); protected Q_SLOTS: void init(); /** * @brief Every minute we are issuing { ping : 1 } command to every used connection * in order to avoid dropped connections. */ void keepAlive(); /** * @brief Initiate connection to MongoDB */ bool handle(EstablishConnectionRequest *event); /** * @brief Try to re-connect to MongoDB replica set in order to refresh connection view. * For more details, see MongoServer::tryRefreshReplicaSetFolder() */ void handle(RefreshReplicaSetFolderRequest *event); /** * @brief Load list of all database names */ void handle(LoadDatabaseNamesRequest *event); /** * @brief Load list of all collection names */ void handle(LoadCollectionNamesRequest *event); /** * @brief Load list of all users */ void handle(LoadUsersRequest *event); /** * @brief Load indexes in collection */ void handle(LoadCollectionIndexesRequest *event); /** * @brief Add/edit indexes in collection */ void handle(AddEditIndexRequest *event); /** * @brief delete index from collection */ void handle(DropCollectionIndexRequest *event); /** * @brief Load list of all JS functions */ void handle(LoadFunctionsRequest *event); /** * @brief Inserts document */ void handle(InsertDocumentRequest *event); /** * @brief Remove documents */ void handle(RemoveDocumentRequest *event); /** * @brief Load list of all collection names */ void handle(ExecuteQueryRequest *event); /** * @brief Execute javascript */ void handle(ExecuteScriptRequest *event); void retry(ExecuteScriptRequest *event); void handle(StopScriptRequest *event); void handle(AutocompleteRequest *event); void handle(CreateDatabaseRequest *event); void handle(DropDatabaseRequest *event); void handle(CreateCollectionRequest *event); void handle(DropCollectionRequest *event); void handle(RenameCollectionRequest *event); void handle(DuplicateCollectionRequest *event); void handle(CopyCollectionToDiffServerRequest *event); // todo: unused? remove void handle(CreateUserRequest *event); void handle(DropUserRequest *event); void handle(CreateFunctionRequest *event); void handle(DropFunctionRequest *event); protected: virtual void timerEvent(QTimerEvent *); private: // Added after Mongo 4.0 to fix connection failures seen after a first edit/add/remove doc. operation void restartReplicaSetConnection(); /** * @brief Send event to this MongoWorker */ void send(Event *event); std::vector<std::string> getDatabaseNamesSafe(EstablishConnectionRequest* event = nullptr); std::string getAuthBase() const; // Returns a pair of DBClientBase* connection and error string std::pair<mongo::DBClientBase*, std::string> getConnection(bool mayReturnNull = false); MongoClient *getClient(); /** *@brief Reset and update global mongo SSL settings (mongo::sslGlobalParams) */ void configureSSL(); /** *@brief Update global mongo SSL settings (mongo::sslGlobalParams) according to active connection * request's SSL settings. */ void updateGlobalSSLparams() const; /** *@brief Reset global mongo SSL settings (mongo::sslGlobalParams) into default zero state */ void resetGlobalSSLparams() const; /** *@brief Update Replica Set related parameters/settings. */ ReplicaSet getReplicaSetInfo() const; std::string connectAndGetReplicaSetName() const; /** * @brief Send reply event to object 'obj' */ void reply(QObject *receiver, Event *event); /** * @brief Send hear beat messages to database in order to keep connection alive */ void pingDatabase(mongo::DBClientBase *dbclient) const; QThread *_thread; QMutex _firstConnectionMutex; std::unique_ptr<ScriptEngine> _scriptEngine; const bool _isLoadMongoRcJs; const int _batchSize; int _timerId; int _dbAutocompleteCacheTimerId; double _mongoTimeoutSec; int _shellTimeoutSec; QAtomicInteger<int> _isQuiting; std::unique_ptr<mongo::DBClientConnection> _dbclient; std::unique_ptr<mongo::DBClientReplicaSet> _dbclientRepSet; ConnectionSettings *_connSettings; // Collection of created databases. // Starting from 3.0, MongoDB drops empty databases. // It means, we did not find a way to create "empty" database. // We save all created databases in this collection and merge with // list of real databases returned from MongoDB server. std::unordered_set<std::string> _createdDbs; }; }
6,047
C++
.h
160
29.00625
109
0.637671
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,126
SshTunnelWorker.h
Studio3T_robomongo/src/robomongo/core/mongodb/SshTunnelWorker.h
#pragma once #include <QObject> #include <robomongo/ssh/ssh.h> #include "robomongo/core/events/MongoEvents.h" QT_BEGIN_NAMESPACE class QThread; QT_END_NAMESPACE struct rbm_ssh_tunnel_config; struct rbm_ssh_session; namespace Robomongo { class ConnectionSettings; class EstablishSshConnectionRequest; class ListenSshConnectionRequest; /* * Helper class for creating rbm_ssh_tunnel_config from ConnectionSettings * Automatically deletes allocated structure */ class SshTunnelConfigCreator { public: explicit SshTunnelConfigCreator(ConnectionSettings *settings); ~SshTunnelConfigCreator(); rbm_ssh_tunnel_config *config() { return _sshConfig; } private: std::string _sshhost; int _sshport; std::string _remotehost; int _remoteport; std::string _localip; int _localport; std::string _userName; std::string _userPassword; std::string _privateKeyFile; std::string _publicKeyFile; std::string _passphrase; std::string _authMethod; // "password" or "publickey" rbm_ssh_tunnel_config* _sshConfig; }; class SshTunnelWorker : public QObject { Q_OBJECT public: explicit SshTunnelWorker(ConnectionSettings *settings); ~SshTunnelWorker(); static void logCallbackHandler(void* context, char *message, int level); protected: void stopAndDelete(); protected Q_SLOTS: // handlers: void handle(EstablishSshConnectionRequest *event); void handle(ListenSshConnectionRequest *event); private: void reply(QObject *receiver, Event *event); void log(const std::string& message, int level = 3); QThread *_thread; QAtomicInteger<int> _isQuiting; ConnectionSettings* _settings; rbm_ssh_session* _sshSession; SshTunnelConfigCreator _configCreator; }; }
1,953
C++
.h
60
26.066667
80
0.687467
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,127
MongoClient.h
Studio3T_robomongo/src/robomongo/core/mongodb/MongoClient.h
#pragma once #include <mongo/client/dbclient_base.h> #include <mongo/bson/bsonobj.h> #include "robomongo/core/Core.h" #include "robomongo/core/domain/MongoQueryInfo.h" #include "robomongo/core/domain/MongoUser.h" #include "robomongo/core/domain/MongoFunction.h" #include "robomongo/core/events/MongoEventsInfo.h" namespace Robomongo { class MongoClient { public: MongoClient(mongo::DBClientBase *const scopedConnection); std::vector<std::string> getCollectionNamesWithDbname(const std::string &dbname) const; std::vector<std::string> getDatabaseNames() const; float getVersion() const; std::string dbVersionStr() const; std::string getStorageEngineType() const; std::vector<MongoUser> getUsers(const std::string &dbName); void createUser(const std::string &dbName, const MongoUser &user); void dropUser(const std::string &dbName, const std::string &user); std::vector<MongoFunction> getFunctions(const std::string &dbName) const; std::vector<IndexInfo> getIndexes(const MongoCollectionInfo &collection) const; void dropIndexFromCollection(const MongoCollectionInfo &collection, const std::string &indexName) const; void addEditIndex(const IndexInfo &oldInfo, const IndexInfo &newInfo) const; void renameIndexFromCollection(const MongoCollectionInfo &collection, const std::string &oldIndexName, const std::string &newIndexName) const; void createFunction(const std::string &dbName, const MongoFunction &fun, const std::string &existingFunctionName = std::string()); void dropFunction(const std::string &dbName, const std::string &name); void createDatabase(const std::string &dbName); void dropDatabase(const std::string &dbName); void createCollection(const std::string &ns, long long size, bool capped, int max, const mongo::BSONObj& extraOptions, mongo::BSONObj* info = nullptr); void renameCollection(const MongoNamespace &ns, const std::string &newCollectionName); void duplicateCollection(const MongoNamespace &ns, const std::string &newCollectionName); void dropCollection(const MongoNamespace &ns); void copyCollectionToDiffServer(mongo::DBClientBase *const, const MongoNamespace &from, const MongoNamespace &to); void insertDocument(const mongo::BSONObj &obj, const MongoNamespace &ns); void saveDocument(const mongo::BSONObj &obj, const MongoNamespace &ns); void removeDocuments(const MongoNamespace &ns, mongo::Query query, bool justOne = true); std::vector<MongoDocumentPtr> query(const MongoQueryInfo &info); MongoCollectionInfo runCollStatsCommand(const std::string &ns); std::vector<MongoCollectionInfo> runCollStatsCommand(const std::vector<std::string> &namespaces); void done(); private: mongo::DBClientBase *const _dbclient; void checkLastErrorAndThrow(const std::string &db); }; }
3,058
C++
.h
50
53.02
159
0.722111
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,128
BsonUtils.h
Studio3T_robomongo/src/robomongo/core/utils/BsonUtils.h
#pragma once #include <mongo/bson/bsonelement.h> #include <mongo/bson/bsonobj.h> #include "robomongo/core/Enums.h" class QString; namespace Robomongo { namespace BsonUtils { namespace detail { template<mongo::BSONType BSONType_t> struct bson_convert_traits { typedef mongo::BSONObj type; enum { mongo_type = BSONType_t }; }; template<> struct bson_convert_traits<mongo::Bool> { typedef bool type; enum { mongo_type = mongo::Bool }; }; template<> struct bson_convert_traits<mongo::String> { typedef std::string type; enum { mongo_type = mongo::String }; }; template<> struct bson_convert_traits<mongo::Array> { typedef std::vector<mongo::BSONElement> type; enum { mongo_type = mongo::Array }; }; template<> struct bson_convert_traits<mongo::NumberInt> { typedef int type; enum { mongo_type = mongo::NumberInt }; }; template<> struct bson_convert_traits<mongo::NumberDouble> { typedef double type; enum { mongo_type = mongo::NumberDouble }; }; template<> struct bson_convert_traits<mongo::NumberLong> { typedef long long type; enum { mongo_type = mongo::NumberLong }; }; template<typename type_t> type_t getField(const mongo::BSONElement &elem); } template<typename type_t> type_t bsonelement_cast(const mongo::BSONElement &elem) { type_t result = type_t(); bool isEoo = !elem.eoo(); if (isEoo) { result = detail::getField<type_t>(elem); } return result; } template<mongo::BSONType BSONType_t> typename detail::bson_convert_traits<BSONType_t>::type getField(const mongo::BSONObj &obj, const char *data) { mongo::BSONElement elem = obj.getField(data); return bsonelement_cast<typename detail::bson_convert_traits<BSONType_t>::type>(elem); } std::string jsonString(const mongo::BSONObj &obj, mongo::JsonStringFormat format, int pretty, UUIDEncoding uuidEncoding, SupportedTimes timeFormat, bool isArray = false); std::string jsonString(const mongo::BSONElement &elem, mongo::JsonStringFormat format, bool includeFieldNames, int pretty, UUIDEncoding uuidEncoding, SupportedTimes timeFormat, bool isArray = false); bool isArray(const mongo::BSONElement &elem); bool isArray(mongo::BSONType type); bool isDocument(const mongo::BSONElement &elem); bool isDocument(mongo::BSONType type); bool isSimpleType(const mongo::BSONType type); bool isUuidType(const mongo::BSONType type, mongo::BinDataType binDataType); bool isSimpleType(const mongo::BSONElement &elem); bool isUuidType(const mongo::BSONElement &elem); const char* BSONTypeToString(mongo::BSONType type, mongo::BinDataType binDataType, UUIDEncoding uuidEncoding); void buildJsonString(const mongo::BSONObj &obj, std::string &con, UUIDEncoding uuid, SupportedTimes tz); void buildJsonString(const mongo::BSONElement &elem, std::string &con, UUIDEncoding uuid, SupportedTimes tz); mongo::BSONElement indexOf(const mongo::BSONObj &doc, int index); int elementsCount(const mongo::BSONObj &doc); std::string reformatDoubleString(QString str, double elemDouble); } }
3,887
C++
.h
92
30.641304
130
0.592367
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,129
SingletonPattern.hpp
Studio3T_robomongo/src/robomongo/core/utils/SingletonPattern.hpp
#pragma once namespace Patterns { template <class T> class Singleton { static T* _self; public: void freeInstance(); static T* instance(); protected: virtual ~Singleton() { _self=NULL; } Singleton() { } }; template <class T> T* Singleton<T>::_self = NULL; template <class T> T* Singleton<T>::instance() { if(!_self) _self=new T; return _self; } template <class T> void Singleton<T>::freeInstance() { delete this; } template <class T> class LazySingleton { public: typedef LazySingleton<T> class_type; static T &instance(); protected: LazySingleton() { } ~LazySingleton(){} private: LazySingleton(class_type const&); LazySingleton& operator=(class_type const& rhs); }; template <class T> T &LazySingleton<T>::instance() { static T _self; return _self; } }
1,019
C++
.h
55
12.781818
54
0.553479
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
15,130
QtUtils.h
Studio3T_robomongo/src/robomongo/core/utils/QtUtils.h
#pragma once #include <QString> #include <QModelIndex> QT_BEGIN_NAMESPACE class QThread; class QTreeWidgetItem; class QAbstractItemModel; QT_END_NAMESPACE #ifdef QT_NO_DEBUG #define VERIFY(x) (x) #else //QT_NO_DEBUG #define VERIFY(x) Q_ASSERT(x) #endif //QT_NO_DEBUG namespace Robomongo { namespace QtUtils { template<typename T> QString toQString(const T &value); std::string toStdString(const QString &value); std::string toStdStringSafe(const QString &value); void cleanUpThread(QThread *const thread); void clearChildItems(QTreeWidgetItem *root); template<typename Type> inline Type item(const QModelIndex &index) { return static_cast<Type>(index.internalPointer()); } struct HackQModelIndex { int r, c; void* i; const QAbstractItemModel *m; }; } }
926
C++
.h
36
19.916667
62
0.660613
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,131
StdUtils.h
Studio3T_robomongo/src/robomongo/core/utils/StdUtils.h
#pragma once #include <algorithm> #include <functional> namespace Robomongo { namespace stdutils { template<typename T> inline void destroy(T *&v) { delete v; v = NULL; } template<typename T> struct RemoveIfFound { RemoveIfFound(T whatSearch) : _whatSearch(whatSearch) {} bool operator()(T item) const { if (item == _whatSearch) { destroy(item); return true; } return false; } T _whatSearch; }; template <typename T> struct default_delete { inline void operator ()(T *ptr) const { destroy(ptr); } }; template <typename T> struct default_delete<T*> { inline void operator ()(T *ptr) const { destroy(ptr); } }; template<typename T, unsigned int N> struct default_delete<T[N]> { inline void operator ()(const T ptr) const { delete [] ptr; } }; } }
1,245
C++
.h
52
13.326923
68
0.443038
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,132
Logger.h
Studio3T_robomongo/src/robomongo/core/utils/Logger.h
#pragma once #include <QObject> #include <QString> #include <string> #include <mongo/logger/log_severity.h> #include "robomongo/core/events/MongoEvents.h" #include "robomongo/core/utils/SingletonPattern.hpp" namespace Robomongo { class Logger : public QObject, public Patterns::LazySingleton<Logger> { Q_OBJECT friend class Patterns::LazySingleton<Logger>; public: void print(const char *msg, mongo::logger::LogSeverity level, bool notify); void print(const std::string &msg, mongo::logger::LogSeverity level, bool notify); void print(const QString &msg, mongo::logger::LogSeverity level, bool notify); Q_SIGNALS: void printed(const QString &msg, mongo::logger::LogSeverity level); private: Logger(); ~Logger(); }; // Use in main thread template<typename T> inline void LOG_MSG(const T &msg, mongo::logger::LogSeverity level, bool notify = true) { return Logger::instance().print(msg, level, notify); } // Use in worker threads (e.g. MongoWorker) to log anything // Sends LogEvent to main thread (App class) void sendLog( QObject *sender, LogEvent::LogLevel const& severity, std::string const& msg, bool const informUser = false ); void debugLog(std::string_view msg); }
1,340
C++
.h
37
30.648649
91
0.687597
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,133
MongoEvents.h
Studio3T_robomongo/src/robomongo/core/events/MongoEvents.h
#pragma once #include <QMessageBox> #include <QString> #include <QStringList> #include <QEvent> #include <mongo/client/dbclient_base.h> #include "robomongo/core/domain/MongoShellResult.h" #include "robomongo/core/domain/CursorPosition.h" #include "robomongo/core/domain/MongoUser.h" #include "robomongo/core/domain/MongoFunction.h" #include "robomongo/core/events/MongoEventsInfo.h" #include "robomongo/core/domain/MongoAggregateInfo.h" #include "robomongo/core/Event.h" #include "robomongo/core/Enums.h" #include "robomongo/core/mongodb/ReplicaSet.h" namespace Robomongo { class MongoServer; class MongoShell; class MongoDatabase; class MongoWorker; class ConnectionSettings; class SshTunnelWorker; /** * @brief EstablishConnection */ struct EstablishConnectionRequest : public Event { R_EVENT EstablishConnectionRequest(QObject *sender, ConnectionType connectionType, std::string const& uuid) : Event(sender), connectionType(connectionType), uuid(uuid) {} ConnectionType const connectionType; std::string const uuid; }; struct EstablishConnectionResponse : public Event { R_EVENT enum ErrorReason { NoError = 0, MongoConnection = 1, MongoAuth = 2, MongoSslConnection = 3 }; EstablishConnectionResponse(QObject *sender, const ConnectionInfo &info, ConnectionType connectionType, const ReplicaSet& replicaSet) : Event(sender), info(info), connectionType(connectionType), replicaSet(replicaSet) {} EstablishConnectionResponse(QObject *sender, const EventError &error, ConnectionType connectionType, ConnectionInfo const& info, const ReplicaSet& replicaSet, ErrorReason errorReason) : Event(sender, error), info(info), connectionType(connectionType), errorReason(errorReason), replicaSet(replicaSet) {} ConnectionInfo const info; ConnectionType const connectionType; ErrorReason const errorReason = NoError; ReplicaSet const replicaSet; }; struct ReplicaSetRefreshed : public Event { R_EVENT ReplicaSetRefreshed(QObject *sender) : Event(sender) {} ReplicaSetRefreshed(QObject *sender, const EventError &error, ReplicaSet const& replicaSet) : Event(sender, error), replicaSet(replicaSet) {} ReplicaSet const replicaSet; }; struct RefreshReplicaSetFolderRequest : public Event { R_EVENT RefreshReplicaSetFolderRequest(QObject *sender, bool expanded) : Event(sender), expanded(expanded) {} bool const expanded = false; }; struct RefreshReplicaSetFolderResponse : public Event { R_EVENT // Primary is reachable RefreshReplicaSetFolderResponse(QObject *sender, ReplicaSet const& replicaSet, bool expanded) : Event(sender), replicaSet(replicaSet), expanded(expanded) {} // Primary is unreachable, secondary(ies) might be reachable RefreshReplicaSetFolderResponse(QObject *sender, ReplicaSet const& replicaSet, bool expanded, const EventError &error) : Event(sender, error), replicaSet(replicaSet), expanded(expanded) {} ReplicaSet const replicaSet; bool const expanded = false; }; struct ReplicaSetFolderLoading : public Event { R_EVENT ReplicaSetFolderLoading(QObject *sender) : Event(sender) {} }; struct ReplicaSetFolderRefreshed : public Event { R_EVENT ReplicaSetFolderRefreshed(QObject *sender, bool expanded) : Event(sender), expanded(expanded) {} ReplicaSetFolderRefreshed(QObject *sender, const EventError &error, bool expanded) : Event(sender, error), expanded(expanded) {} ReplicaSetFolderRefreshed(QObject *sender, const EventError &error, ReplicaSet const& replicaSet, bool expanded) : Event(sender, error), replicaSet(replicaSet), expanded(expanded) {} ReplicaSet const replicaSet; bool const expanded = false; }; /** * @brief LoadDatabaseNames */ class LoadDatabaseNamesRequest : public Event { R_EVENT LoadDatabaseNamesRequest(QObject *sender) : Event(sender) {} }; class LoadDatabaseNamesResponse : public Event { R_EVENT LoadDatabaseNamesResponse(QObject *sender, const std::vector<std::string> &databaseNames) : Event(sender), databaseNames(databaseNames) {} LoadDatabaseNamesResponse(QObject *sender, const EventError &error) : Event(sender, error) {} std::vector<std::string> databaseNames; }; /** * @brief LoadCollectionNames */ class LoadCollectionNamesRequest : public Event { R_EVENT public: LoadCollectionNamesRequest(QObject *sender, const std::string &databaseName) : Event(sender), _databaseName(databaseName) {} std::string databaseName() const { return _databaseName; } private: std::string _databaseName; }; class LoadCollectionNamesResponse : public Event { R_EVENT public: LoadCollectionNamesResponse(QObject *sender, const std::string &databaseName, const std::vector<MongoCollectionInfo> &collectionInfos) : Event(sender), _databaseName(databaseName), _collectionInfos(collectionInfos) { } LoadCollectionNamesResponse(QObject *sender, const EventError &error) : Event(sender, error) {} std::string databaseName() const { return _databaseName; } std::vector<MongoCollectionInfo> collectionInfos() const { return _collectionInfos; } private: std::string _databaseName; std::vector<MongoCollectionInfo> _collectionInfos; }; class LoadCollectionIndexesRequest : public Event { R_EVENT public: LoadCollectionIndexesRequest(QObject *sender, const MongoCollectionInfo &collection) : Event(sender), _collection(collection) {} MongoCollectionInfo collection() const { return _collection; } private: const MongoCollectionInfo _collection; }; class LoadCollectionIndexesResponse : public Event { R_EVENT public: LoadCollectionIndexesResponse(QObject *sender, const std::vector<IndexInfo> &indexes) : Event(sender), _indexes(indexes) {} LoadCollectionIndexesResponse(QObject *sender, const EventError &error) : Event(sender, error) {} std::vector<IndexInfo> indexes() const { return _indexes; } private: std::vector<IndexInfo> _indexes; }; class AddEditIndexRequest : public Event { R_EVENT AddEditIndexRequest(QObject *sender, const IndexInfo &oldInfo, const IndexInfo &newInfo) : Robomongo::Event(sender), oldInfo_(oldInfo), newInfo_(newInfo) {} const IndexInfo &oldInfo() const { return oldInfo_; } const IndexInfo &newInfo() const { return newInfo_; } private: const IndexInfo oldInfo_; const IndexInfo newInfo_; }; struct AddEditIndexResponse : public Event { R_EVENT AddEditIndexResponse(QObject *sender, const IndexInfo &oldIndex, const IndexInfo &newIndex) : Event(sender), oldIndex_(oldIndex), newIndex_(newIndex) {} AddEditIndexResponse(QObject *sender, const EventError &error, const IndexInfo &oldIndex, const IndexInfo &newIndex) : Event(sender, error), oldIndex_(oldIndex), newIndex_(newIndex) {} const IndexInfo oldIndex_; const IndexInfo newIndex_; }; class DropCollectionIndexRequest : public Event { R_EVENT public: DropCollectionIndexRequest(QObject *sender, const MongoCollectionInfo &collection, const std::string &index) : Event(sender), _collection(collection), _index(index) {} MongoCollectionInfo collection() const { return _collection; } std::string index() const { return _index; } private: const MongoCollectionInfo _collection; std::string _index; // todo: rename to index }; class DropCollectionIndexResponse: public Event { R_EVENT public: DropCollectionIndexResponse(QObject *sender, const MongoCollectionInfo &collection, const std::string &index) : Event(sender), _collection(collection), _index(index) {} DropCollectionIndexResponse(QObject *sender, const EventError &error, const std::string &index) : Event(sender, error), _index(index) {} MongoCollectionInfo collection() const { return _collection; } std::string index() const { return _index; } private: MongoCollectionInfo _collection; std::string _index; }; /** * @brief Load Users */ class LoadUsersRequest : public Event { R_EVENT public: LoadUsersRequest(QObject *sender, const std::string &databaseName) : Event(sender), _databaseName(databaseName) {} std::string databaseName() const { return _databaseName; } private: std::string _databaseName; }; class LoadUsersResponse : public Event { R_EVENT public: LoadUsersResponse(QObject *sender, const std::string &databaseName, const std::vector<MongoUser> &users) : Event(sender), _databaseName(databaseName), _users(users) { } LoadUsersResponse(QObject *sender, const EventError &error) : Event(sender, error) {} std::string databaseName() const { return _databaseName; } std::vector<MongoUser> users() const { return _users; } private: std::string _databaseName; std::vector<MongoUser> _users; }; /** * @brief Load Functions */ class LoadFunctionsRequest : public Event { R_EVENT public: LoadFunctionsRequest(QObject *sender, const std::string &databaseName) : Event(sender), _databaseName(databaseName) {} std::string databaseName() const { return _databaseName; } private: std::string _databaseName; }; class LoadFunctionsResponse : public Event { R_EVENT public: LoadFunctionsResponse(QObject *sender, const std::string &databaseName, const std::vector<MongoFunction> &functions) : Event(sender), _databaseName(databaseName), _functions(functions) { } LoadFunctionsResponse(QObject *sender, const EventError &error) : Event(sender, error) {} std::string databaseName() const { return _databaseName; } std::vector<MongoFunction> functions() const { return _functions; } private: std::string _databaseName; std::vector<MongoFunction> _functions; }; /** * @brief InsertDocument */ class InsertDocumentRequest : public Event { R_EVENT public: InsertDocumentRequest(QObject *sender, const mongo::BSONObj &obj, const MongoNamespace &ns, bool overwrite = false) : Event(sender), _obj(obj), _ns(ns), _overwrite(overwrite) {} mongo::BSONObj obj() const { return _obj; } MongoNamespace ns() const { return _ns; } bool overwrite() const { return _overwrite; } private: mongo::BSONObj _obj; const MongoNamespace _ns; bool _overwrite; }; class InsertDocumentResponse : public Event { R_EVENT public: InsertDocumentResponse(QObject *sender) : Event(sender) {} InsertDocumentResponse(QObject *sender, EventError const& error) : Event(sender, error) {} }; /** * @brief Remove Document */ enum class RemoveDocumentCount { ONE, MULTI, ALL }; class RemoveDocumentRequest : public Event { R_EVENT public: RemoveDocumentRequest(QObject *sender, mongo::Query query, const MongoNamespace &ns, RemoveDocumentCount removeCount, int index) : Event(sender), _query(query), _ns(ns), _removeCount(removeCount), _index(index) {} mongo::Query query() const { return _query; } MongoNamespace ns() const { return _ns; } RemoveDocumentCount removeCount() const { return _removeCount; } int index() const { return _index; } private: mongo::Query const _query; MongoNamespace const _ns; RemoveDocumentCount const _removeCount; // if this is a multi remove, this is the index of current document deleted. 0 for first document. int const _index; }; struct RemoveDocumentResponse : public Event { R_EVENT RemoveDocumentResponse(QObject *sender, RemoveDocumentCount removeCount, int index) : Event(sender), removeCount(removeCount), index(index) {} RemoveDocumentResponse(QObject *sender, const EventError &error, RemoveDocumentCount removeCount, int index) : Event(sender, error), removeCount(removeCount), index(index) {} RemoveDocumentCount const removeCount; int const index; }; /** * @brief Create Database */ class CreateDatabaseRequest : public Event { R_EVENT public: CreateDatabaseRequest(QObject *sender, const std::string &database) : Event(sender), _database(database) {} std::string database() const { return _database; } private: std::string const _database; }; struct CreateDatabaseResponse : public Event { R_EVENT CreateDatabaseResponse(QObject *sender, const std::string &database) : Event(sender), database(database) {} CreateDatabaseResponse(QObject *sender, const std::string &database, const EventError &error) : Event(sender, error), database(database) {} std::string const database; }; /** * @brief Drop Database */ struct DropDatabaseRequest : public Event { R_EVENT DropDatabaseRequest(QObject *sender, const std::string &database) : Event(sender), database(database) {} std::string const database; }; struct DropDatabaseResponse : public Event { R_EVENT public: DropDatabaseResponse(QObject *sender, const std::string &database) : Event(sender), database(database) {} DropDatabaseResponse(QObject *sender, const std::string &database, const EventError &error) : Event(sender, error), database(database) {} std::string const database; }; /** * @brief Create Collection */ class CreateCollectionRequest : public Event { R_EVENT public: CreateCollectionRequest(QObject *sender, const MongoNamespace &ns, const mongo::BSONObj& extraOptions, long long size = 0, bool capped = false, int maxDocNum = 0 ) : Event(sender), _ns(ns), _extraOptions(extraOptions), _size(size), _capped(capped), _maxDocNum(maxDocNum) {} MongoNamespace ns() const { return _ns; } long long getSize() const { return _size; } bool getCapped() const { return _capped; } int getMaxDocNum() const { return _maxDocNum; } const mongo::BSONObj getExtraOptions() const { return _extraOptions; } private: MongoNamespace const _ns; long long const _size; bool const _capped; int const _maxDocNum; mongo::BSONObj const _extraOptions; }; struct CreateCollectionResponse : public Event { R_EVENT CreateCollectionResponse(QObject *sender, std::string const& collection) : Event(sender), collection(collection) {} CreateCollectionResponse(QObject *sender, std::string const& collection, const EventError &error) : Event(sender, error), collection(collection) {} std::string const collection; }; /** * @brief Drop Collection */ class DropCollectionRequest : public Event { R_EVENT public: DropCollectionRequest(QObject *sender, const MongoNamespace &ns) : Event(sender), _ns(ns) {} MongoNamespace ns() const { return _ns; } private: MongoNamespace _ns; }; struct DropCollectionResponse : public Event { R_EVENT public: DropCollectionResponse(QObject *sender, std::string const& collection) : Event(sender), collection(collection) {} DropCollectionResponse(QObject *sender, std::string const& collection, const EventError &error) : Event(sender, error), collection(collection) {} std::string const collection; }; /** * @brief Rename Collection */ class RenameCollectionRequest : public Event { R_EVENT public: RenameCollectionRequest(QObject *sender, const MongoNamespace &ns, const std::string &newCollection) : Event(sender), _ns(ns), _newCollection(newCollection) {} MongoNamespace ns() const { return _ns; } std::string newCollection() const { return _newCollection; } private: MongoNamespace const _ns; std::string const _newCollection; }; struct RenameCollectionResponse : public Event { R_EVENT RenameCollectionResponse(QObject *sender, std::string const& oldCollection, std::string const& newCollection) : Event(sender), oldCollection(oldCollection), newCollection(newCollection) {} RenameCollectionResponse(QObject *sender, const EventError &error) : Event(sender, error) {} std::string const oldCollection; std::string const newCollection; }; /** * @brief Clone Collection */ class DuplicateCollectionRequest : public Event { R_EVENT public: DuplicateCollectionRequest(QObject *sender, const MongoNamespace &ns, const std::string &newCollection) : Event(sender), _ns(ns), _newCollection(newCollection) {} MongoNamespace ns() const { return _ns; } std::string newCollection() const { return _newCollection; } private: MongoNamespace const _ns; std::string const _newCollection; }; struct DuplicateCollectionResponse : public Event { R_EVENT public: DuplicateCollectionResponse(QObject *sender, std::string const& sourceCollection, std::string const& duplicateCollection) : Event(sender), sourceCollection(sourceCollection), duplicateCollection(duplicateCollection) {} DuplicateCollectionResponse(QObject *sender, std::string const& sourceCollection, const EventError &error) : Event(sender, error), sourceCollection(sourceCollection) {} std::string const sourceCollection; std::string const duplicateCollection; }; /** * @brief Copy collection to diffrent server */ class CopyCollectionToDiffServerRequest : public Event { R_EVENT public: CopyCollectionToDiffServerRequest(QObject *sender, MongoWorker *worker, const std::string &databaseFrom, const std::string &collection, const std::string &databaseTo) : Event(sender), _worker(worker), _from(databaseFrom, collection), _to(databaseTo, collection) {} MongoWorker *worker() const { return _worker; } MongoNamespace from() const { return _from; } MongoNamespace to() const { return _to; } private: MongoWorker *_worker; const MongoNamespace _from; const MongoNamespace _to; }; class CopyCollectionToDiffServerResponse : public Event { R_EVENT public: CopyCollectionToDiffServerResponse(QObject *sender) : Event(sender) {} CopyCollectionToDiffServerResponse(QObject *sender, const EventError &error) : Event(sender, error) {} }; /** * @brief Create User */ class CreateUserRequest : public Event { R_EVENT public: CreateUserRequest(QObject *sender, const std::string &database, const MongoUser &user) : Event(sender), _database(database), _user(user) {} std::string database() const { return _database; } MongoUser user() const { return _user; } private: std::string _database; MongoUser _user; }; struct CreateUserResponse : public Event { R_EVENT CreateUserResponse(QObject *sender, std::string const& userName) : Event(sender), userName(userName) {} CreateUserResponse(QObject *sender, std::string const& userName, const EventError &error) : Event(sender, error), userName(userName) {} std::string const userName; }; /** * @brief Drop User */ class DropUserRequest : public Event { R_EVENT public: DropUserRequest(QObject *sender, const std::string &database, std::string const& username) : Event(sender), _database(database), _username(username) {} std::string database() const { return _database; } std::string username() const { return _username; } private: std::string _database; std::string const _username; }; struct DropUserResponse : public Event { R_EVENT DropUserResponse(QObject *sender, std::string const& username) : Event(sender), username(username) {} DropUserResponse(QObject *sender, std::string const& username, const EventError &error) : Event(sender, error), username(username) {} std::string const username; }; /** * @brief Create Function */ class CreateFunctionRequest : public Event { R_EVENT public: CreateFunctionRequest(QObject *sender, const std::string &database, float dbVersion, const MongoFunction &function, const std::string &existingFunctionName = std::string(), bool overwrite = false) : Event(sender), _database(database), _dbVersion(dbVersion), _existingFunctionName(existingFunctionName), _function(function), _overwrite(overwrite) {} std::string database() const { return _database; } float dbVersion() const { return _dbVersion; } std::string existingFunctionName() const { return _existingFunctionName; } MongoFunction function() const { return _function; } bool overwrite() const { return _overwrite; } private: std::string _database; float const _dbVersion = 0.0f; std::string _existingFunctionName; MongoFunction _function; bool _overwrite; }; struct CreateFunctionResponse : public Event { R_EVENT enum Operation { NewFunction, NameUpdate, CodeUpdate }; // todo CreateFunctionResponse(QObject *sender, std::string const& functionName) : Event(sender), functionName(functionName) {} CreateFunctionResponse(QObject *sender, std::string const& functionName, const EventError &error) : Event(sender, error), functionName(functionName) {} std::string const functionName; }; /** * @brief Drop Function */ class DropFunctionRequest : public Event { R_EVENT public: DropFunctionRequest(QObject *sender, const std::string &database, float dbVersion, const std::string &funcName) : Event(sender), _database(database), _dbVersion(dbVersion), _functionName(funcName) {} std::string database() const { return _database; } float dbVersion() const { return _dbVersion; } std::string functionName() const { return _functionName; } private: std::string _database; float const _dbVersion = 0.0f; std::string _functionName; }; struct DropFunctionResponse : public Event { R_EVENT DropFunctionResponse(QObject *sender, const std::string &functionName) : Event(sender), functionName(functionName) {} DropFunctionResponse(QObject *sender, const std::string &functionName, const EventError &error) : Event(sender, error), functionName(functionName) {} std::string const functionName; }; /** * @brief Query Mongodb */ class ExecuteQueryRequest : public Event { R_EVENT public: ExecuteQueryRequest(QObject *sender, int resultIndex, const MongoQueryInfo &queryInfo) : Event(sender), _resultIndex(resultIndex), _queryInfo(queryInfo) {} int resultIndex() const { return _resultIndex; } MongoQueryInfo queryInfo() const { return _queryInfo; } private: int _resultIndex; //external user data; MongoQueryInfo _queryInfo; }; class ExecuteQueryResponse : public Event { R_EVENT ExecuteQueryResponse(QObject *sender, int resultIndex, const MongoQueryInfo &queryInfo, const std::vector<MongoDocumentPtr> &documents) : Event(sender), resultIndex(resultIndex), queryInfo(queryInfo), documents(documents) { } ExecuteQueryResponse(QObject *sender, const EventError &error) : Event(sender, error) {} int resultIndex; MongoQueryInfo queryInfo; std::vector<MongoDocumentPtr> documents; }; class AutocompleteRequest : public Event { R_EVENT AutocompleteRequest(QObject *sender, const std::string &prefix, const AutocompletionMode mode) : Event(sender), prefix(prefix), mode(mode) {} std::string prefix; AutocompletionMode mode; }; class AutocompleteResponse : public Event { R_EVENT AutocompleteResponse(QObject *sender, const QStringList &list, const std::string &prefix) : Event(sender), list(list), prefix(prefix) {} AutocompleteResponse(QObject *sender, const EventError &error) : Event(sender, error) {} QStringList list; std::string prefix; }; /** * @brief ExecuteScript */ class ExecuteScriptRequest : public Event { R_EVENT ExecuteScriptRequest(QObject *sender, const std::string &script, const std::string &dbName, AggrInfo aggrInfo = AggrInfo(), int take = 0, int skip = 0) : Event(sender), script(script), databaseName(dbName), aggrInfo(aggrInfo), take(take), skip(skip) {} std::string script; std::string databaseName; int take; // int skip; AggrInfo const aggrInfo; }; class ExecuteScriptResponse : public Event { R_EVENT ExecuteScriptResponse(QObject *sender, const MongoShellExecResult &result, bool empty, bool timeoutReached = false) : Event(sender), result(result), empty(empty), _timeoutReached(timeoutReached) {} ExecuteScriptResponse(QObject *sender, const EventError &error, bool timeoutReached = false) : Event(sender, error), _timeoutReached(timeoutReached) {} bool timeoutReached() const { return _timeoutReached; } MongoShellExecResult result; bool empty; bool const _timeoutReached = false; }; class ConnectingEvent : public Event { R_EVENT ConnectingEvent(QObject *sender) : Event(sender) { } }; class OpeningShellEvent : public Event { R_EVENT OpeningShellEvent(QObject *sender, MongoShell *shell) : Event(sender), shell(shell) {} MongoShell *shell; }; class ConnectionFailedEvent : public Event { R_EVENT enum Reason { MongoConnection = 1, MongoAuth = 2, SshConnection = 3, SshChannel = 4, SslConnection = 5 }; ConnectionFailedEvent(QObject *sender, int serverHandle, ConnectionType connectionType, const std::string& message, Reason reason) : Event(sender), message(message), reason(reason), serverHandle(serverHandle), connectionType(connectionType) {} std::string message; Reason reason; ConnectionType connectionType; int serverHandle; }; // class ScriptExecute struct ConnectionEstablishedEvent : public Event { R_EVENT ConnectionEstablishedEvent(MongoServer *server, ConnectionType type, ConnectionInfo connInfo) : Event((QObject *)server), server(server), connectionType(type), connInfo(connInfo) { } MongoServer *server; ConnectionType const connectionType; ConnectionInfo const connInfo; }; class DatabaseListLoadedEvent : public Event { R_EVENT DatabaseListLoadedEvent(QObject *sender, const QList<MongoDatabase *> &list) : Event(sender), list(list) { } DatabaseListLoadedEvent(QObject *sender, const EventError &error) : Event(sender, error) {} QList<MongoDatabase *> list; }; class DocumentListLoadedEvent : public Event { R_EVENT public: DocumentListLoadedEvent(QObject *sender, int resultIndex, const MongoQueryInfo &queryInfo, const std::string &query, const std::vector<MongoDocumentPtr> &docs) : Event(sender), _resultIndex(resultIndex), _queryInfo(queryInfo), _query(query), _documents(docs) { } DocumentListLoadedEvent(QObject *sender, const EventError &error) : Event(sender, error) {} int resultIndex() const { return _resultIndex; } MongoQueryInfo queryInfo() const { return _queryInfo; } std::vector<MongoDocumentPtr> documents() const { return _documents; } std::string query() const { return _query; } private: int _resultIndex; MongoQueryInfo _queryInfo; std::vector<MongoDocumentPtr> _documents; std::string _query; }; class ScriptExecutedEvent : public Event { R_EVENT public: ScriptExecutedEvent(QObject *sender, const MongoShellExecResult &result, bool empty, bool timeoutReached = false) : Event(sender), _result(result), _empty(empty), _timeoutReached(timeoutReached) {} ScriptExecutedEvent(QObject *sender, const EventError &error, bool timeoutReached = false) : Event(sender, error), _timeoutReached(timeoutReached) {} MongoShellExecResult result() const { return _result; } bool empty() const { return _empty; } bool timeoutReached() const { return _timeoutReached; } private: MongoShellExecResult _result; bool _empty; bool const _timeoutReached = false; }; class ScriptExecutingEvent : public Event { R_EVENT public: ScriptExecutingEvent(QObject *sender) : Event(sender) { } }; class OperationFailedEvent : public Event { R_EVENT public: OperationFailedEvent(QObject *sender, const std::string &technicalErrorMessage, const std::string &userFriendlyErrorMessage) : technicalErrorMessage(technicalErrorMessage), userFriendlyErrorMessage(userFriendlyErrorMessage), Event(sender) { } std::string technicalErrorMessage; std::string userFriendlyErrorMessage; }; class QueryWidgetUpdatedEvent : public Event { R_EVENT public: QueryWidgetUpdatedEvent(QObject *sender, int numOfResults) : Event(sender), _numOfResults(numOfResults) { } int numOfResults() const { return _numOfResults; } private: int _numOfResults; }; /** * @brief Establish SSH Connection */ class EstablishSshConnectionRequest : public Event { R_EVENT EstablishSshConnectionRequest(QObject *sender, int serverHandle, SshTunnelWorker* worker, ConnectionSettings* settings, ConnectionType connectionType) : Event(sender), worker(worker), settings(settings), serverHandle(serverHandle), connectionType(connectionType) {} ConnectionSettings* settings; ConnectionType connectionType; SshTunnelWorker* worker; int serverHandle; }; class EstablishSshConnectionResponse : public Event { R_EVENT EstablishSshConnectionResponse(QObject *sender, int serverHandle, SshTunnelWorker* worker, ConnectionSettings* settings, ConnectionType connectionType, int localport) : Event(sender), worker(worker), settings(settings), connectionType(connectionType), serverHandle(serverHandle), localport(localport) {} EstablishSshConnectionResponse(QObject *sender, int serverHandle, const EventError &error, SshTunnelWorker* worker, ConnectionSettings* settings, ConnectionType connectionType) : Event(sender, error), worker(worker), settings(settings), serverHandle(serverHandle), connectionType(connectionType) {} ConnectionSettings* settings; ConnectionType connectionType; SshTunnelWorker* worker; int localport; int serverHandle; }; /** * @brief Start listening on all opened sockets (SSH tunnel) */ class ListenSshConnectionRequest : public Event { R_EVENT ListenSshConnectionRequest(QObject *sender, int serverHandle, ConnectionType connectionType) : Event(sender), serverHandle(serverHandle), connectionType(connectionType) {} ConnectionType connectionType; int serverHandle; }; class ListenSshConnectionResponse : public Event { R_EVENT ListenSshConnectionResponse(QObject *sender, int serverHandle, ConnectionSettings* settings, ConnectionType connectionType) : Event(sender), settings(settings), serverHandle(serverHandle), connectionType(connectionType) {} ListenSshConnectionResponse(QObject *sender, const EventError &error, int serverHandle, ConnectionSettings* settings, ConnectionType connectionType) : Event(sender, error), settings(settings), serverHandle(serverHandle), connectionType(connectionType) {} ConnectionSettings* settings; ConnectionType connectionType; int serverHandle; }; class LogEvent : public Event { R_EVENT enum LogLevel { RBM_ERROR = 1, RBM_WARN = 2, RBM_INFO = 3, RBM_DEBUG = 100 // log as much as possible }; LogEvent(QObject *sender, const std::string& message, LogLevel level, bool const informUser = false) : Event(sender), message(message), level(level), informUser(informUser) {} std::string severity() const { switch (level) { case RBM_ERROR : return "Error"; case RBM_WARN : return "Warning"; case RBM_INFO : return "Info"; case RBM_DEBUG : return "Debug"; default: return "Undefined"; } } QMessageBox::Icon qMessageBoxIcon() const { switch (level) { case RBM_ERROR: return QMessageBox::Icon::Critical; case RBM_WARN: return QMessageBox::Icon::Warning; case RBM_INFO: return QMessageBox::Icon::Information; case RBM_DEBUG: return QMessageBox::Icon::Information; default: return QMessageBox::Icon::Information; } } mongo::logger::LogSeverity mongoLogSeverity() const { switch (level) { case RBM_ERROR: return mongo::logger::LogSeverity::Error(); case RBM_WARN: return mongo::logger::LogSeverity::Warning(); case RBM_INFO: return mongo::logger::LogSeverity::Info(); case RBM_DEBUG: return mongo::logger::LogSeverity::Log(); default: return mongo::logger::LogSeverity::Info(); } } std::string message; LogLevel level; bool const informUser = false; }; class StopScriptRequest : public Event { R_EVENT StopScriptRequest(QObject *sender) : Event(sender) {} }; }
38,544
C++
.h
1,016
28.376969
186
0.622867
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,134
MongoEventsInfo.h
Studio3T_robomongo/src/robomongo/core/events/MongoEventsInfo.h
#pragma once #include <string> #include "robomongo/core/domain/MongoCollectionInfo.h" namespace Robomongo { struct IndexInfo { IndexInfo( const MongoCollectionInfo &collection, const std::string &name = std::string(), const std::string &request = std::string(), bool isUnique = false, bool isBackGround = false, bool isSparce = false, int expireAfter = -1, const std::string &defaultLanguage = std::string(), const std::string &languageOverride = std::string(), const std::string &textWeights = std::string()); MongoCollectionInfo _collection; std::string _name; std::string _keys; bool _unique; bool _backGround; bool _sparse; int _ttl; std::string _defaultLanguage; std::string _languageOverride; std::string _textWeights; }; struct ConnectionInfo { ConnectionInfo(std::string const& uuid); ConnectionInfo(const std::string &address, const std::vector<std::string> &databases, float version, const std::string& dbVersionStr, const std::string& storageEngine, std::string const& uuid); const std::string _address; const std::vector<std::string> _databases; const float _version; const std::string _dbVersionStr; const std::string _storageEngineType; std::string const _uuid; }; }
1,528
C++
.h
43
26.465116
109
0.603239
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,135
Notifier.h
Studio3T_robomongo/src/robomongo/core/domain/Notifier.h
#pragma once #include <QModelIndex> #include "robomongo/core/domain/MongoQueryInfo.h" QT_BEGIN_NAMESPACE class QAction; class QMenu; QT_END_NAMESPACE namespace Robomongo { class MainWindow; class MongoShell; class BsonTreeItem; class InsertDocumentResponse; struct RemoveDocumentResponse; namespace detail { bool isSimpleType(BsonTreeItem const *item); bool isObjectIdType(BsonTreeItem *item); bool isMultiSelection(const QModelIndexList &indexes); bool isDocumentType(BsonTreeItem const *item); QModelIndexList uniqueRows(QModelIndexList indexes, bool returnSuperParents = false); } class INotifierObserver { public: virtual QModelIndex selectedIndex() const = 0; virtual QModelIndexList selectedIndexes() const = 0; protected: INotifierObserver() {} }; class Notifier : public QObject { Q_OBJECT public: typedef QObject BaseClass; Notifier(INotifierObserver *const observer, MongoShell *shell, const MongoQueryInfo &queryInfo, QObject *parent = NULL); void initMenu(QMenu *const menu, BsonTreeItem *const item); void initMultiSelectionMenu(QMenu *const menu); void deleteDocuments(std::vector<BsonTreeItem*> const& items, bool force); void handleDeleteCommand(); public Q_SLOTS: void onDeleteDocument(); void onDeleteDocuments(); void onEditDocument(); void onViewDocument(); void onInsertDocument(); void onCopyDocument(); void onCopyTimestamp(); void onCopyJson(); void handle(InsertDocumentResponse *event); void handle(RemoveDocumentResponse *event); private Q_SLOTS: void onCopyNameDocument(); void onCopyPathDocument(); private: MainWindow* mainWindow() const; QAction *_deleteDocumentAction; QAction *_deleteDocumentsAction; QAction *_editDocumentAction; QAction *_viewDocumentAction; QAction *_insertDocumentAction; QAction *_copyValueAction; QAction *_copyValueNameAction; QAction *_copyValuePathAction; QAction *_copyTimestampAction; QAction *_copyJsonAction; const MongoQueryInfo _queryInfo; MongoShell *_shell; INotifierObserver *const _observer; }; }
2,389
C++
.h
71
26.690141
128
0.694312
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,136
MongoDatabase.h
Studio3T_robomongo/src/robomongo/core/domain/MongoDatabase.h
#pragma once #include <QObject> #include <mongo/bson/bsonobj.h> #include "robomongo/core/Core.h" #include "robomongo/core/events/MongoEvents.h" namespace Robomongo { class EventBus; /** * @brief Represents MongoDB database. */ class MongoDatabase : public QObject { Q_OBJECT public: /** * @brief Database storage engine type */ struct StorageEngineType { static const std::string WIRED_TIGER; static const std::string MMAPV1; }; /** * @brief MongoDB version */ struct DBVersion { static const float MONGODB_2_6; static const float MONGODB_3_0; static const float MONGODB_3_2; }; /** * @brief MongoDatabase * @param server: pointer to parent MongoServer */ MongoDatabase(MongoServer *server, const std::string &name); ~MongoDatabase(); /** * @brief Initiate listCollection asynchronous operation. */ void loadCollections(); /** * @brief Initiate loadUsers asynchronous operation. */ void loadUsers(); void loadFunctions(); void createCollection(const std::string &collection, long long size, bool capped, int maxDocNum, const mongo::BSONObj& extraOptions); void dropCollection(const std::string &collection); void renameCollection(const std::string &collection, const std::string &newCollection); void duplicateCollection(const std::string &collection, const std::string &newCollection); void copyCollection(MongoServer *server, const std::string &sourceDatabase, const std::string &collection); void createUser(const MongoUser &user); void dropUser(std::string const& userName); void createFunction(const MongoFunction &fun); void updateFunction(const std::string &name, const MongoFunction &fun); void dropFunction(const std::string &name); const std::string &name() const { return _name; } /** * @brief Checks that this is a system database. * @return true if system, false otherwise. */ bool isSystem() const { return _system; } MongoServer *server() const { return _server; } protected Q_SLOTS: void handle(LoadCollectionNamesResponse *event); void handle(LoadUsersResponse *event); void handle(LoadFunctionsResponse *event); void handle(CreateFunctionResponse *event); void handle(CreateUserResponse *event); void handle(CreateCollectionResponse *event); void handle(DropCollectionResponse *event); void handle(DropFunctionResponse *event); void handle(DropUserResponse *event); void handle(RenameCollectionResponse *event); void handle(DuplicateCollectionResponse *event); private: void clearCollections(); void addCollection(MongoCollection *collection); void handleIfReplicaSetUnreachable(Event *event); private: MongoServer *_server; std::vector<MongoCollection *> _collections; const std::string _name; const bool _system; EventBus *_bus; }; class MongoDatabaseCollectionListLoadedEvent : public Event { R_EVENT MongoDatabaseCollectionListLoadedEvent(QObject *sender, const std::vector<MongoCollection *> &list) : Event(sender), collections(list) { } MongoDatabaseCollectionListLoadedEvent(QObject *sender, const EventError &error) : Event(sender, error) {} std::vector<MongoCollection *> collections; }; class MongoDatabaseUsersLoadedEvent : public Event { R_EVENT MongoDatabaseUsersLoadedEvent(QObject *sender, MongoDatabase *database, const std::vector<MongoUser> &list) : Event(sender), _users(list), _database(database) {} MongoDatabaseUsersLoadedEvent(QObject *sender, const EventError &error) : Event(sender, error) {} std::vector<MongoUser> users() const { return _users; } MongoDatabase *database() const { return _database; } private: std::vector<MongoUser> _users; MongoDatabase *_database; }; class MongoDatabaseFunctionsLoadedEvent : public Event { R_EVENT MongoDatabaseFunctionsLoadedEvent(QObject *sender, MongoDatabase *database, const std::vector<MongoFunction> &list) : Event(sender), _functions(list), _database(database) {} MongoDatabaseFunctionsLoadedEvent(QObject *sender, const EventError &error) : Event(sender, error) {} std::vector<MongoFunction> functions() const { return _functions; } MongoDatabase *database() const { return _database; } private: std::vector<MongoFunction> _functions; MongoDatabase *_database; }; class MongoDatabaseUsersLoadingEvent : public Event { R_EVENT MongoDatabaseUsersLoadingEvent(QObject *sender) : Event(sender) {} }; class MongoDatabaseFunctionsLoadingEvent : public Event { R_EVENT MongoDatabaseFunctionsLoadingEvent(QObject *sender) : Event(sender) {} }; class MongoDatabaseCollectionsLoadingEvent : public Event { R_EVENT MongoDatabaseCollectionsLoadingEvent(QObject *sender) : Event(sender) {} }; }
5,542
C++
.h
143
30.27972
141
0.653366
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,137
MongoCollectionInfo.h
Studio3T_robomongo/src/robomongo/core/domain/MongoCollectionInfo.h
#pragma once #include <mongo/bson/bsonobj.h> #include "robomongo/core/domain/MongoNamespace.h" namespace Robomongo { class MongoCollectionInfo { public: MongoCollectionInfo() {} MongoCollectionInfo(const std::string &ns); // MongoCollectionInfo(mongo::BSONObj stats); std::string name() const { return _ns.collectionName(); } std::string fullName() const { return _ns.toString(); } MongoNamespace ns() const { return _ns; } /** * @brief Size in bytes * It is double, because db.stats()'s "size" field may be double * for large values, while Int32 for small. */ // double sizeBytes() const { return _sizeBytes; } /** * @brief Storage size in bytes * It is double, because db.stats()'s "storageSize" field may be double * for large values, while Int32 for small. */ // double storageSizeBytes() const { return _storageSizeBytes; } // long long count() const { return _count; } private: MongoNamespace _ns; /** * @brief Size in bytes * It is double, because db.stats()'s "size" field may be double * for large values, while Int32 for small. */ double _sizeBytes; /** * @brief Storage size in bytes * It is double, because db.stats()'s "storageSize" field may be double * for large values, while Int32 for small. */ double _storageSizeBytes; long long _count; }; }
1,567
C++
.h
44
28.295455
79
0.59881
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,138
MongoUser.h
Studio3T_robomongo/src/robomongo/core/domain/MongoUser.h
#pragma once #include <mongo/bson/bsonobj.h> #include <mongo/bson/bsonelement.h> #include "robomongo/core/utils/BsonUtils.h" namespace Robomongo { class MongoUser { public: typedef std::vector<std::string> RolesVector; explicit MongoUser(const float version, const mongo::BSONObj &obj) : _version(version), _readOnly(false), _name(BsonUtils::getField<mongo::String>(obj, "user")) {}; // Creates new user with empty attributes MongoUser(const float version) : _version(version), _readOnly(false), _roles() {} std::string name() const { return _name; } std::string password() const { return _password; } std::vector<std::string> roles() const { return _roles; } void setName(const std::string &name) { _name = name; } void setPassword(const std::string &pwd) { _password = pwd; } void setRoles(const std::vector<std::string> &roles) { _roles = roles; } std::string userSource() const { return _userSource; } void setUserSource(const std::string &source) { _userSource = source; } bool readOnly() const { return _readOnly; } void setReadOnly(bool readonly) { _readOnly = readonly; } float version() const { return _version; } static constexpr float minimumSupportedVersion = 2.4f; private: float _version; std::string _name; bool _readOnly; RolesVector _roles; std::string _password; std::string _userSource; }; }
1,559
C++
.h
38
33.5
80
0.630119
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,139
MongoFunction.h
Studio3T_robomongo/src/robomongo/core/domain/MongoFunction.h
#pragma once #include <mongo/bson/bsonobj.h> namespace Robomongo { class MongoFunction { public: /** * @brief Creates function from "system.js" document */ MongoFunction(const mongo::BSONObj &obj); /** * @brief Creates new function with empty attributes */ MongoFunction() {} std::string name() const { return _name; } std::string code() const { return _code; } void setCode(const std::string &code) { _code = code; } void setName(const std::string &name) { _name = name; } mongo::BSONObj toBson() const; private: std::string _name; std::string _code; }; }
709
C++
.h
25
21.28
63
0.576923
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,140
MongoNamespace.h
Studio3T_robomongo/src/robomongo/core/domain/MongoNamespace.h
#pragma once #include <string> namespace Robomongo { class MongoNamespace { public: MongoNamespace(const std::string &ns); MongoNamespace(const std::string &database, const std::string &collection); MongoNamespace() {} std::string toString() const { return _ns; } std::string databaseName() const { return _databaseName; } std::string collectionName() const { return _collectionName; } bool isValid() const { return !_ns.empty(); } private: std::string _ns; std::string _databaseName; std::string _collectionName; }; }
621
C++
.h
20
24.95
83
0.639399
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,141
MongoQueryInfo.h
Studio3T_robomongo/src/robomongo/core/domain/MongoQueryInfo.h
#pragma once #include <mongo/bson/bsonobj.h> #include "robomongo/core/domain/MongoNamespace.h" namespace Robomongo { namespace detail { std::string prepareServerAddress(const std::string &address); } struct CollectionInfo { CollectionInfo(); CollectionInfo(const std::string &server, const std::string &database, const std::string &collection); bool isValid() const; std::string _serverAddress; MongoNamespace _ns; }; struct MongoQueryInfo { MongoQueryInfo(); MongoQueryInfo(const CollectionInfo &info, mongo::BSONObj query, mongo::BSONObj fields, int limit, int skip, int batchSize, int options, bool special); CollectionInfo _info; mongo::BSONObj _query; mongo::BSONObj _fields; int _limit; int _skip; int _batchSize; int _options; bool _special; // flag, indicating that `query` contains special fields on // first level, and query data in `query` field. }; }
1,101
C++
.h
34
24.382353
110
0.628925
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,142
App.h
Studio3T_robomongo/src/robomongo/core/domain/App.h
#pragma once #include <QObject> #include <vector> #include <robomongo/core/events/MongoEvents.h> #include "robomongo/core/domain/ScriptInfo.h" namespace Robomongo { class EventBus; class MongoServer; class ConnectionSettings; class MongoCollection; class MongoShell; class MongoDatabase; class EstablishSshConnectionResponse; class LogEvent; namespace detail { /** * @brief Builds single collection query (i.e. db.my_col.find()) from * string that doesn't contain "db.my_col." prefix. * * If you'll call buildCollectionQuery("test", "find()") you'll receive: * db.test.find() * * If you'll call buildCollectionQuery("1234", "find()") you'll receive: * db['1234'].find() * * @param script: query part (without "db.my_col." prefix" */ QString buildCollectionQuery(const std::string &collectionName, const QString &postfix); } class App : public QObject { Q_OBJECT public: App(EventBus *const bus); ~App(); /** * @brief Creates and opens new server connection. * @param connection: ConnectionSettings, that will be owned by MongoServer. * @param visible: should this server be visible in UI (explorer) or not. * @return Succeeded or not */ bool openServer(ConnectionSettings *connection, ConnectionType type); /** * @brief Closes MongoServer connection and frees all resources, owned * by specified MongoServer. Finally, specified MongoServer will also be deleted. */ void closeServer(MongoServer *server); /** * @brief Open new shell based on specified collection */ void openShell(MongoCollection *collection, const QString &filePathToSave = QString()); void openShell(MongoServer *server, const QString &script, const std::string &dbName = std::string(), bool execute = true, const QString &shellName = QString(), const CursorPosition &cursorPosition = CursorPosition(), const QString &file = QString()); void openShell(MongoDatabase *database, const QString &script, bool execute = true, const QString &shellName = QString(), const CursorPosition &cursorPosition = CursorPosition(), const QString &filePathToSave = QString()); /** * @brief Open new shell using explorer's MongoServer (ExplorerServerTreeItem's _server) */ void openShell(MongoServer* server, ConnectionSettings* connSettings, const ScriptInfo &scriptInfo); auto const& getServers() const { return _servers; }; /** * @brief Closes MongoShell and frees all resources, owned by specified MongoShell. * Finally, specified MongoShell will also be deleted. */ void closeShell(MongoShell *shell); void fireConnectionFailedEvent(int serverHandle, ConnectionType type, std::string errormsg, ConnectionFailedEvent::Reason reason); int getLastServerHandle() const { return _lastServerHandle; }; public Q_SLOTS: void handle(EstablishSshConnectionResponse *event); void handle(ListenSshConnectionResponse *event); void handle(LogEvent *event); private: std::unique_ptr<MongoServer> openServerInternal(ConnectionSettings* connSettings, ConnectionType type); std::unique_ptr<MongoServer> continueOpenServer(int serverHandle, ConnectionSettings* connSettings, ConnectionType type, int localport = 0); /** * @brief Create prompt dialog to enter SSL PEM key passphrase and save passphrase into SSL settings * @param connection Pointer to active connection settings * @return true on success, false otherwise */ bool askSslPassphrasePromptDialog(ConnectionSettings *connSettings) const; /** * MongoServers, owned by this App. */ std::vector<std::unique_ptr<MongoServer>> _servers; /** * MongoShells, owned by this App. */ std::vector<std::unique_ptr<MongoShell>> _shells; EventBus *const _bus; // Increase monotonically when new MongoServer is created // Never decreases. int _lastServerHandle; }; }
4,470
C++
.h
101
35.168317
119
0.650991
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,143
MongoServer.h
Studio3T_robomongo/src/robomongo/core/domain/MongoServer.h
#pragma once #include <QObject> #include "robomongo/core/settings/ConnectionSettings.h" #include "robomongo/core/events/MongoEvents.h" namespace Robomongo { class MongoWorker; class MongoDatabase; class EventBus; class App; // Messages struct EstablishConnectionResponse; struct RefreshReplicaSetFolderResponse; class LoadDatabaseNamesResponse; class InsertDocumentResponse; struct CreateDatabaseResponse; struct DropDatabaseResponse; /** * @brief MongoServer represents active connection to MongoDB server. * MongoServer is an Aggregate Root, that manages three internal entities: * MongoDatabase, MongoCollection and MongoWorker. */ class MongoServer : public QObject { Q_OBJECT public: /** * @brief MongoServer * @param connectionRecord: MongoServer will own this ConnectionSettings. * @param visible * @param defaultDatabase */ MongoServer(int handle, ConnectionSettings *connectionRecord, ConnectionType connectionType); ~MongoServer(); void runWorkerThread(); /** * @brief Try to connect to MongoDB single server or replica set. * @throws MongoException, if fails */ void tryConnect(); /** * @brief Try to re-connect to MongoDB server in order to refresh connection view. * Never shown in Explorer and can be used to refresh (via reconnecting) current connection view. * (i.e. db version, storage engine etc...) * @throws MongoException, if fails */ void tryRefresh(); /** * @brief Try to re-connect to MongoDB replica set in order to refresh connection view. * It is used to refresh (via reconnecting) current connection view. * (i.e. db version, storage engine, current replica set primary, status of replica set etc...) * It will update Explorer widgets depending on replica set status (online if primary reachable and * offline otherwise) */ void tryRefreshReplicaSetConnection(); /** * @brief Try to re-connect to MongoDB replica set in order to refresh connection view. * It is used to refresh (via reconnecting) current connection view. * (i.e. db version, storage engine, current replica set primary, status of replica set etc...) * It will update only 'Replica Set' folder widgets depending on replica set status * (online if primary reachable and offline otherwise) */ void tryRefreshReplicaSetFolder(bool expanded, bool showLoading = true); bool isConnected() const; void addDatabase(MongoDatabase *database); void createDatabase(const std::string &dbName); void dropDatabase(const std::string &dbName); QStringList getDatabasesNames() const; QList<MongoDatabase*> const& databases() const { return _databases; }; MongoDatabase *findDatabaseByName(const std::string &dbName) const; void insertDocuments(const std::vector<mongo::BSONObj> &objCont, const MongoNamespace &ns); void insertDocument(const mongo::BSONObj &obj, const MongoNamespace &ns); void saveDocuments(const std::vector<mongo::BSONObj> &objCont, const MongoNamespace &ns); void saveDocument(const mongo::BSONObj &obj, const MongoNamespace &ns); void removeDocuments(mongo::Query query, const MongoNamespace &ns, RemoveDocumentCount removeCount, int index = 0); float version() const{ return _version; } const std::string& getStorageEngineType() const { return _storageEngineType; } /** * @brief Returns associated connection record */ ConnectionSettings *connectionRecord() const; /** * @brief Loads databases of this server asynchronously. */ void loadDatabases(); MongoWorker *const worker() const { return _worker; } ReplicaSet* replicaSetInfo() const { return _replicaSetInfo.get(); } void handle(ReplicaSetRefreshed *event); void changeWorkerShellTimeout(int newTimeout); protected Q_SLOTS: void handle(EstablishConnectionResponse *event); void handle(RefreshReplicaSetFolderResponse *event); void handle(LoadDatabaseNamesResponse *event); void handle(InsertDocumentResponse *event); void handle(RemoveDocumentResponse *event); void handle(CreateDatabaseResponse *event); void handle(DropDatabaseResponse *event); private: void clearDatabases(); void handleReplicaSetRefreshEvents(bool isError, EventError eventError, ReplicaSet const& replicaSet, bool expanded); void updateReplicaSetSettings(EstablishConnectionResponse* event); void handleConnectionFailure(EstablishConnectionResponse* event); void hideProgressBar() const; MongoWorker *_worker; std::unique_ptr<ConnectionSettings> _connSettings; EventBus *_bus; App *_app; float _version; std::string _storageEngineType; ConnectionType _connectionType; bool _isConnected; int _handle; QList<MongoDatabase *> _databases; std::unique_ptr<ReplicaSet> _replicaSetInfo; }; class MongoServerLoadingDatabasesEvent : public Event { R_EVENT MongoServerLoadingDatabasesEvent(QObject *sender) : Event(sender) {} }; }
5,659
C++
.h
123
37.341463
113
0.669993
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,144
ScriptInfo.h
Studio3T_robomongo/src/robomongo/core/domain/ScriptInfo.h
#pragma once #include <QString> #include "robomongo/core/domain/CursorPosition.h" namespace Robomongo { class ScriptInfo { public: ScriptInfo(const QString &script, bool execute = false, const std::string &dbname = "", const CursorPosition &position = CursorPosition(), const QString &title = QString(), const QString &filePath = QString()); bool execute() const { return _execute; } void setExecutable(bool execute) { _execute = execute; } QString script() const { return _script; } std::string dbname() const { return _dbname; } const QString &title() const { return _title; } const CursorPosition &cursor() const { return _cursor; } void setScript(const QString &script) { _script = script; } QString filePath() const { return _filePath; } bool loadFromFile(const QString &filePath); bool loadFromFile(); bool saveToFileAs(); bool saveToFile(); private: QString _script; std::string _dbname; bool _execute; const QString _title; const CursorPosition _cursor; QString _filePath; }; }
1,202
C++
.h
32
29.8125
96
0.626609
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,145
MongoDocument.h
Studio3T_robomongo/src/robomongo/core/domain/MongoDocument.h
#pragma once #include <QStringList> #include <mongo/bson/bsonobj.h> #include "robomongo/core/Core.h" namespace Robomongo { /* ** Represents MongoDB object. */ class MongoDocument { /* ** Owned BSONObj */ const mongo::BSONObj _bsonObj; public: /* ** Constructs empty Document, i.e. { } */ MongoDocument(); ~MongoDocument(); /* ** Create MongoDocument from BsonObj. It will take owned version of BSONObj */ MongoDocument(mongo::BSONObj bsonObj); /* ** Create MongoDocument from BsonObj. It will take owned version of BSONObj */ static MongoDocumentPtr fromBsonObj(const mongo::BSONObj &bsonObj); /* ** Create list of MongoDocuments from QList<BsonObj>. It will take owned version of BSONObj */ static std::vector<MongoDocumentPtr> fromBsonObj(const std::vector<mongo::BSONObj> &bsonObj); /* ** Return "native" BSONObj */ mongo::BSONObj bsonObj() const { return _bsonObj; } }; }
1,113
C++
.h
39
21.461538
101
0.603561
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,146
CursorPosition.h
Studio3T_robomongo/src/robomongo/core/domain/CursorPosition.h
#pragma once namespace Robomongo { class CursorPosition { public: CursorPosition(); CursorPosition(int line, int column); bool isNull() const { return _isNull; } int line() const { return _line; } int column() const { return _column; } private: const bool _isNull; const int _line; const int _column; }; }
393
C++
.h
17
17
47
0.589812
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,147
MongoUtils.h
Studio3T_robomongo/src/robomongo/core/domain/MongoUtils.h
#pragma once #include <QString> namespace Robomongo { namespace MongoUtils { QString buildNiceSizeString(double sizeBytes); std::string buildPasswordHash(const std::string &username, const std::string &password); } }
247
C++
.h
10
20.7
96
0.731915
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,148
MongoAggregateInfo.h
Studio3T_robomongo/src/robomongo/core/domain/MongoAggregateInfo.h
#pragma once namespace Robomongo { struct AggrInfo { AggrInfo() {} AggrInfo(const std::string& collectionName, int skip, int batchSize, mongo::BSONObj const& pipeline, mongo::BSONObj const& options, int resultIndex) : collectionName(collectionName), skip(skip), batchSize(batchSize), pipeline(pipeline), options(options), isValid(true), resultIndex(resultIndex) {} std::string collectionName = ""; int skip = 0; int batchSize = 0; mongo::BSONObj pipeline; mongo::BSONObj options; bool isValid = false; int resultIndex = -1; }; }
670
C++
.h
20
25.45
98
0.616692
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,149
MongoShellResult.h
Studio3T_robomongo/src/robomongo/core/domain/MongoShellResult.h
#pragma once #include "robomongo/core/domain/MongoQueryInfo.h" #include "robomongo/core/domain/MongoAggregateInfo.h" #include "robomongo/core/domain/MongoDocument.h" namespace Robomongo { /* -------------- MongoShellResult Class --------- */ class MongoShellResult { public: MongoShellResult( const std::string &type, const std::string &response, const std::vector<MongoDocumentPtr> &documents, const MongoQueryInfo &queryInfo, const std::string &statement, qint64 elapsedms, AggrInfo aggrInfo = AggrInfo()) : _type(type), _response(response), _documents(documents), _queryInfo(queryInfo), _statement(statement), _elapsedms(elapsedms), _aggrInfo(aggrInfo) { } std::string response() const { return _response; } std::string type() const { return _type; } std::vector<MongoDocumentPtr> documents() const { return _documents; } MongoQueryInfo queryInfo() const { return _queryInfo; } std::string statement() const { return _statement; } std::string statementShort() const { std::size_t const LEN = _statement.size() < 10 ? _statement.size() : 10; std::string statementShort { _statement, 0, LEN }; statementShort.append((_statement.size() > 10) ? ".." : ""); return statementShort; } qint64 elapsedMs() const { return _elapsedms; } AggrInfo const& aggrInfo() const { return _aggrInfo; } private: std::string _type; std::string _response; std::vector<MongoDocumentPtr> _documents; MongoQueryInfo _queryInfo; std::string const _statement; qint64 _elapsedms; AggrInfo _aggrInfo = AggrInfo(); }; /* -------------- MongoShellExecResult Class --------- */ class MongoShellExecResult { public: MongoShellExecResult() { } MongoShellExecResult( const std::vector<MongoShellResult> &results, const std::string &currentServer, bool isCurrentServerValid, const std::string &currentDatabase, bool isCurrentDatabaseValid, bool timeoutReached = false) : _results(results), _currentServer(currentServer), _currentDatabase(currentDatabase), _isCurrentServerValid(isCurrentServerValid), _isCurrentDatabaseValid(isCurrentDatabaseValid), _timeoutReached(timeoutReached) { } MongoShellExecResult(bool error, std::string const& errorMsg = "", bool timeoutReached = false) : _error(error), _errorMessage(errorMsg), _timeoutReached(timeoutReached) { } std::vector<MongoShellResult> const& results() const { return _results; } std::string currentServer() const { return _currentServer; } void setCurrentServer(std::string const& server) { _currentServer = server; } std::string currentDatabase() const { return _currentDatabase; } bool isCurrentServerValid() const { return _isCurrentServerValid; } bool isCurrentDatabaseValid() const { return _isCurrentDatabaseValid; } std::string errorMessage() const { return _errorMessage; } bool error() const { return _error; } bool timeoutReached() const { return _timeoutReached; } private: std::vector<MongoShellResult> _results; std::string _currentServer; std::string _currentDatabase; bool _isCurrentServerValid; bool _isCurrentDatabaseValid; std::string _errorMessage; bool _error = false; bool _timeoutReached = false; }; }
3,736
C++
.h
84
35.261905
106
0.631073
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,150
MongoCollection.h
Studio3T_robomongo/src/robomongo/core/domain/MongoCollection.h
#pragma once #include "robomongo/core/domain/MongoDatabase.h" #include "robomongo/core/domain/MongoCollectionInfo.h" namespace Robomongo { class MongoCollection { public: MongoCollection(MongoDatabase *database, const MongoCollectionInfo &info); bool isSystem() const { return _system; } std::string name() const { return _ns.collectionName(); } const MongoCollectionInfo info() const { return _info; } std::string fullName() const { return _ns.toString(); } MongoDatabase *database() const { return _database; } // std::string sizeString() const; // QString storageSizeString() const; private: MongoDatabase *_database; bool _system; MongoCollectionInfo _info; MongoNamespace _ns; }; }
808
C++
.h
23
29.478261
82
0.673522
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,151
MongoShell.h
Studio3T_robomongo/src/robomongo/core/domain/MongoShell.h
#pragma once #include <QObject> #include "robomongo/core/events/MongoEvents.h" #include "robomongo/core/domain/ScriptInfo.h" #include "robomongo/core/domain/MongoAggregateInfo.h" namespace Robomongo { struct AggrInfo; class MongoShell : public QObject { Q_OBJECT public: MongoShell(MongoServer *server, ScriptInfo scriptInfo); void open(const std::string &script, const std::string &dbName = std::string()); void query(int resultIndex, const MongoQueryInfo &info); void autocomplete(const std::string &prefix); void stop(); MongoServer *server() const { return _server; } std::string query() const; void execute(const std::string &script = "", const std::string &dbName = ""); bool isExecutable() const { return _scriptInfo.execute(); } const QString &title() const { return _scriptInfo.title(); } std::string dbname() const { return _scriptInfo.dbname(); } const CursorPosition &cursor() const { return _scriptInfo.cursor(); } void setScript(const QString &script) { return _scriptInfo.setScript(script); } void setScriptExecutable(bool execute) { _scriptInfo.setExecutable(execute); } void setAggrInfo(AggrInfo const& aggrInfo) { _aggrInfo = aggrInfo; } QString filePath() const { return _scriptInfo.filePath(); } bool saveToFile(); bool saveToFileAs(); bool loadFromFile(); protected Q_SLOTS: void handle(ExecuteQueryResponse *event); void handle(ExecuteScriptResponse *event); void handle(AutocompleteResponse *event); private: ScriptInfo _scriptInfo; AggrInfo _aggrInfo; MongoServer *_server; }; }
1,755
C++
.h
41
35.658537
88
0.671161
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,152
CredentialSettings.h
Studio3T_robomongo/src/robomongo/core/settings/CredentialSettings.h
#pragma once #include <QString> #include <QVariant> #include <QVariantMap> namespace Robomongo { class CredentialSettings { public: CredentialSettings(); explicit CredentialSettings(const QVariantMap &map); /** * @brief Clones credential settings. */ CredentialSettings *clone() const; /** * @brief Converts to QVariantMap */ QVariant toVariant() const; /** * @brief User name */ std::string userName() const { return _userName; } void setUserName(const std::string &userName) { _userName = userName; } /** * @brief Password */ std::string userPassword() const { return _userPassword; } void setUserPassword(const std::string &userPassword) { _userPassword = userPassword; } /** * @brief Database name, on which authentication performed */ std::string databaseName() const { return _databaseName.empty() ? "admin" : _databaseName; } void setDatabaseName(const std::string &databaseName) { _databaseName = databaseName; } /** * @brief Authentication mechanism (SCRAM-SHA-1, SCRAM-SHA-256 or MONGODB-CR) */ std::string mechanism() const { return _mechanism.empty() ? "SCRAM-SHA-1" : _mechanism; } void setMechanism(const std::string &mechanism) { _mechanism = mechanism; } /** * @brief Flag, indecating whether we should use this * credentials to perform authentication, or not. */ bool enabled() const { return _enabled; } void setEnabled(bool enabled) { _enabled = enabled; } bool useManuallyVisibleDbs() const { return _useManuallyVisibleDbs; } void setUseManuallyVisibleDbs(bool enabled) { _useManuallyVisibleDbs = enabled; } std::string manuallyVisibleDbs() const { return _manuallyVisibleDbs; } void setManuallyVisibleDbs(std::string const& dbs) { _manuallyVisibleDbs = dbs; } private: std::string _userName; std::string _userPassword; // clear text password (decrypted) std::string _databaseName; std::string _mechanism; // authentication mechanism (SCRAM-SHA-1, SCRAM-SHA-256 or MONGODB-CR) bool _useManuallyVisibleDbs; std::string _manuallyVisibleDbs; /** * @brief Flag, indecating whether we should use this * credentials to perform authentication, or not. */ bool _enabled; }; }
2,552
C++
.h
63
32.222222
106
0.628837
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,153
SshSettings.h
Studio3T_robomongo/src/robomongo/core/settings/SshSettings.h
#pragma once #include <QString> #include <QVariant> #include <QVariantMap> namespace Robomongo { class SshSettings { public: SshSettings(); /** * Clones credential settings. */ SshSettings *clone() const; /** * Converts to QVariantMap */ QVariant toVariant() const; void fromVariant(const QVariantMap &map); /* * Domain or IPv4 or IPv6 address */ std::string host() const { return _host; } void setHost(const std::string &host) { _host = host; } int port() const { return _port; } void setPort(const int port) { _port = port; } std::string userName() const { return _userName; } void setUserName(const std::string &userName) { _userName = userName; } std::string userPassword() const { return _userPassword; } void setUserPassword(const std::string &userPassword) { _userPassword = userPassword; } std::string privateKeyFile() const { return _privateKeyFile; } void setPrivateKeyFile(const std::string &path) { _privateKeyFile = path; } std::string publicKeyFile() const { return _publicKeyFile; } void setPublicKeyFile(const std::string &path) { _publicKeyFile = path; } std::string passphrase() const { return _passphrase; } void setPassphrase(const std::string &passphrase) { _passphrase = passphrase; } // "password" or "publickey" std::string authMethod() const { return _authMethod.empty() ? "publickey" : _authMethod; } void setAuthMethod(const std::string &method) { _authMethod = method; } /** * @brief Flag, indecating whether we should use this * credentials to perform authentication, or not. */ bool enabled() const { return _enabled; } void setEnabled(bool enabled) { _enabled = enabled; } bool askPassword() const { return _askPassword; } void setAskPassword(bool ask) { _askPassword = ask; } std::string askedPassword() const { return _askedPassword; } void setAskedPassword(const std::string &asked) { _askedPassword = asked; } int logLevel() const { return _logLevel; } void setLogLevel(const int logLevel) { _logLevel = logLevel; } private: std::string _host; // domain or IPv4/v6 int _port; std::string _userName; std::string _userPassword; // clear text password (decrypted) std::string _privateKeyFile; std::string _publicKeyFile; std::string _passphrase; // clear text passphrase (decrypted) std::string _authMethod; // "password" or "publickey" // Should we ask user about password or passphrase // each time when we try to connect bool _askPassword; /** * Flag, indicating whether we should use * this SSH tunnel or not. */ bool _enabled; int _logLevel; // this property is not persisted std::string _askedPassword; // this property is not persisted }; }
3,137
C++
.h
72
35.194444
98
0.618516
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,154
SslSettings.h
Studio3T_robomongo/src/robomongo/core/settings/SslSettings.h
#pragma once #include <QString> #include <QVariant> #include <QVariantMap> namespace Robomongo { class SslSettings { public: SslSettings(); /** * Clones credential settings. */ SslSettings *clone() const; /** * Converts to QVariantMap */ QVariant toVariant() const; void fromVariant(const QVariantMap &map); // Getters for mongo:: SSLGlobalParams related settings std::string pemKeyFile() const { return _pemKeyFile; } std::string caFile() const { return _caFile; } std::string pemPassPhrase() const { return _pemPassPhrase; } std::string crlFile() const { return _crlFile; } bool allowInvalidHostnames() const { return _allowInvalidHostnames; } bool allowInvalidCertificates() const { return _allowInvalidCertificates; } // Getters for helper SSL settings bool usePemFile() const { return _usePemFile; } bool useAdvancedOptions() const { return _useAdvancedOptions; } bool askPassphrase() const { return _askPassphrase; } // Setters for mongo:: SSLGlobalParams related settings void setPemKeyFile(const std::string &path) { _pemKeyFile = path; } void setCaFile(const std::string &path) { _caFile = path; } void setPemPassPhrase(const std::string &pemPassPhrase) { _pemPassPhrase = pemPassPhrase; } void setCrlFile(const std::string &path) { _crlFile = path; } void setAllowInvalidHostnames(const bool state) { _allowInvalidHostnames = state; } void setAllowInvalidCertificates(const bool state) { _allowInvalidCertificates = state; } // Setters for helper SSL settings void setUsePemFile(const bool state) { _usePemFile = state; } void setUseAdvancedOptions(const bool state) { _useAdvancedOptions = state; } void setAskPassphrase(const bool state) { _askPassphrase = state; } /** * Flag, indicating whether we should use * this SSL settings or not. */ bool sslEnabled() const { return _sslEnabled; } void enableSSL(bool enabled) { _sslEnabled = enabled; } private: // mongo:: SSL Global params related settings std::string _caFile; std::string _pemKeyFile; std::string _pemPassPhrase; std::string _crlFile; bool _allowInvalidHostnames; bool _allowInvalidCertificates; // Helper settings indirectly effecting what to pass to SSL global params bool _usePemFile; bool _useAdvancedOptions; bool _askPassphrase; /** * Flag, indicating whether SSL enabled for related connection */ bool _sslEnabled; }; }
2,771
C++
.h
65
34.4
99
0.651802
Studio3T/robomongo
9,296
797
724
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false