swift
Loading...
Searching...
No Matches
viewbase.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QApplication>
7#include <QClipboard>
8#include <QFileDialog>
9#include <QStringBuilder>
10#include <QTextEdit>
11
12#include "config/buildconfig.h"
14#include "gui/guiutility.h"
15#include "gui/models/allmodels.h"
18#include "misc/worker.h"
19
20using namespace swift::misc;
21using namespace swift::gui;
22using namespace swift::gui::menus;
23using namespace swift::gui::models;
24using namespace swift::gui::filters;
25using namespace swift::gui::settings;
26using namespace swift::gui::components;
27
28namespace swift::gui::views
29{
30 template <class T>
32 {
33 this->setSortingEnabled(true);
34 if (model)
35 {
36 this->standardInit(model);
37 }
38 }
39
40 template <class T>
42 {
43 Q_ASSERT_X(m_model, Q_FUNC_INFO, "Missing model");
44 if (container.isEmpty())
45 {
46 // shortcut
47 this->clear();
48 return 0;
49 }
50
51 // we have data
52 this->showLoadIndicator(container.size());
53 const bool reallyResize = resize && isResizeConditionMet(container.size()); // do we really perform resizing
54 bool presize = (m_resizeMode == PresizeSubset) && this->isEmpty() && // only when no data yet
55 !reallyResize; // not when we resize later
56 presize =
57 presize || (this->isEmpty() && resize &&
58 !reallyResize); // we presize if we wanted to resize but actually do not because of condition
59 const bool presizeThresholdReached =
60 presize && container.size() > ResizeSubsetThreshold; // only when size making sense
61
62 // when we will not resize, we might presize
63 if (presizeThresholdReached)
64 {
65 const int presizeRandomElements = this->getPresizeRandomElementsSize(container.size());
66 if (presizeRandomElements > 0)
67 {
68 m_model->update(container.sampleElements(presizeRandomElements), false);
70 }
71 }
72
73 const int c = m_model->update(container, sort);
74
75 // resize after real update according to mode
76 if (presizeThresholdReached) // cppcheck-suppress knownConditionTrueFalse
77 {
78 // currently no furhter actions
79 }
80 else if (reallyResize)
81 {
82 this->resizeToContents(); // mode based resize
83 }
84 else if (presize && !presizeThresholdReached) // cppcheck-suppress knownConditionTrueFalse
85 {
86 // small amount of data not covered before
88 }
89 this->updateSortIndicator(); // make sure sort indicator represents sort order
90 this->hideLoadIndicator();
91 return c;
92 }
93
94 template <class T>
96 {
97 // avoid unnecessary effort when empty
98 if (container.isEmpty())
99 {
100 this->clear();
101 return nullptr;
102 }
103
104 Q_UNUSED(sort)
105 ModelClass *model = this->derivedModel();
106 const auto sortColumn = model->getSortColumn();
107 const auto sortOrder = model->getSortOrder();
108 this->showLoadIndicator(container.size());
109 CWorker *worker = CWorker::fromTask(this, "ViewSort", [model, container, sortColumn, sortOrder]() {
110 return model->sortContainerByColumn(container, sortColumn, sortOrder);
111 });
112 worker->thenWithResult<ContainerType>(this, [this, resize](const ContainerType &sortedContainer) {
113 this->updateContainer(sortedContainer, false, resize);
114 });
115 worker->then(this, &CViewBase::asyncUpdateFinished);
116 return worker;
117 }
118
119 template <class T>
121 {
122 if (container.isEmpty())
123 {
124 this->clear();
125 }
126 else if (container.size() > ASyncRowsCountThreshold && sort)
127 {
128 // larger container with sorting
130 }
131 else
132 {
134 }
135 }
136
137 template <class T>
138 void CViewBase<T>::insert(const ObjectType &value, bool resize)
139 {
140 Q_ASSERT(m_model);
141 if (this->rowCount() < 1)
142 {
143 // this allows presizing
144 this->updateContainerMaybeAsync(ContainerType({ value }), true, resize);
145 }
146 else
147 {
148 m_model->insert(value);
149 if (resize)
150 {
152 }
153 }
154 }
155
156 template <class T>
158 {
159 Q_ASSERT(m_model);
160 if (this->rowCount() < 1)
161 {
162 // this allows presizing
164 }
165 else
166 {
167 m_model->insert(container);
168 if (resize)
169 {
171 }
172 }
173 }
174
175 template <class T>
177 {
178 Q_ASSERT(m_model);
179 if (this->rowCount() < 1)
180 {
181 // this allows presizing
182 this->updateContainerMaybeAsync(ContainerType({ value }), true, resize);
183 }
184 else
185 {
186 m_model->push_back(value);
187 if (resize)
188 {
190 }
191 }
192 }
193
194 template <class T>
196 {
197 Q_ASSERT(m_model);
198 if (this->rowCount() < 1)
199 {
200 // this allows presizing
202 }
203 else
204 {
205 m_model->push_back(container);
206 if (resize)
207 {
209 }
210 }
211 }
212
213 template <class T>
214 const typename CViewBase<T>::ObjectType &CViewBase<T>::at(const QModelIndex &index) const
215 {
216 Q_ASSERT(m_model);
217 return m_model->at(index);
218 }
219
220 template <class T>
222 {
223 Q_ASSERT(m_model);
224 return m_model->container();
225 }
226
227 template <class T>
229 {
230 QList<int> rows;
231 for (const ObjectType &o : container)
232 {
233 const int i = this->rowOf(o);
234 if (i >= 0)
235 {
236 rows.push_back(i);
237 }
238 }
239 return rows;
240 }
241
242 template <class T>
243 int CViewBase<T>::rowOf(const ObjectType &obj) const
244 {
246 const ContainerType objects = m_model->containerOrFilteredContainer();
247 int i = 0;
248 for (const ObjectType &o : objects)
249 {
250 if (o == obj)
251 {
252 return i;
253 }
254 ++i;
255 }
256 return -1;
257 }
258
259 template <class T>
261 {
262 Q_ASSERT(m_model);
263 return m_model->containerOrFilteredContainer(filtered);
264 }
265
266 template <class T>
268 {
269 if (!this->hasSelection())
270 {
271 return ContainerType();
272 }
274 const QModelIndexList indexes = this->selectedRows();
275 for (const QModelIndex &i : indexes)
276 {
277 c.push_back(this->at(i));
278 }
279 return c;
280 }
281
282 template <class T>
284 {
285 if (!this->hasSelection())
286 {
287 return this->containerOrFilteredContainer();
288 }
290 const QModelIndexList indexes = this->unselectedRows();
291 for (const QModelIndex &i : indexes)
292 {
293 c.push_back(this->at(i));
294 }
295 return c;
296 }
297
298 template <class T>
300 {
301 if (this->hasSelection())
302 {
303 return this->selectedObjects().front();
304 }
305 if (this->rowCount() < 2)
306 {
307 return this->containerOrFilteredContainer().frontOrDefault();
308 }
309
310 // too many, not selected
311 return ObjectType();
312 }
313
314 template <class T>
316 {
317 if (vm.isEmpty())
318 {
319 return 0;
320 }
321 if (!hasSelection())
322 {
323 return 0;
324 }
325 int c = 0;
326
327 int lastUpdatedRow = -1;
328 int firstUpdatedRow = -1;
329 const CPropertyIndexList propertyIndexes(vm.indexes());
330 const QModelIndexList indexes = this->selectedRows();
331
332 for (const QModelIndex &i : indexes)
333 {
334 if (i.row() == lastUpdatedRow)
335 {
336 continue;
337 }
338 lastUpdatedRow = i.row();
339 if (firstUpdatedRow < 0 || lastUpdatedRow < firstUpdatedRow)
340 {
341 firstUpdatedRow = lastUpdatedRow;
342 }
343 ObjectType obj(this->at(i));
344
345 // update all properties in map
346 for (const CPropertyIndex &pi : propertyIndexes)
347 {
348 obj.setPropertyByIndex(pi, vm.value(pi));
349 }
350
351 // and update container
352 if (this->derivedModel()->setInContainer(i, obj))
353 {
354 c++;
355 }
356 }
357
358 if (c > 0)
359 {
360 this->derivedModel()->emitDataChanged(firstUpdatedRow, lastUpdatedRow);
361 }
362 return c;
363 }
364
365 template <class T>
366 int CViewBase<T>::updateSelected(const CVariant &variant, const CPropertyIndex &index)
367 {
368 const CPropertyIndexVariantMap vm(index, variant);
369 return this->updateSelected(vm);
370 }
371
372 template <class T>
374 {
375 const ContainerType c = this->selectedObjects();
376 return c.frontOrDefault();
377 }
378
379 template <class T>
381 {
382 if (!this->hasSelection())
383 {
384 return 0;
385 }
386 if (this->isEmpty())
387 {
388 return 0;
389 }
390
391 const int currentRows = this->rowCount();
392 const ContainerType selected(this->selectedObjects());
393 const CVariant deletedObjsVariant = CVariant::fromValue(selected);
394 int delta = 0;
395
396 if (!this->hasFilter() && currentRows == this->selectedRowCount())
397 {
398 // shortcut if all are selected
399 this->clear(); // clear all
400 delta = currentRows;
401 }
402 else
403 {
405 unselectedObjects.removeIfInSubset(selected);
407 delta = currentRows - unselectedObjects.size();
408 }
409 emit this->objectsDeleted(deletedObjsVariant);
410 return delta;
411 }
412
413 template <class T>
415 {
416 const int rc = this->rowCount();
417 if (rc > ResizeSubsetThreshold)
418 {
419 const int presizeRandomElements = this->getPresizeRandomElementsSize(rc);
420 if (presizeRandomElements > 0)
421 {
422 const ContainerType containerBackup(this->container());
423 m_model->update(containerBackup.sampleElements(presizeRandomElements), false);
424 this->fullResizeToContents();
425 m_model->update(containerBackup, false);
426 }
427 }
428 else
429 {
430 this->fullResizeToContents();
431 }
432 }
433
434 template <class T>
436 {
437 Q_ASSERT(m_model);
438 return m_model->clearHighlighting();
439 }
440
441 template <class T>
443 {
444 Q_ASSERT(m_model);
445 if (!m_model->hasFilter())
446 {
447 return;
448 }
449 if (this->isEmpty())
450 {
451 return;
452 }
453 ContainerType filtered(m_model->containerFiltered());
454 this->removeFilter();
455 this->updateContainerMaybeAsync(filtered);
456 }
457
458 template <class T>
460 {
461 Q_ASSERT(m_model);
462 m_model->clear();
463 this->hideLoadIndicator();
464 }
465
466 template <class T>
468 {
469 Q_ASSERT(m_model);
470 return m_model->rowCount();
471 }
472
473 template <class T>
475 {
476 Q_ASSERT(m_model);
477 return m_model->columnCount(QModelIndex());
478 }
479
480 template <class T>
482 {
483 Q_ASSERT(m_model);
484 return m_model->rowCount() < 1;
485 }
486
487 template <class T>
489 {
490 Q_ASSERT(m_model);
491 return m_model->isOrderable();
492 }
493
494 template <class T>
495 void CViewBase<T>::allowDragDrop(bool allowDrag, bool allowDrop, bool allowDropJsonFile)
496 {
497 Q_ASSERT(m_model);
498
499 // see model for implementing logic of drag
500 this->viewport()->setAcceptDrops(allowDrop);
501 this->setDragEnabled(allowDrag);
502 this->setDropIndicatorShown(allowDrag || allowDrop);
503 m_model->allowDrop(allowDrop);
504 m_model->allowJsonFileDrop(allowDropJsonFile);
505 }
506
507 template <class T>
509 {
510 Q_ASSERT(m_model);
511 return m_model->isDropAllowed();
512 }
513
514 template <class T>
516 {
517 if (m_model && m_model->isJsonFileDropAllowed() &&
519 {
520 const QFileInfo fi = CGuiUtility::representedMimeFile(event->mimeData());
521 const CStatusMessage msgs = this->loadJsonFile(fi.absoluteFilePath());
522 Q_UNUSED(msgs)
523 return;
524 }
526 }
527
528 template <class T>
529 bool CViewBase<T>::acceptDrop(const QMimeData *mimeData) const
530 {
531 Q_ASSERT(m_model);
532 const bool a = m_model->acceptDrop(mimeData);
533 return a;
534 }
535
536 template <class T>
537 bool CViewBase<T>::setSorting(const CPropertyIndex &propertyIndex, Qt::SortOrder order)
538 {
539 Q_ASSERT(m_model);
540 return m_model->setSorting(propertyIndex, order);
541 }
542
543 template <class T>
545 {
546 m_model->sortByPropertyIndex(propertyIndex, order);
547 }
548
549 template <class T>
551 {
552 m_model->sort();
553 }
554
555 template <class T>
557 {
558 m_model->resort();
559 }
560
561 template <class T>
562 QJsonObject CViewBase<T>::toJson(bool selectedOnly) const
563 {
564 Q_ASSERT(m_model);
565 return m_model->toJson(selectedOnly);
566 }
567
568 template <class T>
570 {
571 Q_ASSERT(m_model);
572 return m_model->toJsonString(format, selectedOnly);
573 }
574
575 template <class T>
577 {
578 // then name here is mainly set for debugging purposes so each model can be identified
579 Q_ASSERT(m_model);
581 m_model->setObjectName(name);
582 }
583
584 template <class T>
586 {
587 this->derivedModel()->takeFilterOwnership(filter);
588 }
589
590 template <class T>
592 {
593 this->derivedModel()->removeFilter();
594 }
595
596 template <class T>
598 {
599 return derivedModel()->hasFilter();
600 }
601
602 template <class T>
603 void CViewBase<T>::addContainerTypesAsDropTypes(bool objectType, bool containerType)
604 {
605 if (objectType)
606 {
607 m_model->addAcceptedMetaTypeId(qMetaTypeId<ObjectType>());
608 }
609 if (containerType)
610 {
611 m_model->addAcceptedMetaTypeId(qMetaTypeId<ContainerType>());
612 }
613 }
614
615 template <class T>
617 {
618 Q_ASSERT_X(isOrderable(), Q_FUNC_INFO, "Model not orderable");
619 this->allowDragDrop(true, true);
622 this->addContainerTypesAsDropTypes(true, true);
623 }
624
625 template <class T>
627 {
628 if (!tw)
629 {
630 return;
631 }
632 QString o = tw->tabText(index);
633 const QString f = this->hasFilter() ? "F" : "";
635 tw->setTabText(index, o);
636 }
637
638 template <class T>
640 {
641 const int width = this->width() - 25; // avoid scrollbars etc, reserve a little space
642 QList<int> widths = this->getColumns().calculateWidths(width);
643 if (widths.isEmpty())
644 {
645 return;
646 }
647 for (int c = 0; c < this->getColumns().size(); c++)
648 {
649 const int w = widths.at(c);
650 this->setColumnWidth(c, w);
651 }
652 }
653
654 template <class T>
656 {
657 if (m_model->hasValidSortColumn())
658 {
659 Q_ASSERT(this->horizontalHeader());
660 this->horizontalHeader()->setSortIndicator(m_model->getSortColumn(), m_model->getSortOrder());
661 }
662 }
663
664 template <class T>
666 {
667 Q_ASSERT_X(model || m_model, Q_FUNC_INFO, "Missing model");
668 if (model)
669 {
670 if (model == m_model)
671 {
672 return;
673 }
674 if (m_model)
675 {
676 m_model->disconnect();
677 }
678
679 m_model = model;
680 m_model->setSelectionModel(this); // set myself as selection model
681 bool c = connect(m_model, &ModelClass::modelDataChanged, this, &CViewBase::modelDataChanged);
682 Q_ASSERT_X(c, Q_FUNC_INFO, "Connect failed");
684 Q_ASSERT_X(c, Q_FUNC_INFO, "Connect failed");
686 Q_ASSERT_X(c, Q_FUNC_INFO, "Connect failed");
688 Q_ASSERT_X(c, Q_FUNC_INFO, "Connect failed");
690 Q_ASSERT_X(c, Q_FUNC_INFO, "Connect failed");
691 Q_UNUSED(c)
693
694 this->setModel(m_model); // via QTableView
696 this->setSortIndicator();
697 }
699 template <class T>
700 bool CViewBase<T>::reachedResizeThreshold(int containerSize) const
701 {
702 if (containerSize < 0)
703 {
705 }
706 return containerSize > m_skipResizeThreshold;
708
709 template <class T>
711 {
712 // small set or large set? This only performs real resizing, no presizing
713 // remark, see also presizeOrFullResizeToContents
714 if (this->isResizeConditionMet())
715 {
717 }
718 else
719 {
720 m_resizeCount++; // skipped resize
721 }
723
724 template <class T>
726 {
727 auto c(variant.value<ContainerType>());
728 return this->updateContainer(c, sort, resize);
729 }
730
731 template <class T>
733 {
734 if (this->derivedModel()->hasValidSortColumn())
736 const int index = this->derivedModel()->getSortColumn();
737 Qt::SortOrder order = this->derivedModel()->getSortOrder();
738 this->horizontalHeader()->setSortIndicator(index, order);
739 }
740 }
742 template <class T>
743 void CViewBase<T>::mouseOverCallback(const QModelIndex &index, bool mouseOver)
744 {
745 // void
746 Q_UNUSED(index)
747 Q_UNUSED(mouseOver)
748 }
749
750 template <class T>
752 {
753 m_dropIndicator = indicator;
754 }
755
756 template <class T>
761
762 template <class T>
764 {
765 Q_UNUSED(data)
766 static const CStatusMessage e(this, CStatusMessage::SeverityInfo, u"no modification", true);
767 return e;
768 }
769
770 template <class T>
772 {
773 Q_UNUSED(data)
774 static const CStatusMessage e(this, CStatusMessage::SeverityInfo, u"validation passed", true);
775 return e;
776 }
778 template <class T>
781 Q_UNUSED(data)
782 }
784 template <class T>
786 {
788
789 // Clear highlighting
790 if (this->derivedModel()->hasHighlightedRows())
791 {
792 menuActions.addAction(CIcons::refresh16(), "Clear highlighting", CMenuAction::pathViewClearHighlighting(),
794 }
795 }
797 template <class T>
801 do
803 if (fileName.isEmpty())
804 {
805 m = CStatusMessage(this).error(u"Load canceled, no file name");
806 break;
807 }
809 const QString json(CFileUtils::readFileToString(fileName));
810 if (json.isEmpty())
812 m = CStatusMessage(this).warning(u"Reading '%1' yields no data") << fileName;
813 break;
815 if (!json::looksLikeSwiftJson(json))
816 {
817 m = CStatusMessage(this).warning(u"No swift JSON '%1'") << fileName;
818 break;
819 }
820
821 try
822 {
823 const bool allowCacheFormat = this->allowCacheFileFormatJson();
824 const QJsonObject jsonObject = json::jsonObjectFromString(json, allowCacheFormat);
825 if (jsonObject.isEmpty())
826 {
827 m = CStatusMessage(this).warning(u"No valid swift JSON '%1'") << fileName;
828 break;
829 }
830
831 ContainerType container;
832
833 if (jsonObject.contains("type") && jsonObject.contains("value"))
834 {
835 // read from variant format
836 CVariant containerVariant;
837 containerVariant.convertFromJson(jsonObject);
838 if (!containerVariant.canConvert<ContainerType>())
839 {
840 m = CStatusMessage(this).warning(u"No valid swift JSON '%1'") << fileName;
841 break;
842 }
843 container = containerVariant.value<ContainerType>();
845 else
846 {
847 // container format directly
848 container.convertFromJson(jsonObject);
849 }
851 const int countBefore = container.size();
853 if (m.isFailure())
854 {
855 break;
856 } // modification error
857 if (countBefore > 0 && container.isEmpty())
858 {
859 break;
861 m = this->validateLoadedJsonData(container);
862 if (m.isFailure())
864 break;
865 } // validaton error
867 m = CStatusMessage(this, CStatusMessage::SeverityInfo, "Reading " + fileName + " completed", true);
870 }
871 catch (const CJsonException &ex)
872 {
873 m = CStatusMessage::fromJsonException(ex, this, QString("Reading JSON from '%1'").arg(fileName));
874 break;
875 }
876 }
877 while (false);
878
879 emit this->jsonLoadCompleted(m);
880 return m;
881 }
882
883 template <class T>
885 {
886 const ContainerType container = selectedOnly ? this->selectedObjects() : this->container();
887 const QString json = container.toJsonString();
888 QTextEdit *te = this->textEditDialog()->textEdit();
889 te->setReadOnly(true);
890 te->setText(json);
891 this->textEditDialog()->show();
893
894 template <class T>
896 {
897 const QString fileName = QFileDialog::getOpenFileName(
898 nullptr, tr("Load data file"), directory.isEmpty() ? this->getFileDialogFileName(true) : directory,
899 tr("swift (*.json *.txt)"));
900 return this->loadJsonFile(fileName);
902
903 template <class T>
904 CStatusMessage CViewBase<T>::saveJson(bool selectedOnly, const QString &directory)
905 {
906 const QString fileName = QFileDialog::getSaveFileName(
907 nullptr, tr("Save data file"), directory.isEmpty() ? this->getFileDialogFileName(false) : directory,
908 tr("swift (*.json *.txt)"));
909 if (fileName.isEmpty())
911 return CStatusMessage(this, CStatusMessage::SeverityDebug, u"Save canceled", true);
912 }
913 const QString json(this->toJsonString(QJsonDocument::Indented, selectedOnly)); // save as CVariant JSON
914
915 // save file
916 CWorker::fromTask(qApp, Q_FUNC_INFO, [=] { CFileUtils::writeStringToFile(json, fileName); });
917 this->rememberLastJsonDirectory(fileName);
918 return CStatusMessage(this, CStatusMessage::SeverityInfo, u"Writing " % fileName % u" in progress", true);
920
921 template <class T>
923 {
924 QClipboard *clipboard = QApplication::clipboard();
925 if (!clipboard)
926 {
927 return;
928 }
929 if (!this->hasSelection())
930 {
931 return;
932 }
933 const ContainerType selection = this->selectedObjects();
934 if (selection.isEmpty())
935 {
936 return;
938 const CVariant copyJson = CVariant::fromValue(selection);
939 const QString json = copyJson.toJsonString();
940 clipboard->setText(json);
941 }
942
943 template <class T>
945 {
948 return;
949 }
950 this->copy();
952 }
953
954 template <class T>
956 {
958 if (!clipboard)
959 {
960 return;
961 }
962 const QString json = clipboard->text();
963 if (json.isEmpty())
964 {
965 return;
967 if (!json::looksLikeSwiftJson(json))
968 {
969 return;
970 } // no JSON
971 try
973 ContainerType objects;
974 objects.convertFromJson(json);
975 if (!objects.isEmpty())
976 {
977 this->insert(objects);
979 }
980 catch (const CJsonException &ex)
981 {
982 Q_UNUSED(ex)
983 }
984 }
985
986 template <class T>
988 {
989 const auto statusCode = static_cast<QDialog::DialogCode>(status);
990 return filterWidgetChangedFilter(statusCode == QDialog::Accepted);
991 }
992
993 template <class T>
995 {
996 if (enabled)
997 {
998 if (!m_filterWidget)
999 {
1000 this->removeFilter();
1001 }
1002 else
1003 {
1004 // takes the filter and triggers the filtering
1005 auto *provider = dynamic_cast<IModelFilterProvider<ContainerType> *>(m_filterWidget);
1006 Q_ASSERT_X(provider, Q_FUNC_INFO, "Filter widget does not provide interface");
1007 if (!provider)
1008 {
1009 return false;
1010 }
1011 std::unique_ptr<IModelFilter<ContainerType>> f(provider->createModelFilter());
1012 if (f->isValid())
1013 {
1014 this->takeFilterOwnership(f);
1015 }
1016 else
1017 {
1018 this->removeFilter();
1019 }
1020 }
1021 }
1022 else
1023 {
1024 // no filter
1025 this->removeFilter();
1026 }
1027 return true; // handled
1028 }
1029
1030 template <class T>
1032 {
1034 {
1035 return;
1036 }
1037 if (!index.isValid())
1038 {
1039 return;
1040 }
1041 emit this->objectClicked(CVariant::fromValue(at(index)));
1042 }
1043
1044 template <class T>
1046 {
1048 {
1049 return;
1050 }
1051 if (!index.isValid())
1052 {
1053 return;
1054 }
1055 emit this->objectDoubleClicked(CVariant::fromValue(at(index)));
1056 }
1057
1058 template <class T>
1060 {
1062 {
1063 return;
1064 }
1065 if (!index.isValid())
1066 {
1067 return;
1068 }
1069 emit this->objectSelected(CVariant::fromValue(at(index)));
1070 }
1071
1072} // namespace swift::gui::views
static QString replaceTabCountValue(const QString &oldName, int count)
Replace count in name such as "stations (4)".
static bool isMimeRepresentingReadableJsonFile(const QMimeData *mime)
Is representing existing JSON file.
static QFileInfo representedMimeFile(const QMimeData *mime)
Represented file if any.
static const QString & pathViewClearHighlighting()
View clear highlighting.
Definition menuaction.h:316
Bunch of CMenuAction objects.
Definition menuaction.h:384
CMenuAction addAction(const CMenuAction &menuAction)
Add menu action.
void objectChanged(const swift::misc::CVariant &object, const swift::misc::CPropertyIndex &changedIndex)
Template free information, that object changed.
void modelDataChangedDigest(int count, bool withFilter)
Data changed, digest version.
void changed()
Model has been changed Triggered with each change, for performance consider using changedDigest.
Model filter interface.
Definition modelfilter.h:21
Model filter interface for those who can generate such a filter (e.g. a widget or dialog).
Definition modelfilter.h:61
void sort()
Sort if columns or order changed.
Definition viewbase.cpp:550
ContainerType unselectedObjects() const
Unselected objects.
Definition viewbase.cpp:283
bool filterDialogFinished(int status)
Filter dialog finished.
Definition viewbase.cpp:987
int rowOf(const ObjectType &obj) const
The row of the given object.
Definition viewbase.cpp:243
void cut()
Clipboard cut/copy/paste.
Definition viewbase.cpp:944
int performUpdateContainer(const swift::misc::CVariant &variant, bool sort, bool resize)
Helper method with template free signature.
Definition viewbase.cpp:725
void standardInit(ModelClass *model=nullptr)
Standard initialization.
Definition viewbase.cpp:665
swift::misc::CStatusMessage loadJsonFile(const QString &fileName)
Method creating the menu.
Definition viewbase.cpp:798
void initAsOrderable()
Init so items can be ordered, includes enabling drag and drop.
Definition viewbase.cpp:616
bool acceptDrop(const QMimeData *mimeData) const
Accept drop data?
Definition viewbase.cpp:529
QList< int > rowsOf(const ContainerType &container) const
The rows of the given objects.
Definition viewbase.cpp:228
void removeFilter()
Remove filter.
Definition viewbase.cpp:591
void onRowSelected(const QModelIndex &index)
Row selected.
void setTabWidgetViewText(QTabWidget *tw, int index)
Set a tab widget text based on row count, filter etc.
Definition viewbase.cpp:626
swift::misc::CStatusMessage loadJson(const QString &directory={})
Load JSON.
Definition viewbase.cpp:895
void allowDragDrop(bool allowDrag, bool allowDrop, bool allowDropJsonFile=false)
Allow to drag and/or drop value objects.
Definition viewbase.cpp:495
void clearHighlighting()
Clear any highlighted objects.
Definition viewbase.cpp:435
bool isEmpty() const
Empty?
Definition viewbase.cpp:481
const models::CColumns & getColumns() const
The columns.
Definition viewbase.h:678
void updateContainerMaybeAsync(const ContainerType &container, bool sort=true, bool resize=true)
Based on size call sync / async update.
Definition viewbase.cpp:120
void insert(const ObjectType &value, bool resize=true)
Insert.
Definition viewbase.cpp:138
ContainerType selectedObjects() const
Selected objects.
Definition viewbase.cpp:267
swift::misc::CStatusMessage saveJson(bool selectedOnly=false, const QString &directory={})
Save JSON.
Definition viewbase.cpp:904
ModelClass * m_model
corresponding model
Definition viewbase.h:886
void setSortIndicator()
Set the search indicator based on model.
Definition viewbase.cpp:655
int rowCount() const
Elements in container.
Definition viewbase.cpp:467
const ObjectType & at(const QModelIndex &index) const
Value object at.
Definition viewbase.cpp:214
void setDropActions(Qt::DropActions dropActions)
Drop actions.
Definition viewbase.h:872
void clear()
Clear data.
Definition viewbase.cpp:459
typename T::ObjectType ObjectType
Model container element type.
Definition viewbase.h:660
void sortByPropertyIndex(const swift::misc::CPropertyIndex &propertyIndex, Qt::SortOrder order=Qt::AscendingOrder)
Sort by index.
Definition viewbase.cpp:544
bool filterWidgetChangedFilter(bool enabled)
Filter changed in filter widget.
Definition viewbase.cpp:994
virtual void setObjectName(const QString &name)
Set own name and the model's name.
Definition viewbase.cpp:576
void push_back(const ObjectType &value, bool resize=true)
Push back.
Definition viewbase.cpp:176
int columnCount() const
Column count.
Definition viewbase.cpp:474
virtual swift::misc::CStatusMessage validateLoadedJsonData(const ContainerType &data) const
Verify JSON data loaded in swift::gui::views::CViewBaseNonTemplate::loadJson.
Definition viewbase.cpp:771
bool reachedResizeThreshold(int containrerSize=-1) const
Skip resizing because of size?
Definition viewbase.cpp:700
QString toJsonString(QJsonDocument::JsonFormat format=QJsonDocument::Indented, bool selectedOnly=false) const
Convert to JSON string.
Definition viewbase.cpp:569
virtual swift::misc::CStatusMessage modifyLoadedJsonData(ContainerType &data) const
Modify JSON data loaded in swift::gui::views::CViewBaseNonTemplate::loadJson.
Definition viewbase.cpp:763
void selectObjects(const ContainerType &selectedObjects)
Select.
Definition viewbase.cpp:757
void onDoubleClicked(const QModelIndex &index)
Index double clicked.
void setPercentageColumnWidths()
Set the widths based on the column percentages.
Definition viewbase.cpp:639
CViewBase(QWidget *parent, ModelClass *model=nullptr)
Constructor.
Definition viewbase.cpp:31
virtual void displayContainerAsJsonPopup(bool selectedOnly)
Display the container as JSON popup.
Definition viewbase.cpp:884
void performModeBasedResizeToContent()
Perform resizing (no presizing) / non slot method for template.
Definition viewbase.cpp:710
bool hasFilter() const
Has filter set?
Definition viewbase.cpp:597
int removeSelectedRows()
Remove selected rows.
Definition viewbase.cpp:380
bool isDropAllowed() const
Drop allowed?
Definition viewbase.cpp:508
swift::misc::CWorker * updateContainerAsync(const ContainerType &container, bool sort=true, bool resize=true)
Update whole container in background.
Definition viewbase.cpp:95
void resort()
Resort ("forced sorting").
Definition viewbase.cpp:556
void onClicked(const QModelIndex &index)
Remove filter.
virtual void jsonLoadedAndModelUpdated(const ContainerType &data)
In swift::gui::views::CViewBaseNonTemplate::loadJson the view has been updated because of loaded JSON...
Definition viewbase.cpp:779
ObjectType selectedObject() const
Selected object (or default).
Definition viewbase.cpp:373
const ContainerType & container() const
Access to container.
Definition viewbase.cpp:221
typename T::ContainerType ContainerType
Model container type.
Definition viewbase.h:657
QJsonObject toJson(bool selectedOnly=false) const
Convert to JSON.
Definition viewbase.cpp:562
void materializeFilter()
Materialize filter.
Definition viewbase.cpp:442
void presizeOrFullResizeToContents()
Depending on CViewBaseNonTemplate::ResizeSubsetThreshold presize or fully resize.
Definition viewbase.cpp:414
const ContainerType & containerOrFilteredContainer(bool *filtered=nullptr) const
Full container or cached filtered container as approproiate.
Definition viewbase.cpp:260
bool setSorting(const swift::misc::CPropertyIndex &propertyIndex, Qt::SortOrder order=Qt::AscendingOrder)
Sorting.
Definition viewbase.cpp:537
void mouseOverCallback(const QModelIndex &index, bool mouseOver)
From delegate indicating we are in mouse over state.
Definition viewbase.cpp:743
void takeFilterOwnership(std::unique_ptr< models::IModelFilter< ContainerType > > &filter)
Set filter and take ownership, any previously set filter will be destroyed.
Definition viewbase.cpp:585
void drawDropIndicator(bool indicator)
Draw drop indicator.
Definition viewbase.cpp:751
ModelClass * derivedModel()
Model.
Definition viewbase.h:672
void copy()
Clipboard cut/copy/paste.
Definition viewbase.cpp:922
int updateSelected(const swift::misc::CVariant &variant, const swift::misc::CPropertyIndex &index)
Update selected objects.
Definition viewbase.cpp:366
void updateSortIndicator()
Set the sort indicator to the current sort column.
Definition viewbase.cpp:732
void addContainerTypesAsDropTypes(bool objectType=true, bool containerType=true)
Add the object and container type as accepted drop types CDropBase::addAcceptedMetaTypeId.
Definition viewbase.cpp:603
void customMenu(menus::CMenuActions &menuActions)
Method creating the menu.
Definition viewbase.cpp:785
void dropEvent(QDropEvent *event)
Definition viewbase.cpp:515
ObjectType firstSelectedOrDefaultObject() const
First selected, the only one, or default.
Definition viewbase.cpp:299
int updateContainer(const ContainerType &container, bool sort=true, bool resize=true)
Update whole container.
Definition viewbase.cpp:41
bool isOrderable() const
Is the corresponding model orderable, swift::misc::models::CListModelBaseNonTemplate::isOrderable.
Definition viewbase.cpp:488
void paste()
Clipboard cut/copy/paste.
Definition viewbase.cpp:955
QWidget * m_filterWidget
filter widget or dialog
Definition viewbase.h:602
components::CTextEditDialog * textEditDialog()
Init text edit dialog if required and return pointer to it.
static constexpr int ResizeSubsetThreshold
When to use pre-sizing with random elements.
Definition viewbase.h:153
bool m_acceptRowSelection
selection changed
Definition viewbase.h:595
void hideLoadIndicator(int loadingId=-1)
Hide loading indicator.
@ PresizeSubset
use a subset of the data to resize
Definition viewbase.h:104
int selectedRowCount() const
Number of selected rows.
virtual void resizeToContents()
Resize to contents, strategy depends on container size.
int getPresizeRandomElementsSize(int containerSize=-1) const
Calculate presize count.
virtual void clearHighlighting()=0
Clear any highlighted objects.
void modelChanged()
Model bas been changed (means data in view have been changed).
QModelIndexList selectedRows() const
Selected rows if any.
int m_skipResizeThreshold
when to skip resize (rows count)
Definition viewbase.h:587
virtual void rememberLastJsonDirectory(const QString &selectedFileOrDir)
JSON directory.
virtual QModelIndexList unselectedRows() const
Unselected (not selected) rows if any.
void objectChanged(const swift::misc::CVariant &object, const swift::misc::CPropertyIndex &changedIndex)
Single object was changed in model.
void jsonLoadCompleted(const swift::misc::CStatusMessage &msg)
JSON data load from disk completed, the swift::misc::CStatusMessage represents the success.
void onModelChanged()
Underlying model changed.
virtual void fullResizeToContents()
Full resizing to content, might be slow.
bool m_acceptDoubleClickSelection
double clicked
Definition viewbase.h:596
virtual bool isResizeConditionMet(int containerSize=-1) const
Resize or skip resize?
void objectSelected(const swift::misc::CVariant &object)
Object has been selected.
void modelDataChangedDigest(int count, bool withFilter)
Model data changed,.
int showLoadIndicator(int containerSizeDependent=-1, std::chrono::milliseconds timeout=std::chrono::milliseconds { 0 }, bool processEvents=true)
Show loading indicator.
virtual void customMenu(menus::CMenuActions &menuActions)
Method creating the menu.
static constexpr int ASyncRowsCountThreshold
When (row count) to use asynchronous updates.
Definition viewbase.h:150
void asyncUpdateFinished()
Asynchronous update finished.
void modelDataChanged(int count, bool withFilter)
Model data changed.
void objectsDeleted(const swift::misc::CVariant &objectContainer)
Objects deleted from model.
bool hasSelection() const
Selection (selected rows).
void objectDoubleClicked(const swift::misc::CVariant &object)
Object has been double clicked.
CViewBaseNonTemplate(QWidget *parent)
Constructor.
void objectClicked(const swift::misc::CVariant &object)
Object has been clicked.
static bool writeStringToFile(const QString &content, const QString &fileNameAndPath)
Write string to text file.
Definition fileutils.cpp:40
static QString readFileToString(const QString &fileNameAndPath)
Read file into string.
Definition fileutils.cpp:83
static const QPixmap & refresh16()
Refresh.
Thrown when a convertFromJson method encounters an unrecoverable error in JSON data.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Value object encapsulating a list of property indexes.
Specialized value object compliant map for variants, based on indexes.
CVariant value(const CPropertyIndex &index) const
Value.
CPropertyIndexList indexes() const
Indexes.
Streamable status message, e.g.
static CStatusMessage fromJsonException(const CJsonException &ex, const CLogCategoryList &categories, const QString &prefix)
Object from JSON exception message.
static constexpr auto SeverityInfo
Status severities.
bool isFailure() const
Operation considered unsuccessful.
static constexpr auto SeverityDebug
Status severities.
Wrapper around QVariant which provides transparent access to CValueObject methods of the contained ob...
Definition variant.h:69
static CVariant fromValue(T &&value)
Construct a variant from a value.
Definition variant.h:139
T value() const
Return the value converted to the type T.
Definition variant.h:154
void convertFromJson(const QJsonObject &json)
Assign from JSON object.
bool canConvert(int typeId) const
True if this variant can be converted to the type with the given metatype ID.
QString toJsonString(QJsonDocument::JsonFormat format=QJsonDocument::Indented) const
Convenience function JSON as string.
void then(T *context, F functor)
Connects to a functor or method which will be called when the task is finished.
Definition worker.h:97
Class for doing some arbitrary parcel of work in its own thread.
Definition worker.h:230
static CWorker * fromTask(QObject *owner, const QString &name, F &&task)
Returns a new worker object which lives in a new thread.
Definition worker.h:243
void thenWithResult(F functor)
Connects to a functor to which will be passed the result when the task is finished.
Definition worker.h:264
QJsonObject jsonObjectFromString(const QString &json, bool acceptCacheFormat)
JSON Object from string.
Definition json.cpp:419
High level reusable GUI components.
Filter to search data sets.
Models to be used with views, mainly QTableView.
Views, mainly QTableView.
GUI related classes.
Free functions in swift::misc.
void setDragDropMode(QAbstractItemView::DragDropMode behavior)
void setDragEnabled(bool enable)
virtual bool event(QEvent *event) override
QAbstractItemModel * model() const const
void setDropIndicatorShown(bool enable)
QWidget * viewport() const const
void setText(const QString &text, QClipboard::Mode mode)
QString text(QClipboard::Mode mode) const const
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options)
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options)
QString absoluteFilePath() const const
QClipboard * clipboard()
bool contains(QLatin1StringView key) const const
bool isEmpty() const const
QList< T >::const_reference at(qsizetype i) const const
bool isEmpty() const const
void push_back(QList< T >::parameter_type value)
bool isValid() const const
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QObject * parent() const const
void setObjectName(QAnyStringView name)
QString tr(const char *sourceText, const char *disambiguation, int n)
bool isEmpty() const const
MoveAction
SortOrder
QHeaderView * horizontalHeader() const const
void setColumnWidth(int column, int width)
void setSortingEnabled(bool enable)
void setTabText(int index, const QString &label)
QString tabText(int index) const const
void setReadOnly(bool ro)
void setText(const QString &text)
void resize(const QSize &)