9#include <QStringBuilder>
15#include "gui/models/allmodels.h"
22using namespace swift::gui::menus;
25using namespace swift::gui::settings;
43 Q_ASSERT_X(
m_model, Q_FUNC_INFO,
"Missing model");
59 const bool presizeThresholdReached =
63 if (presizeThresholdReached)
66 if (presizeRandomElements > 0)
76 if (presizeThresholdReached)
80 else if (reallyResize)
84 else if (presize && !presizeThresholdReached)
106 const auto sortColumn =
model->getSortColumn();
107 const auto sortOrder =
model->getSortOrder();
110 return model->sortContainerByColumn(
container, sortColumn, sortOrder);
233 const int i = this->
rowOf(o);
263 return m_model->containerOrFilteredContainer(filtered);
277 c.push_back(this->
at(i));
293 c.push_back(this->
at(i));
327 int lastUpdatedRow = -1;
328 int firstUpdatedRow = -1;
334 if (i.row() == lastUpdatedRow)
338 lastUpdatedRow = i.row();
339 if (firstUpdatedRow < 0 || lastUpdatedRow < firstUpdatedRow)
341 firstUpdatedRow = lastUpdatedRow;
348 obj.setPropertyByIndex(pi, vm.
value(pi));
360 this->
derivedModel()->emitDataChanged(firstUpdatedRow, lastUpdatedRow);
376 return c.frontOrDefault();
391 const int currentRows = this->
rowCount();
420 if (presizeRandomElements > 0)
423 m_model->update(containerBackup.sampleElements(presizeRandomElements),
false);
425 m_model->update(containerBackup,
false);
438 return m_model->clearHighlighting();
484 return m_model->rowCount() < 1;
500 this->
viewport()->setAcceptDrops(allowDrop);
504 m_model->allowJsonFileDrop(allowDropJsonFile);
511 return m_model->isDropAllowed();
532 const bool a =
m_model->acceptDrop(mimeData);
540 return m_model->setSorting(propertyIndex, order);
546 m_model->sortByPropertyIndex(propertyIndex, order);
565 return m_model->toJson(selectedOnly);
572 return m_model->toJsonString(format, selectedOnly);
607 m_model->addAcceptedMetaTypeId(qMetaTypeId<ObjectType>());
611 m_model->addAcceptedMetaTypeId(qMetaTypeId<ContainerType>());
618 Q_ASSERT_X(
isOrderable(), Q_FUNC_INFO,
"Model not orderable");
641 const int width = this->width() - 25;
647 for (
int c = 0; c < this->
getColumns().size(); c++)
649 const int w = widths.
at(c);
657 if (
m_model->hasValidSortColumn())
667 Q_ASSERT_X(
model ||
m_model, Q_FUNC_INFO,
"Missing model");
680 m_model->setSelectionModel(
this);
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");
694 this->setModel(m_model);
696 this->setSortIndicator();
702 if (containerSize < 0)
706 return containerSize > m_skipResizeThreshold;
736 const int index = this->
derivedModel()->getSortColumn();
815 if (!json::looksLikeSwiftJson(json))
823 const bool allowCacheFormat = this->allowCacheFileFormatJson();
831 ContainerType container;
838 if (!containerVariant.
canConvert<ContainerType>())
843 container = containerVariant.
value<ContainerType>();
851 const int countBefore =
container.size();
861 m = this->validateLoadedJsonData(container);
898 nullptr,
tr(
"Load data file"), directory.
isEmpty() ? this->getFileDialogFileName(
true) : directory,
899 tr(
"swift (*.json *.txt)"));
907 nullptr,
tr(
"Save data file"), directory.
isEmpty() ? this->getFileDialogFileName(
false) : directory,
908 tr(
"swift (*.json *.txt)"));
917 this->rememberLastJsonDirectory(fileName);
929 if (!this->hasSelection())
933 const ContainerType selection = this->selectedObjects();
934 if (selection.isEmpty())
967 if (!json::looksLikeSwiftJson(json))
974 objects.convertFromJson(json);
975 if (!objects.isEmpty())
1006 Q_ASSERT_X(provider, Q_FUNC_INFO,
"Filter widget does not provide interface");
1011 std::unique_ptr<IModelFilter<ContainerType>> f(provider->createModelFilter());
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.
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 for those who can generate such a filter (e.g. a widget or dialog).
void sort()
Sort if columns or order changed.
ContainerType unselectedObjects() const
Unselected objects.
bool filterDialogFinished(int status)
Filter dialog finished.
int rowOf(const ObjectType &obj) const
The row of the given object.
void cut()
Clipboard cut/copy/paste.
int performUpdateContainer(const swift::misc::CVariant &variant, bool sort, bool resize)
Helper method with template free signature.
void standardInit(ModelClass *model=nullptr)
Standard initialization.
swift::misc::CStatusMessage loadJsonFile(const QString &fileName)
Method creating the menu.
void initAsOrderable()
Init so items can be ordered, includes enabling drag and drop.
bool acceptDrop(const QMimeData *mimeData) const
Accept drop data?
QList< int > rowsOf(const ContainerType &container) const
The rows of the given objects.
void removeFilter()
Remove filter.
void onRowSelected(const QModelIndex &index)
Row selected.
void setTabWidgetViewText(QTabWidget *tw, int index)
Set a tab widget text based on row count, filter etc.
swift::misc::CStatusMessage loadJson(const QString &directory={})
Load JSON.
void allowDragDrop(bool allowDrag, bool allowDrop, bool allowDropJsonFile=false)
Allow to drag and/or drop value objects.
void clearHighlighting()
Clear any highlighted objects.
bool isEmpty() const
Empty?
const models::CColumns & getColumns() const
The columns.
void updateContainerMaybeAsync(const ContainerType &container, bool sort=true, bool resize=true)
Based on size call sync / async update.
void insert(const ObjectType &value, bool resize=true)
Insert.
ContainerType selectedObjects() const
Selected objects.
swift::misc::CStatusMessage saveJson(bool selectedOnly=false, const QString &directory={})
Save JSON.
ModelClass * m_model
corresponding model
void setSortIndicator()
Set the search indicator based on model.
int rowCount() const
Elements in container.
const ObjectType & at(const QModelIndex &index) const
Value object at.
void setDropActions(Qt::DropActions dropActions)
Drop actions.
typename T::ObjectType ObjectType
Model container element type.
void sortByPropertyIndex(const swift::misc::CPropertyIndex &propertyIndex, Qt::SortOrder order=Qt::AscendingOrder)
Sort by index.
bool filterWidgetChangedFilter(bool enabled)
Filter changed in filter widget.
virtual void setObjectName(const QString &name)
Set own name and the model's name.
void push_back(const ObjectType &value, bool resize=true)
Push back.
int columnCount() const
Column count.
virtual swift::misc::CStatusMessage validateLoadedJsonData(const ContainerType &data) const
Verify JSON data loaded in swift::gui::views::CViewBaseNonTemplate::loadJson.
bool reachedResizeThreshold(int containrerSize=-1) const
Skip resizing because of size?
QString toJsonString(QJsonDocument::JsonFormat format=QJsonDocument::Indented, bool selectedOnly=false) const
Convert to JSON string.
virtual swift::misc::CStatusMessage modifyLoadedJsonData(ContainerType &data) const
Modify JSON data loaded in swift::gui::views::CViewBaseNonTemplate::loadJson.
void selectObjects(const ContainerType &selectedObjects)
Select.
void onDoubleClicked(const QModelIndex &index)
Index double clicked.
void setPercentageColumnWidths()
Set the widths based on the column percentages.
CViewBase(QWidget *parent, ModelClass *model=nullptr)
Constructor.
virtual void displayContainerAsJsonPopup(bool selectedOnly)
Display the container as JSON popup.
void performModeBasedResizeToContent()
Perform resizing (no presizing) / non slot method for template.
bool hasFilter() const
Has filter set?
int removeSelectedRows()
Remove selected rows.
bool isDropAllowed() const
Drop allowed?
swift::misc::CWorker * updateContainerAsync(const ContainerType &container, bool sort=true, bool resize=true)
Update whole container in background.
void resort()
Resort ("forced sorting").
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...
ObjectType selectedObject() const
Selected object (or default).
const ContainerType & container() const
Access to container.
typename T::ContainerType ContainerType
Model container type.
QJsonObject toJson(bool selectedOnly=false) const
Convert to JSON.
void materializeFilter()
Materialize filter.
void presizeOrFullResizeToContents()
Depending on CViewBaseNonTemplate::ResizeSubsetThreshold presize or fully resize.
const ContainerType & containerOrFilteredContainer(bool *filtered=nullptr) const
Full container or cached filtered container as approproiate.
bool setSorting(const swift::misc::CPropertyIndex &propertyIndex, Qt::SortOrder order=Qt::AscendingOrder)
Sorting.
void mouseOverCallback(const QModelIndex &index, bool mouseOver)
From delegate indicating we are in mouse over state.
void takeFilterOwnership(std::unique_ptr< models::IModelFilter< ContainerType > > &filter)
Set filter and take ownership, any previously set filter will be destroyed.
void drawDropIndicator(bool indicator)
Draw drop indicator.
ModelClass * derivedModel()
Model.
void copy()
Clipboard cut/copy/paste.
int updateSelected(const swift::misc::CVariant &variant, const swift::misc::CPropertyIndex &index)
Update selected objects.
bool hasValidSortColumn() const
void updateSortIndicator()
Set the sort indicator to the current sort column.
void addContainerTypesAsDropTypes(bool objectType=true, bool containerType=true)
Add the object and container type as accepted drop types CDropBase::addAcceptedMetaTypeId.
void customMenu(menus::CMenuActions &menuActions)
Method creating the menu.
void dropEvent(QDropEvent *event)
ObjectType firstSelectedOrDefaultObject() const
First selected, the only one, or default.
int updateContainer(const ContainerType &container, bool sort=true, bool resize=true)
Update whole container.
bool isOrderable() const
Is the corresponding model orderable, swift::misc::models::CListModelBaseNonTemplate::isOrderable.
void paste()
Clipboard cut/copy/paste.
QWidget * m_filterWidget
filter widget or dialog
bool m_dropIndicator
drop indicator
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.
bool m_acceptRowSelection
selection changed
void hideLoadIndicator(int loadingId=-1)
Hide loading indicator.
@ PresizeSubset
use a subset of the data to resize
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.
ResizeMode m_resizeMode
mode
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)
virtual void rememberLastJsonDirectory(const QString &selectedFileOrDir)
JSON directory.
bool m_acceptClickSelection
clicked
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
void dropEvent(QDropEvent *event)
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.
void asyncUpdateFinished()
Asynchronous update finished.
void modelDataChanged(int count, bool withFilter)
Model data changed.
void init()
Init default values.
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.
static QString readFileToString(const QString &fileNameAndPath)
Read file into string.
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.
bool isEmpty() const
Is empty?
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...
static CVariant fromValue(T &&value)
Construct a variant from a value.
T value() const
Return the value converted to the type T.
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.
Class for doing some arbitrary parcel of work in its own thread.
static CWorker * fromTask(QObject *owner, const QString &name, F &&task)
Returns a new worker object which lives in a new thread.
void thenWithResult(F functor)
Connects to a functor to which will be passed the result when the task is finished.
QJsonObject jsonObjectFromString(const QString &json, bool acceptCacheFormat)
JSON Object from string.
High level reusable GUI components.
Filter to search data sets.
Models to be used with views, mainly QTableView.
Views, mainly QTableView.
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)
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
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
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)