开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
forked from 陈炳煌/sqlitebrowser
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (16)
标签 (31)
master
coverity_scan
v3.11.x
issue1831_v1
qdarkstyle
no_savepoints_ro_db
v3.10.x
v3.9.x
v3.6.x
v3.5.x
v3.4.x
v3.3.x
utf8grammar
sqlb-3.2.x
sqlb-3.1.x
sqlb-3.x
continuous
v3.11.2
v3.11.1v2
v3.11.1
v3.11.0
v3.11.0-beta3
v3.11.0-beta2
v3.11.0-beta1
v3.11.0-alpha1
v3.10.1
v3.10.0
v3.10.0-beta2
v3.10.0-beta1
v3.9.1
v3.9.0
v3.9.0-beta1
v3.8.0
v3.7.0
v3.6.0
v3.5.1
master
分支 (16)
标签 (31)
master
coverity_scan
v3.11.x
issue1831_v1
qdarkstyle
no_savepoints_ro_db
v3.10.x
v3.9.x
v3.6.x
v3.5.x
v3.4.x
v3.3.x
utf8grammar
sqlb-3.2.x
sqlb-3.1.x
sqlb-3.x
continuous
v3.11.2
v3.11.1v2
v3.11.1
v3.11.0
v3.11.0-beta3
v3.11.0-beta2
v3.11.0-beta1
v3.11.0-alpha1
v3.10.1
v3.10.0
v3.10.0-beta2
v3.10.0-beta1
v3.9.1
v3.9.0
v3.9.0-beta1
v3.8.0
v3.7.0
v3.6.0
v3.5.1
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (16)
标签 (31)
master
coverity_scan
v3.11.x
issue1831_v1
qdarkstyle
no_savepoints_ro_db
v3.10.x
v3.9.x
v3.6.x
v3.5.x
v3.4.x
v3.3.x
utf8grammar
sqlb-3.2.x
sqlb-3.1.x
sqlb-3.x
continuous
v3.11.2
v3.11.1v2
v3.11.1
v3.11.0
v3.11.0-beta3
v3.11.0-beta2
v3.11.0-beta1
v3.11.0-alpha1
v3.10.1
v3.10.0
v3.10.0-beta2
v3.10.0-beta1
v3.9.1
v3.9.0
v3.9.0-beta1
v3.8.0
v3.7.0
v3.6.0
v3.5.1
sqlitebrowser
/
src
/
EditDialog.cpp
sqlitebrowser
/
src
/
EditDialog.cpp
EditDialog.cpp 38.88 KB
一键复制 编辑 原始数据 按行查看 历史
Martin Kleusberg 提交于 2019年07月26日 20:18 +08:00 . Don't treat numbers as JSON data in Edit Cell dialog
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
#include "EditDialog.h"
#include "ui_EditDialog.h"
#include "sqlitedb.h"
#include "Settings.h"
#include "qhexedit.h"
#include "docktextedit.h"
#include "FileDialog.h"
#include "Data.h"
#include <QMainWindow>
#include <QKeySequence>
#include <QShortcut>
#include <QImageReader>
#include <QBuffer>
#include <QModelIndex>
#include <QtXml/QDomDocument>
#include <QMessageBox>
#include <QPrinter>
#include <QPrintPreviewDialog>
#include <QPainter>
#include <QClipboard>
#include <QTextDocument>
#include <Qsci/qsciscintilla.h>
#include <json.hpp>
using json = nlohmann::json;
EditDialog::EditDialog(QWidget* parent)
: QDialog(parent),
ui(new Ui::EditDialog),
currentIndex(QModelIndex()),
dataSource(SciBuffer),
dataType(Null),
isReadOnly(true)
{
ui->setupUi(this);
// Add Ctrl-Enter (Cmd-Enter on OSX) as a shortcut for the Apply button
ui->buttonApply->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return));
ui->buttonApply->setToolTip(ui->buttonApply->toolTip() + " [" + ui->buttonApply->shortcut().toString(QKeySequence::NativeText) + "]");
QHBoxLayout* hexLayout = new QHBoxLayout(ui->editorBinary);
hexEdit = new QHexEdit(this);
hexLayout->addWidget(hexEdit);
hexEdit->setOverwriteMode(false);
QHBoxLayout* sciLayout = new QHBoxLayout(ui->editorSci);
sciEdit = new DockTextEdit(this);
sciLayout->addWidget(sciEdit);
QShortcut* ins = new QShortcut(QKeySequence(Qt::Key_Insert), this);
connect(ins, SIGNAL(activated()), this, SLOT(toggleOverwriteMode()));
connect(sciEdit, SIGNAL(textChanged()), this, SLOT(updateApplyButton()));
connect(sciEdit, SIGNAL(textChanged()), this, SLOT(editTextChanged()));
connect(ui->qtEdit, SIGNAL(textChanged()), this, SLOT(updateApplyButton()));
connect(hexEdit, SIGNAL(dataChanged()), this, SLOT(updateApplyButton()));
// Create shortcuts for the widgets that doesn't have its own print action or printing mechanism.
QShortcut* shortcutPrint = new QShortcut(QKeySequence::Print, this, nullptr, nullptr, Qt::WidgetShortcut);
connect(shortcutPrint, &QShortcut::activated, this, &EditDialog::openPrintDialog);
// Add actions to editors that have a context menu based on actions. This also activates the shortcuts.
ui->editorImage->addAction(ui->actionPrintImage);
ui->editorBinary->addAction(ui->actionPrint);
ui->editorBinary->addAction(ui->actionCopyHexAscii);
mustIndentAndCompact = Settings::getValue("databrowser", "indent_compact").toBool();
ui->actionIndent->setChecked(mustIndentAndCompact);
ui->buttonAutoSwitchMode->setChecked(Settings::getValue("databrowser", "auto_switch_mode").toBool());
ui->actionWordWrap->setChecked(Settings::getValue("databrowser", "editor_word_wrap").toBool());
setWordWrapping(ui->actionWordWrap->isChecked());
reloadSettings();
}
EditDialog::~EditDialog()
{
Settings::setValue("databrowser", "indent_compact", mustIndentAndCompact);
Settings::setValue("databrowser", "auto_switch_mode", ui->buttonAutoSwitchMode->isChecked());
Settings::setValue("databrowser", "editor_word_wrap", ui->actionWordWrap->isChecked());
delete ui;
}
void EditDialog::setCurrentIndex(const QModelIndex& idx)
{
currentIndex = QPersistentModelIndex(idx);
QByteArray bArrData = idx.data(Qt::EditRole).toByteArray();
loadData(bArrData);
updateCellInfoAndMode(bArrData);
ui->buttonApply->setDisabled(true);
}
void EditDialog::showEvent(QShowEvent*)
{
// Whenever the dialog is shown, position it at the center of the parent dialog
QMainWindow* parentDialog = qobject_cast<QMainWindow*>(parent());
if(parentDialog)
{
move(parentDialog->x() + parentDialog->width() / 2 - width() / 2,
parentDialog->y() + parentDialog->height() / 2 - height() / 2);
}
}
void EditDialog::reject()
{
// We override this, to ensure the Escape key doesn't make the Edit Cell
// dock go away
return;
}
// Loads data from a cell into the Edit Cell window
void EditDialog::loadData(const QByteArray& bArrdata)
{
QImage img;
QString textData;
// Clear previously removed BOM
removedBom.clear();
// Determine the data type, saving that info in the class variable
dataType = checkDataType(bArrdata);
// Get the current editor mode (eg text, hex, image, json or xml mode)
int editMode = ui->comboMode->currentIndex();
// Data type specific handling
switch (dataType) {
case Null:
// Set enabled the text widget
sciEdit->setEnabled(true);
switch (editMode) {
case TextEditor:
case JsonEditor:
case XmlEditor:
// The JSON widget buffer is now the main data source
dataSource = SciBuffer;
// Empty the text editor contents, then enable text editing
sciEdit->clear();
break;
case RtlTextEditor:
// The text widget buffer is now the main data source
dataSource = QtBuffer;
// Empty the Qt text editor contents, then enable text editing
ui->qtEdit->clear();
break;
case HexEditor:
// The hex widget buffer is now the main data source
dataSource = HexBuffer;
// Load the Null into the hex editor
hexEdit->setData(bArrdata);
break;
case ImageViewer:
// The hex widget buffer is now the main data source
dataSource = HexBuffer;
// Clear any image from the image viewing widget
ui->editorImage->setPixmap(QPixmap(0,0));
// Load the Null into the hex editor
hexEdit->setData(bArrdata);
break;
}
break;
case Text:
case RtlText:
case JSON:
case XML:
// Can be stored in any widget, except the ImageViewer
switch (editMode) {
case TextEditor:
case JsonEditor:
case XmlEditor:
setDataInBuffer(bArrdata, SciBuffer);
break;
case RtlTextEditor:
setDataInBuffer(bArrdata, QtBuffer);
break;
case HexEditor:
setDataInBuffer(bArrdata, HexBuffer);
break;
case ImageViewer:
// The image viewer cannot hold data nor display text.
// Clear any image from the image viewing widget
ui->editorImage->setPixmap(QPixmap(0,0));
// Load the text into the text editor
setDataInBuffer(bArrdata, SciBuffer);
break;
}
break;
case Image:
// Image data is kept in the hex widget, mainly for safety. If we
// stored it in the editorImage widget instead, it would be a pixmap
// and there's no good way to restore that back to the original
// (pristine) image data. eg image metadata would be lost
setDataInBuffer(bArrdata, HexBuffer);
// Update the display if in text edit or image viewer mode
switch (editMode) {
case TextEditor:
case XmlEditor:
case JsonEditor:
// Disable text editing, and use a warning message as the contents
sciEdit->setText(tr("Image data can't be viewed in this mode.") % '\n' %
tr("Try switching to Image or Binary mode."));
sciEdit->setTextInMargin(tr("Image"));
sciEdit->setEnabled(false);
break;
case RtlTextEditor:
// Disable text editing, and use a warning message as the contents
ui->qtEdit->setText(QString("<i>" %
tr("Image data can't be viewed in this mode.") % "<br/>" %
tr("Try switching to Image or Binary mode.") %
"</i>"));
ui->qtEdit->setEnabled(false);
break;
case ImageViewer:
// Load the image into the image viewing widget
if (img.loadFromData(bArrdata)) {
ui->editorImage->setPixmap(QPixmap::fromImage(img));
}
break;
}
break;
case SVG:
// Set the XML data in any buffer or update image in image viewer mode
switch (editMode) {
case TextEditor:
case JsonEditor:
case XmlEditor:
setDataInBuffer(bArrdata, SciBuffer);
break;
case HexEditor:
setDataInBuffer(bArrdata, HexBuffer);
break;
case ImageViewer:
// Set data in the XML (Sci) Buffer and load the SVG Image
setDataInBuffer(bArrdata, SciBuffer);
sciEdit->setLanguage(DockTextEdit::XML);
// Load the image into the image viewing widget
if (img.loadFromData(bArrdata)) {
ui->editorImage->setPixmap(QPixmap::fromImage(img));
}
break;
case RtlTextEditor:
setDataInBuffer(bArrdata, QtBuffer);
break;
}
break;
default:
// The data seems to be general binary data, which is always loaded
// into the hex widget (the only safe place for it)
// Load the data into the hex buffer
setDataInBuffer(bArrdata, HexBuffer);
switch (editMode) {
case TextEditor:
case JsonEditor:
case XmlEditor:
// Disable text editing, and use a warning message as the contents
sciEdit->setText(QString(tr("Binary data can't be viewed in this mode.") % '\n' %
tr("Try switching to Binary mode.")));
sciEdit->setTextInMargin(Settings::getValue("databrowser", "blob_text").toString());
sciEdit->setEnabled(false);
break;
case RtlTextEditor:
// Disable text editing, and use a warning message as the contents
ui->qtEdit->setText(QString("<i>" %
tr("Binary data can't be viewed in this mode.") % "<br/>" %
tr("Try switching to Binary mode.") %
"</i>"));
ui->qtEdit->setEnabled(false);
break;
case ImageViewer:
// Clear any image from the image viewing widget
ui->editorImage->setPixmap(QPixmap(0,0));
break;
}
}
}
void EditDialog::importData()
{
// Get list of supported image file formats to include them in the file dialog filter
QString image_formats;
QList<QByteArray> image_formats_list = QImageReader::supportedImageFormats();
for(int i=0;i<image_formats_list.size();++i)
image_formats.append(QString("*.%1 ").arg(QString::fromUtf8(image_formats_list.at(i))));
// Chop last space
image_formats.chop(1);
QStringList filters;
filters << FILE_FILTER_TXT
<< FILE_FILTER_JSON
<< FILE_FILTER_XML
<< tr("Image files (%1)").arg(image_formats)
<< FILE_FILTER_BIN
<< FILE_FILTER_ALL;
QString selectedFilter;
// Get the current editor mode (eg text, hex, image, json or xml mode)
int mode = ui->comboMode->currentIndex();
// Set as selected filter the appropriate for the current mode.
switch (mode) {
case TextEditor:
case RtlTextEditor:
selectedFilter = FILE_FILTER_TXT;
break;
case HexEditor:
selectedFilter = FILE_FILTER_BIN;
break;
case ImageViewer:
selectedFilter = tr("Image files (%1)").arg(image_formats);
break;
case JsonEditor:
selectedFilter = FILE_FILTER_JSON;
break;
case XmlEditor:
selectedFilter = FILE_FILTER_XML;
break;
}
QString fileName = FileDialog::getOpenFileName(
OpenDataFile,
this,
tr("Choose a file to import")
#ifndef Q_OS_MAC // Filters on OS X are buggy
, filters.join(";;")
, &selectedFilter
#endif
);
if(QFile::exists(fileName))
{
QFile file(fileName);
if(file.open(QIODevice::ReadOnly))
{
QByteArray d = file.readAll();
loadData(d);
file.close();
// Update the cell data info in the bottom left of the Edit Cell
// and update mode (if required) to the just imported data type.
updateCellInfoAndMode(d);
}
}
}
void EditDialog::exportData()
{
QStringList filters;
switch (dataType) {
case Image: {
// Images get special treatment.
// Determine the likely filename extension.
QByteArray cellData = hexEdit->data();
QBuffer imageBuffer(&cellData);
QImageReader imageReader(&imageBuffer);
QString imageFormat = imageReader.format();
filters << tr("%1 Image").arg(imageFormat.toUpper()) % " (*." % imageFormat.toLower() % ")";
break;
}
case Binary:
filters << tr("Binary files (*.bin)");
break;
case RtlText:
case Text:
// Include the XML case on the text data type, since XML detection is not very sofisticated.
if (ui->comboMode->currentIndex() == XmlEditor)
filters << FILE_FILTER_XML
<< FILE_FILTER_TXT;
else
filters << FILE_FILTER_TXT
<< FILE_FILTER_XML;
break;
case JSON:
filters << FILE_FILTER_JSON;
break;
case SVG:
filters << FILE_FILTER_SVG;
break;
case XML:
filters << FILE_FILTER_XML;
break;
case Null:
return;
}
if (dataSource == HexBuffer)
filters << FILE_FILTER_HEX;
filters << FILE_FILTER_ALL;
QString selectedFilter = filters.first();
QString fileName = FileDialog::getSaveFileName(
CreateDataFile,
this,
tr("Choose a filename to export data"),
filters.join(";;"),
/* defaultFileName */ QString(),
&selectedFilter);
if(fileName.size() > 0)
{
QFile file(fileName);
if(file.open(QIODevice::WriteOnly))
{
switch (dataSource) {
case HexBuffer:
// Data source is the hex buffer
// If text option has been selected, the readable representation of the content is saved to file.
if (selectedFilter == FILE_FILTER_HEX)
file.write(hexEdit->toReadableString().toUtf8());
else
file.write(hexEdit->data());
break;
case SciBuffer:
// Data source is the Scintilla buffer
file.write(sciEdit->text().toUtf8());
break;
case QtBuffer:
// Data source is the text buffer
file.write(ui->qtEdit->toPlainText().toUtf8());
break;
}
file.close();
}
}
}
void EditDialog::setNull()
{
ui->qtEdit->clear();
ui->editorImage->clear();
hexEdit->setData(QByteArray());
sciEdit->clear();
dataType = Null;
removedBom.clear();
// The text editors don't know the difference between an empty string
// and a NULL, so we need to record NULL outside of that
dataType = Null;
// Ensure the text (Scintilla) editor is enabled
sciEdit->setEnabled(true);
// Update the cell data info in the bottom left of the Edit Cell
// The mode is also (if required) updated to text since it gives
// the better visual clue of containing a NULL value (placeholder).
updateCellInfoAndMode(hexEdit->data());
sciEdit->setFocus();
}
void EditDialog::updateApplyButton()
{
if (!isReadOnly)
ui->buttonApply->setEnabled(true);
}
bool EditDialog::promptInvalidData(const QString& data_type, const QString& errorString)
{
QMessageBox::StandardButton reply = QMessageBox::question(
this,
tr("Invalid data for this mode"),
tr("The cell contains invalid %1 data. Reason: %2. Do you really want to apply it to the cell?").arg(data_type, errorString),
QMessageBox::Apply | QMessageBox::Cancel);
return (reply == QMessageBox::Apply);
}
void EditDialog::accept()
{
if(!currentIndex.isValid())
return;
if (dataType == Null) {
emit recordTextUpdated(currentIndex, hexEdit->data(), true);
return;
}
// New data for the plain text cases. This is processed after the case.
QString newTextData;
switch (dataSource) {
case QtBuffer:
newTextData = removedBom + ui->qtEdit->toPlainText();
break;
case SciBuffer:
switch (sciEdit->language()) {
case DockTextEdit::PlainText:
newTextData = removedBom + sciEdit->text();
break;
case DockTextEdit::JSON:
{
sciEdit->clearErrorIndicators();
QString oldData = currentIndex.data(Qt::EditRole).toString();
QString newData;
bool proceed = true;
json jsonDoc;
try {
jsonDoc = json::parse(sciEdit->text().toStdString());
} catch(json::parse_error& parseError) {
sciEdit->setErrorIndicator(static_cast<int>(parseError.byte - 1));
proceed = promptInvalidData("JSON", parseError.what());
}
if (!jsonDoc.is_null()) {
if (mustIndentAndCompact)
// Compact the JSON data before storing
newData = QString::fromStdString(jsonDoc.dump());
else
newData = sciEdit->text();
} else {
newData = sciEdit->text();
}
proceed = proceed && (oldData != newData);
if (proceed)
// The data is different, so commit it back to the database
emit recordTextUpdated(currentIndex, newData.toUtf8(), false);
}
break;
case DockTextEdit::XML:
{
QString oldData = currentIndex.data(Qt::EditRole).toString();
QString newData;
QDomDocument xmlDoc;
QString errorMsg;
int errorLine, errorColumn;
bool isValid = xmlDoc.setContent(sciEdit->text().toUtf8(), true, &errorMsg, &errorLine, &errorColumn);
bool proceed;
sciEdit->clearErrorIndicators();
if (!isValid) {
sciEdit->setErrorIndicator(errorLine-1, errorColumn-1, errorLine, 0);
newData = sciEdit->text();
proceed = (oldData != newData && promptInvalidData("XML", errorMsg));
} else {
if (mustIndentAndCompact)
// Compact the XML data before storing. If indent is -1, no whitespace at all is added.
newData = xmlDoc.toString(-1);
else
newData = sciEdit->text();
proceed = (oldData != newData);
}
if (proceed)
// The data is different, so commit it back to the database
emit recordTextUpdated(currentIndex, newData.toUtf8(), false);
}
break;
}
break;
case HexBuffer:
// The data source is the hex widget buffer, thus binary data
QByteArray oldData = currentIndex.data(Qt::EditRole).toByteArray();
QByteArray newData = hexEdit->data();
if (newData != oldData)
emit recordTextUpdated(currentIndex, newData, true);
break;
}
if (!newTextData.isEmpty()) {
QString oldData = currentIndex.data(Qt::EditRole).toString();
// Check first for null case, otherwise empty strings cannot overwrite NULL values
if ((currentIndex.data(Qt::EditRole).isNull() && dataType != Null) || oldData != newTextData)
// The data is different, so commit it back to the database
emit recordTextUpdated(currentIndex, removedBom + newTextData.toUtf8(), false);
}
}
void EditDialog::setDataInBuffer(const QByteArray& bArrdata, DataSources source)
{
dataSource = source;
QString textData;
// 1) Perform validation and text formatting (if applicable).
// 2) Set the text in the corresponding editor widget (the text widget for the Image case).
// 3) Enable the widget.
switch (dataSource) {
case QtBuffer:
{
// Load the text into the text editor, remove BOM first if there is one
QByteArray dataWithoutBom = bArrdata;
removedBom = removeBom(dataWithoutBom);
textData = QString::fromUtf8(dataWithoutBom.constData(), dataWithoutBom.size());
ui->qtEdit->setPlainText(textData);
// Select all of the text by default (this is useful for simple text data that we usually edit as a whole).
// We don't want this when the QtBuffer has been automatically switched due to the insertion of RTL text,
// (detected through the state of the apply button) otherwise that would break the typing flow of the user.
if (!isReadOnly)
if (!ui->buttonApply->isEnabled())
ui->qtEdit->selectAll();
else
ui->qtEdit->moveCursor(QTextCursor::End);
ui->qtEdit->setEnabled(true);
break;
}
case SciBuffer:
switch (sciEdit->language()) {
case DockTextEdit::PlainText:
{
// Load the text into the text editor, remove BOM first if there is one
QByteArray dataWithoutBom = bArrdata;
removedBom = removeBom(dataWithoutBom);
textData = QString::fromUtf8(dataWithoutBom.constData(), dataWithoutBom.size());
sciEdit->setText(textData);
// Select all of the text by default (this is useful for simple text data that we usually edit as a whole)
if (!isReadOnly)
sciEdit->selectAll();
sciEdit->setEnabled(true);
break;
}
case DockTextEdit::JSON:
{
sciEdit->clearErrorIndicators();
json jsonDoc;
try {
jsonDoc = json::parse(std::string(bArrdata.constData(), static_cast<size_t>(bArrdata.size())));
} catch(json::parse_error& parseError) {
sciEdit->setErrorIndicator(static_cast<int>(parseError.byte - 1));
}
if (mustIndentAndCompact && !jsonDoc.is_null() && !jsonDoc.is_discarded()) {
// Load indented JSON into the JSON editor
textData = QString::fromStdString(jsonDoc.dump(4));
} else {
// Fallback case. The data is not yet valid JSON or no auto-formatting applied.
textData = QString::fromUtf8(bArrdata.constData(), bArrdata.size());
}
sciEdit->setText(textData);
sciEdit->setEnabled(true);
}
break;
case DockTextEdit::XML:
{
QString errorMsg;
int errorLine, errorColumn;
QDomDocument xmlDoc;
bool isValid = xmlDoc.setContent(bArrdata, true, &errorMsg, &errorLine, &errorColumn);
if (mustIndentAndCompact && isValid) {
// Load indented XML into the XML editor
textData = xmlDoc.toString(Settings::getValue("editor", "tabsize").toInt());
} else {
// Fallback case. The data is not yet valid JSON or no auto-formatting applied.
textData = QString::fromUtf8(bArrdata.constData(), bArrdata.size());
}
sciEdit->setText(textData);
sciEdit->clearErrorIndicators();
if (!isValid)
// Adjust line and column by one (Scintilla starts at 1 and QDomDocument at 0)
sciEdit->setErrorIndicator(errorLine-1, errorColumn-1, errorLine, 0);
sciEdit->setEnabled(true);
}
break;
}
break;
case HexBuffer:
hexEdit->setData(bArrdata);
hexEdit->setEnabled(true);
break;
}
}
// Called when the user manually changes the "Mode" drop down combobox
void EditDialog::editModeChanged(int newMode)
{
ui->actionIndent->setEnabled(newMode == JsonEditor || newMode == XmlEditor);
setStackCurrentIndex(newMode);
// * If the dataSource is the text buffer, the data is always text *
switch (dataSource) {
case QtBuffer:
switch (newMode) {
case RtlTextEditor: // Switching to the RTL text editor
// Nothing to do, as the text is already in the Qt buffer
break;
case TextEditor: // Switching to one of the Scintilla editor modes
case JsonEditor:
case XmlEditor:
setDataInBuffer(ui->qtEdit->toPlainText().toUtf8(), SciBuffer);
break;
case HexEditor: // Switching to the hex editor
// Convert the text widget buffer for the hex widget
// The hex widget buffer is now the main data source
setDataInBuffer(removedBom + ui->qtEdit->toPlainText().toUtf8(), HexBuffer);
break;
case ImageViewer:
// Clear any image from the image viewing widget
ui->editorImage->setPixmap(QPixmap(0,0));
break;
}
break;
case HexBuffer:
// * If the dataSource is the hex buffer, the contents could be anything
// so we just pass it to our loadData() function to handle *
// Note that we have already set the editor, as loadData() relies on it
// being current
// Load the data into the appropriate widget, as done by loadData()
loadData(hexEdit->data());
break;
case SciBuffer:
switch (newMode) {
case RtlTextEditor: // Switching to the RTL text editor
// Convert the Scintilla widget buffer for the Qt widget
setDataInBuffer(sciEdit->text().toUtf8(), QtBuffer);
break;
case HexEditor: // Switching to the hex editor
// Convert the text widget buffer for the hex widget
setDataInBuffer(sciEdit->text().toUtf8(), HexBuffer);
break;
case ImageViewer:
{
// When SVG format, load the image, else clear it.
QByteArray bArrdata = sciEdit->text().toUtf8();
dataType = checkDataType(bArrdata);
if (dataType == SVG) {
QImage img;
if (img.loadFromData(bArrdata))
ui->editorImage->setPixmap(QPixmap::fromImage(img));
else
// Clear any image from the image viewing widget
ui->editorImage->setPixmap(QPixmap(0,0));
}
}
break;
case TextEditor: // Switching to the text editor
case JsonEditor: // Switching to the JSON editor
case XmlEditor: // Switching to the XML editor
// The text is already in the Sci buffer but we need to perform the necessary formatting.
setDataInBuffer(sciEdit->text().toUtf8(), SciBuffer);
break;
}
}
}
// Called for every keystroke in the text editor (only)
void EditDialog::editTextChanged()
{
if (dataSource == SciBuffer || dataSource == QtBuffer) {
// Update the cell info in the bottom left manually. This is because
// updateCellInfoAndMode() only works with QByteArray's (for now)
int dataLength;
bool isModified;
if(dataSource == QtBuffer) {
// QtBuffer
dataLength = ui->qtEdit->toPlainText().length();
isModified = ui->qtEdit->document()->isModified();
} else {
// SciBuffer
dataLength = sciEdit->text().length();
isModified = sciEdit->isModified();
// Switch to the Qt Editor if we detect right-to-left text,
// since the QScintilla editor does not support it.
if (containsRightToLeft(sciEdit->text()))
ui->comboMode->setCurrentIndex(RtlTextEditor);
}
// If data has been entered in the text editor, it can't be a NULL
// any more. It hasn't been validated yet, so it cannot be JSON nor XML.
if (dataType == Null && isModified && dataLength != 0)
dataType = Text;
if (dataType != Null) {
sciEdit->clearTextInMargin();
ui->labelType->setText(tr("Type of data currently in cell: Text / Numeric"));
}
ui->labelSize->setText(tr("%n character(s)", "", dataLength));
}
}
void EditDialog::setMustIndentAndCompact(bool enable)
{
mustIndentAndCompact = enable;
// Indent or compact if necessary. If data has changed (button Apply indicates so), reload from the widget, else from the table.
if (ui->buttonApply->isEnabled()) {
setDataInBuffer(sciEdit->text().toUtf8(), SciBuffer);
} else
setCurrentIndex(currentIndex);
}
// Determine the type of data in the cell
int EditDialog::checkDataType(const QByteArray& bArrdata)
{
QByteArray cellData = bArrdata;
// Check for NULL data type
if (cellData.isNull()) {
return Null;
}
// Check if it's an image. First do a quick test by calling canRead() which only checks the first couple of bytes or so. Only if
// that returned true, do a more sophisticated test of the data. This way we get both, good performance and proper data checking.
QBuffer imageBuffer(&cellData);
QImageReader readerBuffer(&imageBuffer);
QString imageFormat = readerBuffer.format();
if(readerBuffer.canRead() && !readerBuffer.read().isNull())
return imageFormat == "svg" ? SVG : Image;
// Check if it's text only
if(isTextOnly(cellData))
{
if (cellData.startsWith("<?xml"))
return XML;
auto json_parse_result = json::parse(cellData, nullptr, false);
if(!json_parse_result.is_discarded() && !json_parse_result.is_number())
return JSON;
else {
if (containsRightToLeft(QString::fromUtf8(cellData)))
return RtlText;
else
return Text;
}
}
// It's none of the above, so treat it as general binary data
return Binary;
}
void EditDialog::toggleOverwriteMode()
{
static bool currentMode = false;
currentMode = !currentMode;
hexEdit->setOverwriteMode(currentMode);
ui->qtEdit->setOverwriteMode(currentMode);
sciEdit->setOverwriteMode(currentMode);
}
void EditDialog::setFocus()
{
QDialog::setFocus();
// Set the focus to the editor widget. The idea here is that setting focus
// to the dock itself doesn't make much sense as it's just a frame; you'd
// have to tab to the editor which is what you most likely want to use. So
// in order to save the user from doing this we explicitly set the focus
// to the current editor.
int editMode = ui->editorStack->currentIndex();
switch (editMode) {
case TextEditor:
sciEdit->setFocus();
if (sciEdit->language() == DockTextEdit::PlainText && !isReadOnly)
sciEdit->selectAll();
break;
case RtlTextEditor:
ui->qtEdit->setFocus();
ui->qtEdit->selectAll();
case HexEditor:
hexEdit->setFocus();
break;
case ImageViewer:
// Nothing to do
break;
}
}
// Enables or disables the Apply, Null, & Import buttons in the Edit Cell dock.
// Sets or unsets read-only properties for the editors.
void EditDialog::setReadOnly(bool ro)
{
isReadOnly = ro;
ui->buttonApply->setEnabled(!ro);
ui->actionNull->setEnabled(!ro);
ui->actionImport->setEnabled(!ro);
ui->qtEdit->setReadOnly(ro);
sciEdit->setReadOnly(ro);
hexEdit->setReadOnly(ro);
// This makes the caret being visible for selection, although the editor is read-only. The read-only state is hinted by the
// caret not blinking. The same is done in ExtendedScintilla.
Qt::TextInteractionFlags textFlags = ro? Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard : Qt::TextEditorInteraction;
ui->qtEdit->setTextInteractionFlags(textFlags);
}
void EditDialog::switchEditorMode(bool autoSwitchForType)
{
if (autoSwitchForType) {
// Switch automatically the editing mode according to the detected data.
switch (dataType) {
case Image:
ui->comboMode->setCurrentIndex(ImageViewer);
break;
case Binary:
ui->comboMode->setCurrentIndex(HexEditor);
break;
case Null:
case Text:
ui->comboMode->setCurrentIndex(TextEditor);
break;
case RtlText:
ui->comboMode->setCurrentIndex(RtlTextEditor);
break;
case JSON:
ui->comboMode->setCurrentIndex(JsonEditor);
break;
case SVG:
case XML:
ui->comboMode->setCurrentIndex(XmlEditor);
break;
}
}
}
// Update the information labels in the bottom left corner of the dialog
// and switches the editor mode, if required, according to the detected data type.
void EditDialog::updateCellInfoAndMode(const QByteArray& bArrdata)
{
QByteArray cellData = bArrdata;
switchEditorMode(ui->buttonAutoSwitchMode->isChecked());
// Image data needs special treatment
if (dataType == Image || dataType == SVG) {
QBuffer imageBuffer(&cellData);
QImageReader imageReader(&imageBuffer);
// Display the image format
QString imageFormat = imageReader.format();
ui->labelType->setText(tr("Type of data currently in cell: %1 Image").arg(imageFormat.toUpper()));
// Display the image dimensions and size
QSize imageDimensions = imageReader.size();
int imageSize = cellData.size();
QString labelSizeText = tr("%1x%2 pixel(s)").arg(imageDimensions.width()).arg(imageDimensions.height()) + ", " + humanReadableSize(imageSize);
ui->labelSize->setText(labelSizeText);
return;
}
// Use a switch statement for the other data types to keep things neat :)
switch (dataType) {
case Null: {
// NULL data type
ui->labelType->setText(tr("Type of data currently in cell: NULL"));
ui->labelSize->setText(tr("%n byte(s)", "", 0));
// Use margin to set the NULL text.
sciEdit->setTextInMargin(Settings::getValue("databrowser", "null_text").toString());
break;
}
case XML:
case Text:
case RtlText: {
// Text only
// Determine the length of the cell text in characters (possibly different to number of bytes).
int textLength = QString(cellData).length();
ui->labelType->setText(tr("Type of data currently in cell: Text / Numeric"));
ui->labelSize->setText(tr("%n character(s)", "", textLength));
break;
}
case JSON: {
// Valid JSON
// Determine the length of the cell text in characters (possibly different to number of bytes).
int jsonLength = QString(cellData).length();
ui->labelType->setText(tr("Type of data currently in cell: Valid JSON"));
ui->labelSize->setText(tr("%n character(s)", "", jsonLength));
break;
}
default:
// Determine the length of the cell data
int dataLength = cellData.length();
// If none of the above data types, consider it general binary data
ui->labelType->setText(tr("Type of data currently in cell: Binary"));
ui->labelSize->setText(tr("%n byte(s)", "", dataLength));
break;
}
}
QString EditDialog::humanReadableSize(double byteCount) const
{
QStringList units;
units << "" << "Ki" << "Mi" << "Gi" << "Ti" << "Pi" << "Ei" << "Zi";
for(const QString& unit : units)
{
if(fabs(byteCount) < 1024.0)
{
QString size = QString::number(byteCount, 'f', 2);
return size + " " + unit + "B";
}
byteCount /= 1024.0;
}
QString yiUnit = "Yi";
QString size = QString::number(byteCount, 'f', 2);
return size + " " + yiUnit + "B";
}
void EditDialog::reloadSettings()
{
// Set the (SQL) editor font for hex editor, since it needs a
// Monospace font and the databrowser font would be usually of
// variable width.
QFont hexFont(Settings::getValue("editor", "font").toString());
hexFont.setPointSize(Settings::getValue("databrowser", "fontsize").toInt());
hexEdit->setFont(hexFont);
ui->editCellToolbar->setToolButtonStyle(static_cast<Qt::ToolButtonStyle>
(Settings::getValue("General", "toolbarStyleEditCell").toInt()));
sciEdit->reloadSettings();
}
void EditDialog::setStackCurrentIndex(int editMode)
{
switch (editMode) {
case TextEditor:
// Scintilla case: switch to the single Scintilla editor and set language
ui->editorStack->setCurrentIndex(TextEditor);
sciEdit->setLanguage(DockTextEdit::PlainText);
break;
case HexEditor:
case ImageViewer:
case RtlTextEditor:
// General case: switch to the selected editor
ui->editorStack->setCurrentIndex(editMode);
break;
case JsonEditor:
// Scintilla case: switch to the single Scintilla editor and set language
ui->editorStack->setCurrentIndex(TextEditor);
sciEdit->setLanguage(DockTextEdit::JSON);
break;
case XmlEditor:
// Scintilla case: switch to the single Scintilla editor and set language
ui->editorStack->setCurrentIndex(TextEditor);
sciEdit->setLanguage(DockTextEdit::XML);
break;
}
}
void EditDialog::openPrintDialog()
{
int editMode = ui->editorStack->currentIndex();
if (editMode == ImageViewer) {
openPrintImageDialog();
return;
}
QPrinter printer;
QPrintPreviewDialog *dialog = new QPrintPreviewDialog(&printer);
QTextDocument *document = new QTextDocument();
switch (dataSource) {
case SciBuffer:
// This case isn't really expected because the Scintilla widget has it's own printing slot
document->setPlainText(sciEdit->text());
break;
case HexBuffer:
document->setPlainText(hexEdit->toReadableString());
document->setDefaultFont(hexEdit->font());
break;
case QtBuffer:
document->setPlainText(ui->qtEdit->toPlainText());
break;
}
connect(dialog, &QPrintPreviewDialog::paintRequested, [&](QPrinter *previewPrinter) {
document->print(previewPrinter);
});
dialog->exec();
delete dialog;
delete document;
}
void EditDialog::openPrintImageDialog()
{
QPrinter printer;
QPrintPreviewDialog *dialog = new QPrintPreviewDialog(&printer);
connect(dialog, &QPrintPreviewDialog::paintRequested, [&](QPrinter *previewPrinter) {
QPainter painter(previewPrinter);
QRect rect = painter.viewport();
QSize size = ui->editorImage->pixmap()->size();
size.scale(rect.size(), Qt::KeepAspectRatio);
painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
painter.setWindow(ui->editorImage->pixmap()->rect());
painter.drawPixmap(0, 0, *ui->editorImage->pixmap());
});
dialog->exec();
delete dialog;
}
void EditDialog::copyHexAscii()
{
QApplication::clipboard()->setText(hexEdit->selectionToReadableString());
}
void EditDialog::setWordWrapping(bool value)
{
// Set wrap lines
sciEdit->setWrapMode(value ? QsciScintilla::WrapWord : QsciScintilla::WrapNone);
ui->qtEdit->setWordWrapMode(value ? QTextOption::WrapAtWordBoundaryOrAnywhere : QTextOption::NoWrap);
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

Official home of the DB Browser for SQLite (DB4S) project. Previously known as "SQLite Database Browser" and "Database Browser for SQLite". Website at:
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/my_open_source_software/sqlitebrowser.git
git@gitee.com:my_open_source_software/sqlitebrowser.git
my_open_source_software
sqlitebrowser
sqlitebrowser
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /