GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — sqlitebrowser/src/MainWindow.cpp at master · sqlitebrowser/sqlitebrowser Expand file tree/ Copy pathMainWindow.cppMore file actions 4189 lines (3661 loc) · 180 KB / Copy pathMainWindow.cppFile metadata and controls4189 lines (3661 loc) · 180 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #include "MainWindow.h" #include "sql/ObjectIdentifier.h" #include "sql/sqlitetypes.h" #include "ui_MainWindow.h" #include "Application.h" #include "EditIndexDialog.h" #include "AboutDialog.h" #include "EditTableDialog.h" #include "ImportCsvDialog.h" #include "ExportDataDialog.h" #include "Settings.h" #include "PreferencesDialog.h" #include "EditDialog.h" #include "sqlitetablemodel.h" #include "SqlExecutionArea.h" #include "VacuumDialog.h" #include "DbStructureModel.h" #include "version.h" #include "sqlite.h" #include "CipherDialog.h" #include "ExportSqlDialog.h" #include "SqlUiLexer.h" #include "FileDialog.h" #include "FindReplaceDialog.h" #include "GlobalFilter.h" #include "RunSql.h" #include "ExtendedTableWidget.h" #include "Data.h" #include "RemoteNetwork.h" #include "TableBrowser.h" #include "TableBrowserDock.h" #ifdef Q_OS_WIN #include "WindowsJumpList.h" #endif #include <chrono> #include <QFile> #include <QSaveFile> #include <QTextStream> #include <QWhatsThis> #include <QMessageBox> #include <QPersistentModelIndex> #include <QDragEnterEvent> #include <QScrollBar> #include <QMimeData> #include <QDesktopServices> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <QInputDialog> #include <QProgressDialog> #include <QTextEdit> #include <QClipboard> #include <QShortcut> #include <QUrlQuery> #include <QPrinter> #include <QPrintPreviewDialog> #include <QPushButton> #include <QTemporaryFile> #include <QToolButton> #include <QUrl> #include <QActionGroup> #ifdef Q_OS_MACX //Needed only on macOS #include <QOpenGLWidget> #endif #include <limits> int MainWindow::MaxRecentFiles; MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow), db(), m_currentTabTableModel(nullptr), editDock(new EditDialog(this)), plotDock(new PlotDock(this)), currentTableBrowser(nullptr), findReplaceDialog(new FindReplaceDialog(this)), execute_sql_worker(nullptr), isProjectModified(false) { ui->setupUi(this); init(); activateFields(false); updateRecentFileActions(); if (!Settings::getValue("tmp", "fileWillBeOpenedFromCLI").toBool() && Settings::getValue("General", "autoLoadLastDBFileAtStartup").toBool()) { recentFileActs[0]->trigger(); } } MainWindow::~MainWindow() { delete dbSelected; delete dockDbSelected; delete ui; } void MainWindow::init() { // Load window settings tabifyDockWidget(ui->dockLog, ui->dockPlot); tabifyDockWidget(ui->dockLog, ui->dockSchema); #ifdef Q_OS_MACX // Add OpenGL Context for macOS QOpenGLWidget *ogl = new QOpenGLWidget(this); ui->verticalLayout->addWidget(ogl); ogl->setHidden(true); #endif // Automatic update check #ifdef CHECKNEWVERSION // Check for a new version if automatic update check aren't disabled in the settings dialog if(Settings::getValue("checkversion", "enabled").toBool()) checkNewVersion(true); #endif // create facade objects to dbTreeWidgets dbSelected = new DbStructureQItemViewFacade(*ui->dbTreeWidget); dockDbSelected = new DbStructureQItemViewFacade(*ui->treeSchemaDock); // Connect SQL logging and database state setting to main window connect(&db, &DBBrowserDB::dbChanged, this, &MainWindow::dbState, Qt::QueuedConnection); connect(&db, &DBBrowserDB::sqlExecuted, this, &MainWindow::logSql, Qt::QueuedConnection); connect(&db, &DBBrowserDB::requestCollation, this, &MainWindow::requestCollation); // Set up DB structure tab dbStructureModel = new DbStructureModel(db, this, Settings::getValue("SchemaDock", "dropSelectQuery").toBool(), Settings::getValue("SchemaDock", "dropInsert").toBool()); connect(&db, &DBBrowserDB::structureUpdated, this, [this]() { std::vector<sqlb::ObjectIdentifier> old_tables; for(const auto& d : allTableBrowserDocks()) old_tables.push_back(d->tableBrowser()->currentlyBrowsedTableName()); dbStructureModel->reloadData(); populateStructure(old_tables); }); ui->dbTreeWidget->setModel(dbStructureModel); ui->dbTreeWidget->setColumnWidth(DbStructureModel::ColumnName, 300); ui->dbTreeWidget->setColumnHidden(DbStructureModel::ColumnObjectType, true); ui->dbTreeWidget->setColumnHidden(DbStructureModel::ColumnSchema, true); // Set up DB schema dock ui->treeSchemaDock->setModel(dbStructureModel); ui->treeSchemaDock->setColumnHidden(DbStructureModel::ColumnObjectType, true); ui->treeSchemaDock->setColumnHidden(DbStructureModel::ColumnSchema, true); // Create initial table browser tab ui->tabBrowsers->setWindowFlags(Qt::Widget); ui->tabBrowsers->setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North); newTableBrowserTab(); // Create docks ui->dockEdit->setWidget(editDock); ui->dockPlot->setWidget(plotDock); // Set up edit dock editDock->setReadOnly(true); // Restore window geometry restoreGeometry(Settings::getValue("MainWindow", "geometry").toByteArray()); // Save default and restore window state defaultWindowState = saveState(); restoreState(Settings::getValue("MainWindow", "windowState").toByteArray()); // Save default and restore open tab order if the openTabs setting is saved. defaultOpenTabs = saveOpenTabs(); restoreOpenTabs(Settings::getValue("MainWindow", "openTabs").toString()); // Restore dock state settings ui->comboLogSubmittedBy->setCurrentIndex(ui->comboLogSubmittedBy->findText(Settings::getValue("SQLLogDock", "Log").toString())); // Add keyboard shortcuts QShortcut* shortcutBrowseRefreshF5 = new QShortcut(QKeySequence("F5"), this); connect(shortcutBrowseRefreshF5, &QShortcut::activated, this, &MainWindow::refresh); QShortcut* shortcutBrowseRefreshCtrlR = new QShortcut(QKeySequence("Ctrl+R"), this); connect(shortcutBrowseRefreshCtrlR, &QShortcut::activated, this, &MainWindow::refresh); QShortcut* shortcutBrowseRefreshCtrlEnter = new QShortcut(QKeySequence("Ctrl+Enter"), this); connect(shortcutBrowseRefreshCtrlEnter, &QShortcut::activated, this, &MainWindow::refresh); // Add print shortcut for the DB Structure tab (dbTreeWidget) with context to the widget, so other print shortcuts aren't eclipsed. QShortcut* shortcutPrint = new QShortcut(QKeySequence(QKeySequence::Print), ui->dbTreeWidget, nullptr, nullptr, Qt::WidgetShortcut); connect(shortcutPrint, &QShortcut::activated, this, &MainWindow::printDbStructure); QShortcut* closeTabShortcut = new QShortcut(tr("Ctrl+W"), ui->tabSqlAreas, nullptr, nullptr, Qt::WidgetWithChildrenShortcut); connect(closeTabShortcut, &QShortcut::activated, this, [this]() { if(ui->tabSqlAreas->currentIndex() >= 0) closeSqlTab(ui->tabSqlAreas->currentIndex()); }); // Shortcuts for advancing and going back in the SQL Execution area tabs, independently of the widget which has focus. // This emulates the shortcuts provided by QTabWidget. QShortcut* shortcutNextTab = new QShortcut(QKeySequence(tr("Ctrl+Tab")), ui->tabSqlAreas, nullptr, nullptr, Qt::WidgetWithChildrenShortcut); connect(shortcutNextTab, &QShortcut::activated, this, [this]() { if(ui->tabSqlAreas->currentIndex() == ui->tabSqlAreas->count() - 1) ui->tabSqlAreas->setCurrentIndex(0); else ui->tabSqlAreas->setCurrentIndex(ui->tabSqlAreas->currentIndex() + 1); focusSqlEditor(); }); QShortcut* shortcutPreviousTab = new QShortcut(QKeySequence(tr("Ctrl+Shift+Tab")), ui->tabSqlAreas, nullptr, nullptr, Qt::WidgetWithChildrenShortcut); connect(shortcutPreviousTab, &QShortcut::activated, this, [this]() { if(ui->tabSqlAreas->currentIndex() == 0) ui->tabSqlAreas->setCurrentIndex(ui->tabSqlAreas->count() - 1); else ui->tabSqlAreas->setCurrentIndex(ui->tabSqlAreas->currentIndex() - 1); focusSqlEditor(); }); // Get MaxRecentFiles value from QSettings. MaxRecentFiles = Settings::getValue("General", "maxRecentFiles").toInt(); recentFileActs.resize(MaxRecentFiles); // Create the actions for the recently opened dbs list for(int i = 0; i < MaxRecentFiles; ++i) { recentFileActs[i] = new QAction(this); recentFileActs[i]->setVisible(false); connect(recentFileActs[i], &QAction::triggered, this, &MainWindow::openRecentFile); } for(int i = 0; i < MaxRecentFiles; ++i) ui->fileRecentFiles->insertAction(ui->fileExitAction, recentFileActs[i]); recentSeparatorAct = ui->fileRecentFiles->insertSeparator(ui->fileExitAction); optionToAutoLoadLastDBFileAtStartup = ui->fileRecentFiles->addAction(tr("Automatically load the last opened DB file at startup")); optionToAutoLoadLastDBFileAtStartup->setCheckable(true); optionToAutoLoadLastDBFileAtStartup->setChecked(Settings::getValue("General", "autoLoadLastDBFileAtStartup").toBool()); clearRecentFilesAction = ui->fileRecentFiles->addAction(tr("Clear List")); ui->fileRecentFiles->insertAction(ui->fileExitAction, clearRecentFilesAction); connect(optionToAutoLoadLastDBFileAtStartup, &QAction::triggered, this, &MainWindow::toggleAutoLoadLastDBFileAtStartupOption); connect(clearRecentFilesAction, &QAction::triggered, this, &MainWindow::clearRecentFiles); // Create popup menus popupTableMenu = new QMenu(this); popupTableMenu->addAction(ui->actionEditBrowseTable); popupTableMenu->addAction(ui->editModifyObjectAction); popupTableMenu->addAction(ui->editDeleteObjectAction); popupTableMenu->addAction(ui->fileDetachAction); popupTableMenu->addSeparator(); popupTableMenu->addAction(ui->actionEditCopyCreateStatement); popupTableMenu->addAction(ui->actionExportCsvPopup); popupSchemaDockMenu = new QMenu(this); popupSchemaDockMenu->addAction(ui->actionPopupSchemaDockBrowseTable); popupSchemaDockMenu->addAction(ui->actionPopupSchemaDockDetachDatabase); popupSchemaDockMenu->addSeparator(); auto dropSchemaDockMenu = new QMenu(popupSchemaDockMenu); popupSchemaDockMenu->addMenu(dropSchemaDockMenu); dropSchemaDockMenu->setTitle(tr("Clipboard/Drop Options")); dropSchemaDockMenu->setStatusTip(tr("Options for Drag && Drop and Copy to Clipboard operations.")); dropSchemaDockMenu->addAction(ui->actionDropSelectQueryCheck); dropSchemaDockMenu->addAction(ui->actionDropInsertCheck); dropSchemaDockMenu->addAction(ui->actionDropNamesCheck); QActionGroup* dropGroup = new QActionGroup(dropSchemaDockMenu); dropGroup->addAction(ui->actionDropSelectQueryCheck); dropGroup->addAction(ui->actionDropInsertCheck); dropGroup->addAction(ui->actionDropNamesCheck); dropSchemaDockMenu->addSeparator(); dropSchemaDockMenu->addAction(ui->actionDropQualifiedCheck); dropSchemaDockMenu->addAction(ui->actionEnquoteNamesCheck); popupSchemaDockMenu->addAction(ui->actionCopyInSchema); connect(ui->actionCopyInSchema, &QAction::triggered, this, [=]() { dbStructureModel->copy(ui->treeSchemaDock->selectionModel()->selectedIndexes()); }); auto copyShortcut = new QShortcut(QKeySequence::Copy, ui->treeSchemaDock, nullptr, nullptr, Qt::WidgetShortcut); connect(copyShortcut, &QShortcut::activated, this, [=]() { dbStructureModel->copy(ui->treeSchemaDock->selectionModel()->selectedIndexes()); }); popupOpenDbMenu = new QMenu(this); popupOpenDbMenu->addAction(ui->fileOpenAction); popupOpenDbMenu->addAction(ui->fileOpenReadOnlyAction); ui->fileOpenActionPopup->setMenu(popupOpenDbMenu); popupSaveSqlFileMenu = new QMenu(this); popupSaveSqlFileMenu->addAction(ui->actionSqlSaveFile); popupSaveSqlFileMenu->addAction(ui->actionSqlSaveFileAs); ui->actionSqlSaveFilePopup->setMenu(popupSaveSqlFileMenu); popupSaveSqlResultsMenu = new QMenu(this); popupSaveSqlResultsMenu->addAction(ui->actionSqlResultsExportCsv); popupSaveSqlResultsMenu->addAction(ui->actionSqlResultsExportJson); popupSaveSqlResultsMenu->addAction(ui->actionSqlResultsSaveAsView); ui->actionSqlResultsSave->setMenu(popupSaveSqlResultsMenu); qobject_cast<QToolButton*>(ui->toolbarSql->widgetForAction(ui->actionSqlResultsSave))->setPopupMode(QToolButton::InstantPopup); // Add menu item for log dock ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockLog->toggleViewAction()); ui->viewMenu->actions().at(0)->setShortcut(QKeySequence(tr("Ctrl+L"))); ui->viewMenu->actions().at(0)->setIcon(QIcon(":/icons/log_dock")); // Add menu item for plot dock ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockPlot->toggleViewAction()); ui->viewMenu->actions().at(1)->setShortcut(QKeySequence(tr("Ctrl+D"))); ui->viewMenu->actions().at(1)->setIcon(QIcon(":/icons/log_dock")); // Add menu item for schema dock ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockSchema->toggleViewAction()); ui->viewMenu->actions().at(2)->setShortcut(QKeySequence(tr("Ctrl+I"))); ui->viewMenu->actions().at(2)->setIcon(QIcon(":/icons/log_dock")); // Add menu item for edit dock ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockEdit->toggleViewAction()); ui->viewMenu->actions().at(3)->setShortcut(QKeySequence(tr("Ctrl+E"))); ui->viewMenu->actions().at(3)->setIcon(QIcon(":/icons/log_dock")); // Set checked state if toolbar is visible ui->viewDBToolbarAction->setChecked(!ui->toolbarDB->isHidden()); ui->viewExtraDBToolbarAction->setChecked(!ui->toolbarExtraDB->isHidden()); ui->viewProjectToolbarAction->setChecked(!ui->toolbarProject->isHidden()); // Add separator between docks and toolbars ui->viewMenu->insertSeparator(ui->viewDBToolbarAction); // Connect the tabCloseRequested to the actual closeTab function. // This must be done before the connections for checking the actions in the View menu so // they are updated accordingly. connect(ui->mainTab, &QTabWidget::tabCloseRequested, this, &MainWindow::closeTab); // Add entries for toggling the visibility of main tabs for (QWidget* widget : {ui->structure, ui->browser, ui->pragmas, ui->query}) { QAction* action = ui->viewMenu->addAction(QIcon(":/icons/open_sql"), widget->accessibleName()); action->setObjectName(widget->accessibleName()); action->setCheckable(true); action->setChecked(ui->mainTab->indexOf(widget) != -1); connect(action, &QAction::toggled, this, [=](bool show) { toggleTabVisible(widget, show); }); // Connect tabCloseRequested for setting checked the appropriate menu entry. // Note these are called after the actual tab is closed only because they are connected // after connecting closeTab. connect(ui->mainTab, &QTabWidget::tabCloseRequested, this, [=](int /*index*/) { action->setChecked(ui->mainTab->indexOf(widget) != -1); }); } ui->viewMenu->addSeparator(); QMenu* layoutMenu = new QMenu(tr("Window Layout"), this); ui->viewMenu->addMenu(layoutMenu); QAction* resetLayoutAction = layoutMenu->addAction(tr("Reset Window Layout")); resetLayoutAction->setShortcut(QKeySequence(tr("Ctrl+0"))); connect(resetLayoutAction, &QAction::triggered, this, [=]() { restoreState(defaultWindowState); restoreOpenTabs(defaultOpenTabs); ui->viewDBToolbarAction->setChecked(!ui->toolbarDB->isHidden()); ui->viewExtraDBToolbarAction->setChecked(!ui->toolbarExtraDB->isHidden()); ui->viewProjectToolbarAction->setChecked(!ui->toolbarProject->isHidden()); }); QAction* simplifyLayoutAction = layoutMenu->addAction(tr("Simplify Window Layout")); simplifyLayoutAction->setShortcut(QKeySequence(tr("Alt+Shift+0"))); connect(simplifyLayoutAction, &QAction::triggered, this, [=]() { ui->viewMenu->findChild<QAction *>(ui->pragmas->accessibleName())->activate(QAction::Trigger); ui->dockLog->hide(); ui->dockPlot->hide(); ui->dockSchema->hide(); ui->dockEdit->hide(); }); QAction* atBottomLayoutAction = layoutMenu->addAction(tr("Dock Windows at Bottom")); connect(atBottomLayoutAction, &QAction::triggered, this, [=]() { moveDocksTo(Qt::BottomDockWidgetArea); }); QAction* atLeftLayoutAction = layoutMenu->addAction(tr("Dock Windows at Left Side")); connect(atLeftLayoutAction, &QAction::triggered, this, [=]() { moveDocksTo(Qt::LeftDockWidgetArea); }); QAction* atTopLayoutAction = layoutMenu->addAction(tr("Dock Windows at Top")); connect(atTopLayoutAction, &QAction::triggered, this, [=]() { moveDocksTo(Qt::TopDockWidgetArea); }); // If we're not compiling in SQLCipher, hide its FAQ link in the help menu #ifndef ENABLE_SQLCIPHER ui->actionSqlCipherFaq->setVisible(false); #endif // Set statusbar fields statusBusyLabel = new QLabel(ui->statusbar); statusBusyLabel->setEnabled(false); statusBusyLabel->setVisible(false); statusBusyLabel->setToolTip(tr("The database is currently busy.")); ui->statusbar->addPermanentWidget(statusBusyLabel); statusStopButton = new QToolButton(ui->statusbar); statusStopButton->setVisible(false); statusStopButton->setIcon(QIcon(":icons/cancel")); statusStopButton->setToolTip(tr("Click here to interrupt the currently running query.")); statusStopButton->setMaximumSize(ui->statusbar->geometry().height() - 6, ui->statusbar->geometry().height() - 6); statusStopButton->setAutoRaise(true); ui->statusbar->addPermanentWidget(statusStopButton); statusEncryptionLabel = new QLabel(ui->statusbar); statusEncryptionLabel->setEnabled(false); statusEncryptionLabel->setVisible(false); statusEncryptionLabel->setText(tr("Encrypted")); statusEncryptionLabel->setToolTip(tr("Database is encrypted using SQLCipher")); ui->statusbar->addPermanentWidget(statusEncryptionLabel); statusReadOnlyLabel = new QLabel(ui->statusbar); statusReadOnlyLabel->setEnabled(false); statusReadOnlyLabel->setVisible(false); statusReadOnlyLabel->setText(tr("Read only")); statusReadOnlyLabel->setToolTip(tr("Database file is read only. Editing the database is disabled.")); ui->statusbar->addPermanentWidget(statusReadOnlyLabel); statusEncodingLabel = new QLabel(ui->statusbar); statusEncodingLabel->setEnabled(false); statusEncodingLabel->setText("UTF-8"); statusEncodingLabel->setToolTip(tr("Database encoding")); ui->statusbar->addPermanentWidget(statusEncodingLabel); // When changing the text of the toolbar actions, also automatically change their icon text and their tooltip text connect(ui->editModifyObjectAction, &QAction::changed, this, [=]() { ui->editModifyObjectAction->setIconText(ui->editModifyObjectAction->text()); ui->editModifyObjectAction->setToolTip(ui->editModifyObjectAction->text()); }); connect(ui->editDeleteObjectAction, &QAction::changed, this, [=]() { ui->editDeleteObjectAction->setIconText(ui->editDeleteObjectAction->text()); ui->editDeleteObjectAction->setToolTip(ui->editDeleteObjectAction->text()); }); // When clicking the interrupt query button in the status bar, ask SQLite to interrupt the current query connect(statusStopButton, &QToolButton::clicked, this, [this]() { db.interruptQuery(); }); // Connect some more signals and slots connect(editDock, &EditDialog::recordTextUpdated, this, &MainWindow::updateRecordText); connect(editDock, &EditDialog::evaluateText, this, &MainWindow::evaluateText); connect(editDock, &EditDialog::requestUrlOrFileOpen, this, &MainWindow::openUrlOrFile); connect(ui->dbTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::changeObjectSelection); connect(ui->dockEdit, &QDockWidget::visibilityChanged, this, &MainWindow::toggleEditDock); connect(ui->actionDropSelectQueryCheck, &QAction::toggled, dbStructureModel, &DbStructureModel::setDropSelectQuery); connect(ui->actionDropInsertCheck, &QAction::toggled, dbStructureModel, &DbStructureModel::setDropInsert); connect(ui->actionDropNamesCheck, &QAction::toggled, dbStructureModel, [this]() { dbStructureModel->setDropSelectQuery(false); dbStructureModel->setDropInsert(false); }); connect(ui->actionDropQualifiedCheck, &QAction::toggled, dbStructureModel, &DbStructureModel::setDropQualifiedNames); connect(ui->actionEnquoteNamesCheck, &QAction::toggled, dbStructureModel, &DbStructureModel::setDropEnquotedNames); connect(&db, &DBBrowserDB::databaseInUseChanged, this, &MainWindow::updateDatabaseBusyStatus); connect(ui->actionSqlStop, &QAction::triggered, this, [this]() { if(execute_sql_worker && execute_sql_worker->isRunning()) execute_sql_worker->stop(); }); // Connect tool pragmas connect(ui->actionIntegrityCheck, &QAction::triggered, this, [this]() { runSqlNewTab("PRAGMA integrity_check;", ui->actionIntegrityCheck->text(), "https://www.sqlite.org/pragma.html#pragma_integrity_check"); }); connect(ui->actionQuickCheck, &QAction::triggered, this, [this]() { runSqlNewTab("PRAGMA quick_check;", ui->actionQuickCheck->text(), "https://www.sqlite.org/pragma.html#pragma_quick_check"); }); connect(ui->actionForeignKeyCheck, &QAction::triggered, this, [this]() { runSqlNewTab("PRAGMA foreign_key_check;", ui->actionForeignKeyCheck->text(), "https://www.sqlite.org/pragma.html#pragma_foreign_key_check"); }); connect(ui->actionOptimize, &QAction::triggered, this, [this]() { runSqlNewTab("PRAGMA optimize;", ui->actionOptimize->text(), "https://www.sqlite.org/pragma.html#pragma_optimize"); }); // Action for switching the table via the Database Structure tab connect(ui->actionPopupSchemaDockBrowseTable, &QAction::triggered, this, [this]() { switchToBrowseDataTab(dockDbSelected->object()); refresh(); // Required in case the Browse Data tab already was the active main tab }); // Set other window settings setAcceptDrops(true); setWindowTitle(QApplication::applicationName()); // Add the documentation of shortcuts, which aren't otherwise visible in the user interface, to some buttons. addShortcutsTooltip(ui->actionDbPrint); addShortcutsTooltip(ui->actionSqlOpenTab); addShortcutsTooltip(ui->actionSqlOpenFile); addShortcutsTooltip(ui->actionSqlPrint); addShortcutsTooltip(ui->actionExecuteSql, {shortcutBrowseRefreshF5->key(), shortcutBrowseRefreshCtrlR->key()}); addShortcutsTooltip(ui->actionSqlExecuteLine); addShortcutsTooltip(ui->actionSqlFind); addShortcutsTooltip(ui->actionSqlFindReplace); addShortcutsTooltip(ui->actionSqlToggleComment); // Since in some keyboards pressing F keys is cumbersome, add an alternate shortcut and document // it in the toolbar. ui->fileCloseAction->setShortcuts({QKeySequence(tr("Ctrl+F4")), QKeySequence(tr("Alt+Shift+W"))}); ui->actionCloseProject->setShortcuts({QKeySequence(tr("Ctrl+Shift+W")), QKeySequence(tr("Ctrl+Shift+F4"))}); addShortcutsTooltip(ui->fileCloseAction); // Load all settings reloadSettings(); #ifndef ENABLE_SQLCIPHER // Only show encryption menu action when SQLCipher support is enabled ui->actionEncryption->setVisible(false); #endif /* Remove all the '&' signs from the dock titles. On at least Windows and * OSX, Qt doesn't seem to support them properly, so they end up being * visible instead of creating a keyboard shortcut */ ui->dockEdit->setWindowTitle(ui->dockEdit->windowTitle().remove('&')); ui->dockLog->setWindowTitle(ui->dockLog->windowTitle().remove('&')); ui->dockPlot->setWindowTitle(ui->dockPlot->windowTitle().remove('&')); ui->dockSchema->setWindowTitle(ui->dockSchema->windowTitle().remove('&')); } bool MainWindow::fileOpen(const QString& fileName, bool openFromProject, bool readOnly) { bool retval = false; QString wFile = fileName; // QFile::exist will produce error message if passed empty string. // Test string length before usage w/ QFile to silence warning if (wFile.isEmpty() || !QFile::exists(wFile)) { wFile = FileDialog::getOpenFileName( OpenDatabaseFile, this, tr("Choose a database file") #ifndef Q_OS_MAC // Filters on OS X are buggy , FileDialog::getSqlDatabaseFileFilter() #endif ); } // catch situation where user has canceled file selection from dialog if(!wFile.isEmpty() && QFile::exists(wFile) ) { // Try opening it as a project file first. If confirmed, this will include closing current // database and project files. switch (loadProject(wFile, readOnly)) { case Success: return true; case Aborted: return false; case NotValidFormat: // It's not a project. Continue trying to open the file as CSV or DB. break; } if(isTextOnlyFile(wFile)) { // If it's a text file, cannot be an SQLite/SQLCipher database, // so try to import it as CSV. importCSVfiles({wFile}); } else { if(!confirmOpenWithoutLocking(wFile)) return false; // Close the database. If the user didn't want to close it, though, stop here if (db.isOpen()) if(!fileClose()) return false; // No project file; so it should be a database file if(db.open(wFile, readOnly)) { // Close all open but empty SQL tabs for(int i=ui->tabSqlAreas->count()-1;i>=0;i--) { if(qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getSql().trimmed().isEmpty()) closeSqlTab(i, true); } statusEncodingLabel->setText(db.getPragma("encoding")); statusEncryptionLabel->setVisible(db.encrypted()); statusReadOnlyLabel->setVisible(db.readOnly()); setCurrentFile(wFile); if(!openFromProject) { addToRecentFilesMenu(wFile, readOnly); // When a new DB file has been open while a project is open, set the project modified. if(!currentProjectFilename.isEmpty()) isProjectModified = true; } else { // loadProject will init the rest return true; } if(ui->tabSqlAreas->count() == 0) // Create a new tab if there isn't one. openSqlTab(true); if(ui->mainTab->currentWidget() == ui->pragmas) loadPragmas(); refreshTableBrowsers(); if (db.readOnly()) { if (!fileSystemWatch.files().isEmpty()) fileSystemWatch.removePaths(fileSystemWatch.files()); fileSystemWatch.addPath(wFile); } retval = true; } else { QMessageBox::warning(this, qApp->applicationName(), tr("Could not open database file.\nReason: %1").arg(db.lastError())); retval = false; } } } return retval; } void MainWindow::fileNew() { QString fileName = FileDialog::getSaveFileName( CreateDatabaseFile, this, tr("Choose a filename to save under"), FileDialog::getSqlDatabaseFileFilter()); if(!fileName.isEmpty() && confirmOpenWithoutLocking(fileName)) { if(QFile::exists(fileName)) QFile::remove(fileName); db.create(fileName); setCurrentFile(fileName); addToRecentFilesMenu(fileName); statusEncodingLabel->setText(db.getPragma("encoding")); statusEncryptionLabel->setVisible(false); statusReadOnlyLabel->setVisible(false); refreshTableBrowsers(); if(ui->tabSqlAreas->count() == 0) openSqlTab(true); createTable(); } } void MainWindow::fileNewInMemoryDatabase(bool open_create_dialog) { // Open an in-memory database. We use open() instead of create() here because the extra work create() does is not needed // when no files are stored on disk. db.open(":memory:"); setCurrentFile(tr("In-Memory database")); statusEncodingLabel->setText(db.getPragma("encoding")); statusEncryptionLabel->setVisible(false); statusReadOnlyLabel->setVisible(false); refreshTableBrowsers(); if(ui->tabSqlAreas->count() == 0) openSqlTab(true); if(open_create_dialog) createTable(); } void MainWindow::populateStructure(const std::vector<sqlb::ObjectIdentifier>& old_tables) { // Refresh the structure tab ui->dbTreeWidget->setRootIndex(dbStructureModel->index(1, 0)); // Show the 'All' part of the db structure ui->dbTreeWidget->expandToDepth(0); ui->treeSchemaDock->setRootIndex(dbStructureModel->index(1, 0)); // Show the 'All' part of the db structure ui->treeSchemaDock->expandToDepth(0); // Refresh the browse data tabs const auto all_table_browsers = allTableBrowserDocks(); for(int i=0;i<all_table_browsers.size()&&i<static_cast<int>(old_tables.size());i++) all_table_browsers.at(i)->tableBrowser()->setStructure(dbStructureModel, old_tables.at(static_cast<size_t>(i))); // Cancel here if no database is opened if(!db.isOpen()) return; // Update table and column names for syntax highlighting SqlUiLexer::QualifiedTablesMap qualifiedTablesMap; for(const auto& it : db.schemata) { SqlUiLexer::TablesAndColumnsMap tablesToColumnsMap; for(const auto& jt : it.second.tables) { QString objectname = QString::fromStdString(jt.first); for(const auto& f : jt.second->fields) tablesToColumnsMap[objectname].push_back(QString::fromStdString(f.name())); } qualifiedTablesMap[QString::fromStdString(it.first)] = tablesToColumnsMap; } SqlTextEdit::sqlLexer->setTableNames(qualifiedTablesMap); ui->editLogApplication->reloadKeywords(); ui->editLogUser->reloadKeywords(); for(int i=0;i<ui->tabSqlAreas->count();i++) qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getEditor()->reloadKeywords(); // Resize SQL column to fit contents ui->dbTreeWidget->resizeColumnToContents(DbStructureModel::ColumnSQL); ui->treeSchemaDock->resizeColumnToContents(DbStructureModel::ColumnSQL); // Resize also the Name column in the Dock since it has usually // short content and there is little space there. ui->treeSchemaDock->resizeColumnToContents(DbStructureModel::ColumnName); } void MainWindow::refreshTableBrowsers(bool all) { QApplication::setOverrideCursor(Qt::WaitCursor); for(const auto& d : allTableBrowserDocks()) { // When in the Browse Data tab update all docks. Otherwise just update the floating ones because they might // be visible even when another tab is active. if(all || ui->mainTab->currentWidget() == ui->browser || d->isFloating()) { TableBrowser* t = d->tableBrowser(); if(t) t->refresh(); } } QApplication::restoreOverrideCursor(); } void MainWindow::refreshDb() { refreshTableBrowsers(); } bool MainWindow::fileSaveAs() { QString fileName = FileDialog::getSaveFileName( OpenDatabaseFile, this, tr("Choose a database file to save under"), FileDialog::getSqlDatabaseFileFilter() ); // catch situation where user has canceled file selection from dialog if(!fileName.isEmpty()) { bool result = db.saveAs(fileName.toStdString()); if(result) { setCurrentFile(fileName); addToRecentFilesMenu(fileName); } else { QMessageBox::warning(this, QApplication::applicationName(), tr("Error while saving the database to the new file.")); } return result; } else { return false; } } bool MainWindow::fileClose() { // Stop any running SQL statements before closing the database if(execute_sql_worker && execute_sql_worker->isRunning()) { if(QMessageBox::warning(this, qApp->applicationName(), tr("You are still executing SQL statements. Closing the database now will stop their execution, possibly " "leaving the database in an inconsistent state. Are you sure you want to close the database?"), QMessageBox::Yes, QMessageBox::Cancel | QMessageBox::Default | QMessageBox::Escape) == QMessageBox::Cancel) return false; execute_sql_worker->stop(); execute_sql_worker->wait(); } // Close the database but stop the closing process here if the user pressed the cancel button in there if(!db.close()) return false; if (!fileSystemWatch.files().isEmpty()) fileSystemWatch.removePaths(fileSystemWatch.files()); TableBrowser::resetSharedSettings(); setCurrentFile(QString()); loadPragmas(); statusEncryptionLabel->setVisible(false); statusReadOnlyLabel->setVisible(false); // Reset the table browser of the Browse Data tab. // We call delete here to avoid the closed() signal being emitted // which would open a new dock. for(auto d : allTableBrowserDocks()) delete d; newTableBrowserTab(); allTableBrowserDocks().at(0)->tableBrowser()->setEnabled(false); // Clear edit dock editDock->setCurrentIndex(QModelIndex()); // Clear the SQL Log ui->editLogApplication->clear(); ui->editLogUser->clear(); ui->editLogErrorLog->clear(); // Remove completion and highlighting for identifiers SqlTextEdit::sqlLexer->setTableNames(SqlUiLexer::QualifiedTablesMap()); for(int i=0; i < ui->tabSqlAreas->count(); i++) qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getEditor()->reloadKeywords(); return true; } void MainWindow::closeEvent( QCloseEvent* event ) { if(closeFiles()) { Settings::setValue("MainWindow", "geometry", saveGeometry()); Settings::setValue("MainWindow", "windowState", saveState()); Settings::setValue("MainWindow", "openTabs", saveOpenTabs()); Settings::setValue("SQLLogDock", "Log", ui->comboLogSubmittedBy->currentText()); Settings::setValue("SchemaDock", "dropSelectQuery", ui->actionDropSelectQueryCheck->isChecked()); Settings::setValue("SchemaDock", "dropInsert", ui->actionDropInsertCheck->isChecked()); Settings::setValue("SchemaDock", "dropQualifiedNames", ui->actionDropQualifiedCheck->isChecked()); Settings::setValue("SchemaDock", "dropEnquotedNames", ui->actionEnquoteNamesCheck->isChecked()); SqlExecutionArea::saveState(); Settings::sync(); QMainWindow::closeEvent(event); } else { event->ignore(); } } bool MainWindow::closeFiles() { bool ignoreUnattachedBuffers = false; // Ask for saving all modified open SQL files in their files and all the unattached tabs in a project file. for(int i=0; i<ui->tabSqlAreas->count(); i++) { // Ask for saving and comply with cancel answer. if(!askSaveSqlTab(i, ignoreUnattachedBuffers)) return false; } bool projectClosed = closeProject(); if (projectClosed) { // Now all tabs can be closed at once without asking user. // Close tabs in reverse order (so indexes are not changed in the process). for(int i=ui->tabSqlAreas->count()-1; i>=0; i--) closeSqlTab(i, /* force */ true, /* askSaving */ false); } return projectClosed; } bool MainWindow::closeProject() { if(!currentProjectFilename.isEmpty() && isProjectModified) { QMessageBox::StandardButton reply = QMessageBox::question (nullptr, QApplication::applicationName(), tr("Do you want to save the changes made to the project file '%1'?"). arg(QFileInfo(currentProjectFilename).fileName()), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); switch(reply) { case QMessageBox::Save: saveProject(); break; case QMessageBox::Cancel: return false; default: break; } } currentProjectFilename.clear(); return fileClose(); } void MainWindow::attachPlot(ExtendedTableWidget* tableWidget, SqliteTableModel* model, BrowseDataTableSettings* settings, bool keepOrResetSelection) { plotDock->updatePlot(model, settings, true, keepOrResetSelection); // Disconnect previous connection disconnect(plotDock, &PlotDock::pointsSelected, nullptr, nullptr); if(tableWidget) { // Connect plot selection to the current table results widget. connect(plotDock, &PlotDock::pointsSelected, tableWidget, &ExtendedTableWidget::selectTableLines); connect(tableWidget, &ExtendedTableWidget::destroyed, plotDock, &PlotDock::resetPlot); // Disconnect requestUrlOrFileOpen in order to make sure that there is only one connection. Otherwise we can open it several times. disconnect(tableWidget, &ExtendedTableWidget::requestUrlOrFileOpen, this, &MainWindow::openUrlOrFile); connect(tableWidget, &ExtendedTableWidget::requestUrlOrFileOpen, this, &MainWindow::openUrlOrFile); } } void MainWindow::refresh() { // What the Refresh function does depends on the currently active tab. This way the keyboard shortcuts (F5 and Ctrl+R) // always perform some meaningful task; they just happen to be context dependent in the function they trigger. QWidget* currentTab = ui->mainTab->currentWidget(); if (currentTab == ui->structure) { // Refresh the schema db.updateSchema(); } else if (currentTab == ui->browser) { // Refresh the schema and reload the current table refreshTableBrowsers(); } else if (currentTab == ui->pragmas) { // Reload pragma values loadPragmas(); } else if (currentTab == ui->query) { // (Re-)Run the current SQL query executeQuery(); } } void MainWindow::createTable() { EditTableDialog dialog(db, sqlb::ObjectIdentifier(), true, this); if(dialog.exec()) { refreshTableBrowsers(); } } void MainWindow::createIndex() { EditIndexDialog dialog(db, sqlb::ObjectIdentifier(), true, this); if(dialog.exec()) refreshTableBrowsers(); } void MainWindow::compact() { VacuumDialog dialog(&db, this); dialog.exec(); } void MainWindow::deleteObject() { // Get name and type of object to delete sqlb::ObjectIdentifier obj; QString type; getSelectedObject(type, obj); // Due to different grammar in languages (e.g. gender or declension), each message must be given separately to translation. QString message; if (type == "table") message = tr("Are you sure you want to delete the table '%1'?\nAll data associated with the table will be lost."); else if (type == "view") message = tr("Are you sure you want to delete the view '%1'?"); else if (type == "trigger") message = tr("Are you sure you want to delete the trigger '%1'?"); else if (type == "index") message = tr("Are you sure you want to delete the index '%1'?"); // Ask user if he really wants to delete that table if(QMessageBox::warning(this, QApplication::applicationName(), message.arg(QString::fromStdString(obj.name())), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { // Delete the table QString statement = QString("DROP %1 %2;").arg(type.toUpper(), QString::fromStdString(obj.toString())); if(!db.executeSQL(statement.toStdString())) { if (type == "table") message = tr("Error: could not delete the table."); else if (type == "view") message = tr("Error: could not delete the view."); else if (type == "trigger") message = tr("Error: could not delete the trigger."); else if (type == "index") message = tr("Error: could not delete the index."); QString error = tr("Message from database engine:\n%1").arg(db.lastError()); QMessageBox::warning(this, QApplication::applicationName(), message + " " + error); } else { refreshTableBrowsers(); changeObjectSelection(); } } } void MainWindow::getSelectedObject(QString &type, sqlb::ObjectIdentifier& obj) { type = ""; obj = sqlb::ObjectIdentifier(); QWidget* currentTab = ui->mainTab->currentWidget(); if (currentTab == ui->structure) { if(!dbSelected->hasSelection()) return; // Get name and type of the object to edit obj = dbSelected->object(); type = dbSelected->objectType(); } else if (currentTab == ui->browser) { // Get name of the current table from the Data Browser obj = currentlyBrowsedTableName(); sqlb::TablePtr tablePtr = db.getTableByName(obj); if (!tablePtr) { return; } else { type = tablePtr->isView()? "view" : "table"; } } } void MainWindow::editObject() { QString type; sqlb::ObjectIdentifier obj; // Get name and type of object to edit getSelectedObject(type, obj); if(type == "table") { // For a safe and possibly complex table modification we must follow the steps documented in |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |