-
Notifications
You must be signed in to change notification settings - Fork 1
/
search_list.cc
3253 lines (2875 loc) · 112 KB
/
search_list.cc
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
/* ----------------------------------------------------------------------------
* Copyright (C) 2007-2010,2020 Th. Zoerner
* ----------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ----------------------------------------------------------------------------
*
* Module description:
*
* This module implements the search list dialog, which is used to show a
* user-selected sub-set of text lines in the mmain window. The user can add or
* remove text lines via "search all" in the main window (or the find toolbar
* in several other dialogs). Lines can also be added "manually" via the
* "Insert" key and menu entries in the main window. Lines can also be removed
* via the "Delete" key within the list dialog. Any changes to the list are
* covered by an undo/redo mechanism.
*
* The search list is designed specifically to support a large number of lines.
* Therefore addition and removal as well as undo/redo are broken into steps of
* may 100 ms within a timer-driven background task. Only one such change can
* be going on at a time; the user will be asked to wait for the previous
* change to complete via a dialog when making further changes. (The underlying
* model is designed to handle large lists and large number of insertions and
* removals efficiently; see performance considerations class description
* below.)
*
* Finally the dialog offers saving the entire contents, or just the line
* indices to a file, or inversely add line numbers listed in a file to the
* dialog.
*
* By default the dialog only shows a copy of the text for each line. Via the
* menu the user can add columns showing the line number, or a line number
* delta, or user-defined columns with content extracted from adjacent text
* lines via regular expression pattern matching & capturing.
*
* Currently only one instance of this class can exists. Attempts to open
* another instance will just raise the window of the existing instance.
* Technically however multiple instances are possible, and could be useful.
* This would however require extending the user-interface in other dialogs so
* that the user can select which instance operations such as "search all"
* should work on.
*/
#include <QWidget>
#include <QTableView>
#include <QAbstractItemModel>
#include <QItemSelection>
#include <QHeaderView>
#include <QPainter>
#include <QApplication>
#include <QDesktopWidget>
#include <QMenuBar>
#include <QMenu>
#include <QVBoxLayout>
#include <QPushButton>
#include <QProgressBar>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextBlock>
#include <QJsonObject>
#include <QJsonArray>
#include <QTextStream>
#include <QDateTime>
#include <QByteArray>
#include <QFileDialog>
#include <QDebug>
#include <cstdio>
#include <string>
#include <vector>
#include <set>
#include <initializer_list>
#include "main_win.h"
#include "main_text.h"
#include "main_search.h"
#include "status_line.h"
#include "config_file.h"
#include "bg_task.h"
#include "text_block_find.h"
#include "bookmarks.h"
#include "highlighter.h"
#include "highl_view_dlg.h"
#include "search_list.h"
#include "parse_frame.h"
#include "dlg_bookmarks.h"
#include "dlg_parser.h"
#include "dlg_higl.h"
#include "dlg_history.h"
#define SEARCH_LIST_NO_DEBUG
// ----------------------------------------------------------------------------
/**
* This class implements the "model" associated with the search list "view".
* The central part of this model is a plain array of line indices, which
* represent a sub-set of the lines (i.e. paragraphs) of the main text
* document. The model is designed for table view. The right-most column is
* rendered as a copy of the respective main text line (i.e. the actual text
* content of that line is not stored in the model). Other columns can
* optionally be made visible to display additional related information,
* specifically: A flag when the line has been bookmarked; the line number;
* line number delta to a user-selected "root" line; and several columns with
* user-defined content that is obtained from an external ParseFrame class.
*
* In addition to the standard QAbstractItemModel interface, the model provides
* an interface HighlightViewModelIf which is used by the delegate rendering
* the text content for obtaining the data and mark-up configuration.
*
* Notes to performance optimizations: The main part of the model state is a
* sorted set of numbers, specifically a sub-set of the range of indices
* between 0 and the number of lines in the main document. The container used
* for this set has to support reasonably fast random access by index (for the
* view) and fast insertions/removals. There is currently no standard container
* that supports both: std::set supports fast insertion and lookup by value,
* however not fast or random access by index. std:vector supports the fast
* random access, but gets very slow for insertions/removals when the size of
* the list is already large.
*
* Nevertheless, the solution is based around std::vector, because we can avoid
* the performance issues due to the fact that insertions/removals are always
* done in order. This means in particular, for large changes, successive
* points of insertion or removal are close. This means, when breaking the
* while list of numbers to be inserted/removed into chunks (which needs to be
* done to support use of background tasks), processing of each chunk only
* affects a relatively small portion of the whole vector. Using this idea,
* there are many possible solutions to perform insertions and removals of the
* sub-sets effifiently. For example, insertion could be done simply by
* inserting all new numbers consecutively at the position where the first
* value needs to be inserted, and then resort the range between this position
* and the correct position of the last value to be inserted. This is not the
* implemented solution however, as this can be done even more efficiently
* without sorting; See below for details.
*/
class SearchListModel : public QAbstractItemModel, public HighlightViewModelIf
{
public:
enum TblColIdx { COL_IDX_BOOK, COL_IDX_LINE, COL_IDX_LINE_D,
COL_IDX_CUST_VAL, COL_IDX_CUST_VAL_DELTA, COL_IDX_CUST_FRM, COL_IDX_CUST_FRM_DELTA,
COL_IDX_TXT, COL_COUNT };
SearchListModel(MainText * mainText, Highlighter * higl, const ParseSpec& parseSpec,
bool showSrchHall, bool showBookmarkMarkup)
: m_mainText(mainText)
, m_higl(higl)
, m_parser(ParseFrame::create(m_mainText->document(), parseSpec)) // may return nullptr
, m_showSrchHall(showSrchHall)
, m_showBookmarkMarkup(showBookmarkMarkup)
{
}
virtual ~SearchListModel() = default;
virtual QModelIndex index(int row, int column, const QModelIndex& parent __attribute__((unused)) = QModelIndex()) const override
{
return createIndex(row, column);
}
virtual QModelIndex parent(const QModelIndex&) const override
{
return QModelIndex();
}
virtual int rowCount(const QModelIndex& parent __attribute__((unused)) = QModelIndex()) const override
{
return dlg_srch_lines.size();
}
virtual int columnCount(const QModelIndex& parent __attribute__((unused)) = QModelIndex()) const override
{
return COL_COUNT;
}
virtual Qt::ItemFlags flags(const QModelIndex& index __attribute__((unused))) const override
{
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
virtual QVariant headerData(int section __attribute__((unused)), Qt::Orientation orientation __attribute__((unused)), int role __attribute__((unused))) const override
{
if (orientation == Qt::Horizontal)
{
if (role == Qt::DisplayRole)
{
switch (section)
{
case COL_IDX_BOOK: return QVariant("BM.");
case COL_IDX_LINE: return QVariant("#");
case COL_IDX_LINE_D: return QVariant("\xCE\x94"); // UTF-8 0xCE94: Greek delta
case COL_IDX_CUST_VAL: return QVariant(m_parser.get() ? m_parser->getHeader(ParseColumnFlags::Val) : "");
case COL_IDX_CUST_VAL_DELTA: return QVariant(m_parser.get() ? ("\xCE\x94" + m_parser->getHeader(ParseColumnFlags::Val)) : "");
case COL_IDX_CUST_FRM: return QVariant(m_parser.get() ? m_parser->getHeader(ParseColumnFlags::Frm) : "");
case COL_IDX_CUST_FRM_DELTA: return QVariant(m_parser.get() ? ("\xCE\x94" + m_parser->getHeader(ParseColumnFlags::Frm)) : "");
case COL_IDX_TXT: return QVariant("Text");
case COL_COUNT: break;
}
}
else if (role == Qt::ToolTipRole)
{
switch (section)
{
case COL_IDX_BOOK: return QVariant("<P>Bookmarked lines are marked with a blue dot in this column.</P>");
case COL_IDX_LINE: return QVariant("<P>Number of each line in the main window</P>");
case COL_IDX_LINE_D: return QVariant("<P>Line number delta to a selected base line</P>");
case COL_IDX_CUST_VAL: return QVariant("<P>Value extracted from text content as per \"custom column configuration\"</P>");
case COL_IDX_CUST_VAL_DELTA: return QVariant("<P>Delta between extracted value of each line to that of a selected line</P>");
case COL_IDX_CUST_FRM: return QVariant("<P>Frame boundary value extracted from text content as per \"custom column configuration\"</P>");
case COL_IDX_CUST_FRM_DELTA: return QVariant("<P>Delta between frame boundary value of each line to that of a selected line</P>");
case COL_IDX_TXT: return QVariant("<P>Copy of the text in the main window</P>");
case COL_COUNT: break;
}
}
// Qt::SizeHintRole
}
return QVariant();
}
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
//virtual bool setData(const QModelIndex& index, const QVariant &value, int role = Qt::EditRole) override;
//virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
//virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
int getLineIdx(int ins_line) const;
bool getLineIdx(int line, int& idx) const
{
idx = getLineIdx(line);
return ((size_t(idx) < dlg_srch_lines.size()) && (dlg_srch_lines[idx] == line));
}
bool isIdxValid(int line, int idx) const
{
return (idx >= 0)
&& (size_t(idx) < dlg_srch_lines.size())
&& (dlg_srch_lines[idx] == line);
}
int getLineOfIdx(int idx) const
{
return ((size_t(idx) < dlg_srch_lines.size()) ? dlg_srch_lines[idx] : -1);
}
int lineCount() const
{
return dlg_srch_lines.size();
}
void insertLinePreSorted(const std::vector<int>& line_list, const std::vector<int>& idx_list);
void removeLinePreSorted(const std::vector<int>& idx_list);
void removeAll(std::vector<int>& removedLines);
void setLineDeltaRoot(int line);
bool isValidLineDeltaRoot();
bool setCustomDeltaRoot(TblColIdx col, int line);
bool isValidCustomDeltaRoot(TblColIdx col);
void forceRedraw(TblColIdx col, int line = -1);
const std::vector<int>& exportLineList() const
{
return dlg_srch_lines;
}
void adjustLineNums(int top_l, int bottom_l);
void showSearchHall(bool enable)
{
m_showSrchHall = enable;
}
void showBookmarkMarkup(bool enable)
{
m_showBookmarkMarkup = enable;
}
void setCustomColCfg(const ParseSpec& parseSpec)
{
m_parser = ParseFrame::create(m_mainText->document(), parseSpec);
if (dlg_srch_lines.size() != 0)
{
emit dataChanged(createIndex(0, COL_IDX_CUST_VAL),
createIndex(dlg_srch_lines.size() - 1, COL_IDX_CUST_FRM_DELTA));
}
}
ParseColumns getCustomColumns() const
{
return (m_parser.get() ? m_parser->getColumns() : ParseColumns{});
}
// implementation of HighlightViewModelIf interfaces
virtual const HiglFmtSpec * getFmtSpec(const QModelIndex& index) const override
{
int line = getLineOfIdx(index.row());
if (line >= 0)
return m_higl->getFmtSpecForLine(line, !m_showBookmarkMarkup, !m_showSrchHall);
else
return nullptr;
}
virtual QVariant higlModelData(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
return data(index, role);
}
private:
MainText * const m_mainText;
Highlighter * const m_higl;
ParseFramePtr m_parser;
bool m_showSrchHall = true;
bool m_showBookmarkMarkup = false;
int m_rootLineIdx = 0;
int m_rootCustVal = 0;
int m_rootCustFrm = 0;
std::vector<int> dlg_srch_lines;
};
QVariant SearchListModel::data(const QModelIndex &index, int role) const
{
if ( (role == Qt::DisplayRole)
&& ((size_t)index.row() < dlg_srch_lines.size()))
{
int line = dlg_srch_lines[index.row()];
bool ok;
switch (index.column())
{
case COL_IDX_LINE:
return QVariant(QString::number(line + 1));
case COL_IDX_LINE_D:
return QVariant(QString::number(line - m_rootLineIdx));
case COL_IDX_CUST_VAL:
if (m_parser.get() != nullptr)
return QVariant(m_parser->parseFrame(line, 0));
break;
case COL_IDX_CUST_VAL_DELTA:
if (m_parser.get() != nullptr)
{
int val = m_parser->parseFrame(line, 0).toInt(&ok);
if (ok)
return QVariant(QString::number(val - m_rootCustVal));
}
break;
case COL_IDX_CUST_FRM:
if (m_parser.get() != nullptr)
return QVariant(m_parser->parseFrame(line, 1));
break;
case COL_IDX_CUST_FRM_DELTA:
if (m_parser.get() != nullptr)
{
int val = m_parser->parseFrame(line, 1).toInt(&ok);
if (ok)
return QVariant(QString::number(val - m_rootCustFrm));
}
break;
case COL_IDX_TXT:
return QVariant(m_mainText->document()->findBlockByNumber(line).text());
case COL_IDX_BOOK:
case COL_COUNT:
break;
}
}
return QVariant();
}
void SearchListModel::insertLinePreSorted(const std::vector<int>& line_list,
const std::vector<int>& idx_list)
{
Q_ASSERT(line_list.size() == idx_list.size());
if (idx_list.size() == 0)
return;
// small list, or all lines inserted at the same place?
if ( (dlg_srch_lines.size() <= 20000)
|| (idx_list[0] == idx_list[idx_list.size() - 1]))
{
// yes -> standard way, i.e. keep display in sync with every insertion
dlg_srch_lines.reserve(dlg_srch_lines.size() + line_list.size());
int idx = 0;
int prev = -1;
while (size_t(idx) < idx_list.size())
{
Q_ASSERT(idx_list[idx] > prev); prev = idx_list[idx];
int count = 1;
while ((size_t(idx + count) < idx_list.size()) && (idx_list[idx] == idx_list[idx + count]))
++count;
int row = idx_list[idx] + idx;
this->beginInsertRows(QModelIndex(), row, row + count - 1);
dlg_srch_lines.insert(dlg_srch_lines.begin() + row,
line_list.begin() + idx,
line_list.begin() + idx + count);
this->endInsertRows();
idx += count;
}
}
else // non-consecutive insertions
{
// Step #1: insert dummy entries at the point of 1st insertion to make space for all new entries
dlg_srch_lines.insert(dlg_srch_lines.begin() + idx_list[0], idx_list.size(), 0);
// Step #2: merge sorted list of new entries with pre-existing range of list (also sorted);
// The range of pre-existing ("old") entries is that between first and last point of insertion for new entries;
// This means simultaneously filling the gap with new entries & copying forward old entries as needed to keep sort order.
size_t end_old = idx_list[idx_list.size() - 1] + idx_list.size(); // not included; may be one off past end of dlg_srch_lines
size_t src_old_idx = idx_list[0] + idx_list.size(); // start of old entries after shift by insertion above
size_t src_new_idx = 0;
size_t dst_idx = idx_list[0];
Q_ASSERT(src_old_idx < dlg_srch_lines.size());
while (true)
{
if (dlg_srch_lines[src_old_idx] < line_list[src_new_idx])
{
dlg_srch_lines[dst_idx++] = dlg_srch_lines[src_old_idx++];
if (src_old_idx >= end_old)
{
while (src_new_idx < idx_list.size())
dlg_srch_lines[dst_idx++] = line_list[src_new_idx++];
break;
}
}
else
{
dlg_srch_lines[dst_idx++] = line_list[src_new_idx++];
if (src_new_idx >= idx_list.size())
{
// no need to copy old data: already in place
Q_ASSERT(false); // never reached as above "while" would copy last range of new entries
break;
}
}
}
Q_ASSERT(dst_idx == size_t(idx_list[idx_list.size() - 1]) + idx_list.size());
// Step #3: resync display
emit layoutChanged();
}
}
void SearchListModel::removeLinePreSorted(const std::vector<int>& idx_list)
{
if (idx_list.size() == 0)
return;
// small list or single consecutive span of removed lines?
if ( (dlg_srch_lines.size() <= 20000)
|| (size_t(idx_list[0]) == idx_list[idx_list.size() - 1] + idx_list.size() - 1))
{
// yes -> standard way, i.e. keep display in sync with every removal
int prev = dlg_srch_lines.size();
int idx = 0;
while (size_t(idx) < idx_list.size())
{
// detect consecutive index values in descending order(!)
Q_ASSERT(idx_list[idx] < prev); prev = idx_list[idx];
int count = 1;
while ((size_t(idx + count) < idx_list.size()) && (idx_list[idx] == idx_list[idx + count] + count))
++count;
int row = idx_list[idx + count - 1];
this->beginRemoveRows(QModelIndex(), row, row + count - 1);
dlg_srch_lines.erase(dlg_srch_lines.begin() + row,
dlg_srch_lines.begin() + row + count);
this->endRemoveRows();
idx += count;
}
}
else // non-consecutive removals
{
// following is unnecessarily complex due to input list being in reverse order
int dst_idx = idx_list[idx_list.size() - 1];
int org_idx = idx_list[idx_list.size() - 1] + 1;
// Step #1: copy non-removed line numbers to position starting at first removed line
for (int src_idx = idx_list.size() - 2; src_idx >= 0; --src_idx)
{
int next_rm = idx_list[src_idx];
while (org_idx < next_rm)
dlg_srch_lines[dst_idx++] = dlg_srch_lines[org_idx++];
++org_idx;
}
// Step #2: remove single remaining gap after last non-removed line from vector
dlg_srch_lines.erase(dlg_srch_lines.begin() + dst_idx,
dlg_srch_lines.begin() + idx_list[0] + 1);
// Step #3: resync display
emit layoutChanged();
}
}
void SearchListModel::removeAll(std::vector<int>& removedLines)
{
if (dlg_srch_lines.size() != 0)
{
this->beginRemoveRows(QModelIndex(), 0, dlg_srch_lines.size() - 1);
removedLines = std::move(dlg_srch_lines);
this->endRemoveRows();
}
Q_ASSERT(dlg_srch_lines.size() == 0);
}
/**
* Helper function which performs a binary search in the sorted line index
* list for the first value which is larger or equal to the given value.
* Returns the index of the element, or the length of the list if all
* values in the list are smaller.
*/
int SearchListModel::getLineIdx(int ins_line) const
{
int end = dlg_srch_lines.size();
int min = -1;
int max = end;
if (end > 0)
{
int idx = end >> 1;
end -= 1;
while (true)
{
int el = dlg_srch_lines[idx];
if (el < ins_line)
{
min = idx;
idx = (idx + max) >> 1;
if ((idx >= max) || (idx <= min))
break;
}
else if (el > ins_line)
{
max = idx;
idx = (min + idx) >> 1;
if (idx <= min)
break;
}
else
{
max = idx;
break;
}
}
}
return max;
}
void SearchListModel::setLineDeltaRoot(int line)
{
m_rootLineIdx = line;
if (dlg_srch_lines.size() != 0)
{
emit dataChanged(createIndex(0, COL_IDX_LINE_D),
createIndex(dlg_srch_lines.size() - 1, COL_IDX_LINE_D));
}
}
bool SearchListModel::isValidLineDeltaRoot()
{
return m_rootLineIdx != 0;
}
bool SearchListModel::setCustomDeltaRoot(TblColIdx col, int line)
{
Q_ASSERT((col == COL_IDX_CUST_VAL_DELTA) || (col == COL_IDX_CUST_FRM_DELTA));
bool result = false;
int val = m_parser->parseFrame(line, ((col == COL_IDX_CUST_VAL_DELTA) ? 0 : 1)).toInt(&result);
if (result)
{
if (col == COL_IDX_CUST_VAL_DELTA)
m_rootCustVal = val;
else
m_rootCustFrm = val;
if (dlg_srch_lines.size() != 0)
{
emit dataChanged(createIndex(0, col),
createIndex(dlg_srch_lines.size() - 1, col));
}
}
return result;
}
bool SearchListModel::isValidCustomDeltaRoot(TblColIdx col)
{
int line = (col == COL_IDX_CUST_VAL_DELTA) ? m_rootCustVal : m_rootCustFrm;
return line != 0;
}
// called when external state has changed that affects rendering
void SearchListModel::forceRedraw(TblColIdx col, int line) // ATTN row/col order reverse of usual
{
if (dlg_srch_lines.size() != 0)
{
int idx;
if (line < 0)
{
emit dataChanged(createIndex(0, col),
createIndex(dlg_srch_lines.size() - 1, col));
}
else if (getLineIdx(line, idx))
{
auto midx = createIndex(idx, col);
emit dataChanged(midx, midx);
}
}
}
void SearchListModel::adjustLineNums(int top_l, int bottom_l)
{
if (bottom_l >= 0)
{
// delete from [bottom_l ... end[
int idx = getLineIdx(bottom_l);
if (size_t(idx) < dlg_srch_lines.size())
{
this->beginRemoveRows(QModelIndex(), idx, dlg_srch_lines.size() - 1);
dlg_srch_lines.erase(dlg_srch_lines.begin() + idx, dlg_srch_lines.end());
this->endRemoveRows();
}
}
if (top_l > 0)
{
// delete lines from [0 ... topl[
int idx = getLineIdx(top_l);
if (idx > 0)
{
this->beginRemoveRows(QModelIndex(), 0, idx - 1);
dlg_srch_lines.erase(dlg_srch_lines.begin(), dlg_srch_lines.begin() + idx);
this->endRemoveRows();
}
// now actually adjust remaining line numbers
if (dlg_srch_lines.size() != 0)
{
for (int& line : dlg_srch_lines)
line -= top_l;
emit dataChanged(createIndex(0, COL_IDX_LINE),
createIndex(dlg_srch_lines.size() - 1, COL_IDX_LINE));
}
}
if (m_parser != nullptr)
{
m_parser->clearCache();
}
}
// ----------------------------------------------------------------------------
/**
* This struct describes one entry in the undo/redo lists.
*/
class UndoRedoItem
{
public:
UndoRedoItem(bool doAdd, const std::initializer_list<int>& v)
: isAdded(doAdd)
, lines(v)
{}
UndoRedoItem(bool doAdd, const std::vector<int>& v)
: isAdded(doAdd)
, lines(v)
{}
UndoRedoItem(bool doAdd, std::vector<int>&& v)
: isAdded(doAdd)
, lines(std::move(v))
{}
public:
bool isAdded;
std::vector<int> lines;
};
/**
* The SearchListUndo class manages the undo/redo list for the search list
* dialog. Any changes to the content of the search list are recorded to the
* undo list. Changes can be either additions or removals. Changes done by
* background tasks of the search list class are usually split into many parts
* for performance reasons; the UndoRedoItem class offers special interfaces
* for these cases to allow concatenating them to a single entry in the undo
* list.
*
* When a change is undone, the respective change description is moved from the
* undo list to the redo list. For performance reasons any undo/redo may be
* split in many steps. In this phase entries are kept in both undo and redo
* list, but portions of the contained line number lists are moved from one
* list to the other, always in sync with changes to the model. When the undo
* or redo is completed the obsolete entry is removed. Is the process is
* aborted in the middle, the partial entries remain in both lists.
*
* Note this class is coupled tightly with the state of the model. To ensure
* consistency there's an invariant function checking all undo entries combined
* result exactly in the current content of the model.
*/
class SearchListUndo
{
public:
SearchListUndo() = default;
~SearchListUndo() = default;
void appendChange(bool doAdd, const std::vector<int>& lines);
void prepareBgChange(bool doAdd);
void appendBgChange(bool doAdd,
std::vector<int>::const_iterator lines_begin,
std::vector<int>::const_iterator lines_end);
void finalizeBgChange(bool doAdd);
void abortBgChange();
void prepareUndoRedo(bool isRedo);
bool popUndoRedo(bool isRedo, bool *retDoAdd, std::vector<int>& retLines, size_t maxCount);
void finalizeUndoRedo(bool isRedo);
void adjustLineNums(int top_l, int bottom_l);
bool hasUndo(int *count = nullptr) const;
bool hasRedo(int *count = nullptr) const;
std::pair<bool,int> describeFirstOp(bool forUndo);
private:
std::vector<UndoRedoItem> dlg_srch_undo;
std::vector<UndoRedoItem> dlg_srch_redo;
int m_bgDstIdx = -1;
bool m_bgForUndo = false;
bool m_bgDoAdd = false;
#if !defined (QT_NO_DEBUG) && !defined (SEARCH_LIST_NO_DEBUG)
void invariant() const;
SearchListModel * m_modelDebug = nullptr;
public:
void connectModelForDebug(SearchListModel * model) { m_modelDebug = model; }
#define SEARCH_LIST_UNDO_INVARIANT() do{ invariant(); }while(0)
#else
#define SEARCH_LIST_UNDO_INVARIANT() do{}while(0)
#endif
};
/**
* This is the basic interface for adding to the "undo" list. It is used by
* small "atomic" changes, usually via user interaction (i.e. adding a few
* selected text lines). The redo list is cleared, so that any changes that
* were previously undone are lost.
*/
void SearchListUndo::appendChange(bool doAdd, const std::vector<int>& lines)
{
Q_ASSERT(m_bgDstIdx < 0);
dlg_srch_undo.push_back(UndoRedoItem(doAdd, lines));
dlg_srch_redo.clear();
SEARCH_LIST_UNDO_INVARIANT();
}
/**
* This interface has to be called at the start of background tasks to prepare
* combining subsequent changes to a single entry. Target is always the undo
* list; the redo list is cleared.
*/
void SearchListUndo::prepareBgChange(bool doAdd)
{
std::vector<UndoRedoItem>& undo_list = dlg_srch_undo;
Q_ASSERT(m_bgDstIdx < 0);
m_bgDstIdx = undo_list.size();
m_bgDoAdd = doAdd;
m_bgForUndo = true;
dlg_srch_redo.clear();
}
/**
* This function is during background tasks which fill the search match dialog
* after adding new matches. The function adds the respective line numbers to
* the undo list. If there's already an undo item for the current search, the
* numbers are merged into it.
*/
void SearchListUndo::appendBgChange(bool doAdd,
std::vector<int>::const_iterator lines_begin,
std::vector<int>::const_iterator lines_end)
{
std::vector<UndoRedoItem>& undo_list = dlg_srch_undo;
Q_ASSERT((m_bgDstIdx >= 0) && (size_t(m_bgDstIdx) <= undo_list.size()));
Q_ASSERT(m_bgDoAdd == doAdd);
Q_ASSERT(m_bgForUndo == true);
if (size_t(m_bgDstIdx) == undo_list.size())
undo_list.emplace_back(UndoRedoItem(doAdd, std::vector<int>(lines_begin, lines_end)));
else
undo_list.back().lines.insert(undo_list.back().lines.end(), lines_begin, lines_end);
SEARCH_LIST_UNDO_INVARIANT();
}
/**
* This function is invoked at the end of background tasks which fill the
* search list window to mark the entry on the undo list as closed (so that
* future search matches go into a new undo element.)
*
* Note it's allowed that there actually were no changes (e.g. no matching
* lines found in text), so that no item may have been added to the list.
*/
void SearchListUndo::finalizeBgChange(bool doAdd)
{
std::vector<UndoRedoItem>& undo_list = dlg_srch_undo;
Q_ASSERT((m_bgDstIdx >= 0) && (size_t(m_bgDstIdx) <= undo_list.size()));
Q_ASSERT(m_bgDoAdd == doAdd);
Q_ASSERT(m_bgForUndo == true);
m_bgDstIdx = -1;
SEARCH_LIST_UNDO_INVARIANT();
}
/**
* This function aborts either kind of ongoing changes via background tasks,
* i.e. either additions via "search all", or undo/redo. The function just
* resets the "background state", but leaves undo/redo lists unchanged. This is
* possible because each step done by background tasks keeps model and
* undo/redo lists in sync.
*/
void SearchListUndo::abortBgChange()
{
Q_ASSERT(m_bgDstIdx >= 0);
m_bgDstIdx = -1;
SEARCH_LIST_UNDO_INVARIANT();
}
/**
* This function is called upon start of an undo/redo that will be executed via
* background tasks. It prepares for combination of all following changes into
* a single entry in the opposite list. The function does not actually add an
* entry yet, as empty entries are not allowed in the lists.
*/
void SearchListUndo::prepareUndoRedo(bool isRedo)
{
std::vector<UndoRedoItem>& src_list = isRedo ? dlg_srch_redo : dlg_srch_undo;
std::vector<UndoRedoItem>& dst_list = isRedo ? dlg_srch_undo : dlg_srch_redo;
Q_ASSERT(m_bgDstIdx < 0);
Q_ASSERT(src_list.size() != 0);
if (src_list.size() != 0)
{
m_bgDstIdx = dst_list.size();
m_bgDoAdd = src_list.back().isAdded;
m_bgForUndo = !isRedo;
}
}
/**
* This function "pops" a set of line numbers from the last entry of the undo
* or redo list (the actual list to be used is indicated via parameter). These
* line numbers are added to the last entry of the opposite list (or a new
* entry is created, if this is the first call after prepareUndoRedo) and then
* returns the same set of line numbers to the caller. The caller has to apply
* the change to the model (so that it remains in sync with the undo list).
*/
bool SearchListUndo::popUndoRedo(bool isRedo, bool *retDoAdd, std::vector<int>& retLines, size_t maxCount)
{
std::vector<UndoRedoItem>& src_list = isRedo ? dlg_srch_redo : dlg_srch_undo;
std::vector<UndoRedoItem>& dst_list = isRedo ? dlg_srch_undo : dlg_srch_redo;
Q_ASSERT((m_bgDstIdx >= 0) && (size_t(m_bgDstIdx) <= dst_list.size()));
Q_ASSERT(m_bgForUndo == !isRedo);
if (src_list.size() != 0)
{
UndoRedoItem& src_op = src_list.back();
bool done;
*retDoAdd = src_op.isAdded;
if (size_t(m_bgDstIdx) == dst_list.size())
{
dst_list.emplace_back(UndoRedoItem(src_op.isAdded, std::vector<int>()));
dst_list.back().lines.reserve(src_op.lines.size());
}
UndoRedoItem& dst_op = dst_list.back();
if (src_op.lines.size() > maxCount)
{
#if 0
// NOTE could be more efficient by removing chunks from the end of the list
// however that would require sorting the destination list upon "finalizing"
dst_op.lines.insert(dst_op.lines.end(), src_op.lines.begin() + start,
src_op.lines.end());
retLines.insert(retLines.end(), src_op.lines.begin() + start,
src_op.lines.end());
src_op.lines.erase(src_op.lines.begin() + start, src_op.lines.end());
#else
dst_op.lines.insert(dst_op.lines.end(), src_op.lines.begin(),
src_op.lines.begin() + maxCount);
retLines.insert(retLines.end(), src_op.lines.begin(),
src_op.lines.begin() + maxCount);
src_op.lines.erase(src_op.lines.begin(),
src_op.lines.begin() + maxCount);
#endif
}
else
{
dst_op.lines.insert(dst_op.lines.end(), src_op.lines.begin(), src_op.lines.end());
retLines = std::move(src_op.lines);
src_list.pop_back();
done = true;
}
return done;
}
Q_ASSERT(false);
return true;
}
/**
* This function has to be invoked at the end of background tasks which perform
* undo/redo. The function resets the background task-related state variables.
*/
void SearchListUndo::finalizeUndoRedo(bool isRedo)
{
std::vector<UndoRedoItem>& dst_list = isRedo ? dlg_srch_undo : dlg_srch_redo;
Q_ASSERT((m_bgDstIdx >= 0) && (size_t(m_bgDstIdx) == dst_list.size() - 1));
Q_ASSERT(m_bgForUndo == !isRedo);
m_bgDstIdx = -1;
SEARCH_LIST_UNDO_INVARIANT();
}
/**
* This function is called when portions of the text in the main window have
* been deleted to update references to text lines. The function removes all
* references to removed lines from the undo/redo lists and prunes remaining
* empty entries. Remaining line numbers may be shifted, if lines at the top
* of the document were removed.
*
* @param top_l First line which is NOT deleted, or 0 to delete nothing at top
* @param bottom_l This line and all below are removed, or -1 if none
*/
void SearchListUndo::adjustLineNums(int top_l, int bottom_l)
{
std::vector<UndoRedoItem> tmp2;
for (const auto& cmd : dlg_srch_undo)
{
std::vector<int> tmpl;
tmpl.reserve(cmd.lines.size());
for (int line : cmd.lines)
{
if ((line >= top_l) && ((line < bottom_l) || (bottom_l < 0)))
{
tmpl.push_back(line - top_l);
}
}
if (tmpl.size() > 0)
{
tmp2.emplace_back(UndoRedoItem(cmd.isAdded, std::move(tmpl)));
}
}
dlg_srch_undo = std::move(tmp2);
dlg_srch_redo.clear();
SEARCH_LIST_UNDO_INVARIANT();
}
/**
* This query function indicates if there are any entries in the undo list, and
* optionally the number of lines in the last entry.
*/
bool SearchListUndo::hasUndo(int *count) const
{
if (count != nullptr)
*count = ((dlg_srch_undo.size() != 0) ? dlg_srch_undo.back().lines.size() : 0);
return dlg_srch_undo.size() != 0;
}
/**
* This query function indicates if there are any entries in the redo list, and
* optionally the number of lines in the last entry.
*/
bool SearchListUndo::hasRedo(int *count) const
{
if (count != nullptr)