Repository navigation
Expand file tree
/
Copy pathdlg_higl.cc
More file actions
1406 lines (1250 loc) · 49.5 KB
/
Copy pathdlg_higl.cc
File metadata and controls
1406 lines (1250 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ----------------------------------------------------------------------------
* 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 a dialog that shows a list of all used-defined
* highlighting patterns and a sample of the respective mark-up format. The
* dialog can be used either for searching lines matching selected patterns in
* the main window, or for editing the list. This functionality is provided via
* the two toolbars as well as the context menu and standard table view
* bindings.
*
* Only a single-instance of this dialog is allowed, as only a single instance
* exists of the underlying data. Attempts to open another instance will just
* raise the window of the existing instance.
*/
#include <QWidget>
#include <QTableView>
#include <QAbstractItemModel>
#include <QItemSelection>
#include <QHeaderView>
#include <QPainter>
#include <QApplication>
#include <QStyle>
#include <QMenu>
#include <QToolBar>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QMessageBox>
#include <QFontDialog>
#include <QColorDialog>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <cstdio>
#include <string>
#include <vector>
#include "main_win.h"
#include "main_text.h"
#include "main_search.h"
#include "status_line.h"
#include "highlighter.h"
#include "search_list.h"
#include "highl_view_dlg.h"
#include "dlg_markup.h"
#include "dlg_higl.h"
// ----------------------------------------------------------------------------
/**
* This class implements the data model that is underlying the table view of
* the pattern list. Upon instantiation, the dialog takes a copy of the pattern
* list managed by the Highlighting class. Various standard and non-standard
* interface functions allow the view moving, inserting, or removing list
* items. Each list entry carries an ID that allows associating list items with
* entries originating from the Highlighting class when finally saving back the
* modified list.
*
* The class also supports an interface for the item view delegate used for
* rendering the sample text.
*/
class DlgHiglModel : public QAbstractItemModel, public HighlightViewModelIf
{
public:
enum TblColIdx { COL_IDX_PAT, COL_IDX_REGEXP, COL_IDX_CASE, COL_IDX_FMT, COL_COUNT };
DlgHiglModel(Highlighter * higl);
virtual ~DlgHiglModel() {}
const SearchPar& getSearchPar(const QModelIndex& index) const;
virtual const HiglFmtSpec * getFmtSpec(const QModelIndex& index) const override;
HiglId getFmtId(const QModelIndex& index) const;
int getIdxForId(HiglId id) const;
bool isModified() const { return m_modified; }
void saveData(Highlighter * higl);
virtual QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
virtual QModelIndex parent(const QModelIndex&) const override { return QModelIndex(); }
virtual int rowCount(const QModelIndex& parent = QModelIndex()) const override;
virtual int columnCount(const QModelIndex& parent = QModelIndex()) const override;
virtual Qt::ItemFlags flags(const QModelIndex& index) const override;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
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 moveRows(const QModelIndex &sourceParent, int sourceRow, int count,
const QModelIndex &destinationParent, int destinationChild) override;
virtual bool insertRowData(int row, const SearchPar& pat, const HiglFmtSpec& fmtSpec); /*non-override*/
void setFmtData(int row, const HiglFmtSpec& fmtSpec);
void forceRedraw(TblColIdx col);
// implementation of HighlightViewModelIf interfaces
virtual QVariant higlModelData(const QModelIndex& index, int role = Qt::DisplayRole) const override;
private:
std::vector<HiglPatExport> m_patList;
HiglId m_firstFreeId;
bool m_modified;
};
DlgHiglModel::DlgHiglModel(Highlighter * higl)
{
// get a copy of the pattern & highlighting format list
higl->getPatList(m_patList);
m_firstFreeId = m_patList.size();
m_modified = false;
}
void DlgHiglModel::saveData(Highlighter * higl)
{
higl->setPatList(m_patList);
m_modified = false;
}
const HiglFmtSpec * DlgHiglModel::getFmtSpec(const QModelIndex& index) const
{
if ((size_t)index.row() < m_patList.size())
return &m_patList.at(index.row()).m_fmtSpec;
return nullptr;
}
const SearchPar& DlgHiglModel::getSearchPar(const QModelIndex& index) const
{
return m_patList.at(index.row()).m_srch;
}
HiglId DlgHiglModel::getFmtId(const QModelIndex& index) const
{
return m_patList.at(index.row()).m_id;
}
int DlgHiglModel::getIdxForId(HiglId id) const
{
for (size_t idx = 0; idx < m_patList.size(); ++idx)
if (m_patList[idx].m_id == id)
return idx;
return -1;
}
QModelIndex DlgHiglModel::index(int row, int column, const QModelIndex& /*parent*/) const
{
return createIndex(row, column);
}
int DlgHiglModel::rowCount(const QModelIndex& /*parent*/) const
{
return m_patList.size();
}
int DlgHiglModel::columnCount(const QModelIndex& /*parent*/) const
{
return COL_COUNT;
}
QVariant DlgHiglModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal)
{
if (role == Qt::DisplayRole)
{
switch (section)
{
case COL_IDX_PAT: return QVariant("Pattern");
case COL_IDX_REGEXP: return QVariant("Reg.Exp.?");
case COL_IDX_CASE: return QVariant("Match case?");
case COL_IDX_FMT: return QVariant("Format");
default: break;
}
qWarning("Invalid index:%d for headerData()", section);
}
else if (role == Qt::ToolTipRole)
{
switch (section)
{
case COL_IDX_PAT: return QVariant("<P>Shows the search text or regular expression.</P>");
case COL_IDX_REGEXP: return QVariant("<P>Shows \"true\" if the search string is a Regular Expression (Perl syntax), or \"false\" if it is a plain sub-string.</P>");
case COL_IDX_CASE: return QVariant("<P>Shows \"true\" if text matches only when in the same case as in the given pattern.</P>");
case COL_IDX_FMT: return QVariant("<P>Shows the assigned mark-up applied to a sample text. (Double-click for opening the mark-up editor.)</P>");
default: break;
}
}
}
else
{
if ((role == Qt::DisplayRole) && ((size_t)section < m_patList.size()))
{
return QVariant(QString::number(section + 1));
}
}
return QVariant();
}
QVariant DlgHiglModel::data(const QModelIndex &index, int role) const
{
if ( ((role == Qt::DisplayRole) || (role == Qt::EditRole))
&& ((size_t)index.row() < m_patList.size()))
{
const SearchPar& el = m_patList.at(index.row()).m_srch;
switch (index.column())
{
case COL_IDX_PAT: return QVariant(el.m_pat);
case COL_IDX_REGEXP: return QVariant(el.m_opt_regexp);
case COL_IDX_CASE: return QVariant(el.m_opt_case);
case COL_IDX_FMT: return QVariant(); // content rendered by item delegate
default: break;
}
qWarning("Invalid index:%d for data()", index.column());
}
return QVariant();
}
Qt::ItemFlags DlgHiglModel::flags(const QModelIndex &index) const
{
if ((size_t)index.row() < m_patList.size())
{
switch (index.column())
{
case COL_IDX_PAT: return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
case COL_IDX_REGEXP: /* fall-through */
case COL_IDX_CASE: return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable;
case COL_IDX_FMT: return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
default: break;
}
}
return Qt::NoItemFlags;
}
bool DlgHiglModel::setData(const QModelIndex &index, const QVariant &value, int /*role*/)
{
int row = index.row();
int col = index.column();
bool result = false;
if ((size_t)row < m_patList.size())
{
SearchPar& el = m_patList.at(row).m_srch;
if (col == COL_IDX_PAT)
{
QString str = value.toString();
// TODO also validate reg.exp. if applicable; display warning
if (!str.isEmpty() && (str != el.m_pat))
{
el.m_pat = str;
m_modified = true;
result = true;
}
}
else if (col == COL_IDX_REGEXP)
{
if (el.m_opt_regexp != value.toBool())
{
el.m_opt_regexp = value.toBool();
m_modified = true;
result = true;
}
}
else if (col == COL_IDX_CASE)
{
if (el.m_opt_case != value.toBool())
{
el.m_opt_case = value.toBool();
m_modified = true;
result = true;
}
}
if (result)
emit dataChanged(index, index);
}
return result;
}
void DlgHiglModel::setFmtData(int row, const HiglFmtSpec& fmtSpec)
{
if ((size_t)row < m_patList.size())
{
m_patList.at(row).m_fmtSpec = fmtSpec;
m_modified = true;
QModelIndex index = createIndex(row, COL_IDX_FMT);
emit dataChanged(index, index);
}
}
bool DlgHiglModel::removeRows(int row, int count, const QModelIndex& parent)
{
bool result = false;
if (size_t(row) + size_t(count) <= m_patList.size())
{
this->beginRemoveRows(parent, row, row + count - 1);
m_patList.erase(m_patList.begin() + row,
m_patList.begin() + (row + count));
this->endRemoveRows();
m_modified = true;
result = true;
}
return result;
}
bool DlgHiglModel::moveRows(const QModelIndex& srcParent, int srcRow, int count,
const QModelIndex& dstParent, int dstRow)
{
bool result = false;
if (size_t(srcRow) + size_t(count) <= m_patList.size())
{
Q_ASSERT(count > 0);
Q_ASSERT((dstRow < srcRow) || (dstRow >= srcRow + count));
if (this->beginMoveRows(srcParent, srcRow, srcRow + count - 1, dstParent, dstRow))
{
std::vector<HiglPatExport> tmp;
tmp.insert(tmp.begin(), m_patList.begin() + srcRow,
m_patList.begin() + srcRow + count);
m_patList.insert(m_patList.begin() + dstRow, tmp.begin(), tmp.end());
// remove the original; adapt index change due to insertion, if needed
int off = ((dstRow < srcRow) ? count : 0);
m_patList.erase( m_patList.begin() + srcRow + off,
m_patList.begin() + srcRow + count + off);
this->endMoveRows();
m_modified = true;
result = true;
}
else
qCritical("DlgHiglModel::moveRows failed in beginMoveRows");
}
return result;
}
bool DlgHiglModel::insertRowData(int row, const SearchPar& pat, const HiglFmtSpec& fmtSpec)
{
bool result = false;
if (size_t(row) <= m_patList.size()) // == OK: insert at end
{
HiglPatExport w;
w.m_srch = pat;
w.m_fmtSpec = fmtSpec;
w.m_id = ++m_firstFreeId;
this->beginInsertRows(QModelIndex(), row, row);
m_patList.insert(m_patList.begin() + row, w);
this->endInsertRows();
m_modified = true;
result = true;
}
return result;
}
// called when external state has changed that affects rendering
void DlgHiglModel::forceRedraw(TblColIdx col) // ATTN row/col order reverse of usual
{
if (m_patList.size() != 0)
{
emit dataChanged(createIndex(0, col),
createIndex(m_patList.size() - 1, col));
}
}
// implementation of HighlightViewModelIf interfaces
QVariant DlgHiglModel::higlModelData(const QModelIndex& /*index*/, int /*role*/) const
{
return QVariant("...Sample text...");
}
// ----------------------------------------------------------------------------
/**
* This helper class overloads the standard QTableView class to allow
* overriding several key bindings.
*/
class DlgHiglView : public QTableView
{
public:
DlgHiglView(QWidget *parent)
: QTableView(parent)
{
}
virtual void keyPressEvent(QKeyEvent *e) override;
};
void DlgHiglView::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
// Firstly make Home key behave same with and without CTRL
// Secondly correct behavior so that target line is selected
case Qt::Key_Home:
if (model()->rowCount() != 0)
{
QModelIndex midx = model()->index(0, 0);
this->setCurrentIndex(midx);
}
break;
case Qt::Key_End:
if (int count = model()->rowCount())
{
QModelIndex midx = model()->index(count - 1, 0);
this->setCurrentIndex(midx);
}
break;
default:
QTableView::keyPressEvent(e);
break;
}
}
// ----------------------------------------------------------------------------
/**
* This function creates and shows the highlight list editor dialog.
*/
DlgHigl::DlgHigl(Highlighter * higl, MainSearch * search, MainText * mainText, MainWin * mainWin)
: m_higl(higl)
, m_search(search)
, m_mainText(mainText)
, m_mainWin(mainWin)
{
this->setWindowTitle("Highlight patterns - trowser");
auto central_wid = new QWidget();
auto layout_top = new QVBoxLayout(central_wid);
m_model = new DlgHiglModel(higl);
m_fmtDelegate = new HighlightViewDelegate(m_model, true,
m_mainText->getFontContent(),
m_mainText->getFgColDefault(),
m_mainText->getBgColDefault());
// main dialog component: table view, showing a list of user-defined patterns
m_table = new DlgHiglView(central_wid);
m_table->setModel(m_model);
m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
m_table->horizontalHeader()->setSectionResizeMode(DlgHiglModel::COL_IDX_PAT, QHeaderView::Stretch);
m_table->horizontalHeader()->setSectionResizeMode(DlgHiglModel::COL_IDX_FMT, QHeaderView::ResizeToContents);
m_table->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // use delegate's sizeHint()
m_table->setItemDelegateForColumn(DlgHiglModel::COL_IDX_FMT, m_fmtDelegate);
m_table->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_table, &QAbstractItemView::customContextMenuRequested, this, &DlgHigl::showContextMenu);
connect(m_table, &QAbstractItemView::doubleClicked, [=](const QModelIndex & midx){
if (midx.column() == DlgHiglModel::COL_IDX_FMT) cmdEditFormat(true); // else use "inline" editor
});
connect(m_table->selectionModel(), &QItemSelectionModel::selectionChanged, this, &DlgHigl::selectionChanged);
layout_top->addWidget(m_table);
// Standard buttons at the bottom of the dialog window: Ok/Cancel/Apply
m_cmdButs = new QDialogButtonBox(QDialogButtonBox::Cancel |
QDialogButtonBox::Apply |
QDialogButtonBox::Ok,
Qt::Horizontal, central_wid);
m_cmdButs->button(QDialogButtonBox::Ok)->setToolTip("<P>Apply changes and close the dialog window.</P>");
m_cmdButs->button(QDialogButtonBox::Cancel)->setToolTip("<P>Discard all changes (if any, since last 'Apply') and close the dialog window.</P>");
m_cmdButs->button(QDialogButtonBox::Apply)->setToolTip("<P>Apply search pattern or mark-up changes to the text in the main window.</P>");
connect(m_cmdButs, &QDialogButtonBox::clicked, this, &DlgHigl::cmdButton);
layout_top->addWidget(m_cmdButs);
// enable "Apply" button only upon modification of model data
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(false);
connect(m_model, &DlgHiglModel::dataChanged, this, &DlgHigl::cbDataChanged);
// Status line overlay: used to display notification text
m_stline = new StatusLine(m_table);
connect(mainText, &MainText::textFontChanged, this, &DlgHigl::mainFontChanged);
//
// "Edit" toolbar: functionality for adding/removing/sorting the list
//
auto f1 = new QToolBar("Edit", this);
f1->setObjectName("DlgHigl::Edit"); // for saveState
addToolBar(Qt::TopToolBarArea, f1);
auto f1_l = new QLabel("Edit:", f1);
f1->addWidget(f1_l);
auto m_f1_add = new QPushButton(this->style()->standardIcon(QStyle::SP_FileIcon), "Add new item", f1);
m_f1_add->setToolTip("<P>Create a new highlight entry in the list, containing main window's "
"current search parameters and a default background mark-up. Note the "
"context menu also allows duplicating existing entries.</P>");
m_f1_add->setFocusPolicy(Qt::TabFocus);
connect(m_f1_add, &QPushButton::clicked, this, &DlgHigl::cmdAdd);
f1->addWidget(m_f1_add);
m_f1_del = new QPushButton(this->style()->standardIcon(QStyle::SP_TrashIcon), "Remove...", f1);
m_f1_del->setToolTip("<P>Delete the currently selected entry from the list. "
"(Can be undone by leaving the dialog window via 'Cancel'.)</P>");
m_f1_del->setEnabled(false);
m_f1_del->setShortcut(QKeySequence(Qt::Key_Delete));
m_f1_del->setFocusPolicy(Qt::TabFocus);
connect(m_f1_del, &QPushButton::clicked, this, &DlgHigl::cmdRemove);
f1->addWidget(m_f1_del);
m_f1_up = new QPushButton(this->style()->standardIcon(QStyle::SP_ArrowUp), "Move up", f1);
m_f1_up->setToolTip("<P>Move all selected entries upwards in the list (unless the top-most entry is selected). "
"Note order of list entries may affect mark-up of text lines that match multiple entries.</P>");
m_f1_up->setEnabled(false);
m_f1_up->setFocusPolicy(Qt::TabFocus);
connect(m_f1_up, &QPushButton::clicked, this, &DlgHigl::cmdShiftUp);
f1->addWidget(m_f1_up);
m_f1_down = new QPushButton(this->style()->standardIcon(QStyle::SP_ArrowDown), "Move down", f1);
m_f1_down->setToolTip("<P>Move all selected entries downwards in the list (unless the bottom-most entry is selected). "
"Note order of list entries may affect mark-up of text lines that match multiple entries.</P>");
m_f1_down->setEnabled(false);
m_f1_down->setFocusPolicy(Qt::TabFocus);
connect(m_f1_down, &QPushButton::clicked, this, &DlgHigl::cmdShiftDown);
f1->addWidget(m_f1_down);
m_f1_fmt = new QPushButton("Format...", f1);
m_f1_fmt->setToolTip("<P>Open the mark-up editor for the selected entry, which allows "
"modifying the appearance of text lines matching this pattern.</P>");
m_f1_fmt->setEnabled(false);
m_f1_fmt->setFocusPolicy(Qt::TabFocus);
connect(m_f1_fmt, &QPushButton::clicked, this, &DlgHigl::cmdEditFormat);
f1->addWidget(m_f1_fmt);
//
// "Find" toolbar: functionality for applying search patterns
//
auto f2 = new QToolBar("Find", this);
f2->setObjectName("DlgHigl::Find"); // for saveState
addToolBar(Qt::RightToolBarArea, f2);
auto f2_l = new QLabel("Find:", f2);
f2->addWidget(f2_l);
m_f2_bn = new QPushButton("&Next", f2);
m_f2_bn->setToolTip("<P>Start searching forward in the main window for the first occurence of one of the selected patterns.</P>");
m_f2_bn->setEnabled(false);
m_f2_bn->setFocusPolicy(Qt::TabFocus);
connect(m_f2_bn, &QPushButton::clicked, [=](){ cmdSearch(true); });
f2->addWidget(m_f2_bn);
m_f2_bp = new QPushButton("&Prev.", f2);
m_f2_bp->setToolTip("<P>Start searching backward in the main window for the first occurence of one of the selected patterns.</P>");
m_f2_bp->setEnabled(false);
m_f2_bp->setFocusPolicy(Qt::TabFocus);
connect(m_f2_bp, &QPushButton::clicked, [=](){ cmdSearch(false); });
f2->addWidget(m_f2_bp);
m_f2_ball = new QPushButton("&All", f2);
m_f2_ball->setToolTip("<P>Open a new window showing all lines of the main text that contain a match on one of the selected patterns.</P>");
m_f2_ball->setEnabled(false);
m_f2_ball->setFocusPolicy(Qt::TabFocus);
connect(m_f2_ball, &QPushButton::clicked, [=](){ cmdSearchList(0); });
f2->addWidget(m_f2_ball);
m_f2_ballb = new QPushButton("All below", f2);
m_f2_ballb->setToolTip("<P>Open a new window showing all lines of the main text below the currently selected line that contain a match on one of the selected patterns.</P>");
m_f2_ballb->setEnabled(false);
m_f2_ballb->setFocusPolicy(Qt::TabFocus);
m_f2_ballb->setShortcut(QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_N));
connect(m_f2_ballb, &QPushButton::clicked, [=](){ cmdSearchList(1); });
f2->addWidget(m_f2_ballb);
m_f2_balla = new QPushButton("All above", f2);
m_f2_balla->setToolTip("<P>Open a new window showing all lines of the main text above the currently selected line that contain a match on one of the selected patterns.</P>");
m_f2_balla->setEnabled(false);
m_f2_balla->setFocusPolicy(Qt::TabFocus);
m_f2_balla->setShortcut(QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_P));
connect(m_f2_balla, &QPushButton::clicked, [=](){ cmdSearchList(-1); });
f2->addWidget(m_f2_balla);
auto act = new QAction(central_wid);
act->setShortcut(QKeySequence(Qt::Key_Ampersand));
connect(act, &QAction::triggered, [=](){ m_search->searchHighlightClear(); });
central_wid->addAction(act);
this->setCentralWidget(central_wid);
if (!s_winGeometry.isEmpty())
this->restoreGeometry(s_winGeometry);
if (!s_winState.isEmpty())
this->restoreState(s_winState);
m_table->setFocus(Qt::ShortcutFocusReason);
this->show();
}
/**
* Destructor: Freeing resources not automatically deleted via widget tree
*/
DlgHigl::~DlgHigl()
{
delete m_model;
delete m_fmtDelegate;
}
/**
* This slot is connected to notification of font changes in the main text
* window, as the same font is used for displaying text content in the dialog.
* The function resizes row height and then forces a redraw. Note the new font
* need not be passed to the view delegate as it gets passed a reference to the
* font so that it picks up the new font automatically.
*/
void DlgHigl::mainFontChanged()
{
QFontMetrics metrics1(m_mainText->getFontContent());
QFontMetrics metrics2(m_table->font());
m_table->verticalHeader()->setDefaultSectionSize(2*3 + std::max(metrics1.height(), metrics2.height()));
m_model->forceRedraw(DlgHiglModel::COL_IDX_FMT);
}
/**
* This function is bound to changes of the selection in the color tags list.
*/
void DlgHigl::selectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/)
{
auto sel = m_table->selectionModel()->selectedRows();
bool enabled = (sel.size() > 0);
m_f1_del->setEnabled(enabled);
m_f1_up->setEnabled(enabled);
m_f1_down->setEnabled(enabled);
m_f1_fmt->setEnabled(sel.size() == 1);
m_f2_bn->setEnabled(enabled);
m_f2_bp->setEnabled(enabled);
m_f2_ball->setEnabled(enabled);
m_f2_ballb->setEnabled(enabled);
m_f2_balla->setEnabled(enabled);
}
/**
* This slot is connected to a signal sent by the model whenever data is
* modified. The function enables the "Apply" button, which allows saving
* the changes as well as visually indicates the status to the user.
*/
void DlgHigl::cbDataChanged(const QModelIndex &, const QModelIndex &)
{
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(true);
}
/**
* This function is bound to right mouse clicks in the highlight tag list and pops
* up a context menu. The menu is populated and shown at the given coordinates.
*/
void DlgHigl::showContextMenu(const QPoint& pos)
{
auto menu = new QMenu("Pattern list actions", this);
auto searchPar = m_search->getCurSearchParams();
auto sel = m_table->selectionModel()->selectedRows();
bool state_find_sel_1 = (!searchPar.m_pat.isEmpty() && (sel.size() == 1));
bool state_sel_1 = (sel.size() == 1);
bool state_sel_n0 = (sel.size() > 0);
auto act = menu->addAction("Change background color");
act->setEnabled(state_sel_1);
connect(act, &QAction::triggered, [=](){ cmdChangeBgFgColor(true); });
act = menu->addAction("Change foreground color");
act->setEnabled(state_sel_1);
connect(act, &QAction::triggered, [=](){ cmdChangeBgFgColor(false); });
QMenu *sub = menu->addMenu("Font options");
if (state_sel_1)
{
const HiglFmtSpec * pFmtSpec = m_model->getFmtSpec(sel.front());
bool optEna = pFmtSpec->m_font.isEmpty();
act = sub->addAction("Bold");
act->setEnabled(optEna);
act->setCheckable(true);
act->setChecked(pFmtSpec->m_bold);
connect(act, &QAction::triggered, [=](){ cmdToggleFontBold(sel.front(), act->isChecked()); });
act = sub->addAction("Italic");
act->setEnabled(optEna);
act->setCheckable(true);
act->setChecked(pFmtSpec->m_italic);
connect(act, &QAction::triggered, [=](){ cmdToggleFontItalic(sel.front(), act->isChecked()); });
act = sub->addAction("Underline");
act->setEnabled(optEna);
act->setCheckable(true);
act->setChecked(pFmtSpec->m_underline);
connect(act, &QAction::triggered, [=](){ cmdToggleFontUnderline(sel.front(), act->isChecked()); });
act = sub->addAction("Strikeout");
act->setEnabled(optEna);
act->setCheckable(true);
act->setChecked(pFmtSpec->m_strikeout);
connect(act, &QAction::triggered, [=](){ cmdToggleFontStrikeout(sel.front(), act->isChecked()); });
act = sub->addAction("Overline");
act->setEnabled(optEna);
act->setCheckable(true);
act->setChecked(pFmtSpec->m_overline);
connect(act, &QAction::triggered, [=](){ cmdToggleFontOverline(sel.front(), act->isChecked()); });
act = sub->addSeparator();
act = sub->addAction("Reset font to default");
act->setEnabled(!optEna);
connect(act, &QAction::triggered, [=](){ cmdResetFont(sel.front()); });
act = sub->addAction("Font family && options...");
connect(act, &QAction::triggered, this, &DlgHigl::cmdChangeFont);
}
else
{
sub->setEnabled(false);
}
act = menu->addAction("More format options...");
act->setEnabled(state_sel_1);
connect(act, &QAction::triggered, this, &DlgHigl::cmdEditFormat);
menu->addSeparator();
act = menu->addAction("Copy pattern to main window");
act->setEnabled(state_sel_1);
connect(act, &QAction::triggered, this, &DlgHigl::cmdCopyToMain);
act = menu->addAction("Copy pattern from main window");
act->setEnabled(state_find_sel_1);
connect(act, &QAction::triggered, this, &DlgHigl::cmdCopyFromMain);
menu->addSeparator();
act = menu->addAction("Duplicate this entry");
act->setEnabled(state_sel_1);
connect(act, &QAction::triggered, this, &DlgHigl::cmdDuplicate);
act = menu->addAction("Remove selected entries");
act->setEnabled(state_sel_n0);
connect(act, &QAction::triggered, this, &DlgHigl::cmdRemove);
act = menu->addAction("Move Up");
act->setEnabled(state_sel_n0);
connect(act, &QAction::triggered, this, &DlgHigl::cmdShiftUp);
act = menu->addAction("Move Down");
act->setEnabled(state_sel_n0);
connect(act, &QAction::triggered, this, &DlgHigl::cmdShiftDown);
menu->exec(mapToGlobal(pos));
}
/**
* This function is bound to destruction of the dialog window. The event is
* also sent artificially upon the "Cancel" button.
*/
void DlgHigl::closeEvent(QCloseEvent * event)
{
if (m_model->isModified())
{
auto answer = QMessageBox::question(this, "trowser", "Discard unsaved changes in the pattern highlight list?",
QMessageBox::Ok | QMessageBox::Cancel);
if (answer != QMessageBox::Ok)
{
if (event)
event->ignore();
return;
}
}
s_winGeometry = this->saveGeometry();
s_winState = this->saveState();
if (event)
event->accept();
else
this->close();
s_instance->deleteLater();
s_instance = nullptr;
}
/**
* This function is bound to all of the grouped main command buttons: Ok,
* Apply, Cancel. As usual, Ok will save & close, Cancel will confirm &
* discard & close, and Apply will only save.
*/
void DlgHigl::cmdButton(QAbstractButton * button)
{
if (button == m_cmdButs->button(QDialogButtonBox::Cancel))
{
QCoreApplication::postEvent(this, new QCloseEvent());
}
else if (button == m_cmdButs->button(QDialogButtonBox::Ok))
{
if (m_model->isModified())
m_model->saveData(m_higl);
QCoreApplication::postEvent(this, new QCloseEvent());
}
else if (button == m_cmdButs->button(QDialogButtonBox::Apply))
{
if (m_model->isModified())
{
m_model->saveData(m_higl);
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(false);
}
}
}
/**
* This function is invoked by the "Add new item" entry in the highlight
* list's toolbar and context menu. The new entry is given the current or
* last used search parameters from the main menu and a default highlight
* format with a hard-coded background color.
*/
void DlgHigl::cmdAdd(bool)
{
auto sel = m_table->selectionModel()->selectedRows();
int row = ((sel.size() > 0) ? sel.front().row() : m_model->rowCount());
auto pat = m_search->getCurSearchParams();
if (pat.m_pat.isEmpty())
pat.m_pat = "Enter pattern...";
HiglFmtSpec fmtSpec;
fmtSpec.m_bgCol = 0xfffaee0a; //TODO s_colFind
m_model->insertRowData(row, pat, fmtSpec);
// select item and make it visible
QModelIndex midx = m_model->index(row, DlgHiglModel::COL_IDX_PAT);
m_table->selectionModel()->select(midx, QItemSelectionModel::Clear);
m_table->setCurrentIndex(midx);
m_table->scrollTo(midx);
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(true);
}
/**
* This function is invoked by the "Duplicate entry" command in the highlight
* list's context menu. (The command is not available via toolbar.) It creates
* a new entry with the same search pattern and highlighting format as the
* selected one.
*/
void DlgHigl::cmdDuplicate(bool)
{
auto sel = m_table->selectionModel()->selectedRows();
if (sel.size() == 1)
{
auto midx = sel.front();
m_model->insertRowData(midx.row(), m_model->getSearchPar(midx),
*m_model->getFmtSpec(midx));
// select item and make it visible
m_table->selectionModel()->select(midx, QItemSelectionModel::Clear);
m_table->setCurrentIndex(midx);
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(true);
}
else // should never occur as button (incl. shortcut) gets disabled
m_stline->showError("search", "No pattern is selected in the list");
}
/**
* This function is invoked by the "Remove entry" command in the highlight
* list's toolbar and context menu. It removes all selected entries without
* asking for confirmation (the user can still "Cancel" the dialog to undo
* the deletion.)
*/
void DlgHigl::cmdRemove(bool)
{
auto sel = m_table->selectionModel()->selectedRows();
if (sel.size() > 0)
{
for (auto& midx : sel)
{
auto it = findDlgMarkup(m_model->getFmtId(midx), m_dlgMarkup);
if (it != m_dlgMarkup.end())
m_dlgMarkup.erase(it);
}
// reverse-sort index list so that indices do not need adaption during removal
std::sort(sel.begin(), sel.end(),
[](const QModelIndex& a, const QModelIndex&b)->bool {return a.row() > b.row();});
for (auto& midx : sel)
{
m_model->removeRows(midx.row(), 1);
}
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(true);
}
else // should never occur as button (incl. shortcut) gets disabled
m_stline->showError("search", "No pattern is selected in the list");
}
/**
* This function is bound to the "Move up" button. Each selected item (where
* selection may be non-consecutive) is shifted up by one row. If the first
* selected item is already at top, the function does nothing.
*/
void DlgHigl::cmdShiftUp(bool)
{
auto sel = m_table->selectionModel()->selectedRows();
if (sel.size() > 0)
{
// sort index list so that indices do not need adaption during removal
std::sort(sel.begin(), sel.end(),
[](const QModelIndex& a, const QModelIndex&b)->bool {return a.row() < b.row();});
if (sel.front().row() > 0) // first element is already at top
{
for (auto& midx : sel)
{
m_model->moveRows(QModelIndex(), midx.row(), 1,
QModelIndex(), midx.row() - 1);
}
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(true);
}
else
m_stline->showWarning("edit", "Item is already at the top - cannot move up");
}
}
/**
* This function is bound to the "down" button next to the color highlight
* list. Each selected item is shifted down by one line.
*/
void DlgHigl::cmdShiftDown(bool)
{
auto sel = m_table->selectionModel()->selectedRows();
if (sel.size() > 0)
{
// reverse-sort index list so that indices do not need adaption during removal
std::sort(sel.begin(), sel.end(),
[](const QModelIndex& a, const QModelIndex&b)->bool {return a.row() > b.row();});
if (sel.front().row() + 1 < m_model->rowCount()) // lowest element is already at bottom
{
for (auto& midx : sel)
{
// second +1 needed due to semantics of QAbstractItemModel::beginMoveRows
m_model->moveRows(QModelIndex(), midx.row(), 1,
QModelIndex(), midx.row() + 1 + 1);
}
m_cmdButs->button(QDialogButtonBox::Apply)->setEnabled(true);
}
else
m_stline->showWarning("edit", "Item is already at the bottom - cannot move down");
}
}
/**
* This helper function searches the list of pointers to mark-up editor dialogs
* for one working for the given highlight id. It returns a list iterator that
* has value end() as usual when no such item was found.
*/
DlgHigl::DlgMarkupPtrList::iterator DlgHigl::findDlgMarkup(HiglId id, DlgHigl::DlgMarkupPtrList& v)
{
for (auto it = v.begin(); it != v.end(); ++it)
if ((*it)->getFmtId() == id)
return it;
return v.end();
}
/**
* This function is invoked by the "Format..." command in the highlight list's
* toolbar and context menu. It can also be used via double-click on a list
* item. The function opens the mark-up editor for the selected entry.
*/
void DlgHigl::cmdEditFormat(bool)
{
auto sel = m_table->selectionModel()->selectedRows();
if (sel.size() > 0)
{
const HiglFmtSpec * fmtSpec = m_model->getFmtSpec(sel.front());
const SearchPar& pat = m_model->getSearchPar(sel.front());
HiglId id = m_model->getFmtId(sel.front());
auto it = findDlgMarkup(id, m_dlgMarkup);
if (it == m_dlgMarkup.end())
{
QString title = QString("Pattern /") + pat.m_pat + "/ mark-up";
auto ptr = std::make_unique<DlgMarkup>(id, fmtSpec, title, m_higl, m_mainText, m_mainWin);
connect(ptr.get(), &DlgMarkup::closeReq, this, &DlgHigl::signalMarkupCloseReq);
connect(ptr.get(), &DlgMarkup::applyReq, this, &DlgHigl::signalMarkupApplyReq);
m_dlgMarkup.push_back(std::move(ptr));
}
else // dialog for that pattern is already open
{
(*it)->activateWindow();
(*it)->raise();
}
}
}
/**
* This slot is connected to the signal sent when a mark-up editor dialog is
* closed. The function releases the dialog resources.
*/
void DlgHigl::signalMarkupCloseReq(HiglId id)
{
auto it = findDlgMarkup(id, m_dlgMarkup);
if (it != m_dlgMarkup.end())