forked from kambala-decapitator/QTblEditor
/
qtbleditor.cpp
1412 lines (1227 loc) · 52.7 KB
/
qtbleditor.cpp
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 "qtbleditor.h"
#include "gotorowdialog.h"
#include "tablepanelwidget.h"
#include "findreplacedialog.h"
#include <QMainWindow>
#include <QCloseEvent>
#include <QLabel>
#include <QSplitter>
#include <QMessageBox>
#include <QFileDialog>
#include <QSpinBox>
#include <QTextEdit>
#include <QInputDialog>
#include <QScrollBar>
#include <QClipboard>
#include <QListWidget>
#include <QTextStream>
#include <QSettings>
#include <QFileInfo>
#include <QMimeData>
#include <QDateTime>
#include <QNetworkReply>
#ifndef QT_NO_DEBUG
#include <QDebug>
#endif
static const QString kNewTblFileName("!newstring!.tbl"), kCustomColorsFileName("customcolors.ini");
const int kMaxRecentFiles = 10;
// global auxiliary functions
#define CONNECT_ACTION_TO_SLOT(action, slot) connect(action, SIGNAL(triggered()), slot)
QDataStream &operator <<(QDataStream &out, const TblHeader &th)
{
return out << th.CRC << th.NodesNumber << th.HashTableSize << th.Version << th.DataStartOffset << th.HashMaxTries
<< th.FileSize;
}
QDataStream &operator <<(QDataStream &out, const TblHashNode &tn)
{
return out << tn.Active << tn.Index << tn.HashValue << tn.StringKeyOffset << tn.StringValOffset << tn.StringValLength;
}
// end of global auxiliary functions
extern QList<QChar> colorCodes;
extern QStringList colorStrings;
extern QList<QColor> colors;
extern QString colorHeader;
extern int colorsNum;
QTblEditor::QTblEditor(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(parent, flags), _openedTables(0), _isTableLoaded(false)
{
ui.setupUi(this);
ui.mainToolBar->setWindowTitle(tr("Toolbar"));
#ifdef Q_OS_MAC
ui.actionInsertAfterCurrent->setShortcut(QKeySequence("+"));
ui.actionAppendEntry->setShortcut(QKeySequence("Ctrl++"));
ui.actionGoTo->setShortcut(QKeySequence("Ctrl+L"));
#else
ui.actionGoTo->setShortcut(QKeySequence("Ctrl+G"));
#endif
ui.actionSwap->setShortcut(QKeySequence("Meta+Tab"));
ui.actionChangeActive->setShortcut(QKeySequence("Tab"));
QActionGroup *csvSeparators = new QActionGroup(this);
csvSeparators->addAction(ui.actionCsvComma);
csvSeparators->addAction(ui.actionCsvSemiColon);
QList<QAction *> diffActions = QList<QAction *>() << ui.actionKeys << ui.actionStrings << ui.actionBoth << ui.actionSameStrings;
for (int i = 0; i < diffActions.size(); ++i)
diffActions[i]->setData(i);
_locationLabel = new QLabel("00000 (0x00000) / 00000 (0x00000)", this);
_locationLabel->setToolTip(tr("Current row / total rows"));
_locationLabel->setAlignment(Qt::AlignHCenter);
_locationLabel->setMinimumSize(_locationLabel->sizeHint());
_locationLabel->clear();
_keyHashLabel = new QLabel("0x00000 | 0x00000", this);
_keyHashLabel->setToolTip(tr("Key hash value"));
_keyHashLabel->setAlignment(Qt::AlignHCenter);
_keyHashLabel->setMinimumSize(_keyHashLabel->sizeHint());
_keyHashLabel->clear();
#ifndef Q_OS_MAC
ui.statusBar->addWidget(new QLabel, 1);
#endif
ui.statusBar->addPermanentWidget(_keyHashLabel);
ui.statusBar->addPermanentWidget(_locationLabel);
_leftTablePanelWidget = new TablePanelWidget(this);
_rightTablePanelWidget = new TablePanelWidget(this);
_leftTableWidget = _leftTablePanelWidget->tableWidget();
_rightTableWidget = _rightTablePanelWidget->tableWidget();
_rightTablePanelWidget->hide();
_tableSplitter = new QSplitter(Qt::Horizontal, this);
_tableSplitter->addWidget(_leftTablePanelWidget);
_tableSplitter->addWidget(_rightTablePanelWidget);
_tableSplitter->setChildrenCollapsible(false);
setCentralWidget(_tableSplitter);
_findReplaceDlg = new FindReplaceDialog(this);
_startNumberingGroup = new QActionGroup(this);
_startNumberingGroup->addAction(ui.actionStartNumberingFrom0);
_startNumberingGroup->addAction(ui.actionStartNumberingFrom1);
connectActions();
connect(ui.menuView, SIGNAL(aboutToShow()), SLOT(updateToolbarStateInMenu()));
connect(_leftTableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem *)), SLOT(editString(QTableWidgetItem *)));
connect(_leftTableWidget, SIGNAL(currentCellChanged(int, int, int, int)), SLOT(updateLocationLabel(int)));
connect(_leftTableWidget, SIGNAL(tableGotFocus(QWidget *)), SLOT(changeCurrentTable(QWidget *)));
connect(_leftTableWidget, SIGNAL(itemChanged(QTableWidgetItem *)), SLOT(updateItem(QTableWidgetItem *)));
connect(_rightTableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem *)), SLOT(editString(QTableWidgetItem *)));
connect(_rightTableWidget, SIGNAL(currentCellChanged(int, int, int, int)), SLOT(updateLocationLabel(int)));
connect(_rightTableWidget, SIGNAL(tableGotFocus(QWidget *)), SLOT(changeCurrentTable(QWidget *)));
connect(_rightTableWidget, SIGNAL(itemChanged(QTableWidgetItem *)), SLOT(updateItem(QTableWidgetItem *)));
connect(ui.actionShowHexInRow, SIGNAL(toggled(bool)), _leftTableWidget, SLOT(toggleDisplayHex(bool)));
connect(ui.actionShowHexInRow, SIGNAL(toggled(bool)), _rightTableWidget, SLOT(toggleDisplayHex(bool)));
connect(ui.actionStartNumberingFrom1, SIGNAL(toggled(bool)), _leftTableWidget, SLOT(changeRowNumberingTo1(bool)));
connect(ui.actionStartNumberingFrom1, SIGNAL(toggled(bool)), _rightTableWidget, SLOT(changeRowNumberingTo1(bool)));
connect(_findReplaceDlg, SIGNAL(getStrings(QString, bool, bool, bool)), SLOT(findNextString(QString, bool, bool, bool)));
connect(_findReplaceDlg, SIGNAL(currentItemChanged(QTableWidgetItem *)), SLOT(changeCurrentTableItem(QTableWidgetItem *)));
_currentTableWidget = _leftTableWidget;
readSettings();
updateRecentFilesActions();
_leftTableWidget->changeRowHeaderDisplay();
_rightTableWidget->changeRowHeaderDisplay();
}
void QTblEditor::connectActions()
{
CONNECT_ACTION_TO_SLOT(ui.actionNew, SLOT(newTable()));
CONNECT_ACTION_TO_SLOT(ui.actionOpen, SLOT(open()));
CONNECT_ACTION_TO_SLOT(ui.actionReopen, SLOT(reopen()));
CONNECT_ACTION_TO_SLOT(ui.actionSendToServer, SLOT(sendToServer()));
CONNECT_ACTION_TO_SLOT(ui.actionSave, SLOT(save()));
CONNECT_ACTION_TO_SLOT(ui.actionSaveAs, SLOT(saveAs()));
CONNECT_ACTION_TO_SLOT(ui.actionSaveAll, SLOT(saveAll()));
CONNECT_ACTION_TO_SLOT(ui.actionClose, SLOT(closeTable()));
CONNECT_ACTION_TO_SLOT(ui.actionCloseAll, SLOT(closeAll()));
CONNECT_ACTION_TO_SLOT(ui.actionChangeText, SLOT(changeText()));
CONNECT_ACTION_TO_SLOT(ui.actionAppendEntry, SLOT(appendEntry()));
CONNECT_ACTION_TO_SLOT(ui.actionInsertAfterCurrent, SLOT(insertAfterCurrent()));
CONNECT_ACTION_TO_SLOT(ui.actionClearSelected, SLOT(deleteSelectedItems()));
CONNECT_ACTION_TO_SLOT(ui.actionDeleteSelected, SLOT(deleteSelectedItems()));
CONNECT_ACTION_TO_SLOT(ui.actionCopy, SLOT(copy()));
CONNECT_ACTION_TO_SLOT(ui.actionPaste, SLOT(paste()));
CONNECT_ACTION_TO_SLOT(ui.actionFindReplace, SLOT(showFindReplaceDialog()));
CONNECT_ACTION_TO_SLOT(ui.actionGoTo, SLOT(goTo()));
connect(ui.actionToolbar, SIGNAL(toggled(bool)), ui.mainToolBar, SLOT(setVisible(bool)));
connect(ui.actionSmallRows, SIGNAL(toggled(bool)), SLOT(toggleRowsHeight(bool)));
CONNECT_ACTION_TO_SLOT(ui.actionSupplement, SLOT(supplement()));
CONNECT_ACTION_TO_SLOT(ui.actionSwap, SLOT(swapTables()));
CONNECT_ACTION_TO_SLOT(ui.actionChangeActive, SLOT(activateAnotherTable()));
CONNECT_ACTION_TO_SLOT(ui.actionKeys, SLOT(showDifferences()));
CONNECT_ACTION_TO_SLOT(ui.actionStrings, SLOT(showDifferences()));
CONNECT_ACTION_TO_SLOT(ui.actionBoth, SLOT(showDifferences()));
CONNECT_ACTION_TO_SLOT(ui.actionSameStrings, SLOT(showDifferences()));
connect(ui.actionSyncScrolling, SIGNAL(toggled(bool)), SLOT(syncScrollingChanged(bool)));
CONNECT_ACTION_TO_SLOT(ui.actionAbout, SLOT(aboutApp()));
connect(ui.actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
void QTblEditor::updateRecentFilesActions()
{
ui.menuRecentFiles->clear();
if (!_recentFilesList.isEmpty())
{
ui.menuRecentFiles->setEnabled(true);
QMutableStringListIterator i(_recentFilesList);
while (i.hasNext())
{
QString filePath = i.next();
if (QFile::exists(filePath))
ui.menuRecentFiles->addAction(
#ifdef Q_OS_WIN32
QDir::toNativeSeparators(filePath),
#else
filePath,
#endif
this, SLOT(openRecentFile()));
else
i.remove();
}
}
else
ui.menuRecentFiles->setEnabled(false);
}
int QTblEditor::openTableMsgBoxResult()
{
QMessageBox openOptsDlg(this);
openOptsDlg.setIcon(QMessageBox::Question);
openOptsDlg.setDefaultButton(openOptsDlg.addButton(tr("Open one more"), QMessageBox::AcceptRole));
openOptsDlg.setEscapeButton(openOptsDlg.addButton(QMessageBox::Cancel));
openOptsDlg.addButton(tr("Replace active"), QMessageBox::NoRole);
openOptsDlg.setText(tr("How do you want to open the table?"));
#ifdef Q_OS_MAC
openOptsDlg.setWindowModality(Qt::WindowModal);
#endif
return openOptsDlg.exec();
}
void QTblEditor::tableMenuSetEnabled(bool isEnabled)
{
ui.menuTables->setEnabled(isEnabled);
foreach (QAction *action, ui.menuTables->actions())
action->setEnabled(isEnabled);
}
void QTblEditor::newTable()
{
bool okPressed;
int rowsNum = QInputDialog::getInt(this, tr("New table"), tr("Enter desired number of rows (1-100000):"), 1, 1, 100000, 1, &okPressed);
if (okPressed)
{
bool areTwoTablesOpened = _openedTables == 2;
int result = -1;
if (_openedTables == 1)
{
result = openTableMsgBoxResult(); // 0 - add one more, 1 - replace active, rest - cancel
if (result != 0 && result != 1)
return;
}
if (result && !currentTablePanelWidget()->absoluteFileName().isEmpty() && !closeTable())
return;
if (!result || (result == -1 && areTwoTablesOpened))
{
activateAnotherTable();
currentTablePanelWidget()->show();
inactiveNamedTableWidget(currentTablePanelWidget())->setActive(false);
tableMenuSetEnabled(true);
closeAllDialogs();
}
if (!_openedTables || (_openedTables == 1 && (!result || result == -1)))
_openedTables++;
_currentTableWidget->setRowCount(rowsNum);
currentTablePanelWidget()->updateRowCountLabel();
for (int i = 0; i < rowsNum; i++)
_currentTableWidget->createNewEntry(i, QString(), QString());
currentTablePanelWidget()->setFilePath(kNewTblFileName);
currentTablePanelWidget()->setActive(true);
_currentTableWidget->setCurrentCell(0, 0, QItemSelectionModel::Select);
updateWindow();
enableTableActions(true);
ui.actionSaveAll->setEnabled(true);
}
}
void QTblEditor::openRecentFile()
{
QAction *action = qobject_cast<QAction *>(sender());
#ifdef Q_OS_WIN32
QString fileName = QDir::fromNativeSeparators(action->text());
#else
QString fileName = action->text();
#endif
if (loadFile(fileName))
{
_recentFilesList.move(_recentFilesList.indexOf(fileName), 0);
updateRecentFilesActions();
}
}
void QTblEditor::addToRecentFiles(const QString &fileName)
{
int index = _recentFilesList.indexOf(fileName);
if (index != -1) // it's already in the list
_recentFilesList.move(index, 0);
else
{
if (_recentFilesList.length() == kMaxRecentFiles)
_recentFilesList.removeLast();
_recentFilesList.prepend(fileName);
}
updateRecentFilesActions();
}
void QTblEditor::open()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open table file"), _lastPath,
tr("All supported formats (*.tbl *.txt *.csv);;Tbl files (*.tbl);;Tab-delimited txt files (*.txt);;CSV files (*.csv);;All files (*)"));
if (!fileName.isEmpty() && loadFile(fileName))
{
addToRecentFiles(fileName);
_findReplaceDlg->needsRefind();
}
}
void QTblEditor::reopen()
{
if (processTable(currentTablePanelWidget()->absoluteFileName()))
{
updateWindow(false);
setWindowModified(_leftTableWidget->isWindowModified() && _rightTableWidget->isWindowModified());
updateLocationLabel(_currentTableWidget->currentRow());
}
}
void QTblEditor::sendToServer()
{
QSettings settings;
QString url = settings.value("serverUrl").toString();
if (url.isEmpty())
{
url = QInputDialog::getText(this, tr("Server URL"), QString());
if (url.isEmpty())
return;
settings.setValue("serverUrl", url);
}
// force wrapping in quotes
bool wrapCurrent = ui.actionWrapStrings->isChecked();
ui.actionWrapStrings->setChecked(true);
QByteArray data;
writeAsText(data, false);
ui.actionWrapStrings->setChecked(wrapCurrent);
QNetworkRequest request(QUrl(url + "?name=" + QFileInfo(currentTablePanelWidget()->absoluteFileName()).baseName()));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkAccessManager qnam;
QNetworkReply *reply = qnam.post(request, data);
QEventLoop eventLoop;
connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
if (reply->error())
QMessageBox::critical(this, tr("Error"), reply->errorString());
else
QMessageBox::information(this, tr("Success"), tr("Response:") + "\n" + reply->readAll());
reply->deleteLater();
}
bool QTblEditor::loadFile(const QString &fileName, bool shouldShowOpenOptions)
{
bool areTwoTablesOpened = _openedTables == 2;
int result = shouldShowOpenOptions ? -1 : 0;
if (_openedTables == 1 && shouldShowOpenOptions)
{
result = openTableMsgBoxResult(); // 0 - add one more, 1 - replace active, rest - cancel
if (result != 0 && result != 1)
return false;
}
if (result && !currentTablePanelWidget()->absoluteFileName().isEmpty() && !closeTable())
return false;
if (!result || (result == -1 && areTwoTablesOpened))
{
activateAnotherTable();
currentTablePanelWidget()->show();
closeAllDialogs();
}
TablePanelWidget *w = currentTablePanelWidget();
if (processTable(fileName))
{
if (!_openedTables || (_openedTables == 1 && (!result || result == -1)))
_openedTables++;
w->setFilePath(fileName);
w->setActive(true);
w->setWindowModified(false);
int row = _lastSelectedRowsHash[QDir::toNativeSeparators(fileName)].toInt();
_currentTableWidget->setCurrentCell(row, 1);
_currentTableWidget->scrollTo(_currentTableWidget->model()->index(row, 1));
if (_openedTables == 2)
{
inactiveNamedTableWidget(w)->setActive(false);
tableMenuSetEnabled(true);
}
_lastPath = w->fileDirPath();
enableTableActions(true);
return true;
}
else
{
if (!result || (result == -1 && areTwoTablesOpened))
{
w->hide();
activateAnotherTable();
}
return false;
}
}
bool QTblEditor::processTable(const QString &fileName)
{
_isTableLoaded = false;
QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
QString extension = fileName.right(4).toLower();
if (extension == ".tbl")
return _isTableLoaded = processTblFile(&inputFile);
else if (extension == ".txt" || extension == ".csv")
return _isTableLoaded = processTxtOrCsvFile(&inputFile);
else // arbitrary file opened
{
QTextStream in(&inputFile);
in.readLine();
QString secondLine = in.readLine(); // it should equal "X" if it's tbl file
inputFile.reset();
if (secondLine.contains('\t') || secondLine.contains(';') || secondLine.contains(',')) // text format
_isTableLoaded = processTxtOrCsvFile(&inputFile);
else // tbl format
_isTableLoaded = processTblFile(&inputFile);
}
}
else
{
QMessageBox::critical(this, qApp->applicationName(), tr("Error opening file \"%1\"\nReason: %2")
.arg(fileName, inputFile.errorString()));
return false;
}
return _isTableLoaded;
}
bool QTblEditor::processTblFile(QFile *inputFile)
{
QDataStream in(inputFile);
in.setByteOrder(QDataStream::LittleEndian);
TblStructure tbl;
tbl.fillHeader(in); // reading header
DWORD numElem = tbl.header().FileSize - TblHeader::size; // number of bytes to read without header
char *table = new char[numElem];
if (in.readRawData(table, numElem) == numElem)
{
delete [] table;
inputFile->reset(); // current offset for reading = 0x00
in.skipRawData(TblHeader::size); // current offset for reading = 0x15 (we don't need header any more)
tbl.getStringTable(in);
inputFile->close();
int rowCount = tbl.header().NodesNumber;
_currentTableWidget->setRowCount(rowCount);
currentTablePanelWidget()->updateRowCountLabel();
int maxKeyWidth = 0;
for (WORD i = 0; i < rowCount; i++)
{
QPair<QString, QString> currentDataStrings = tbl.dataStrings(i); // reading pair <key, value>
_currentTableWidget->createNewEntry(i, currentDataStrings.first, currentDataStrings.second);
int currentKeyWidth = QFontMetrics(_currentTableWidget->item(i, 0)->font()).width(currentDataStrings.first);
if (maxKeyWidth < currentKeyWidth)
maxKeyWidth = currentKeyWidth;
}
_currentTableWidget->setColumnWidth(0, maxKeyWidth + 1); // making "key" column width fit all the entries
return true;
}
else
{
delete [] table;
QMessageBox::critical(this, qApp->applicationName(), tr("Couldn't read entire file, read only %n byte(s) after header.\n"
"Probably file is corrupted or wrong file format.", 0, numElem));
return false;
}
}
bool QTblEditor::processTxtOrCsvFile(QFile *inputFile)
{
QList<QByteArray> entries = inputFile->readAll().split('\n'); // TODO: maybe read line by line to improve performance
inputFile->close();
if (entries.isEmpty())
return true;
int rows = entries.size() - 1; // don't include last empty line
_currentTableWidget->setRowCount(rows);
currentTablePanelWidget()->updateRowCountLabel();
QByteArray currentLine = entries.at(0).trimmed();
char separator = '\t', wrappingCharKey = '\"', wrappingCharValue = '\"';
if (inputFile->fileName().right(4).toLower() == ".csv" || currentLine.contains("\",\"") || currentLine.contains("\";\""))
{
int secondDoubleQuoteIndex = currentLine.indexOf('\"', 1);
if (secondDoubleQuoteIndex == -1)
{
QMessageBox::critical(this, qApp->applicationName(), tr("Wrong file format - all strings in *.csv should be wrapped in double quotes"));
closeTable();
return false;
}
separator = currentLine.at(secondDoubleQuoteIndex + 1);
}
else
{
QList<QByteArray> s = currentLine.split(separator);
QByteArray currentKey = s.at(0), currentValue = s.at(1);
if (!currentKey.startsWith(wrappingCharKey) || !currentKey.endsWith(wrappingCharKey))
wrappingCharKey = 0;
if (!currentValue.startsWith(wrappingCharValue) || !currentValue.endsWith(wrappingCharValue))
wrappingCharValue = 0;
}
QByteArray keyValueSeparator(1, separator);
if (wrappingCharKey)
keyValueSeparator.prepend(wrappingCharKey);
if (wrappingCharValue)
keyValueSeparator.append(wrappingCharValue);
QString wrappingCharKeyString = wrappingCharKey ? QChar(wrappingCharKey) : QString(), wrappingCharValueString = wrappingCharValue ? QChar(wrappingCharValue) : QString();
QString utf8TblEditHeaderString = QString("%1Key%1%2%3Value%3").arg(wrappingCharKeyString, QChar(separator), wrappingCharValueString);
QString afj666HeaderString = QString("%1String Index%1%2%3Text%3").arg(wrappingCharKeyString, QChar(separator), wrappingCharValueString);
int i = 0;
if (currentLine == utf8TblEditHeaderString || currentLine == afj666HeaderString)
{
if (!rows)
return true;
currentLine = entries.at(++i);
}
int maxKeyWidth = 0;
for (; i < rows; currentLine = entries.at(++i))
{
currentLine = currentLine.trimmed();
int separatorIndex = currentLine.indexOf(keyValueSeparator);
if (separatorIndex == -1)
{
QMessageBox::critical(this, qApp->applicationName(), tr("Wrong file format - separator is absent at line %1").arg(i + 1));
closeTable();
return false;
}
QString key = TblStructure::decodeKey(currentLine.left(separatorIndex));
_currentTableWidget->createNewEntry(i, key, restoreNewlines(QString::fromUtf8(currentLine.mid(separatorIndex + keyValueSeparator.length()))));
int currentKeyWidth = QFontMetrics(_currentTableWidget->item(i, 0)->font()).width(key);
if (maxKeyWidth < currentKeyWidth)
maxKeyWidth = currentKeyWidth;
}
_currentTableWidget->setColumnWidth(0, maxKeyWidth + 1);
return true;
}
bool QTblEditor::closeTable(bool hideTable)
{
if (!_openedTables)
return true;
if (wasSaved())
{
_locationLabel->clear();
_keyHashLabel->clear();
closeAllDialogs();
QString filePath = currentTablePanelWidget()->absoluteFileName();
if (filePath != kNewTblFileName)
_lastSelectedRowsHash[QDir::toNativeSeparators(filePath)] = _currentTableWidget->currentRow();
if (hideTable || filePath == kNewTblFileName)
{
currentTablePanelWidget()->clearContents();
_openedTables--;
}
if (_openedTables)
{
if (hideTable || filePath == kNewTblFileName)
currentTablePanelWidget()->hide();
activateAnotherTable();
currentTablePanelWidget()->setActive(true);
tableMenuSetEnabled(false);
updateWindow(_currentTableWidget->isWindowModified());
ui.actionSaveAll->setEnabled(_currentTableWidget->isWindowModified());
}
else
{
enableTableActions(false);
updateWindow(false);
ui.actionSaveAll->setEnabled(false);
}
return true;
}
return false;
}
void QTblEditor::enableTableActions(bool state)
{
QList<QAction *> actions = QList<QAction *>() << ui.actionSaveAs << ui.actionClose << ui.actionCloseAll << ui.menuEdit->actions() << ui.actionSendToServer;
foreach (QAction *action, actions)
action->setEnabled(state);
ui.menuEdit->setEnabled(state);
}
void QTblEditor::closeEvent(QCloseEvent *event)
{
if (closeAll(false))
{
writeSettings();
event->accept();
}
else
event->ignore();
}
bool QTblEditor::wasSaved()
{
if (_currentTableWidget->isWindowModified())
{
QMessageBox msgBox(this);
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText(tr("The table \"%1\" has been modified.").arg(currentTablePanelWidget()->fileName()));
msgBox.setInformativeText(tr("Do you want to save your changes?"));
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Save);
msgBox.setWindowModality(Qt::WindowModal);
msgBox.setWindowFlags(msgBox.windowFlags() & ~Qt::WindowContextHelpButtonHint);
int answer = msgBox.exec();
if (answer == QMessageBox::Save)
save();
else if (answer == QMessageBox::Cancel)
return false;
}
return true;
}
void QTblEditor::save()
{
QString fileName = currentTablePanelWidget()->absoluteFileName();
if (fileName == kNewTblFileName)
saveAs();
else
saveFile(fileName);
}
void QTblEditor::saveAs()
{
QString fileName = currentTablePanelWidget()->absoluteFileName();
#ifdef Q_OS_WIN32
if (QSysInfo::WindowsVersion <= QSysInfo::WV_XP) // workaround for XP and earlier Windows versions
{
QFileInfo info(fileName);
fileName = info.canonicalPath() + '/' + info.baseName(); // removing extension
}
#endif
QString fileNameToSave = QFileDialog::getSaveFileName(this, tr("Save table"), fileName,
tr("Tbl files (*.tbl);;Tab-delimited text files (*.txt);;CSV files (*.csv);;All files (*)"));
if (!fileNameToSave.isEmpty() && saveFile(fileNameToSave))
{
// change opened file path only if saving with the same extension
if (fileName.right(4) == fileNameToSave.right(4))
currentTablePanelWidget()->setFilePath(fileNameToSave);
addToRecentFiles(fileNameToSave);
}
}
void QTblEditor::saveAll()
{
if (_currentTableWidget->isWindowModified())
save();
if (_openedTables == 2)
{
activateAnotherTable();
if (_currentTableWidget->isWindowModified())
save();
activateAnotherTable();
}
ui.actionSaveAll->setDisabled(true);
}
bool QTblEditor::saveFile(const QString &fileName)
{
QByteArray bytesToWrite; // first of all, write everything to buffer
QString extension = fileName.right(4);
bool isCsv = extension == ".csv";
DWORD fileSize;
if (extension == ".tbl")
fileSize = writeAsTbl(bytesToWrite);
else if (extension == ".txt" || isCsv)
fileSize = writeAsText(bytesToWrite, isCsv);
else // any file
{
QMessageBox msgbox(this);
msgbox.setWindowTitle(qApp->applicationName());
msgbox.setText(tr("Choose file format"));
msgbox.addButton("tbl", QMessageBox::AcceptRole);
msgbox.addButton("txt", QMessageBox::AcceptRole);
msgbox.addButton("csv", QMessageBox::AcceptRole);
msgbox.setWindowModality(Qt::WindowModal);
switch (msgbox.exec())
{
case 0: // tbl
fileSize = writeAsTbl(bytesToWrite);
break;
case 1: // txt
fileSize = writeAsText(bytesToWrite, false);
break;
case 2: // csv
fileSize = writeAsText(bytesToWrite, true);
break;
}
}
QFile output(fileName);
if (output.open(QIODevice::WriteOnly))
{
if (output.write(bytesToWrite) == fileSize)
{
_currentTableWidget->clearBackground();
_lastPath = QFileInfo(fileName).canonicalPath();
if (_openedTables == 1 || !inactiveNamedTableWidget(currentTablePanelWidget())->tableWidget()->isWindowModified())
ui.actionSaveAll->setDisabled(true);
updateWindow(false);
ui.statusBar->showMessage(tr("File \"%1\" successfully saved").arg(QDir::toNativeSeparators(fileName)), 3000);
return true;
}
else
QMessageBox::critical(this, qApp->applicationName(), tr("Error writing file \"%1\"\nReason: %2").arg(QDir::toNativeSeparators(fileName), output.errorString()));
}
else
QMessageBox::critical(this, qApp->applicationName(), tr("Error creating file \"%1\"\nReason: %2").arg(QDir::toNativeSeparators(fileName), output.errorString()));
return false;
}
DWORD QTblEditor::writeAsTbl(QByteArray &bytesToWrite)
{
int entriesNumber = _currentTableWidget->rowCount();
QStringList stringValsWithModifiedColors; // replacing user-readable colors with their internal form
for (WORD i = 0; i < entriesNumber; i++)
{
QString currentVal = _currentTableWidget->item(i, 1)->text();
for (int j = 0; j < colorStrings.size(); j++)
{
if (currentVal.contains(colorStrings.at(j)) && j)
currentVal.replace(colorStrings.at(j), colorHeader + colorCodes.at(j - 1));
else
currentVal.replace(colorStrings.at(j), colorHeader); // string "\color;" found
}
stringValsWithModifiedColors << currentVal;
}
DWORD dataStartOffset = TblHeader::size + entriesNumber*sizeof(WORD) + entriesNumber*TblHashNode::size;
QVector<WORD> indices(entriesNumber);
QVector<TblHashNode> nodes(entriesNumber);
QVector<bool> collisionsDetected(entriesNumber, false);
DWORD currentOffset = dataStartOffset, maxCollisionsNumber = 0;
for (WORD i = 0; i < entriesNumber; i++)
{
QByteArray currentKey = TblStructure::encodeKey(_currentTableWidget->item(i, 0)->text()),
currentVal = stringValsWithModifiedColors.at(i).toUtf8();
DWORD hashValue = TblStructure::hashValue(currentKey.data(), entriesNumber), hashIndex = hashValue,
currentCollisionsNumber = 0;
while (collisionsDetected[hashIndex]) // counting collisions for current hash value
{
currentCollisionsNumber++;
hashIndex++;
hashIndex %= entriesNumber;
}
collisionsDetected[hashIndex] = true;
if (currentCollisionsNumber > maxCollisionsNumber)
maxCollisionsNumber = currentCollisionsNumber;
indices[i] = hashIndex;
// we need the size of UTF-8 data, not QString
WORD currentKeyLength = qstrlen(currentKey.constData()) + 1, currentValLength = qstrlen(currentVal.constData()) + 1;
// convenient constructor instead of nodes[hashIndex].Active = 1; ...
nodes[hashIndex] = TblHashNode(1, i, hashValue, currentOffset, currentOffset + currentKeyLength, currentValLength);
currentOffset += currentKeyLength + currentValLength;
}
bytesToWrite.fill(0, TblHeader::size); // header will be filled in the end, so we reserve bytes for it
QDataStream out(&bytesToWrite, QIODevice::WriteOnly);
out.setByteOrder(QDataStream::LittleEndian);
out.skipRawData(TblHeader::size); // current offset for writing = 0x15
for (WORD i = 0; i < entriesNumber; i++)
out << indices[i];
for (WORD i = 0; i < entriesNumber; i++)
out << nodes[i];
for (WORD i = 0; i < entriesNumber; i++)
{
QByteArray keyLatin1 = TblStructure::encodeKey(_currentTableWidget->item(i, 0)->text()), valUtf8 = stringValsWithModifiedColors.at(i).toUtf8();
out.writeRawData(keyLatin1.constData(), keyLatin1.size() + 1);
out.writeRawData(valUtf8.constData(), qstrlen(valUtf8.constData()) + 1);
}
DWORD fileSize = bytesToWrite.size();
out.device()->reset(); // current offset for writing = 0x00 (to write the header)
out << TblHeader(TblStructure::getCRC(bytesToWrite.data() + dataStartOffset, fileSize - dataStartOffset), entriesNumber,
entriesNumber, 1, dataStartOffset, maxCollisionsNumber + 1, fileSize); // convenient constructor
return fileSize;
}
DWORD QTblEditor::writeAsText(QByteArray &bytesToWrite, bool isCsv)
{
// format: [wrapper]key[wrapper]<separator>[wrapper]value[wrapper]<newline>,
// where <separator> is '\t' (for *.txt) or ','/';' (for *.csv),
// [wrapper] - double quotes or nothing (depends on current settings).
// for *.csv [wrapper] is always '\"'
quint8 separator = '\t', wrappingChar = '\"';
if (isCsv)
separator = ui.actionCsvComma->isChecked() ? ',' : ';';
else if (!ui.actionWrapStrings->isChecked())
wrappingChar = 0;
QDataStream out(&bytesToWrite, QIODevice::WriteOnly);
for (WORD i = 0, n = _currentTableWidget->rowCount(); i < n; ++i)
{
QByteArray keyLatin1 = TblStructure::encodeKey(_currentTableWidget->item(i, 0)->text());
if (wrappingChar)
out << wrappingChar;
out.writeRawData(keyLatin1.constData(), keyLatin1.size());
if (wrappingChar)
out << wrappingChar;
out << separator;
QByteArray valUtf8 = foldNewlines(_currentTableWidget->item(i, 1)->text()).toUtf8();
if (wrappingChar)
out << wrappingChar;
if (!valUtf8.isEmpty())
out.writeRawData(valUtf8.constData(), qstrlen(valUtf8.constData()));
if (wrappingChar)
out << wrappingChar;
out << static_cast<quint8>('\n');
}
return bytesToWrite.size();
}
void QTblEditor::showFindReplaceDialog()
{
_findReplaceDlg->show(_openedTables == 2);
_findReplaceDlg->raise();
_findReplaceDlg->activateWindow();
}
void QTblEditor::changeCurrentTableItem(QTableWidgetItem *newItem)
{
_currentTableWidget = qobject_cast<D2StringTableWidget *>(newItem->tableWidget());
_currentTableWidget->setCurrentCell(newItem->row(), newItem->column());
currentTablePanelWidget()->setActive(true);
if (_openedTables == 2)
inactiveNamedTableWidget(currentTablePanelWidget())->setActive(false);
}
void QTblEditor::findNextString(const QString &query, bool isCaseSensitive, bool isExactString, bool isSearchBothTables)
{
Qt::MatchFlags searchOptions(Qt::MatchWrap | Qt::MatchContains);
if (isCaseSensitive)
searchOptions |= Qt::MatchCaseSensitive;
if (isExactString)
searchOptions &= ~Qt::MatchContains;
QList<QTableWidgetItem *> foundItems = _currentTableWidget->findItems(query, searchOptions);
if (isSearchBothTables && _openedTables == 2)
foundItems.append(inactiveTableWidget(_currentTableWidget)->findItems(query, searchOptions));
_findReplaceDlg->getFoundStrings(foundItems);
}
void QTblEditor::goTo()
{
GoToRowDialog dlg(this, _currentTableWidget->rowCount());
if (dlg.exec())
_currentTableWidget->setCurrentCell(dlg.row() - 1, 1);
}
void QTblEditor::editString(QTableWidgetItem *itemToEdit)
{
int row = itemToEdit->row();
KeyValueItemsPair itemsPair;
if (itemToEdit->column()) // value selected
itemsPair = KeyValueItemsPair(itemToEdit->tableWidget()->item(row, 0), itemToEdit);
else // key selected
itemsPair = KeyValueItemsPair(itemToEdit, itemToEdit->tableWidget()->item(row, 1));
EditStringCellDialog *editStringCellDlg = 0;
if (_openedTables == 1 || row >= inactiveTableWidget(_currentTableWidget)->rowCount() || !ui.actionSyncScrolling->isChecked())
editStringCellDlg = new EditStringCellDialog(this, itemsPair);
else
{
QTableWidget *w = inactiveTableWidget(itemToEdit->tableWidget());
KeyValueItemsPair otherItemsPair(w->item(row, 0), w->item(row, 1));
if (_currentTableWidget == _leftTableWidget)
editStringCellDlg = new EditStringCellDialog(this, itemsPair, otherItemsPair);
else
editStringCellDlg = new EditStringCellDialog(this, otherItemsPair, itemsPair);
}
connect(editStringCellDlg, SIGNAL(editorClosedAt(int)), _currentTableWidget, SLOT(changeCurrentCell(int)));
if (_openedTables == 2 && ui.actionSyncScrolling->isChecked())
{
connect(editStringCellDlg, SIGNAL(editorClosedAt(int)), inactiveTableWidget(_currentTableWidget), SLOT(changeCurrentCell(int)));
connect(this, SIGNAL(tablesWereSwapped()), editStringCellDlg, SLOT(swapEditors()));
}
editStringCellDlg->show();
}
void QTblEditor::updateItem(QTableWidgetItem *item)
{
if (_isTableLoaded && item && item->background().color() != Qt::green)
{
item->setBackground(QBrush(Qt::green));
TablePanelWidget *w = _leftTablePanelWidget->tableWidget() == item->tableWidget() ? _leftTablePanelWidget : _rightTablePanelWidget;
w->tableWidget()->addEditedItem(item);
w->setWindowModified(true);
setWindowModified(true);
ui.actionSave->setEnabled(true);
ui.actionSaveAll->setEnabled(true);
ui.actionReopen->setEnabled(w->absoluteFileName() != kNewTblFileName);
}
}
bool QTblEditor::isDialogQuestionConfirmed(const QString &text)
{
QMessageBox confirmationDialog(QMessageBox::Question, qApp->applicationName(), text, QMessageBox::Yes | QMessageBox::No, this);
confirmationDialog.setDefaultButton(QMessageBox::Yes);
#ifdef Q_OS_MAC
confirmationDialog.setWindowModality(Qt::WindowModal);
#endif
return confirmationDialog.exec() == QMessageBox::Yes;
}
void QTblEditor::deleteSelectedItems()
{
bool needsClear = sender() == ui.actionClearSelected; // clear if true, delete if false
if (isDialogQuestionConfirmed(tr("Are you sure you want to %1 selected items?").arg(needsClear ? tr("clear") : tr("delete"))))
{
_currentTableWidget->deleteItems(needsClear);
updateWindow();
if (!needsClear)
currentTablePanelWidget()->updateRowCountLabel();
}
}
void QTblEditor::updateWindow(bool isModified)
{
setWindowModified(isModified);
currentTablePanelWidget()->setWindowModified(isModified);
ui.actionSave->setEnabled(isModified);
if (currentTablePanelWidget()->absoluteFileName() == kNewTblFileName)
ui.actionReopen->setEnabled(false);
else
ui.actionReopen->setEnabled(isModified);
}
void QTblEditor::updateLocationLabel(int newRow)
{
if (newRow < 0)
return;
int row = newRow + 1, rows = _currentTableWidget->rowCount();
_locationLabel->setText(QString("%1 (0x%2) / %3 (0x%4)").arg(row).arg(row, 0, 16).arg(rows).arg(rows, 0, 16));
QString keyHash = QString("0x%1").arg(TblStructure::hashValue(TblStructure::encodeKey(_currentTableWidget->item(newRow, 0)->text()).data(), rows), 0, 16);
D2StringTableWidget *otherTableWidget = inactiveTableWidget(_currentTableWidget);
int inactiveRows = otherTableWidget->rowCount();
if (_openedTables == 2 && newRow < inactiveRows)
{