diff --git a/include/nodes/internal/Compiler.hpp b/include/nodes/internal/Compiler.hpp index 70fc98e30..179f84b93 100644 --- a/include/nodes/internal/Compiler.hpp +++ b/include/nodes/internal/Compiler.hpp @@ -1,53 +1,40 @@ #pragma once -#if \ - defined (__MINGW32__) || \ - defined (__MINGW64__) -# define NODE_EDITOR_COMPILER "MinGW" -# define NODE_EDITOR_COMPILER_MINGW -#elif \ - defined (__GNUC__) -# define NODE_EDITOR_COMPILER "GNU" -# define NODE_EDITOR_COMPILER_GNU -# define NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR __GNUC__ -# define NODE_EDITOR_COMPILER_GNU_VERSION_MINOR __GNUC_MINOR__ -# define NODE_EDITOR_COMPILER_GNU_VERSION_PATCH __GNUC_PATCHLEVEL__ -#elif \ - defined (__clang__) -# define NODE_EDITOR_COMPILER "Clang" -# define NODE_EDITOR_COMPILER_CLANG -#elif \ - defined (_MSC_VER) -# define NODE_EDITOR_COMPILER "Microsoft Visual C++" -# define NODE_EDITOR_COMPILER_MICROSOFT -#elif \ - defined (__BORLANDC__) -# define NODE_EDITOR_COMPILER "Borland C++ Builder" -# define NODE_EDITOR_COMPILER_BORLAND -#elif \ - defined (__CODEGEARC__) -# define NODE_EDITOR_COMPILER "CodeGear C++ Builder" -# define NODE_EDITOR_COMPILER_CODEGEAR -#elif \ - defined (__INTEL_COMPILER) || \ - defined (__ICL) -# define NODE_EDITOR_COMPILER "Intel C++" -# define NODE_EDITOR_COMPILER_INTEL -#elif \ - defined (__xlC__) || \ - defined (__IBMCPP__) -# define NODE_EDITOR_COMPILER "IBM XL C++" -# define NODE_EDITOR_COMPILER_IBM -#elif \ - defined (__HP_aCC) -# define NODE_EDITOR_COMPILER "HP aC++" -# define NODE_EDITOR_COMPILER_HP -#elif \ - defined (__WATCOMC__) -# define NODE_EDITOR_COMPILER "Watcom C++" -# define NODE_EDITOR_COMPILER_WATCOM +#if defined(__MINGW32__) || defined(__MINGW64__) +#define NODE_EDITOR_COMPILER "MinGW" +#define NODE_EDITOR_COMPILER_MINGW +#elif defined(__GNUC__) +#define NODE_EDITOR_COMPILER "GNU" +#define NODE_EDITOR_COMPILER_GNU +#define NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR __GNUC__ +#define NODE_EDITOR_COMPILER_GNU_VERSION_MINOR __GNUC_MINOR__ +#define NODE_EDITOR_COMPILER_GNU_VERSION_PATCH __GNUC_PATCHLEVEL__ +#elif defined(__clang__) +#define NODE_EDITOR_COMPILER "Clang" +#define NODE_EDITOR_COMPILER_CLANG +#elif defined(_MSC_VER) +#define NODE_EDITOR_COMPILER "Microsoft Visual C++" +#define NODE_EDITOR_COMPILER_MICROSOFT +#elif defined(__BORLANDC__) +#define NODE_EDITOR_COMPILER "Borland C++ Builder" +#define NODE_EDITOR_COMPILER_BORLAND +#elif defined(__CODEGEARC__) +#define NODE_EDITOR_COMPILER "CodeGear C++ Builder" +#define NODE_EDITOR_COMPILER_CODEGEAR +#elif defined(__INTEL_COMPILER) || defined(__ICL) +#define NODE_EDITOR_COMPILER "Intel C++" +#define NODE_EDITOR_COMPILER_INTEL +#elif defined(__xlC__) || defined(__IBMCPP__) +#define NODE_EDITOR_COMPILER "IBM XL C++" +#define NODE_EDITOR_COMPILER_IBM +#elif defined(__HP_aCC) +#define NODE_EDITOR_COMPILER "HP aC++" +#define NODE_EDITOR_COMPILER_HP +#elif defined(__WATCOMC__) +#define NODE_EDITOR_COMPILER "Watcom C++" +#define NODE_EDITOR_COMPILER_WATCOM #endif #ifndef NODE_EDITOR_COMPILER -# error "Current compiler is not supported." +#error "Current compiler is not supported." #endif diff --git a/include/nodes/internal/Connection.hpp b/include/nodes/internal/Connection.hpp index 009e6cd39..a187ede9f 100644 --- a/include/nodes/internal/Connection.hpp +++ b/include/nodes/internal/Connection.hpp @@ -4,22 +4,21 @@ #include #include -#include "PortType.hpp" #include "NodeData.hpp" +#include "PortType.hpp" -#include "Serializable.hpp" -#include "ConnectionState.hpp" #include "ConnectionGeometry.hpp" -#include "TypeConverter.hpp" -#include "QUuidStdHash.hpp" +#include "ConnectionID.hpp" +#include "ConnectionState.hpp" #include "Export.hpp" +#include "QUuidStdHash.hpp" +#include "Serializable.hpp" +#include "TypeConverter.hpp" #include "memory.hpp" -#include "ConnectionID.hpp" class QPointF; -namespace QtNodes -{ +namespace QtNodes { class Node; class NodeData; @@ -28,94 +27,63 @@ class ConnectionGraphicsObject; /// Connection is a representation in DataFlowScene of a connection /// It is part of the model, and not the rendering system. /// This class is not to be used if you're implementing FlowScene model yourself -class NODE_EDITOR_PUBLIC Connection - : public QObject - , public Serializable -{ +class NODE_EDITOR_PUBLIC Connection : public QObject, public Serializable { Q_OBJECT public: + Connection(Node &nodeIn, PortIndex portIndexIn, Node &nodeOut, + PortIndex portIndexOut, TypeConverter converter = TypeConverter{}); - Connection(Node& nodeIn, - PortIndex portIndexIn, - Node& nodeOut, - PortIndex portIndexOut, - TypeConverter converter = - TypeConverter{}); - - Connection(const Connection&) = delete; - Connection - operator=(const Connection&) = delete; + Connection(const Connection &) = delete; + Connection operator=(const Connection &) = delete; ~Connection(); public: - - QJsonObject - save() const override; + QJsonObject save() const override; public: + ConnectionID id() const; - ConnectionID - id() const; - - Node* - getNode(PortType portType) const; + Node *getNode(PortType portType) const; private: - - Node*& - getNodePtrRef(PortType portType); + Node *&getNodePtrRef(PortType portType); public: + PortIndex getPortIndex(PortType portType) const; - PortIndex - getPortIndex(PortType portType) const; + NodeDataType dataType(PortType portType) const; - NodeDataType - dataType(PortType portType) const; - - void - setTypeConverter(TypeConverter converter); + void setTypeConverter(TypeConverter converter); public: // data propagation + void propagateData(std::shared_ptr nodeData) const; - void - propagateData(std::shared_ptr nodeData) const; - - void - propagateEmptyData() const; + void propagateEmptyData() const; private: - QUuid _uid; private: + void setNodeToPort(Node &node, PortType portType, PortIndex portIndex); - void - setNodeToPort(Node& node, - PortType portType, - PortIndex portIndex); - - Node* _outNode = nullptr; - Node* _inNode = nullptr; + Node *_outNode = nullptr; + Node *_inNode = nullptr; PortIndex _outPortIndex; PortIndex _inPortIndex; private: - ConnectionState _connectionState; - ConnectionGeometry _connectionGeometry; - std::unique_ptr_connectionGraphicsObject; + std::unique_ptr _connectionGraphicsObject; TypeConverter _converter; signals: - void - updated(Connection& conn) const; + void updated(Connection &conn) const; }; -} +} // namespace QtNodes diff --git a/include/nodes/internal/ConnectionGeometry.hpp b/include/nodes/internal/ConnectionGeometry.hpp index 870c3559d..dda4edbab 100644 --- a/include/nodes/internal/ConnectionGeometry.hpp +++ b/include/nodes/internal/ConnectionGeometry.hpp @@ -7,54 +7,49 @@ #include -namespace QtNodes -{ +namespace QtNodes { + +class ConnectionGraphicsObject; class ConnectionGeometry { -public: - - ConnectionGeometry(); + friend ConnectionGraphicsObject; public: + /**\brief this class change bounding rect of obj, so, it have to call + * prepareGeometrychange for do this safely + */ + explicit ConnectionGeometry(ConnectionGraphicsObject& obj); - QPointF const& - getEndPoint(PortType portType) const; +public: + QPointF const& getEndPoint(PortType portType) const; - void - setEndPoint(PortType portType, QPointF const& point); + void setEndPoint(PortType portType, QPointF const& point); - void - moveEndPoint(PortType portType, QPointF const &offset); + void moveEndPoint(PortType portType, QPointF const& offset); - QRectF - boundingRect() const; + QRectF boundingRect() const; - std::pair - pointsC1C2() const; + std::pair pointsC1C2() const; - QPointF - source() const { return _out; } - QPointF - sink() const { return _in; } + QPointF source() const { return _out; } + QPointF sink() const { return _in; } - double - lineWidth() const { return _lineWidth; } + double lineWidth() const { return _lineWidth; } - bool - hovered() const { return _hovered; } - void - setHovered(bool hovered) { _hovered = hovered; } + bool hovered() const { return _hovered; } + void setHovered(bool hovered) { _hovered = hovered; } private: // local object coordinates + ConnectionGraphicsObject& _obj; QPointF _in; QPointF _out; - //int _animationPhase; + // int _animationPhase; double _lineWidth; bool _hovered; }; -} +} // namespace QtNodes diff --git a/include/nodes/internal/ConnectionGraphicsObject.hpp b/include/nodes/internal/ConnectionGraphicsObject.hpp index 85a6d2c32..a6a4f4ef6 100644 --- a/include/nodes/internal/ConnectionGraphicsObject.hpp +++ b/include/nodes/internal/ConnectionGraphicsObject.hpp @@ -4,149 +4,101 @@ #include -#include "PortType.hpp" -#include "NodeData.hpp" -#include "NodeIndex.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionState.hpp" +#include "NodeData.hpp" +#include "NodeIndex.hpp" +#include "PortType.hpp" class QGraphicsSceneMouseEvent; -namespace QtNodes -{ +namespace QtNodes { class FlowScene; struct ConnectionID; /// Graphic Object for connection. -class ConnectionGraphicsObject - : public QGraphicsObject +class ConnectionGraphicsObject : public QGraphicsObject { Q_OBJECT -public: + /**\brief ConnectionGeometry set boundingRect for the class, so, every time, + * when values, which neded for change boundingRect, changes - we have to call + * prepareGeometryChange. So we can call this function in ConnectionGeometry - + * this is simple and we can forget about do it by hand. And it fix problems + */ + friend ConnectionGeometry; +public: ConnectionGraphicsObject(NodeIndex const& leftNode, PortIndex leftPortIndex, NodeIndex const& rightNode, PortIndex rightPortIndex, FlowScene& scene); - virtual - ~ConnectionGraphicsObject(); + virtual ~ConnectionGraphicsObject(); - enum { Type = UserType + 2 }; - int - type() const override + enum { - return Type; - } + Type = UserType + 2 + }; + int type() const override { return Type; } public: - - NodeIndex - node(PortType pType) const + NodeIndex node(PortType pType) const { return pType == PortType::In ? _rightNode : _leftNode; } - PortIndex - portIndex(PortType pType) const + PortIndex portIndex(PortType pType) const { return pType == PortType::In ? _rightPortIndex : _leftPortIndex; } - FlowScene& - flowScene() const - { - return _scene; - } - - ConnectionGeometry const& - geometry() const - { - return _geometry; - } - ConnectionGeometry& - geometry() - { - return _geometry; - } + FlowScene& flowScene() const { return _scene; } - ConnectionState const& - state() const - { - return _state; - } - ConnectionState& - state() - { - return _state; - } + ConnectionGeometry const& geometry() const { return _geometry; } + ConnectionGeometry& geometry() { return _geometry; } - QRectF - boundingRect() const override; + ConnectionState const& state() const { return _state; } + ConnectionState& state() { return _state; } - QPainterPath - shape() const override; + QRectF boundingRect() const override; - void - setGeometryChanged(); + QPainterPath shape() const override; - ConnectionID - id() const; + ConnectionID id() const; - NodeDataType - dataType(PortType ty) const; + NodeDataType dataType(PortType ty) const; /// Updates the position of both ends - void - move(); + void move(); - void - lock(bool locked); + void lock(bool locked); - const FlowScene& - scene() const - { - return _scene; - } + const FlowScene& scene() const { return _scene; } - FlowScene& - scene() - { - return _scene; - } + FlowScene& scene() { return _scene; } protected: + void paint(QPainter* painter, + QStyleOptionGraphicsItem const* option, + QWidget* widget = 0) override; - void - paint(QPainter* painter, - QStyleOptionGraphicsItem const* option, - QWidget* widget = 0) override; - - void - mousePressEvent(QGraphicsSceneMouseEvent* event) override; + void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void - mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - void - mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override; - void - hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void - hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; private: - - void - addGraphicsEffect(); + void addGraphicsEffect(); private: - - FlowScene & _scene; + FlowScene& _scene; ConnectionGeometry _geometry; ConnectionState _state; @@ -156,6 +108,5 @@ class ConnectionGraphicsObject PortIndex _leftPortIndex; PortIndex _rightPortIndex; - }; -} +} // namespace QtNodes diff --git a/include/nodes/internal/ConnectionID.hpp b/include/nodes/internal/ConnectionID.hpp index 8f9303a4e..539149e38 100644 --- a/include/nodes/internal/ConnectionID.hpp +++ b/include/nodes/internal/ConnectionID.hpp @@ -5,8 +5,7 @@ #include -namespace QtNodes -{ +namespace QtNodes { struct ConnectionID { @@ -20,27 +19,24 @@ struct ConnectionID inline bool operator==(ConnectionID const& lhs, ConnectionID const& rhs) { - return lhs.lNodeID == rhs.lNodeID && - lhs.rNodeID == rhs.rNodeID && - lhs.lPortID == rhs.lPortID && - lhs.rPortID == rhs.rPortID; + return lhs.lNodeID == rhs.lNodeID && lhs.rNodeID == rhs.rNodeID && + lhs.lPortID == rhs.lPortID && lhs.rPortID == rhs.rPortID; } } // namespace QtNodes // hash for ConnectionID -namespace std -{ +namespace std { template<> struct hash<::QtNodes::ConnectionID> { - size_t - operator()(::QtNodes::ConnectionID const& toHash) const + size_t operator()(::QtNodes::ConnectionID const& toHash) const { - return qHash(toHash.rNodeID) ^ qHash(toHash.lNodeID) ^ std::hash()(toHash.lPortID) ^ std::hash()(toHash.rPortID); + return qHash(toHash.rNodeID) ^ qHash(toHash.lNodeID) ^ + std::hash()(toHash.lPortID) ^ + std::hash()(toHash.rPortID); } }; } // namespace std - diff --git a/include/nodes/internal/ConnectionState.hpp b/include/nodes/internal/ConnectionState.hpp index a97bc55eb..f5e1fcdcf 100644 --- a/include/nodes/internal/ConnectionState.hpp +++ b/include/nodes/internal/ConnectionState.hpp @@ -6,8 +6,7 @@ class QPointF; -namespace QtNodes -{ +namespace QtNodes { class NodeGraphicsObject; @@ -16,54 +15,36 @@ class NodeGraphicsObject; class ConnectionState { public: - ConnectionState(PortType port = PortType::None) : _requiredPort(port) {} ConnectionState(const ConnectionState&) = delete; - ConnectionState - operator=(const ConnectionState&) = delete; + ConnectionState operator=(const ConnectionState&) = delete; ~ConnectionState(); public: + void setRequiredPort(PortType end) { _requiredPort = end; } - void - setRequiredPort(PortType end) - { _requiredPort = end; } - - PortType - requiredPort() const - { return _requiredPort; } + PortType requiredPort() const { return _requiredPort; } - bool - requiresPort() const - { return _requiredPort != PortType::None; } + bool requiresPort() const { return _requiredPort != PortType::None; } - void - setNoRequiredPort() - { _requiredPort = PortType::None; } + void setNoRequiredPort() { _requiredPort = PortType::None; } public: + void interactWithNode(NodeGraphicsObject* node); - void - interactWithNode(NodeGraphicsObject* node); + void setLastHoveredNode(NodeGraphicsObject* node); - void - setLastHoveredNode(NodeGraphicsObject* node); + NodeGraphicsObject* lastHoveredNode() const { return _lastHoveredNode; } - NodeGraphicsObject* - lastHoveredNode() const - { return _lastHoveredNode; } - - void - resetLastHoveredNode(); + void resetLastHoveredNode(); private: - PortType _requiredPort; - NodeGraphicsObject* _lastHoveredNode{nullptr}; + NodeGraphicsObject* _lastHoveredNode{ nullptr }; }; } diff --git a/include/nodes/internal/ConnectionStyle.hpp b/include/nodes/internal/ConnectionStyle.hpp index 86f9e294c..22681d60c 100644 --- a/include/nodes/internal/ConnectionStyle.hpp +++ b/include/nodes/internal/ConnectionStyle.hpp @@ -5,67 +5,47 @@ #include "Export.hpp" #include "Style.hpp" -namespace QtNodes -{ +namespace QtNodes { class NODE_EDITOR_PUBLIC ConnectionStyle : public Style { public: - ConnectionStyle(); ConnectionStyle(QString jsonText); public: - - static void - setConnectionStyle(QString jsonText); + static void setConnectionStyle(QString jsonText); private: + void loadJsonText(QString jsonText) override; - void - loadJsonText(QString jsonText) override; + void loadJsonFile(QString fileName) override; - void - loadJsonFile(QString fileName) override; - - void - loadJsonFromByteArray(QByteArray const &byteArray) override; + void loadJsonFromByteArray(QByteArray const& byteArray) override; public: + QColor constructionColor() const; - QColor - constructionColor() const; - - QColor - normalColor() const; + QColor normalColor() const; - QColor - normalColor(QString typeId) const; + QColor normalColor(QString typeId) const; - QColor - selectedColor() const; + QColor selectedColor() const; - QColor - selectedHaloColor() const; + QColor selectedHaloColor() const; - QColor - hoveredColor() const; + QColor hoveredColor() const; - float - lineWidth() const; + float lineWidth() const; - float - constructionLineWidth() const; + float constructionLineWidth() const; - float - pointDiameter() const; + float pointDiameter() const; - bool - useDataDefinedColors() const; + bool useDataDefinedColors() const; private: - QColor ConstructionColor; QColor NormalColor; QColor SelectedColor; diff --git a/include/nodes/internal/DataFlowModel.hpp b/include/nodes/internal/DataFlowModel.hpp index 86b9278ac..1942f1194 100644 --- a/include/nodes/internal/DataFlowModel.hpp +++ b/include/nodes/internal/DataFlowModel.hpp @@ -1,8 +1,10 @@ -#include "FlowSceneModel.hpp" -#include "DataModelRegistry.hpp" +#pragma once + #include "ConnectionID.hpp" -#include "QUuidStdHash.hpp" +#include "DataModelRegistry.hpp" #include "Export.hpp" +#include "FlowSceneModel.hpp" +#include "QUuidStdHash.hpp" namespace QtNodes { @@ -10,100 +12,104 @@ class Node; class Connection; /// Model for simple data flow -class NODE_EDITOR_PUBLIC DataFlowModel - : public FlowSceneModel +class NODE_EDITOR_PUBLIC DataFlowModel : public FlowSceneModel { public: - DataFlowModel(std::shared_ptr reg); // FlowSceneModel read interface - QStringList - modelRegistry() const override; + QStringList modelRegistry() const override; + + QString nodeTypeCategory(QString const& name) const override; + + bool getTypeConvertable(TypeConverterId const& id) const override; - QString - nodeTypeCategory(QString const& name) const override; + QList nodeUUids() const override; - bool - getTypeConvertable(TypeConverterId const& id ) const override; + NodeIndex nodeIndex(const QUuid& ID) const override; - QList - nodeUUids() const override; + QString nodeTypeIdentifier(NodeIndex const& index) const override; - NodeIndex - nodeIndex(const QUuid& ID) const override; + QString nodeCaption(NodeIndex const& index) const override; - QString - nodeTypeIdentifier(NodeIndex const& index) const override; + QPointF nodeLocation(NodeIndex const& index) const override; - QString - nodeCaption(NodeIndex const& index) const override; + QWidget* nodeWidget(NodeIndex const& index) const override; - QPointF - nodeLocation(NodeIndex const& index) const override; + bool nodeResizable(NodeIndex const& index) const override; - QWidget* - nodeWidget(NodeIndex const& index) const override; + NodeValidationState nodeValidationState( + NodeIndex const& index) const override; - bool - nodeResizable(NodeIndex const& index) const override; + QString nodeValidationMessage(NodeIndex const& index) const override; - NodeValidationState - nodeValidationState(NodeIndex const& index) const override; + NodePainterDelegate* nodePainterDelegate( + NodeIndex const& index) const override; - QString - nodeValidationMessage(NodeIndex const& index) const override; + unsigned int nodePortCount(NodeIndex const& index, + PortType portType) const override; - NodePainterDelegate* - nodePainterDelegate(NodeIndex const& index) const override; + QString nodePortCaption(NodeIndex const& index, + PortIndex pIndex, + PortType portType) const override; - unsigned int - nodePortCount(NodeIndex const& index, PortType portType) const override; + NodeDataType nodePortDataType(NodeIndex const& index, + PortIndex pIndex, + PortType portType) const override; - QString - nodePortCaption(NodeIndex const& index, PortIndex pIndex, PortType portType) const override; - NodeDataType - nodePortDataType(NodeIndex const& index, PortIndex pIndex, PortType portType) const override; - ConnectionPolicy - nodePortConnectionPolicy(NodeIndex const& index, PortIndex pIndex, PortType portType) const override; - std::vector > - nodePortConnections(NodeIndex const& index, PortIndex id, PortType portType) const override; + ConnectionPolicy nodePortConnectionPolicy(NodeIndex const& index, + PortIndex pIndex, + PortType portType) const override; + + std::vector> nodePortConnections( + NodeIndex const& index, + PortIndex id, + PortType portType) const override; // FlowSceneModel write interface - bool - removeConnection(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const& rightNode, PortIndex rightPortID) override; - bool - addConnection(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const& rightNode, PortIndex rightPortID) override; - bool - removeNode(NodeIndex const& index) override; - QUuid - addNode(QString const& typeID, QPointF const& location) override; - bool - moveNode(NodeIndex const& index, QPointF newLocation) override; + bool removeConnection(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID) override; + bool addConnection(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID) override; + bool removeNode(NodeIndex const& index) override; + QUuid addNode(QString const& typeID, QPointF const& location) override; + bool moveNode(NodeIndex const& index, QPointF newLocation) override; // convenience functions - QUuid - addNode(QString const& typeID, QPointF const& location, QUuid const& uuid); - QUuid - addNode(std::unique_ptr&& model, QPointF const& location, QUuid const& uuid = QUuid::createUuid()); - ConnectionID - addConnection(Node* left, PortIndex leftIdx, Node* right, PortIndex rightIdx, TypeConverter converter); + QUuid addNode(QString const& typeID, + QPointF const& location, + QUuid const& uuid); + QUuid addNode(std::unique_ptr&& model, + QPointF const& location, + QUuid const& uuid = QUuid::createUuid()); + ConnectionID addConnection(Node* left, + PortIndex leftIdx, + Node* right, + PortIndex rightIdx, + TypeConverter converter); using SharedConnection = std::shared_ptr; - using UniqueNode = std::unique_ptr; + using UniqueNode = std::unique_ptr; - std::unordered_map& connections() { return _connections; } + std::unordered_map& connections() + { + return _connections; + } std::unordered_map& nodes() { return _nodes; } DataModelRegistry& registry() { return *_registry; } - void setRegistry(std::shared_ptr registry) { + void setRegistry(std::shared_ptr registry) + { _registry = std::move(registry); } private: - - std::unordered_map _nodes; + std::unordered_map _nodes; std::unordered_map _connections; - std::shared_ptr _registry; + std::shared_ptr _registry; }; -} \ No newline at end of file +} diff --git a/include/nodes/internal/DataFlowScene.hpp b/include/nodes/internal/DataFlowScene.hpp index b0d7cd4cf..5c0c4dab6 100644 --- a/include/nodes/internal/DataFlowScene.hpp +++ b/include/nodes/internal/DataFlowScene.hpp @@ -1,15 +1,15 @@ #pragma once +#include "ConnectionID.hpp" +#include "Export.hpp" #include "FlowScene.hpp" -#include "PortType.hpp" #include "FlowSceneModel.hpp" +#include "PortType.hpp" #include "QUuidStdHash.hpp" -#include "ConnectionID.hpp" -#include "Export.hpp" #include "TypeConverter.hpp" -#include #include +#include #include namespace QtNodes { @@ -27,117 +27,87 @@ class NODE_EDITOR_PUBLIC DataFlowScene : public FlowScene Q_OBJECT public: + explicit DataFlowScene(std::shared_ptr registry = + std::make_shared(), + QObject* parent = Q_NULLPTR); - explicit - DataFlowScene(std::shared_ptr registry = std::make_shared(), - QObject* parent = Q_NULLPTR); + virtual ~DataFlowScene(); - std::shared_ptr - createConnection(Node& nodeIn, - PortIndex portIndexIn, - Node& nodeOut, - PortIndex portIndexOut, - TypeConverter const& converter = TypeConverter()); + std::shared_ptr createConnection( + Node& nodeIn, + PortIndex portIndexIn, + Node& nodeOut, + PortIndex portIndexOut, + TypeConverter const& converter = TypeConverter()); - std::shared_ptr - restoreConnection(QJsonObject const &connectionJson); + std::shared_ptr restoreConnection( + QJsonObject const& connectionJson); - void - deleteConnection(Connection& connection); + void deleteConnection(Connection& connection); - Node& - createNode(std::unique_ptr && dataModel); + Node& createNode(std::unique_ptr&& dataModel); - Node& - restoreNode(QJsonObject const& nodeJson); + Node& restoreNode(QJsonObject const& nodeJson); - void - removeNode(Node& node); + void removeNode(Node& node); - DataModelRegistry& - registry() const; + DataModelRegistry& registry() const; - void - setRegistry(std::shared_ptr registry); + void setRegistry(std::shared_ptr registry); - void - iterateOverNodes(std::function const& visitor); + void iterateOverNodes(std::function const& visitor); - void - iterateOverNodeData(std::function const& visitor); + void iterateOverNodeData(std::function const& visitor); - void - iterateOverNodeDataDependentOrder(std::function const& visitor); + void iterateOverNodeDataDependentOrder( + std::function const& visitor); - QPointF - getNodePosition(Node const& node) const; + QPointF getNodePosition(Node const& node) const; - void - setNodePosition(Node& node, QPointF const& pos) const; + void setNodePosition(Node& node, QPointF const& pos) const; public: + std::unordered_map> const& nodes() const; - std::unordered_map > const & - nodes() const; - - std::unordered_map > const & + std::unordered_map> const& connections() const; - std::vector - selectedNodes() const; + std::vector selectedNodes() const; public: + void clearScene(); - void - clearScene(); + void save() const; - void - save() const; + void load(); - void - load(); + QByteArray saveToMemory() const; - QByteArray - saveToMemory() const; - - void - loadFromMemory(const QByteArray& data); + void loadFromMemory(const QByteArray& data); signals: - void - nodeCreated(Node &n); + void nodeCreated(Node& n); - void - nodeDeleted(Node &n); + void nodeDeleted(Node& n); - void - connectionCreated(Connection &c); - void - connectionDeleted(Connection &c); + void connectionCreated(Connection& c); + void connectionDeleted(Connection& c); - void - nodeMoved(Node& n, const QPointF& newLocation); + void nodeMoved(Node& n, const QPointF& newLocation); - void - nodeDoubleClicked(Node& n); + void nodeDoubleClicked(Node& n); - void - connectionHovered(Connection& c, QPoint screenPos); + void connectionHovered(Connection& c, QPoint screenPos); - void - nodeHovered(Node& n, QPoint screenPos); + void nodeHovered(Node& n, QPoint screenPos); - void - connectionHoverLeft(Connection& c); + void connectionHoverLeft(Connection& c); - void - nodeHoverLeft(Node& n); + void nodeHoverLeft(Node& n); private: - DataFlowModel* _dataFlowModel; - }; } // namespace QtNodes diff --git a/include/nodes/internal/DataModelRegistry.hpp b/include/nodes/internal/DataModelRegistry.hpp index 35fdbddc2..d5b72eb1a 100644 --- a/include/nodes/internal/DataModelRegistry.hpp +++ b/include/nodes/internal/DataModelRegistry.hpp @@ -1,96 +1,92 @@ #pragma once -#include -#include #include +#include +#include #include #include #include -#include "NodeDataModel.hpp" -#include "TypeConverter.hpp" #include "Export.hpp" +#include "NodeDataModel.hpp" #include "QStringStdHash.hpp" +#include "TypeConverter.hpp" #include "memory.hpp" -namespace QtNodes -{ +namespace QtNodes { -inline -bool -operator<(QtNodes::NodeDataType const & d1, - QtNodes::NodeDataType const & d2) +inline bool +operator<(QtNodes::NodeDataType const& d1, QtNodes::NodeDataType const& d2) { return d1.id < d2.id; } - /// Class uses map for storing models (name, model) class NODE_EDITOR_PUBLIC DataModelRegistry { public: - - using RegistryItemPtr = std::unique_ptr; + using RegistryItemPtr = std::unique_ptr; using RegistryItemCreator = std::function; - using RegisteredModelCreatorsMap = std::unordered_map; + using RegisteredModelCreatorsMap = + std::unordered_map; using RegisteredModelsCategoryMap = std::unordered_map; using CategoriesSet = std::set; using RegisteredTypeConvertersMap = std::map; - DataModelRegistry() = default; + DataModelRegistry() = default; ~DataModelRegistry() = default; - DataModelRegistry(DataModelRegistry const &) = delete; - DataModelRegistry(DataModelRegistry &&) = default; + DataModelRegistry(DataModelRegistry const&) = delete; + DataModelRegistry(DataModelRegistry&&) = default; - DataModelRegistry&operator=(DataModelRegistry const &) = delete; - DataModelRegistry&operator=(DataModelRegistry &&) = default; + DataModelRegistry& operator=(DataModelRegistry const&) = delete; + DataModelRegistry& operator=(DataModelRegistry&&) = default; public: - template void registerModel(RegistryItemCreator creator, - QString const &category = "Nodes") + QString const& category = "Nodes") { registerModelImpl(std::move(creator), category); } template - void registerModel(QString const &category = "Nodes") + void registerModel(QString const& category = "Nodes") { - RegistryItemCreator creator = [](){ return std::make_unique(); }; + RegistryItemCreator creator = []() { + return std::make_unique(); + }; registerModelImpl(std::move(creator), category); } template - void registerModel(QString const &category, - RegistryItemCreator creator) + void registerModel(QString const& category, RegistryItemCreator creator) { registerModelImpl(std::move(creator), category); } - void registerTypeConverter(TypeConverterId const & id, + void registerTypeConverter(TypeConverterId const& id, TypeConverter typeConverter) { _registeredTypeConverters[id] = std::move(typeConverter); } - std::unique_ptrcreate(QString const &modelName); + std::unique_ptr create(QString const& modelName); - RegisteredModelCreatorsMap const ®isteredModelCreators() const; + RegisteredModelCreatorsMap const& registeredModelCreators() const; - RegisteredModelsCategoryMap const ®isteredModelsCategoryAssociation() const; + RegisteredModelsCategoryMap const& registeredModelsCategoryAssociation() + const; - CategoriesSet const &categories() const; + CategoriesSet const& categories() const; - TypeConverter getTypeConverter(NodeDataType const & d1, - NodeDataType const & d2) const; + TypeConverter getTypeConverter(NodeDataType const& d1, + NodeDataType const& d2) const; private: - RegisteredModelsCategoryMap _registeredModelsCategory; CategoriesSet _categories; @@ -100,7 +96,6 @@ class NODE_EDITOR_PUBLIC DataModelRegistry RegisteredTypeConvertersMap _registeredTypeConverters; private: - // If the registered ModelType class has the static member method // // static Qstring Name(); @@ -109,24 +104,23 @@ class NODE_EDITOR_PUBLIC DataModelRegistry // // virtual QString name() const; - template - struct HasStaticMethodName - : std::false_type + template + struct HasStaticMethodName : std::false_type {}; - template - struct HasStaticMethodName::value>::type> - : std::true_type + template + struct HasStaticMethodName< + T, + typename std::enable_if< + std::is_same::value>::type> : std::true_type {}; template - typename std::enable_if< HasStaticMethodName::value>::type - registerModelImpl(RegistryItemCreator creator, QString const &category ) + typename std::enable_if::value>::type + registerModelImpl(RegistryItemCreator creator, QString const& category) { const QString name = ModelType::Name(); - if (_registeredItemCreators.count(name) == 0) - { + if (_registeredItemCreators.count(name) == 0) { _registeredItemCreators[name] = std::move(creator); _categories.insert(category); _registeredModelsCategory[name] = category; @@ -134,20 +128,16 @@ class NODE_EDITOR_PUBLIC DataModelRegistry } template - typename std::enable_if< !HasStaticMethodName::value>::type - registerModelImpl(RegistryItemCreator creator, QString const &category ) + typename std::enable_if::value>::type + registerModelImpl(RegistryItemCreator creator, QString const& category) { const QString name = creator()->name(); - if (_registeredItemCreators.count(name) == 0) - { + if (_registeredItemCreators.count(name) == 0) { _registeredItemCreators[name] = std::move(creator); _categories.insert(category); _registeredModelsCategory[name] = category; } } - }; - - } diff --git a/include/nodes/internal/Export.hpp b/include/nodes/internal/Export.hpp index 6d25d6a99..007039e08 100644 --- a/include/nodes/internal/Export.hpp +++ b/include/nodes/internal/Export.hpp @@ -4,48 +4,46 @@ #include "OperatingSystem.hpp" #ifdef NODE_EDITOR_PLATFORM_WINDOWS -# define NODE_EDITOR_EXPORT __declspec(dllexport) -# define NODE_EDITOR_IMPORT __declspec(dllimport) -# define NODE_EDITOR_LOCAL -#elif \ - NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR >= 4 || \ - defined (NODE_EDITOR_COMPILER_CLANG) -# define NODE_EDITOR_EXPORT __attribute__((visibility("default"))) -# define NODE_EDITOR_IMPORT __attribute__((visibility("default"))) -# define NODE_EDITOR_LOCAL __attribute__((visibility("hidden"))) +#define NODE_EDITOR_EXPORT __declspec(dllexport) +#define NODE_EDITOR_IMPORT __declspec(dllimport) +#define NODE_EDITOR_LOCAL +#elif NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR >= 4 || \ + defined(NODE_EDITOR_COMPILER_CLANG) +#define NODE_EDITOR_EXPORT __attribute__((visibility("default"))) +#define NODE_EDITOR_IMPORT __attribute__((visibility("default"))) +#define NODE_EDITOR_LOCAL __attribute__((visibility("hidden"))) #else -# define NODE_EDITOR_EXPORT -# define NODE_EDITOR_IMPORT -# define NODE_EDITOR_LOCAL +#define NODE_EDITOR_EXPORT +#define NODE_EDITOR_IMPORT +#define NODE_EDITOR_LOCAL #endif #ifdef __cplusplus -# define NODE_EDITOR_DEMANGLED extern "C" +#define NODE_EDITOR_DEMANGLED extern "C" #else -# define NODE_EDITOR_DEMANGLED +#define NODE_EDITOR_DEMANGLED #endif - -#if defined (NODE_EDITOR_SHARED) && !defined (NODE_EDITOR_STATIC) -# ifdef NODE_EDITOR_EXPORTS -# define NODE_EDITOR_PUBLIC NODE_EDITOR_EXPORT -# else -# define NODE_EDITOR_PUBLIC NODE_EDITOR_IMPORT -# endif -# define NODE_EDITOR_PRIVATE NODE_EDITOR_LOCAL -#elif !defined (NODE_EDITOR_SHARED) && defined (NODE_EDITOR_STATIC) -# define NODE_EDITOR_PUBLIC -# define NODE_EDITOR_PRIVATE -#elif defined (NODE_EDITOR_SHARED) && defined (NODE_EDITOR_STATIC) -# ifdef NODE_EDITOR_EXPORTS -# error "Cannot build as shared and static simultaneously." -# else -# error "Cannot link against shared and static simultaneously." -# endif +#if defined(NODE_EDITOR_SHARED) && !defined(NODE_EDITOR_STATIC) +#ifdef NODE_EDITOR_EXPORTS +#define NODE_EDITOR_PUBLIC NODE_EDITOR_EXPORT +#else +#define NODE_EDITOR_PUBLIC NODE_EDITOR_IMPORT +#endif +#define NODE_EDITOR_PRIVATE NODE_EDITOR_LOCAL +#elif !defined(NODE_EDITOR_SHARED) && defined(NODE_EDITOR_STATIC) +#define NODE_EDITOR_PUBLIC +#define NODE_EDITOR_PRIVATE +#elif defined(NODE_EDITOR_SHARED) && defined(NODE_EDITOR_STATIC) +#ifdef NODE_EDITOR_EXPORTS +#error "Cannot build as shared and static simultaneously." #else -# ifdef NODE_EDITOR_EXPORTS -# error "Choose whether to build as shared or static." -# else -# error "Choose whether to link against shared or static." -# endif +#error "Cannot link against shared and static simultaneously." +#endif +#else +#ifdef NODE_EDITOR_EXPORTS +#error "Choose whether to build as shared or static." +#else +#error "Choose whether to link against shared or static." +#endif #endif diff --git a/include/nodes/internal/FlowScene.hpp b/include/nodes/internal/FlowScene.hpp index 4f49d507f..7fe15e9b4 100644 --- a/include/nodes/internal/FlowScene.hpp +++ b/include/nodes/internal/FlowScene.hpp @@ -3,19 +3,18 @@ #include #include -#include -#include #include +#include +#include -#include "QUuidStdHash.hpp" -#include "Export.hpp" #include "ConnectionID.hpp" #include "DataModelRegistry.hpp" +#include "Export.hpp" +#include "QUuidStdHash.hpp" #include "TypeConverter.hpp" #include "memory.hpp" -namespace QtNodes -{ +namespace QtNodes { class FlowSceneModel; class ConnectionGraphicsObject; @@ -23,69 +22,61 @@ class NodeGraphicsObject; /// The FlowScene is responsible for rendering a FlowSceneModel /// If you're looking for a basic dataflow model, see DataFlowScene -class NODE_EDITOR_PUBLIC FlowScene - : public QGraphicsScene +class NODE_EDITOR_PUBLIC FlowScene : public QGraphicsScene { Q_OBJECT friend NodeGraphicsObject; friend ConnectionGraphicsObject; -public: +public: FlowScene(FlowSceneModel* model, QObject* parent = Q_NULLPTR); - ~FlowScene(); + virtual ~FlowScene(); public: + FlowSceneModel* model() const { return _model; } - FlowSceneModel* - model() const { return _model; } + NodeGraphicsObject* nodeGraphicsObject(const NodeIndex& index); - NodeGraphicsObject* - nodeGraphicsObject(const NodeIndex& index); - - std::vector - selectedNodes() const; + std::vector selectedNodes() const; private slots: - void - nodeRemoved(const QUuid& id); + void nodeRemoved(const QUuid& id); - void - nodeAdded(const QUuid& newID); + void nodeAdded(const QUuid& newID); - void - nodePortUpdated(NodeIndex const& id); + void nodePortUpdated(NodeIndex const& id); - void - nodeValidationUpdated(NodeIndex const& id); + void nodeValidationUpdated(NodeIndex const& id); - void - connectionRemoved(NodeIndex const& leftNode, PortIndex leftPortID, - NodeIndex const& rightNode, PortIndex rightPortID); + void connectionRemoved(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID); - void - connectionAdded(NodeIndex const& leftNode, PortIndex leftPortID, - NodeIndex const& rightNode, PortIndex rightPortID); + void connectionAdded(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID); - void - nodeMoved(NodeIndex const& index); + void nodeMoved(NodeIndex const& index); private: - FlowSceneModel* _model; std::unordered_map _nodeGraphicsObjects; - std::unordered_map _connGraphicsObjects; + std::unordered_map + _connGraphicsObjects; // This is for when you're creating a connection ConnectionGraphicsObject* _temporaryConn = nullptr; - }; NodeGraphicsObject* -locateNodeAt(QPointF scenePoint, FlowScene &scene, - QTransform const & viewTransform); +locateNodeAt(QPointF scenePoint, + FlowScene& scene, + QTransform const& viewTransform); } diff --git a/include/nodes/internal/FlowSceneModel.hpp b/include/nodes/internal/FlowSceneModel.hpp index bd8ead70c..f6e447e53 100644 --- a/include/nodes/internal/FlowSceneModel.hpp +++ b/include/nodes/internal/FlowSceneModel.hpp @@ -1,20 +1,18 @@ #pragma once -#include "PortType.hpp" #include "Export.hpp" #include "NodeStyle.hpp" +#include "PortType.hpp" #include -#include -#include +#include #include +#include +#include #include -#include - -namespace QtNodes -{ +namespace QtNodes { class NodeIndex; struct NodeDataType; @@ -34,179 +32,179 @@ enum class NodeValidationState }; // data-type-in, data-type-out -using TypeConverterId = - std::pair; - +using TypeConverterId = std::pair; class NODE_EDITOR_PUBLIC FlowSceneModel : public QObject { Q_OBJECT public: - FlowSceneModel() = default; // Scene specific functions - virtual QStringList - modelRegistry() const = 0; + virtual QStringList modelRegistry() const = 0; /// Get the category for a node type /// name will be from `modelRegistry()` - virtual QString - nodeTypeCategory(QString const& /*name*/) const { return {}; } + virtual QString nodeTypeCategory(QString const& /*name*/) const { return {}; } /// Get if two types are convertable - virtual bool - getTypeConvertable(TypeConverterId const& /*id*/) const { return false; } + virtual bool getTypeConvertable(TypeConverterId const& /*id*/) const + { + return false; + } // Retrieval functions ////////////////////// /// Get the list of node IDs - virtual QList - nodeUUids() const = 0; + virtual QList nodeUUids() const = 0; /// Create a NodeIndex for a node - virtual NodeIndex - nodeIndex(const QUuid& ID) const = 0; + virtual NodeIndex nodeIndex(const QUuid& ID) const = 0; /// Get the type ID for the node - virtual QString - nodeTypeIdentifier(NodeIndex const& index) const = 0; + virtual QString nodeTypeIdentifier(NodeIndex const& index) const = 0; /// Get the caption for the node - virtual QString - nodeCaption(NodeIndex const& index) const = 0; + virtual QString nodeCaption(NodeIndex const& index) const = 0; /// Get the location of a node - virtual QPointF - nodeLocation(NodeIndex const& index) const = 0; + virtual QPointF nodeLocation(NodeIndex const& index) const = 0; /// Get the embedded widget - virtual QWidget* - nodeWidget(NodeIndex const& index) const = 0; + virtual QWidget* nodeWidget(NodeIndex const& index) const = 0; /// Get if it's resizable - virtual bool - nodeResizable(NodeIndex const& index) const = 0; + virtual bool nodeResizable(NodeIndex const& index) const = 0; /// Get the validation state - virtual NodeValidationState - nodeValidationState(NodeIndex const& index) const = 0; + virtual NodeValidationState nodeValidationState( + NodeIndex const& index) const = 0; /// Get the validation error/warning - virtual QString - nodeValidationMessage(NodeIndex const& index) const = 0; + virtual QString nodeValidationMessage(NodeIndex const& index) const = 0; /// Get the painter delegate - virtual NodePainterDelegate* - nodePainterDelegate(NodeIndex const& index) const = 0; + virtual NodePainterDelegate* nodePainterDelegate( + NodeIndex const& index) const = 0; /// Get the style - {} for default - virtual NodeStyle - nodeStyle(NodeIndex const& /*index*/) const { return {}; } + virtual NodeStyle nodeStyle(NodeIndex const& /*index*/) const { return {}; } /// Get the count of DataPorts - virtual unsigned int - nodePortCount(NodeIndex const& index, PortType portType) const = 0; + virtual unsigned int nodePortCount(NodeIndex const& index, + PortType portType) const = 0; /// Get the port caption - virtual QString - nodePortCaption(NodeIndex const& index, PortIndex portID, PortType portType) const = 0; + virtual QString nodePortCaption(NodeIndex const& index, + PortIndex portID, + PortType portType) const = 0; /// Get the port data type - virtual NodeDataType - nodePortDataType(NodeIndex const& index, PortIndex portID, PortType portType) const = 0; + virtual NodeDataType nodePortDataType(NodeIndex const& index, + PortIndex portID, + PortType portType) const = 0; /// Port Policy - virtual ConnectionPolicy - nodePortConnectionPolicy(NodeIndex const& index, PortIndex portID, PortType portType) const = 0; + virtual ConnectionPolicy nodePortConnectionPolicy( + NodeIndex const& index, + PortIndex portID, + PortType portType) const = 0; /// Get a connection at a port /// Returns the remote node and the remote port index for that node - virtual std::vector > - nodePortConnections(NodeIndex const& index, PortIndex portID, PortType portTypes) const = 0; + virtual std::vector> nodePortConnections( + NodeIndex const& index, + PortIndex portID, + PortType portTypes) const = 0; // Mutation functions ///////////////////// /// Remove a connection - virtual bool - removeConnection(NodeIndex const& /*leftNode*/, - PortIndex /*leftPortID*/, - NodeIndex const& /*rightNode*/, - PortIndex /*rightPortID*/) - { return false; } + virtual bool removeConnection(NodeIndex const& /*leftNode*/, + PortIndex /*leftPortID*/, + NodeIndex const& /*rightNode*/, + PortIndex /*rightPortID*/) + { + return false; + } /// Add a connection - virtual bool - addConnection(NodeIndex const& /*leftNode*/, - PortIndex /*leftPortID*/, - NodeIndex const& /*rightNode*/, - PortIndex /*rightPortID*/) - { return false; } + virtual bool addConnection(NodeIndex const& /*leftNode*/, + PortIndex /*leftPortID*/, + NodeIndex const& /*rightNode*/, + PortIndex /*rightPortID*/) + { + return false; + } /// Remove a node - virtual bool - removeNode(NodeIndex const& /*index*/) { return false; } + virtual bool removeNode(NodeIndex const& /*index*/) { return false; } /// Add a -- return {} if it fails - virtual QUuid - addNode(QString const& /*typeID*/, QPointF const& /*pos*/) { return QUuid{}; } + virtual QUuid addNode(QString const& /*typeID*/, QPointF const& /*pos*/) + { + return QUuid{}; + } /// Move a node to a new location - virtual bool - moveNode(NodeIndex const& /*index*/, QPointF /*newLocation*/) { return false; } + virtual bool moveNode(NodeIndex const& /*index*/, QPointF /*newLocation*/) + { + return false; + } public: - /// Helper functions //////////////////// // try to remove all connections and then the node - bool - removeNodeWithConnections(NodeIndex const& index); + bool removeNodeWithConnections(NodeIndex const& index); public: - - /// Notifications ///////////////// - virtual void - connectionHovered(NodeIndex const& /*lhs*/, PortIndex /*lPortIndex*/, NodeIndex const& /*rhs*/, PortIndex /*rPortIndex*/, QPoint const& /*pos*/, bool /*entered*/) {} + virtual void connectionHovered(NodeIndex const& /*lhs*/, + PortIndex /*lPortIndex*/, + NodeIndex const& /*rhs*/, + PortIndex /*rPortIndex*/, + QPoint const& /*pos*/, + bool /*entered*/) + {} - virtual void - nodeHovered(NodeIndex const& /*index*/, QPoint const& /*pos*/, bool /*entered*/) {} + virtual void nodeHovered(NodeIndex const& /*index*/, + QPoint const& /*pos*/, + bool /*entered*/) + {} - virtual void - nodeDoubleClicked(NodeIndex const& /*index*/, QPoint const& /*pos*/) {} + virtual void nodeDoubleClicked(NodeIndex const& /*index*/, + QPoint const& /*pos*/) + {} - virtual void - nodeContextMenu(NodeIndex const& /*index*/, QPoint const& /*pos*/) {} + virtual void nodeContextMenu(NodeIndex const& /*index*/, + QPoint const& /*pos*/) + {} signals: - void - nodeRemoved(const QUuid& id); - void - nodeAdded(const QUuid& newID); - void - nodePortUpdated(NodeIndex const& id); - void - nodeValidationUpdated(NodeIndex const& id); - void - connectionRemoved(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const& rightNode, PortIndex rightPortID); - void - connectionAdded(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const& rightNode, PortIndex rightPortID); - void - nodeMoved(NodeIndex const& index); + void nodeRemoved(const QUuid& id); + void nodeAdded(const QUuid& newID); + void nodePortUpdated(NodeIndex const& id); + void nodeValidationUpdated(NodeIndex const& id); + void connectionRemoved(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID); + void connectionAdded(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID); + void nodeMoved(NodeIndex const& index); protected: - - NodeIndex - createIndex(const QUuid& id, void* internalPointer) const; - + NodeIndex createIndex(const QUuid& id, void* internalPointer) const; }; } // namespace QtNodes diff --git a/include/nodes/internal/FlowView.hpp b/include/nodes/internal/FlowView.hpp index 6fe449baa..2095779c4 100644 --- a/include/nodes/internal/FlowView.hpp +++ b/include/nodes/internal/FlowView.hpp @@ -4,77 +4,57 @@ #include "Export.hpp" -namespace QtNodes -{ +namespace QtNodes { class FlowScene; -class NODE_EDITOR_PUBLIC FlowView - : public QGraphicsView +class NODE_EDITOR_PUBLIC FlowView : public QGraphicsView { Q_OBJECT public: - - FlowView(QWidget *parent = Q_NULLPTR); - FlowView(FlowScene *scene, QWidget *parent = Q_NULLPTR); + FlowView(QWidget* parent = Q_NULLPTR); + FlowView(FlowScene* scene, QWidget* parent = Q_NULLPTR); FlowView(const FlowView&) = delete; - FlowView - operator=(const FlowView&) = delete; + FlowView operator=(const FlowView&) = delete; - QAction* - clearSelectionAction() const; + QAction* clearSelectionAction() const; - QAction* - deleteSelectionAction() const; + QAction* deleteSelectionAction() const; - void - setScene(FlowScene *scene); + void setScene(FlowScene* scene); public slots: - void - scaleUp(); + void scaleUp(); - void - scaleDown(); + void scaleDown(); - void - deleteSelectedNodes(); + void deleteSelectedNodes(); protected: + void contextMenuEvent(QContextMenuEvent* event) override; - void - contextMenuEvent(QContextMenuEvent *event) override; + void wheelEvent(QWheelEvent* event) override; - void - wheelEvent(QWheelEvent *event) override; + void keyPressEvent(QKeyEvent* event) override; - void - keyPressEvent(QKeyEvent *event) override; + void keyReleaseEvent(QKeyEvent* event) override; - void - keyReleaseEvent(QKeyEvent *event) override; + void mousePressEvent(QMouseEvent* event) override; - void - mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent* event) override; - void - mouseMoveEvent(QMouseEvent *event) override; + void drawBackground(QPainter* painter, const QRectF& r) override; - void - drawBackground(QPainter* painter, const QRectF& r) override; + void showEvent(QShowEvent* event) override; - void - showEvent(QShowEvent *event) override; + void resizeEvent(QResizeEvent* event) override; protected: - - FlowScene * - scene(); + FlowScene* scene(); private: - QAction* _clearSelectionAction; QAction* _deleteSelectionAction; diff --git a/include/nodes/internal/FlowViewStyle.hpp b/include/nodes/internal/FlowViewStyle.hpp index 1041e9ef1..90a528830 100644 --- a/include/nodes/internal/FlowViewStyle.hpp +++ b/include/nodes/internal/FlowViewStyle.hpp @@ -5,35 +5,26 @@ #include "Export.hpp" #include "Style.hpp" -namespace QtNodes -{ +namespace QtNodes { class NODE_EDITOR_PUBLIC FlowViewStyle : public Style { public: - FlowViewStyle(); FlowViewStyle(QString jsonText); public: - - static void - setStyle(QString jsonText); + static void setStyle(QString jsonText); private: + void loadJsonText(QString jsonText) override; - void - loadJsonText(QString jsonText) override; + void loadJsonFile(QString fileName) override; - void - loadJsonFile(QString fileName) override; - - void - loadJsonFromByteArray(QByteArray const &byteArray) override; + void loadJsonFromByteArray(QByteArray const& byteArray) override; public: - QColor BackgroundColor; QColor FineGridColor; QColor CoarseGridColor; diff --git a/include/nodes/internal/Node.hpp b/include/nodes/internal/Node.hpp index 01beb05e5..aae593168 100644 --- a/include/nodes/internal/Node.hpp +++ b/include/nodes/internal/Node.hpp @@ -1,6 +1,5 @@ #pragma once - #include #include @@ -8,17 +7,16 @@ #include "PortType.hpp" +#include "ConnectionGraphicsObject.hpp" #include "Export.hpp" -#include "NodeState.hpp" -#include "NodeGeometry.hpp" #include "NodeData.hpp" +#include "NodeGeometry.hpp" #include "NodeGraphicsObject.hpp" -#include "ConnectionGraphicsObject.hpp" +#include "NodeState.hpp" #include "Serializable.hpp" #include "memory.hpp" -namespace QtNodes -{ +namespace QtNodes { class Connection; class ConnectionState; @@ -32,70 +30,53 @@ class NODE_EDITOR_PUBLIC Node Q_OBJECT public: - /// NodeDataModel should be an rvalue and is moved into the Node - Node(std::unique_ptr && dataModel, - QUuid const& id); + Node(std::unique_ptr&& dataModel, QUuid const& id); - virtual - ~Node(); + virtual ~Node(); public: + QJsonObject save() const override; - QJsonObject - save() const override; - - void - restore(QJsonObject const &json) override; + void restore(QJsonObject const& json) override; public: + QUuid id() const; - QUuid - id() const; + QPointF position() const; - QPointF - position() const; - - void - setPosition(QPointF const& newPos); + void setPosition(QPointF const& newPos); public: + NodeDataModel* nodeDataModel() const; - NodeDataModel* - nodeDataModel() const; - - std::vector const& - connections(PortType pType, PortIndex pIdx) const; + std::vector const& connections(PortType pType, + PortIndex pIdx) const; - std::vector& - connections(PortType pType, PortIndex pIdx); + std::vector& connections(PortType pType, PortIndex pIdx); public slots: // data propagation /// Propagates incoming data to the underlying model. - void - propagateData(std::shared_ptr nodeData, - PortIndex inPortIndex) const; + void propagateData(std::shared_ptr nodeData, + PortIndex inPortIndex) const; /// Fetches data from model's OUT #index port /// and propagates it to the connection - void - onDataUpdated(PortIndex index); + void onDataUpdated(PortIndex index); signals: - void - positionChanged(QPointF const& newPos); + void positionChanged(QPointF const& newPos); private: - // addressing QUuid _uid; // data std::unique_ptr _nodeDataModel; - std::vector > _inConnections, _outConnections; + std::vector> _inConnections, _outConnections; QPointF _pos; }; } diff --git a/include/nodes/internal/NodeData.hpp b/include/nodes/internal/NodeData.hpp index 088b6343b..52f64cade 100644 --- a/include/nodes/internal/NodeData.hpp +++ b/include/nodes/internal/NodeData.hpp @@ -4,8 +4,7 @@ #include "Export.hpp" -namespace QtNodes -{ +namespace QtNodes { struct NodeDataType { @@ -19,18 +18,14 @@ struct NodeDataType class NODE_EDITOR_PUBLIC NodeData { public: + virtual ~NodeData() = default; - virtual - ~NodeData() = default; - - virtual bool - sameType(NodeData const &nodeData) const + virtual bool sameType(NodeData const& nodeData) const { return (this->type().id == nodeData.type().id); } /// Type for inner use - virtual NodeDataType - type() const = 0; + virtual NodeDataType type() const = 0; }; } diff --git a/include/nodes/internal/NodeDataModel.hpp b/include/nodes/internal/NodeDataModel.hpp index dc7bdc418..9a8e469a8 100644 --- a/include/nodes/internal/NodeDataModel.hpp +++ b/include/nodes/internal/NodeDataModel.hpp @@ -1,20 +1,18 @@ #pragma once - #include -#include "PortType.hpp" +#include "Export.hpp" +#include "FlowSceneModel.hpp" #include "NodeData.hpp" -#include "Serializable.hpp" #include "NodeGeometry.hpp" -#include "NodeStyle.hpp" #include "NodePainterDelegate.hpp" -#include "Export.hpp" +#include "NodeStyle.hpp" +#include "PortType.hpp" +#include "Serializable.hpp" #include "memory.hpp" -#include "FlowSceneModel.hpp" -namespace QtNodes -{ +namespace QtNodes { class StyleCollection; @@ -25,110 +23,75 @@ class NODE_EDITOR_PUBLIC NodeDataModel Q_OBJECT public: - NodeDataModel(); - virtual - ~NodeDataModel() = default; + virtual ~NodeDataModel() = default; /// Caption is used in GUI - virtual QString - caption() const = 0; + virtual QString caption() const = 0; /// It is possible to hide caption in GUI - virtual bool - captionVisible() const { return true; } + virtual bool captionVisible() const { return true; } /// Port caption is used in GUI to label individual ports - virtual QString - portCaption(PortType, PortIndex) const { return QString(); } + virtual QString portCaption(PortType, PortIndex) const { return QString(); } /// It is possible to hide port caption in GUI - virtual bool - portCaptionVisible(PortType, PortIndex) const { return false; } + virtual bool portCaptionVisible(PortType, PortIndex) const { return false; } /// Name makes this model unique - virtual QString - name() const = 0; + virtual QString name() const = 0; public: - - QJsonObject - save() const override; + QJsonObject save() const override; public: + virtual unsigned int nPorts(PortType portType) const = 0; - virtual - unsigned int - nPorts(PortType portType) const = 0; - - virtual - NodeDataType - dataType(PortType portType, PortIndex portIndex) const = 0; + virtual NodeDataType dataType(PortType portType, + PortIndex portIndex) const = 0; public: - - virtual - ConnectionPolicy - portOutConnectionPolicy(PortIndex) const + virtual ConnectionPolicy portOutConnectionPolicy(PortIndex) const { return ConnectionPolicy::Many; } - NodeStyle const& - nodeStyle() const; + NodeStyle const& nodeStyle() const; - void - setNodeStyle(NodeStyle const& style); + void setNodeStyle(NodeStyle const& style); public: - /// Triggers the algorithm - virtual - void - setInData(std::shared_ptr nodeData, - PortIndex port) = 0; + virtual void setInData(std::shared_ptr nodeData, + PortIndex port) = 0; - virtual - std::shared_ptr - outData(PortIndex port) = 0; + virtual std::shared_ptr outData(PortIndex port) = 0; - virtual - QWidget * - embeddedWidget() = 0; + virtual QWidget* embeddedWidget() = 0; - virtual - bool - resizable() const { return false; } + virtual bool resizable() const { return false; } - virtual - NodeValidationState - validationState() const { return NodeValidationState::Valid; } + virtual NodeValidationState validationState() const + { + return NodeValidationState::Valid; + } - virtual - QString - validationMessage() const { return QString(""); } + virtual QString validationMessage() const { return QString(""); } - virtual - NodePainterDelegate* - painterDelegate() const { return nullptr; } + virtual NodePainterDelegate* painterDelegate() const { return nullptr; } signals: - void - dataUpdated(PortIndex index); + void dataUpdated(PortIndex index); - void - dataInvalidated(PortIndex index); + void dataInvalidated(PortIndex index); - void - computingStarted(); + void computingStarted(); - void - computingFinished(); + void computingFinished(); private: - NodeStyle _nodeStyle; }; } diff --git a/include/nodes/internal/NodeGeometry.hpp b/include/nodes/internal/NodeGeometry.hpp index 9039c96d4..12953f925 100644 --- a/include/nodes/internal/NodeGeometry.hpp +++ b/include/nodes/internal/NodeGeometry.hpp @@ -1,133 +1,103 @@ #pragma once -#include #include -#include +#include #include +#include -#include "PortType.hpp" #include "Export.hpp" -#include "memory.hpp" #include "NodeIndex.hpp" +#include "PortType.hpp" +#include "memory.hpp" -namespace QtNodes -{ +namespace QtNodes { class NodeGraphicsObject; class NODE_EDITOR_PUBLIC NodeGeometry { public: - - NodeGeometry(NodeIndex const& index); + NodeGeometry(NodeIndex const& index, NodeGraphicsObject& obj); public: - unsigned int - height() const { return _height; } + unsigned int height() const { return _height; } - void - setHeight(unsigned int h) { _height = h; } + void setHeight(unsigned int h) { _height = h; } - unsigned int - width() const { return _width; } + unsigned int width() const { return _width; } - void - setWidth(unsigned int w) { _width = w; } + void setWidth(unsigned int w) { _width = w; } - unsigned int - entryHeight() const { return _entryHeight; } - void - setEntryHeight(unsigned int h) { _entryHeight = h; } + unsigned int entryHeight() const { return _entryHeight; } + void setEntryHeight(unsigned int h) { _entryHeight = h; } - unsigned int - entryWidth() const { return _entryWidth; } + unsigned int entryWidth() const { return _entryWidth; } - void - setEntryWidth(unsigned int w) { _entryWidth = w; } + void setEntryWidth(unsigned int w) { _entryWidth = w; } - unsigned int - spacing() const { return _spacing; } + unsigned int spacing() const { return _spacing; } - void - setSpacing(unsigned int s) { _spacing = s; } + void setSpacing(unsigned int s) { _spacing = s; } - bool - hovered() const { return _hovered; } + bool hovered() const { return _hovered; } - void - setHovered(unsigned int h) { _hovered = h; } + void setHovered(unsigned int h) { _hovered = h; } - unsigned int - nSources() const { return _nSources; } + unsigned int nSources() const { return _nSources; } - unsigned int - nSinks() const { return _nSinks; } + unsigned int nSinks() const { return _nSinks; } - QPointF const& - draggingPos() const - { return _draggingPos; } + QPointF const& draggingPos() const { return _draggingPos; } - void - setDraggingPosition(QPointF const& pos) - { _draggingPos = pos; } + void setDraggingPosition(QPointF const& pos) { _draggingPos = pos; } public: + QRectF entryBoundingRect() const; - QRectF - entryBoundingRect() const; - - QRectF - boundingRect() const; + QRectF boundingRect() const; /// Updates size unconditionally - void - recalculateSize() const; + void recalculateSize() const; /// Updates size if the QFontMetrics is changed - void - recalculateSize(QFont const &font) const; + void recalculateSize(QFont const& font) const; // TODO removed default QTransform() - QPointF - portScenePosition(PortIndex index, - PortType portType, - QTransform const & t = QTransform()) const; + QPointF portScenePosition(PortIndex index, + PortType portType, + QTransform const& t = QTransform()) const; - PortIndex - checkHitScenePoint(PortType portType, - QPointF point, - QTransform const & t = QTransform()) const; + PortIndex checkHitScenePoint(PortType portType, + QPointF point, + QTransform const& t = QTransform()) const; - QRect - resizeRect() const; + QRect resizeRect() const; /// Returns the position of a widget on the Node surface - QPointF - widgetPosition() const; + QPointF widgetPosition() const; - unsigned int - validationHeight() const; + unsigned int validationHeight() const; - unsigned int - validationWidth() const; + unsigned int validationWidth() const; - static - QPointF - calculateNodePositionBetweenNodePorts(PortIndex targetPortIndex, PortType targetPort, NodeGraphicsObject const& targetNode, - PortIndex sourcePortIndex, PortType sourcePort, NodeGraphicsObject const& sourceNode, - NodeGeometry const& newNodeGeom); -private: + static QPointF calculateNodePositionBetweenNodePorts( + PortIndex targetPortIndex, + PortType targetPort, + NodeGraphicsObject const& targetNode, + PortIndex sourcePortIndex, + PortType sourcePort, + NodeGraphicsObject const& sourceNode, + NodeGeometry const& newNodeGeom); - unsigned int - captionHeight() const; +private: + unsigned int captionHeight() const; - unsigned int - captionWidth() const; + unsigned int captionWidth() const; - unsigned int - portWidth(PortType portType) const; + unsigned int portWidth(PortType portType) const; private: + NodeGraphicsObject& _obj; // some variables are mutable because // we need to change drawing metrics diff --git a/include/nodes/internal/NodeGraphicsObject.hpp b/include/nodes/internal/NodeGraphicsObject.hpp index ecc5b841a..efddae25c 100644 --- a/include/nodes/internal/NodeGraphicsObject.hpp +++ b/include/nodes/internal/NodeGraphicsObject.hpp @@ -4,14 +4,13 @@ #include #include "Export.hpp" -#include "NodeIndex.hpp" #include "NodeGeometry.hpp" +#include "NodeIndex.hpp" #include "NodeState.hpp" class QGraphicsProxyWidget; -namespace QtNodes -{ +namespace QtNodes { class FlowScene; @@ -21,101 +20,82 @@ class NODE_EDITOR_PUBLIC NodeGraphicsObject : public QGraphicsObject { Q_OBJECT -public: - NodeGraphicsObject(FlowScene &scene, - NodeIndex const& index); + /**\brief NodeGeometry set boundingRect for the class, so, every time, + * when values, which neded for change boundingRect, changes - we have to call + * prepareGeometryChange. So we can call this function in NodeGeometry - + * this is simple and we can forget about do it by hand. And it fix problems + */ + friend NodeGeometry; - virtual - ~NodeGraphicsObject(); +public: + NodeGraphicsObject(FlowScene& scene, NodeIndex const& index); - NodeIndex - index() const; + virtual ~NodeGraphicsObject(); - FlowScene& - flowScene(); + NodeIndex index() const; - FlowScene const& - flowScene() const; + FlowScene& flowScene(); - NodeGeometry& - geometry(); + FlowScene const& flowScene() const; - NodeGeometry const& - geometry() const; + NodeGeometry& geometry(); - NodeState& - nodeState(); + NodeGeometry const& geometry() const; - NodeState const& - nodeState() const; + NodeState& nodeState(); - QRectF - boundingRect() const override; + NodeState const& nodeState() const; - void - setGeometryChanged(); + QRectF boundingRect() const override; /// Visits all attached connections and corrects /// their corresponding end points. - void - moveConnections() const; - + void moveConnections() const; void reactToPossibleConnection(PortType, NodeDataType, QPointF const& scenePoint); - void - resetReactionToConnection(); + void resetReactionToConnection(); - enum { Type = UserType + 1 }; + enum + { + Type = UserType + 1 + }; - int - type() const override { return Type; } + int type() const override { return Type; } - void - lock(bool locked); + void lock(bool locked); protected: - void - paint(QPainter* painter, - QStyleOptionGraphicsItem const* option, - QWidget* widget = 0) override; + void paint(QPainter* painter, + QStyleOptionGraphicsItem const* option, + QWidget* widget = 0) override; - QVariant - itemChange(GraphicsItemChange change, const QVariant &value) override; + QVariant itemChange(GraphicsItemChange change, + const QVariant& value) override; - void - mousePressEvent(QGraphicsSceneMouseEvent* event) override; + void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void - mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - void - mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override; - void - hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void - hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; - void - hoverMoveEvent(QGraphicsSceneHoverEvent *) override; + void hoverMoveEvent(QGraphicsSceneHoverEvent*) override; - void - mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; - void - contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override; + void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override; private: - void - embedQWidget(); + void embedQWidget(); private: - - FlowScene & _scene; + FlowScene& _scene; NodeIndex _nodeIndex; @@ -126,6 +106,6 @@ class NODE_EDITOR_PUBLIC NodeGraphicsObject : public QGraphicsObject bool _locked; // either nullptr or owned by parent QGraphicsItem - QGraphicsProxyWidget * _proxyWidget; + QGraphicsProxyWidget* _proxyWidget; }; } diff --git a/include/nodes/internal/NodeIndex.hpp b/include/nodes/internal/NodeIndex.hpp index df76bfa99..37abb8732 100644 --- a/include/nodes/internal/NodeIndex.hpp +++ b/include/nodes/internal/NodeIndex.hpp @@ -6,64 +6,52 @@ #include #include -namespace QtNodes -{ +namespace QtNodes { class FlowSceneModel; class NodeIndex { friend FlowSceneModel; -public: +public: /// Construct an invalid NodeIndex NodeIndex() = default; private: /// Regular constructor NodeIndex(const QUuid& uuid, void* internalPtr, const FlowSceneModel* model) - : _id {uuid} - , _internalPointer{internalPtr} - , _model{model} + : _id{ uuid } + , _internalPointer{ internalPtr } + , _model{ model } { Q_ASSERT(!_id.isNull()); Q_ASSERT(_model != nullptr); } public: - /// Get the internal pointer - void* - internalPointer() const { return _internalPointer; } + void* internalPointer() const { return _internalPointer; } /// Get the owning model - const FlowSceneModel* - model() const { return _model; } + const FlowSceneModel* model() const { return _model; } /// Get the id for the node - QUuid - id() const { return _id; } + QUuid id() const { return _id; } /// Test if it's valid - bool - isValid() const - { - return !id().isNull() && model() != nullptr; - } - + bool isValid() const { return !id().isNull() && model() != nullptr; } private: - QUuid _id; - void* _internalPointer = nullptr; + void* _internalPointer = nullptr; const FlowSceneModel* _model = nullptr; }; inline bool operator==(NodeIndex const& lhs, NodeIndex const& rhs) { - return lhs.model() == rhs.model() && - lhs.id() == rhs.id(); + return lhs.model() == rhs.model() && lhs.id() == rhs.id(); } inline bool @@ -73,4 +61,3 @@ operator!=(NodeIndex const& lhs, NodeIndex const& rhs) } } // namespace QtNodes - diff --git a/include/nodes/internal/NodePainterDelegate.hpp b/include/nodes/internal/NodePainterDelegate.hpp index 75be43f3f..73f296c3d 100644 --- a/include/nodes/internal/NodePainterDelegate.hpp +++ b/include/nodes/internal/NodePainterDelegate.hpp @@ -4,8 +4,7 @@ #include "Export.hpp" -namespace QtNodes -{ +namespace QtNodes { class NodeGraphicsObject; class NodeIndex; @@ -15,13 +14,10 @@ class NODE_EDITOR_PUBLIC NodePainterDelegate { public: + virtual ~NodePainterDelegate() = default; - virtual - ~NodePainterDelegate() = default; - - virtual void - paint(QPainter* painter, - NodeGeometry const& ngo, - NodeIndex const& index) = 0; + virtual void paint(QPainter* painter, + NodeGeometry const& ngo, + NodeIndex const& index) = 0; }; } diff --git a/include/nodes/internal/NodeState.hpp b/include/nodes/internal/NodeState.hpp index fb656ef3b..c7388a27d 100644 --- a/include/nodes/internal/NodeState.hpp +++ b/include/nodes/internal/NodeState.hpp @@ -1,18 +1,17 @@ #pragma once -#include #include +#include #include #include "Export.hpp" -#include "PortType.hpp" #include "NodeData.hpp" +#include "PortType.hpp" #include "memory.hpp" -namespace QtNodes -{ +namespace QtNodes { class NodeIndex; class ConnectionGraphicsObject; @@ -21,6 +20,7 @@ class ConnectionGraphicsObject; /// Stores bool for reacting on hovering connections class NODE_EDITOR_PUBLIC NodeState { + public: enum ReactToConnectionState { @@ -29,62 +29,45 @@ class NODE_EDITOR_PUBLIC NodeState }; public: - - NodeState(NodeIndex const& index); + explicit NodeState(NodeIndex const& index); public: - - using ConnectionPtrVec = - std::vector; + using ConnectionPtrVec = std::vector; /// Returns vector of connections ID. /// Some of them can be empty (null) - std::vector const& - getEntries(PortType) const; + std::vector const& getEntries(PortType) const; - std::vector & - getEntries(PortType); + std::vector& getEntries(PortType); - ConnectionPtrVec - connections(PortType portType, PortIndex portIndex) const; + ConnectionPtrVec connections(PortType portType, PortIndex portIndex) const; - void - setConnection(PortType portType, - PortIndex portIndex, - ConnectionGraphicsObject& connection); + void setConnection(PortType portType, + PortIndex portIndex, + ConnectionGraphicsObject& connection); - void - eraseConnection(PortType portType, - PortIndex portIndex, - ConnectionGraphicsObject& connection); + void eraseConnection(PortType portType, + PortIndex portIndex, + ConnectionGraphicsObject& connection); - ReactToConnectionState - reaction() const; + ReactToConnectionState reaction() const; - PortType - reactingPortType() const; + PortType reactingPortType() const; - NodeDataType - reactingDataType() const; + NodeDataType reactingDataType() const; - void - setReaction(ReactToConnectionState reaction, - PortType reactingPortType = PortType::None, + void setReaction(ReactToConnectionState reaction, + PortType reactingPortType = PortType::None, - NodeDataType reactingDataType = - NodeDataType()); + NodeDataType reactingDataType = NodeDataType()); - bool - isReacting() const; + bool isReacting() const; - void - setResizing(bool resizing); + void setResizing(bool resizing); - bool - resizing() const; + bool resizing() const; private: - std::vector _inConnections; std::vector _outConnections; diff --git a/include/nodes/internal/NodeStyle.hpp b/include/nodes/internal/NodeStyle.hpp index 154210f43..6d56e01ae 100644 --- a/include/nodes/internal/NodeStyle.hpp +++ b/include/nodes/internal/NodeStyle.hpp @@ -5,35 +5,26 @@ #include "Export.hpp" #include "Style.hpp" -namespace QtNodes -{ +namespace QtNodes { class NODE_EDITOR_PUBLIC NodeStyle : public Style { public: - NodeStyle(); NodeStyle(QString jsonText); public: - - static void - setNodeStyle(QString jsonText); + static void setNodeStyle(QString jsonText); private: + void loadJsonText(QString jsonText) override; - void - loadJsonText(QString jsonText) override; + void loadJsonFile(QString fileName) override; - void - loadJsonFile(QString fileName) override; - - void - loadJsonFromByteArray(QByteArray const &byteArray) override; + void loadJsonFromByteArray(QByteArray const& byteArray) override; public: - QColor NormalBoundaryColor; QColor SelectedBoundaryColor; QColor GradientColor0; diff --git a/include/nodes/internal/OperatingSystem.hpp b/include/nodes/internal/OperatingSystem.hpp index 8eddb67e1..ad47dc7d6 100644 --- a/include/nodes/internal/OperatingSystem.hpp +++ b/include/nodes/internal/OperatingSystem.hpp @@ -1,78 +1,50 @@ #pragma once -#if \ - defined (__CYGWIN__) || \ - defined (__CYGWIN32__) -# define NODE_EDITOR_PLATFORM "Cygwin" -# define NODE_EDITOR_PLATFORM_CYGWIN -# define NODE_EDITOR_PLATFORM_UNIX -# define NODE_EDITOR_PLATFORM_WINDOWS -#elif \ - defined (_WIN16) || \ - defined (_WIN32) || \ - defined (_WIN64) || \ - defined (__WIN32__) || \ - defined (__TOS_WIN__) || \ - defined (__WINDOWS__) -# define NODE_EDITOR_PLATFORM "Windows" -# define NODE_EDITOR_PLATFORM_WINDOWS -#elif \ - defined (macintosh) || \ - defined (Macintosh) || \ - defined (__TOS_MACOS__) || \ - (defined (__APPLE__) && defined (__MACH__)) -# define NODE_EDITOR_PLATFORM "Mac" -# define NODE_EDITOR_PLATFORM_MAC -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (linux) || \ - defined (__linux) || \ - defined (__linux__) || \ - defined (__TOS_LINUX__) -# define NODE_EDITOR_PLATFORM "Linux" -# define NODE_EDITOR_PLATFORM_LINUX -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (__FreeBSD__) || \ - defined (__OpenBSD__) || \ - defined (__NetBSD__) || \ - defined (__bsdi__) || \ - defined (__DragonFly__) -# define NODE_EDITOR_PLATFORM "BSD" -# define NODE_EDITOR_PLATFORM_BSD -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (sun) || \ - defined (__sun) -# define NODE_EDITOR_PLATFORM "Solaris" -# define NODE_EDITOR_PLATFORM_SOLARIS -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (_AIX) || \ - defined (__TOS_AIX__) -# define NODE_EDITOR_PLATFORM "AIX" -# define NODE_EDITOR_PLATFORM_AIX -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (hpux) || \ - defined (_hpux) || \ - defined (__hpux) -# define NODE_EDITOR_PLATFORM "HPUX" -# define NODE_EDITOR_PLATFORM_HPUX -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (__QNX__) -# define NODE_EDITOR_PLATFORM "QNX" -# define NODE_EDITOR_PLATFORM_QNX -# define NODE_EDITOR_PLATFORM_UNIX -#elif \ - defined (unix) || \ - defined (__unix) || \ - defined (__unix__) -# define NODE_EDITOR_PLATFORM "Unix" -# define NODE_EDITOR_PLATFORM_UNIX +#if defined(__CYGWIN__) || defined(__CYGWIN32__) +#define NODE_EDITOR_PLATFORM "Cygwin" +#define NODE_EDITOR_PLATFORM_CYGWIN +#define NODE_EDITOR_PLATFORM_UNIX +#define NODE_EDITOR_PLATFORM_WINDOWS +#elif defined(_WIN16) || defined(_WIN32) || defined(_WIN64) || \ + defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__) +#define NODE_EDITOR_PLATFORM "Windows" +#define NODE_EDITOR_PLATFORM_WINDOWS +#elif defined(macintosh) || defined(Macintosh) || defined(__TOS_MACOS__) || \ + (defined(__APPLE__) && defined(__MACH__)) +#define NODE_EDITOR_PLATFORM "Mac" +#define NODE_EDITOR_PLATFORM_MAC +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(linux) || defined(__linux) || defined(__linux__) || \ + defined(__TOS_LINUX__) +#define NODE_EDITOR_PLATFORM "Linux" +#define NODE_EDITOR_PLATFORM_LINUX +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || \ + defined(__bsdi__) || defined(__DragonFly__) +#define NODE_EDITOR_PLATFORM "BSD" +#define NODE_EDITOR_PLATFORM_BSD +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(sun) || defined(__sun) +#define NODE_EDITOR_PLATFORM "Solaris" +#define NODE_EDITOR_PLATFORM_SOLARIS +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(_AIX) || defined(__TOS_AIX__) +#define NODE_EDITOR_PLATFORM "AIX" +#define NODE_EDITOR_PLATFORM_AIX +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(hpux) || defined(_hpux) || defined(__hpux) +#define NODE_EDITOR_PLATFORM "HPUX" +#define NODE_EDITOR_PLATFORM_HPUX +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(__QNX__) +#define NODE_EDITOR_PLATFORM "QNX" +#define NODE_EDITOR_PLATFORM_QNX +#define NODE_EDITOR_PLATFORM_UNIX +#elif defined(unix) || defined(__unix) || defined(__unix__) +#define NODE_EDITOR_PLATFORM "Unix" +#define NODE_EDITOR_PLATFORM_UNIX #endif #ifndef NODE_EDITOR_PLATFORM -# error "Current platform is not supported." +#error "Current platform is not supported." #endif diff --git a/include/nodes/internal/PortType.hpp b/include/nodes/internal/PortType.hpp index cd76769ff..541661f94 100644 --- a/include/nodes/internal/PortType.hpp +++ b/include/nodes/internal/PortType.hpp @@ -1,10 +1,9 @@ #pragma once -#include #include +#include -namespace QtNodes -{ +namespace QtNodes { enum class PortType { @@ -33,23 +32,19 @@ struct Port , index(i) {} - bool - indexIsValid() { return index != INVALID; } + bool indexIsValid() { return index != INVALID; } - bool - portTypeIsValid() { return type != PortType::None; } + bool portTypeIsValid() { return type != PortType::None; } }; -//using PortAddress = std::pair; +// using PortAddress = std::pair; -inline -PortType +inline PortType oppositePort(PortType port) { PortType result = PortType::None; - switch (port) - { + switch (port) { case PortType::In: result = PortType::Out; break; diff --git a/include/nodes/internal/QStringStdHash.hpp b/include/nodes/internal/QStringStdHash.hpp index 3d47a3f84..4daa7c47d 100644 --- a/include/nodes/internal/QStringStdHash.hpp +++ b/include/nodes/internal/QStringStdHash.hpp @@ -5,15 +5,10 @@ #include #include -namespace std -{ +namespace std { template<> struct hash { - inline std::size_t - operator()(QString const &s) const - { - return qHash(s); - } + inline std::size_t operator()(QString const& s) const { return qHash(s); } }; } diff --git a/include/nodes/internal/QUuidStdHash.hpp b/include/nodes/internal/QUuidStdHash.hpp index 813b30c20..07fd94a05 100644 --- a/include/nodes/internal/QUuidStdHash.hpp +++ b/include/nodes/internal/QUuidStdHash.hpp @@ -5,17 +5,10 @@ #include #include -namespace std -{ +namespace std { template<> struct hash { - inline - std::size_t - operator()(QUuid const& uid) const - { - return qHash(uid); - } + inline std::size_t operator()(QUuid const& uid) const { return qHash(uid); } }; } - diff --git a/include/nodes/internal/Serializable.hpp b/include/nodes/internal/Serializable.hpp index 822c4f201..aed479663 100644 --- a/include/nodes/internal/Serializable.hpp +++ b/include/nodes/internal/Serializable.hpp @@ -2,21 +2,15 @@ #include -namespace QtNodes -{ +namespace QtNodes { class Serializable { public: + virtual ~Serializable() = default; - virtual - ~Serializable() = default; - - virtual - QJsonObject - save() const = 0; + virtual QJsonObject save() const = 0; - virtual void - restore(QJsonObject const & /*p*/) {} + virtual void restore(QJsonObject const& /*p*/) {} }; } diff --git a/include/nodes/internal/Style.hpp b/include/nodes/internal/Style.hpp index a0d24cf65..f9ed05402 100644 --- a/include/nodes/internal/Style.hpp +++ b/include/nodes/internal/Style.hpp @@ -5,18 +5,12 @@ class Style { public: - - virtual - ~Style() = default; + virtual ~Style() = default; private: + virtual void loadJsonText(QString jsonText) = 0; - virtual void - loadJsonText(QString jsonText) = 0; - - virtual void - loadJsonFile(QString fileName) = 0; + virtual void loadJsonFile(QString fileName) = 0; - virtual void - loadJsonFromByteArray(QByteArray const &byteArray) = 0; + virtual void loadJsonFromByteArray(QByteArray const& byteArray) = 0; }; diff --git a/include/nodes/internal/TypeConverter.hpp b/include/nodes/internal/TypeConverter.hpp index 24471f258..c97fc8256 100644 --- a/include/nodes/internal/TypeConverter.hpp +++ b/include/nodes/internal/TypeConverter.hpp @@ -5,13 +5,11 @@ #include -namespace QtNodes -{ +namespace QtNodes { using SharedNodeData = std::shared_ptr; // a function taking in NodeData and returning NodeData -using TypeConverter = - std::function; +using TypeConverter = std::function; } diff --git a/include/nodes/internal/memory.hpp b/include/nodes/internal/memory.hpp index 241d6e4de..e91e9ed6c 100644 --- a/include/nodes/internal/memory.hpp +++ b/include/nodes/internal/memory.hpp @@ -3,24 +3,26 @@ #include #include -namespace QtNodes -{ - namespace detail { -#if (!defined(_MSC_VER) && (__cplusplus < 201300)) || \ - ( defined(_MSC_VER) && (_MSC_VER < 1800)) -//_MSC_VER == 1800 is Visual Studio 2013, which is already somewhat C++14 compilant, +namespace QtNodes { +namespace detail { +#if (!defined(_MSC_VER) && (__cplusplus < 201300)) || \ + (defined(_MSC_VER) && (_MSC_VER < 1800)) +//_MSC_VER == 1800 is Visual Studio 2013, which is already somewhat C++14 +//compilant, // and it has make_unique in it's standard library implementation - template - std::unique_ptr make_unique(Args&&... args) - { - return std::unique_ptr(new T(std::forward(args)...)); - } +template +std::unique_ptr +make_unique(Args&&... args) +{ + return std::unique_ptr(new T(std::forward(args)...)); +} #else - template - std::unique_ptr make_unique(Args&&... args) - { - return std::make_unique(std::forward(args)...); - } +template +std::unique_ptr +make_unique(Args&&... args) +{ + return std::make_unique(std::forward(args)...); +} #endif - } +} } diff --git a/src/Connection.cpp b/src/Connection.cpp index 39cfb6e45..2047e8678 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -3,39 +3,38 @@ #include #include -#include #include +#include -#include "Node.hpp" #include "FlowScene.hpp" #include "FlowView.hpp" +#include "Node.hpp" +#include "NodeDataModel.hpp" #include "NodeGeometry.hpp" #include "NodeGraphicsObject.hpp" -#include "NodeDataModel.hpp" -#include "ConnectionState.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionGraphicsObject.hpp" +#include "ConnectionState.hpp" using QtNodes::Connection; +using QtNodes::ConnectionGeometry; +using QtNodes::ConnectionGraphicsObject; using QtNodes::ConnectionID; -using QtNodes::PortType; -using QtNodes::PortIndex; using QtNodes::ConnectionState; using QtNodes::Node; using QtNodes::NodeData; using QtNodes::NodeDataType; -using QtNodes::ConnectionGraphicsObject; -using QtNodes::ConnectionGeometry; +using QtNodes::PortIndex; +using QtNodes::PortType; using QtNodes::TypeConverter; -Connection:: -Connection(Node& nodeIn, - PortIndex portIndexIn, - Node& nodeOut, - PortIndex portIndexOut, - TypeConverter typeConverter) +Connection::Connection(Node& nodeIn, + PortIndex portIndexIn, + Node& nodeOut, + PortIndex portIndexOut, + TypeConverter typeConverter) : _uid(QUuid::createUuid()) , _outNode(&nodeOut) , _inNode(&nodeIn) @@ -48,43 +47,39 @@ Connection(Node& nodeIn, setNodeToPort(nodeOut, PortType::Out, portIndexOut); } - -Connection:: -~Connection() +Connection::~Connection() { - propagateEmptyData(); -} + // TODO when call destructor for connection objects, which recive this data, + // already deleted + // propagateEmptyData(); +} QJsonObject -Connection:: -save() const +Connection::save() const { QJsonObject connectionJson; - if (_inNode && _outNode) - { - connectionJson["in_id"] = _inNode->id().toString(); + if (_inNode && _outNode) { + connectionJson["in_id"] = _inNode->id().toString(); connectionJson["in_index"] = _inPortIndex; - connectionJson["out_id"] = _outNode->id().toString(); + connectionJson["out_id"] = _outNode->id().toString(); connectionJson["out_index"] = _outPortIndex; - if (_converter) - { - auto getTypeJson = [this](PortType type) - { - QJsonObject typeJson; - NodeDataType nodeType = this->dataType(type); - typeJson["id"] = nodeType.id; - typeJson["name"] = nodeType.name; + if (_converter) { + auto getTypeJson = [this](PortType type) { + QJsonObject typeJson; + NodeDataType nodeType = this->dataType(type); + typeJson["id"] = nodeType.id; + typeJson["name"] = nodeType.name; - return typeJson; - }; + return typeJson; + }; QJsonObject converterTypeJson; - converterTypeJson["in"] = getTypeJson(PortType::In); + converterTypeJson["in"] = getTypeJson(PortType::In); converterTypeJson["out"] = getTypeJson(PortType::Out); connectionJson["converter"] = converterTypeJson; @@ -95,8 +90,7 @@ save() const } ConnectionID -Connection:: -id() const +Connection::id() const { ConnectionID ret; ret.lNodeID = getNode(PortType::Out)->id(); @@ -109,10 +103,7 @@ id() const } void -Connection:: -setNodeToPort(Node& node, - PortType portType, - PortIndex portIndex) +Connection::setNodeToPort(Node& node, PortType portType, PortIndex portIndex) { auto& nodeWeak = getNodePtrRef(portType); @@ -128,16 +119,12 @@ setNodeToPort(Node& node, updated(*this); } - - PortIndex -Connection:: -getPortIndex(PortType portType) const +Connection::getPortIndex(PortType portType) const { PortIndex result = INVALID; - switch (portType) - { + switch (portType) { case PortType::In: result = _inPortIndex; break; @@ -155,11 +142,9 @@ getPortIndex(PortType portType) const } Node* -Connection:: -getNode(PortType portType) const +Connection::getNode(PortType portType) const { - switch (portType) - { + switch (portType) { case PortType::In: return _inNode; break; @@ -175,13 +160,10 @@ getNode(PortType portType) const Q_UNREACHABLE(); } - Node*& -Connection:: -getNodePtrRef(PortType portType) +Connection::getNodePtrRef(PortType portType) { - switch (portType) - { + switch (portType) { case PortType::In: return _inNode; break; @@ -197,41 +179,29 @@ getNodePtrRef(PortType portType) Q_UNREACHABLE(); } - NodeDataType -Connection:: -dataType(PortType portType) const +Connection::dataType(PortType portType) const { - if (_inNode && _outNode) - { - auto const & model = (portType == PortType::In) ? - _inNode->nodeDataModel() : - _outNode->nodeDataModel(); - PortIndex index = (portType == PortType::In) ? - _inPortIndex : - _outPortIndex; + if (_inNode && _outNode) { + auto const& model = (portType == PortType::In) ? _inNode->nodeDataModel() + : _outNode->nodeDataModel(); + PortIndex index = (portType == PortType::In) ? _inPortIndex : _outPortIndex; return model->dataType(portType, index); - } - else - { + } else { Node* validNode; PortIndex index = INVALID; - if ((validNode = _inNode)) - { - index = _inPortIndex; + if ((validNode = _inNode)) { + index = _inPortIndex; portType = PortType::In; - } - else if ((validNode = _outNode)) - { - index = _outPortIndex; + } else if ((validNode = _outNode)) { + index = _outPortIndex; portType = PortType::Out; } - if (validNode) - { - auto const &model = validNode->nodeDataModel(); + if (validNode) { + auto const& model = validNode->nodeDataModel(); return model->dataType(portType, index); } @@ -240,23 +210,17 @@ dataType(PortType portType) const Q_UNREACHABLE(); } - void -Connection:: -setTypeConverter(TypeConverter converter) +Connection::setTypeConverter(TypeConverter converter) { _converter = std::move(converter); } - void -Connection:: -propagateData(std::shared_ptr nodeData) const +Connection::propagateData(std::shared_ptr nodeData) const { - if (_inNode) - { - if (_converter) - { + if (_inNode) { + if (_converter) { nodeData = _converter(nodeData); } @@ -264,10 +228,8 @@ propagateData(std::shared_ptr nodeData) const } } - void -Connection:: -propagateEmptyData() const +Connection::propagateEmptyData() const { std::shared_ptr emptyData; diff --git a/src/ConnectionBlurEffect.cpp b/src/ConnectionBlurEffect.cpp index ca80609b6..843222404 100644 --- a/src/ConnectionBlurEffect.cpp +++ b/src/ConnectionBlurEffect.cpp @@ -6,20 +6,17 @@ using QtNodes::ConnectionBlurEffect; using QtNodes::ConnectionGraphicsObject; -ConnectionBlurEffect:: -ConnectionBlurEffect(ConnectionGraphicsObject*) +ConnectionBlurEffect::ConnectionBlurEffect(ConnectionGraphicsObject*) { // } - void -ConnectionBlurEffect:: -draw(QPainter* painter) +ConnectionBlurEffect::draw(QPainter* painter) { QGraphicsBlurEffect::draw(painter); - //ConnectionPainter::paint(painter, + // ConnectionPainter::paint(painter, //_object->connectionGeometry(), //_object->connectionState()); diff --git a/src/ConnectionBlurEffect.hpp b/src/ConnectionBlurEffect.hpp index abea71cdf..436986364 100644 --- a/src/ConnectionBlurEffect.hpp +++ b/src/ConnectionBlurEffect.hpp @@ -2,8 +2,7 @@ #include -namespace QtNodes -{ +namespace QtNodes { class ConnectionGraphicsObject; @@ -11,11 +10,9 @@ class ConnectionBlurEffect : public QGraphicsBlurEffect { public: - ConnectionBlurEffect(ConnectionGraphicsObject* item); - void - draw(QPainter* painter) override; + void draw(QPainter* painter) override; private: }; diff --git a/src/ConnectionGeometry.cpp b/src/ConnectionGeometry.cpp index 2f8e4be33..e0582001c 100644 --- a/src/ConnectionGeometry.cpp +++ b/src/ConnectionGeometry.cpp @@ -2,38 +2,42 @@ #include +#include "ConnectionGraphicsObject.hpp" #include "StyleCollection.hpp" using QtNodes::ConnectionGeometry; using QtNodes::PortType; -ConnectionGeometry:: -ConnectionGeometry() - : _in(0, 0) +ConnectionGeometry::ConnectionGeometry(QtNodes::ConnectionGraphicsObject& obj) + : _obj{ obj } + , _in(0, 0) , _out(0, 0) //, _animationPhase(0) , _lineWidth(3.0) , _hovered(false) -{ } +{ + + // TODO if style can change dynamicly, so it have to be unkomment + // connect(&QtNodes::StyleCollection::instance(), + // &StyleCollection::connectionStyleChanged, this, [&]() { + // _obj.prepareGeometryChange(); + // _obj.boundingRect(); + // }); +} QPointF const& -ConnectionGeometry:: -getEndPoint(PortType portType) const +ConnectionGeometry::getEndPoint(PortType portType) const { Q_ASSERT(portType != PortType::None); - return (portType == PortType::Out ? - _out : - _in); + return (portType == PortType::Out ? _out : _in); } - void -ConnectionGeometry:: -setEndPoint(PortType portType, QPointF const& point) +ConnectionGeometry::setEndPoint(PortType portType, QPointF const& point) { - switch (portType) - { + _obj.prepareGeometryChange(); + switch (portType) { case PortType::Out: _out = point; break; @@ -47,13 +51,11 @@ setEndPoint(PortType portType, QPointF const& point) } } - void -ConnectionGeometry:: -moveEndPoint(PortType portType, QPointF const &offset) +ConnectionGeometry::moveEndPoint(PortType portType, QPointF const& offset) { - switch (portType) - { + _obj.prepareGeometryChange(); + switch (portType) { case PortType::Out: _out += offset; break; @@ -67,23 +69,23 @@ moveEndPoint(PortType portType, QPointF const &offset) } } - QRectF -ConnectionGeometry:: -boundingRect() const +ConnectionGeometry::boundingRect() const { + // it have to be first for guaranty copy elision + QRectF commonRect; + auto points = pointsC1C2(); QRectF basicRect = QRectF(_out, _in).normalized(); QRectF c1c2Rect = QRectF(points.first, points.second).normalized(); - auto const &connectionStyle = - StyleCollection::connectionStyle(); + auto const& connectionStyle = StyleCollection::connectionStyle(); float const diam = connectionStyle.pointDiameter(); - QRectF commonRect = basicRect.united(c1c2Rect); + commonRect = basicRect.united(c1c2Rect); QPointF const cornerOffset(diam, diam); @@ -93,13 +95,11 @@ boundingRect() const return commonRect; } - std::pair -ConnectionGeometry:: -pointsC1C2() const +ConnectionGeometry::pointsC1C2() const { double xDistance = _in.x() - _out.x(); - //double yDistance = _in.y() - _out.y() - 100; + // double yDistance = _in.y() - _out.y() - 100; double defaultOffset = 200; @@ -109,24 +109,21 @@ pointsC1C2() const double ratio1 = 0.5; - if (xDistance <= 0) - { + if (xDistance <= 0) { verticalOffset = -minimum; ratio1 = 1.0; } - //double verticalOffset2 = verticalOffset; - //if (xDistance <= 0) - //verticalOffset2 = qMin(defaultOffset, std::abs(yDistance)); - //auto sign = [](double d) { return d > 0.0 ? +1.0 : -1.0; }; - //verticalOffset2 = 0.0; + // double verticalOffset2 = verticalOffset; + // if (xDistance <= 0) + // verticalOffset2 = qMin(defaultOffset, std::abs(yDistance)); + // auto sign = [](double d) { return d > 0.0 ? +1.0 : -1.0; }; + // verticalOffset2 = 0.0; - QPointF c1(_out.x() + minimum * ratio1, - _out.y() + verticalOffset); + QPointF c1(_out.x() + minimum * ratio1, _out.y() + verticalOffset); - QPointF c2(_in.x() - minimum * ratio1, - _in.y() + verticalOffset); + QPointF c2(_in.x() - minimum * ratio1, _in.y() + verticalOffset); return std::make_pair(c1, c2); } diff --git a/src/ConnectionGraphicsObject.cpp b/src/ConnectionGraphicsObject.cpp index c7a81714a..6ad7f1eea 100644 --- a/src/ConnectionGraphicsObject.cpp +++ b/src/ConnectionGraphicsObject.cpp @@ -1,17 +1,17 @@ #include "ConnectionGraphicsObject.hpp" -#include -#include #include -#include +#include +#include #include +#include #include "FlowScene.hpp" +#include "ConnectionBlurEffect.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionPainter.hpp" #include "ConnectionState.hpp" -#include "ConnectionBlurEffect.hpp" #include "NodeGraphicsObject.hpp" @@ -19,8 +19,8 @@ #include "Node.hpp" -using QtNodes::ConnectionGraphicsObject; using QtNodes::Connection; +using QtNodes::ConnectionGraphicsObject; using QtNodes::ConnectionID; using QtNodes::FlowScene; using QtNodes::NodeDataType; @@ -28,20 +28,20 @@ using QtNodes::NodeIndex; using QtNodes::PortIndex; using QtNodes::PortType; -ConnectionGraphicsObject:: -ConnectionGraphicsObject(NodeIndex const& leftNode, - PortIndex leftPortIndex, - NodeIndex const& rightNode, - PortIndex rightPortIndex, - FlowScene& scene) - : _scene{scene} - , _state(leftNode.isValid() ? - (rightNode.isValid() ? PortType::None : PortType::In) : - PortType::Out) - , _leftNode{leftNode} - , _rightNode{rightNode} - , _leftPortIndex{leftPortIndex} - , _rightPortIndex{rightPortIndex} +ConnectionGraphicsObject::ConnectionGraphicsObject(NodeIndex const& leftNode, + PortIndex leftPortIndex, + NodeIndex const& rightNode, + PortIndex rightPortIndex, + FlowScene& scene) + : _scene{ scene } + , _geometry{ *this } + , _state(leftNode.isValid() + ? (rightNode.isValid() ? PortType::None : PortType::In) + : PortType::Out) + , _leftNode{ leftNode } + , _rightNode{ rightNode } + , _leftPortIndex{ leftPortIndex } + , _rightPortIndex{ rightPortIndex } { _scene.addItem(this); @@ -56,48 +56,49 @@ ConnectionGraphicsObject(NodeIndex const& leftNode, setZValue(-1.0); // initialize the end points - if (leftNode.isValid()) - { + if (leftNode.isValid()) { auto ngo = _scene.nodeGraphicsObject(leftNode); Q_ASSERT(ngo != nullptr); - geometry().moveEndPoint(PortType::Out, ngo->geometry().portScenePosition(leftPortIndex, PortType::Out, ngo->sceneTransform())); - + geometry().moveEndPoint( + PortType::Out, + ngo->geometry().portScenePosition( + leftPortIndex, PortType::Out, ngo->sceneTransform())); } - if (rightNode.isValid()) - { + if (rightNode.isValid()) { auto ngo = _scene.nodeGraphicsObject(rightNode); Q_ASSERT(ngo != nullptr); - geometry().moveEndPoint(PortType::In, ngo->geometry().portScenePosition(rightPortIndex, PortType::In, ngo->sceneTransform())); + geometry().moveEndPoint( + PortType::In, + ngo->geometry().portScenePosition( + rightPortIndex, PortType::In, ngo->sceneTransform())); } - } -ConnectionGraphicsObject:: -~ConnectionGraphicsObject() + +ConnectionGraphicsObject::~ConnectionGraphicsObject() { + // TODO I think it is uncorrect. When, for example, we set parent to item - it + // will be big problem, because, when we remove parent item, all childs will + // be removed form scene automaticly _scene.removeItem(this); } - QRectF -ConnectionGraphicsObject:: -boundingRect() const +ConnectionGraphicsObject::boundingRect() const { return _geometry.boundingRect(); } - QPainterPath -ConnectionGraphicsObject:: -shape() const +ConnectionGraphicsObject::shape() const { #ifdef DEBUG_DRAWING - //QPainterPath path; + // QPainterPath path; - //path.addRect(boundingRect()); - //return path; + // path.addRect(boundingRect()); + // return path; #else @@ -106,17 +107,8 @@ shape() const #endif } - -void -ConnectionGraphicsObject:: -setGeometryChanged() -{ - prepareGeometryChange(); -} - ConnectionID -ConnectionGraphicsObject:: -id() const +ConnectionGraphicsObject::id() const { ConnectionID ret; @@ -129,8 +121,7 @@ id() const } NodeDataType -ConnectionGraphicsObject:: -dataType(PortType ty) const +ConnectionGraphicsObject::dataType(PortType ty) const { // get a valid node auto n = node(ty); @@ -140,86 +131,71 @@ dataType(PortType ty) const } void -ConnectionGraphicsObject:: -move() +ConnectionGraphicsObject::move() { - for(PortType portType: { PortType::In, PortType::Out } ) - { + for (PortType portType : { PortType::In, PortType::Out }) { auto nodeIndex = node(portType); - if (nodeIndex.isValid()) - { - auto const &nodeGraphics = *_scene.nodeGraphicsObject(nodeIndex); - - auto const &nodeGeom = nodeGraphics.geometry(); + if (nodeIndex.isValid()) { + // here we dereference pointer, which can be nullptr! So we first check + // this + auto temp = _scene.nodeGraphicsObject(nodeIndex); + if (temp) { + auto const& nodeGraphics = *temp; - QPointF scenePos = - nodeGeom.portScenePosition(portIndex(portType), - portType, - nodeGraphics.sceneTransform()); + auto const& nodeGeom = nodeGraphics.geometry(); - QTransform sceneTransform = this->sceneTransform(); + QPointF scenePos = nodeGeom.portScenePosition( + portIndex(portType), portType, nodeGraphics.sceneTransform()); - QPointF connectionPos = sceneTransform.inverted().map(scenePos); + QTransform sceneTransform = this->sceneTransform(); - geometry().setEndPoint(portType, - connectionPos); + QPointF connectionPos = sceneTransform.inverted().map(scenePos); - setGeometryChanged(); - update(); + geometry().setEndPoint(portType, connectionPos); + } else { + std::cerr << __FILE__ << ':' << __LINE__ << ' ' << __FUNCTION__; + } } } - } void -ConnectionGraphicsObject:: -lock(bool locked) +ConnectionGraphicsObject::lock(bool locked) { setFlag(QGraphicsItem::ItemIsMovable, !locked); setFlag(QGraphicsItem::ItemIsFocusable, !locked); setFlag(QGraphicsItem::ItemIsSelectable, !locked); } - void -ConnectionGraphicsObject:: -paint(QPainter* painter, - QStyleOptionGraphicsItem const* option, - QWidget*) +ConnectionGraphicsObject::paint(QPainter* painter, + QStyleOptionGraphicsItem const* option, + QWidget*) { painter->setClipRect(option->exposedRect); - ConnectionPainter::paint(painter, - *this); + ConnectionPainter::paint(painter, *this); } - void -ConnectionGraphicsObject:: -mousePressEvent(QGraphicsSceneMouseEvent* event) +ConnectionGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent* event) { QGraphicsItem::mousePressEvent(event); - //event->ignore(); + // event->ignore(); } - void -ConnectionGraphicsObject:: -mouseMoveEvent(QGraphicsSceneMouseEvent* event) +ConnectionGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { - prepareGeometryChange(); - auto view = static_cast(event->widget()); - auto node = locateNodeAt(event->scenePos(), - _scene, - view->transform()); + auto node = locateNodeAt(event->scenePos(), _scene, view->transform()); state().interactWithNode(node); - if (node) - { - node->reactToPossibleConnection(state().requiredPort(), - dataType(oppositePort(state().requiredPort())), - event->scenePos()); + if (node) { + node->reactToPossibleConnection( + state().requiredPort(), + dataType(oppositePort(state().requiredPort())), + event->scenePos()); } //------------------- @@ -227,34 +203,25 @@ mouseMoveEvent(QGraphicsSceneMouseEvent* event) QPointF offset = event->pos() - event->lastPos(); auto requiredPort = _state.requiredPort(); - if (requiredPort != PortType::None) - { + if (requiredPort != PortType::None) { _geometry.moveEndPoint(requiredPort, offset); } - //------------------- - - update(); - event->accept(); } - void -ConnectionGraphicsObject:: -mouseReleaseEvent(QGraphicsSceneMouseEvent* event) +ConnectionGraphicsObject::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { ungrabMouse(); event->accept(); - auto node = locateNodeAt(event->scenePos(), _scene, - _scene.views()[0]->transform()); + auto node = + locateNodeAt(event->scenePos(), _scene, _scene.views()[0]->transform()); - if (!node) - { + if (!node) { - if (state().requiresPort()) - { + if (state().requiresPort()) { Q_ASSERT(this == _scene._temporaryConn); // remove this from the scene _scene._temporaryConn = nullptr; @@ -264,66 +231,66 @@ mouseReleaseEvent(QGraphicsSceneMouseEvent* event) return; } - if (!state().requiresPort()) - { + if (!state().requiresPort()) { return; } NodeConnectionInteraction interaction(node->index(), *this); - if (node && interaction.tryConnect()) - { + if (node && interaction.tryConnect()) { node->resetReactionToConnection(); Q_ASSERT(this == _scene._temporaryConn); _scene._temporaryConn = nullptr; deleteLater(); - } - else if (state().requiresPort()) - { + } else if (state().requiresPort()) { Q_ASSERT(this == _scene._temporaryConn); _scene._temporaryConn = nullptr; deleteLater(); } } - void -ConnectionGraphicsObject:: -hoverEnterEvent(QGraphicsSceneHoverEvent* event) +ConnectionGraphicsObject::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { geometry().setHovered(true); update(); - flowScene().model()->connectionHovered(_leftNode, _leftPortIndex, _rightNode, _rightPortIndex, event->screenPos(), true); + flowScene().model()->connectionHovered(_leftNode, + _leftPortIndex, + _rightNode, + _rightPortIndex, + event->screenPos(), + true); event->accept(); } - void -ConnectionGraphicsObject:: -hoverLeaveEvent(QGraphicsSceneHoverEvent* event) +ConnectionGraphicsObject::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { geometry().setHovered(false); update(); - flowScene().model()->connectionHovered(_leftNode, _leftPortIndex, _rightNode, _rightPortIndex, event->screenPos(), false); + flowScene().model()->connectionHovered(_leftNode, + _leftPortIndex, + _rightNode, + _rightPortIndex, + event->screenPos(), + false); event->accept(); } - void -ConnectionGraphicsObject:: -addGraphicsEffect() +ConnectionGraphicsObject::addGraphicsEffect() { auto effect = new QGraphicsBlurEffect; effect->setBlurRadius(5); setGraphicsEffect(effect); - //auto effect = new QGraphicsDropShadowEffect; - //auto effect = new ConnectionBlurEffect(this); - //effect->setOffset(4, 4); - //effect->setColor(QColor(Qt::gray).darker(800)); + // auto effect = new QGraphicsDropShadowEffect; + // auto effect = new ConnectionBlurEffect(this); + // effect->setOffset(4, 4); + // effect->setColor(QColor(Qt::gray).darker(800)); } diff --git a/src/ConnectionPainter.cpp b/src/ConnectionPainter.cpp index 3949ba1ae..07291d7c8 100644 --- a/src/ConnectionPainter.cpp +++ b/src/ConnectionPainter.cpp @@ -3,25 +3,22 @@ #include #include "ConnectionGeometry.hpp" -#include "ConnectionState.hpp" #include "ConnectionGraphicsObject.hpp" +#include "ConnectionState.hpp" #include "NodeData.hpp" #include "StyleCollection.hpp" - -using QtNodes::ConnectionPainter; using QtNodes::ConnectionGeometry; using QtNodes::ConnectionGraphicsObject; +using QtNodes::ConnectionPainter; - -static -QPainterPath +static QPainterPath cubicPath(ConnectionGeometry const& geom) { QPointF const& source = geom.source(); - QPointF const& sink = geom.sink(); + QPointF const& sink = geom.sink(); auto c1c2 = geom.pointsC1C2(); @@ -33,10 +30,8 @@ cubicPath(ConnectionGeometry const& geom) return cubic; } - QPainterPath -ConnectionPainter:: -getPainterStroke(ConnectionGeometry const& geom) +ConnectionPainter::getPainterStroke(ConnectionGeometry const& geom) { auto cubic = cubicPath(geom); @@ -45,32 +40,28 @@ getPainterStroke(ConnectionGeometry const& geom) unsigned segments = 20; - for (auto i = 0ul; i < segments; ++i) - { + for (auto i = 0ul; i < segments; ++i) { double ratio = double(i + 1) / segments; result.lineTo(cubic.pointAtPercent(ratio)); } - QPainterPathStroker stroker; stroker.setWidth(10.0); + QPainterPathStroker stroker; + stroker.setWidth(10.0); return stroker.createStroke(result); } - #ifdef NODE_DEBUG_DRAWING -static -void -debugDrawing(QPainter * painter, - ConnectionGraphicsObject const & connection) +static void +debugDrawing(QPainter* painter, ConnectionGraphicsObject const& connection) { Q_UNUSED(painter); Q_UNUSED(connection); - ConnectionGeometry const& geom = - connection.geometry(); + ConnectionGeometry const& geom = connection.geometry(); { QPointF const& source = geom.source(); - QPointF const& sink = geom.sink(); + QPointF const& sink = geom.sink(); auto points = geom.pointsC1C2(); @@ -96,20 +87,15 @@ debugDrawing(QPainter * painter, } #endif -static -void -drawSketchLine(QPainter * painter, - ConnectionGraphicsObject const & connection) +static void +drawSketchLine(QPainter* painter, ConnectionGraphicsObject const& connection) { using QtNodes::ConnectionState; - ConnectionState const& state = - connection.state(); + ConnectionState const& state = connection.state(); - if (state.requiresPort()) - { - auto const & connectionStyle = - QtNodes::StyleCollection::connectionStyle(); + if (state.requiresPort()) { + auto const& connectionStyle = QtNodes::StyleCollection::connectionStyle(); QPen p; p.setWidth(connectionStyle.constructionLineWidth()); @@ -128,32 +114,26 @@ drawSketchLine(QPainter * painter, } } -static -void -drawHoveredOrSelected(QPainter * painter, - ConnectionGraphicsObject const & cgo) +static void +drawHoveredOrSelected(QPainter* painter, ConnectionGraphicsObject const& cgo) { using QtNodes::ConnectionGeometry; ConnectionGeometry const& geom = cgo.geometry(); - bool const hovered = geom.hovered(); - + bool const hovered = geom.hovered(); bool const selected = cgo.isSelected(); // drawn as a fat background - if (hovered || selected) - { + if (hovered || selected) { QPen p; - auto const &connectionStyle = - QtNodes::StyleCollection::connectionStyle(); + auto const& connectionStyle = QtNodes::StyleCollection::connectionStyle(); double const lineWidth = connectionStyle.lineWidth(); p.setWidth(2 * lineWidth); - p.setColor(selected ? - connectionStyle.selectedHaloColor() : - connectionStyle.hoveredColor()); + p.setColor(selected ? connectionStyle.selectedHaloColor() + : connectionStyle.hoveredColor()); painter->setPen(p); painter->setBrush(Qt::NoBrush); @@ -164,43 +144,37 @@ drawHoveredOrSelected(QPainter * painter, } } - -static -void -drawNormalLine(QPainter * painter, - ConnectionGraphicsObject const & connection) +static void +drawNormalLine(QPainter* painter, ConnectionGraphicsObject const& connection) { using QtNodes::ConnectionState; - ConnectionState const& state = - connection.state(); + ConnectionState const& state = connection.state(); if (state.requiresPort()) return; // colors - auto const &connectionStyle = - QtNodes::StyleCollection::connectionStyle(); + auto const& connectionStyle = QtNodes::StyleCollection::connectionStyle(); QColor normalColorOut = connectionStyle.normalColor(); - QColor normalColorIn = connectionStyle.normalColor(); - QColor selectedColor = connectionStyle.selectedColor(); + QColor normalColorIn = connectionStyle.normalColor(); + QColor selectedColor = connectionStyle.selectedColor(); bool gradientColor = false; - if (connectionStyle.useDataDefinedColors()) - { + if (connectionStyle.useDataDefinedColors()) { using QtNodes::PortType; auto dataTypeOut = connection.dataType(PortType::Out); - auto dataTypeIn = connection.dataType(PortType::In); + auto dataTypeIn = connection.dataType(PortType::In); gradientColor = (dataTypeOut.id != dataTypeIn.id); normalColorOut = connectionStyle.normalColor(dataTypeOut.id); - normalColorIn = connectionStyle.normalColor(dataTypeIn.id); - selectedColor = normalColorOut.darker(200); + normalColorIn = connectionStyle.normalColor(dataTypeIn.id); + selectedColor = normalColorOut.darker(200); } // geometry @@ -216,10 +190,8 @@ drawNormalLine(QPainter * painter, bool const selected = connection.isSelected(); - auto cubic = cubicPath(geom); - if (gradientColor) - { + if (gradientColor) { painter->setBrush(Qt::NoBrush); QColor cOut = normalColorOut; @@ -230,13 +202,11 @@ drawNormalLine(QPainter * painter, unsigned int const segments = 60; - for (unsigned int i = 0ul; i < segments; ++i) - { + for (unsigned int i = 0ul; i < segments; ++i) { double ratioPrev = double(i) / segments; - double ratio = double(i + 1) / segments; + double ratio = double(i + 1) / segments; - if (i == segments / 2) - { + if (i == segments / 2) { QColor cIn = normalColorIn; if (selected) cIn = cIn.darker(200); @@ -252,18 +222,14 @@ drawNormalLine(QPainter * painter, QIcon icon(":convert.png"); QPixmap pixmap = icon.pixmap(QSize(22, 22)); - painter->drawPixmap(cubic.pointAtPercent(0.50) - QPoint(pixmap.width()/2, - pixmap.height()/2), + painter->drawPixmap(cubic.pointAtPercent(0.50) - + QPoint(pixmap.width() / 2, pixmap.height() / 2), pixmap); - } - } - else - { + } else { p.setColor(normalColorOut); - if (selected) - { + if (selected) { p.setColor(selectedColor); } @@ -274,11 +240,9 @@ drawNormalLine(QPainter * painter, } } - void -ConnectionPainter:: -paint(QPainter* painter, - ConnectionGraphicsObject const &connection) +ConnectionPainter::paint(QPainter* painter, + ConnectionGraphicsObject const& connection) { drawHoveredOrSelected(painter, connection); @@ -293,11 +257,10 @@ paint(QPainter* painter, // draw end points ConnectionGeometry const& geom = connection.geometry(); - QPointF const & source = geom.source(); - QPointF const & sink = geom.sink(); + QPointF const& source = geom.source(); + QPointF const& sink = geom.sink(); - auto const & connectionStyle = - QtNodes::StyleCollection::connectionStyle(); + auto const& connectionStyle = QtNodes::StyleCollection::connectionStyle(); double const pointDiameter = connectionStyle.pointDiameter(); diff --git a/src/ConnectionPainter.hpp b/src/ConnectionPainter.hpp index b0887e3b9..93183d15a 100644 --- a/src/ConnectionPainter.hpp +++ b/src/ConnectionPainter.hpp @@ -2,8 +2,7 @@ #include -namespace QtNodes -{ +namespace QtNodes { class ConnectionGeometry; class ConnectionGraphicsObject; @@ -11,14 +10,9 @@ class ConnectionGraphicsObject; class ConnectionPainter { public: + static void paint(QPainter* painter, + ConnectionGraphicsObject const& connection); - static - void - paint(QPainter* painter, - ConnectionGraphicsObject const& connection); - - static - QPainterPath - getPainterStroke(ConnectionGeometry const& geom); + static QPainterPath getPainterStroke(ConnectionGeometry const& geom); }; } diff --git a/src/ConnectionState.cpp b/src/ConnectionState.cpp index ba526dbf7..2b018f9f0 100644 --- a/src/ConnectionState.cpp +++ b/src/ConnectionState.cpp @@ -10,39 +10,29 @@ using QtNodes::ConnectionState; using QtNodes::NodeGraphicsObject; -ConnectionState:: -~ConnectionState() +ConnectionState::~ConnectionState() { resetLastHoveredNode(); } - void -ConnectionState:: -interactWithNode(NodeGraphicsObject* node) +ConnectionState::interactWithNode(NodeGraphicsObject* node) { - if (node) - { + if (node) { _lastHoveredNode = node; - } - else - { + } else { resetLastHoveredNode(); } } - void -ConnectionState:: -setLastHoveredNode(NodeGraphicsObject* node) +ConnectionState::setLastHoveredNode(NodeGraphicsObject* node) { _lastHoveredNode = node; } - void -ConnectionState:: -resetLastHoveredNode() +ConnectionState::resetLastHoveredNode() { if (_lastHoveredNode) _lastHoveredNode->resetReactionToConnection(); diff --git a/src/ConnectionStyle.cpp b/src/ConnectionStyle.cpp index 385ff6a48..b0c1f61ed 100644 --- a/src/ConnectionStyle.cpp +++ b/src/ConnectionStyle.cpp @@ -3,10 +3,10 @@ #include #include +#include #include #include #include -#include #include @@ -15,31 +15,30 @@ using QtNodes::ConnectionStyle; inline void -initResources() { Q_INIT_RESOURCE(resources); } +initResources() +{ + Q_INIT_RESOURCE(resources); +} -ConnectionStyle:: -ConnectionStyle() +ConnectionStyle::ConnectionStyle() { // Explicit resources inialization for preventing the static initialization // order fiasco: https://isocpp.org/wiki/faq/ctors#static-init-order initResources(); - // This configuration is stored inside the compiled unit and is loaded statically + // This configuration is stored inside the compiled unit and is loaded + // statically loadJsonFile(":DefaultStyle.json"); } - -ConnectionStyle:: -ConnectionStyle(QString jsonText) +ConnectionStyle::ConnectionStyle(QString jsonText) { loadJsonFile(":DefaultStyle.json"); loadJsonText(jsonText); } - void -ConnectionStyle:: -setConnectionStyle(QString jsonText) +ConnectionStyle::setConnectionStyle(QString jsonText) { ConnectionStyle style(jsonText); @@ -47,59 +46,59 @@ setConnectionStyle(QString jsonText) } #ifdef STYLE_DEBUG - #define CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(v, variable) { \ - if (v.type() == QJsonValue::Undefined || \ - v.type() == QJsonValue::Null) \ - qWarning() << "Undefined value for parameter:" << #variable; \ -} +#define CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(v, variable) \ + { \ + if (v.type() == QJsonValue::Undefined || v.type() == QJsonValue::Null) \ + qWarning() << "Undefined value for parameter:" << #variable; \ + } #else - #define CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(v, variable) +#define CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(v, variable) #endif +#define CONNECTION_VALUE_EXISTS(v) \ + (v.type() != QJsonValue::Undefined && v.type() != QJsonValue::Null) + +#define CONNECTION_STYLE_READ_COLOR(values, variable) \ + { \ + auto valueRef = values[#variable]; \ + CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ + if (CONNECTION_VALUE_EXISTS(valueRef)) { \ + if (valueRef.isArray()) { \ + auto colorArray = valueRef.toArray(); \ + std::vector rgb; \ + rgb.reserve(3); \ + for (auto it = colorArray.begin(); it != colorArray.end(); ++it) { \ + rgb.push_back((*it).toInt()); \ + } \ + variable = QColor(rgb[0], rgb[1], rgb[2]); \ + } else { \ + variable = QColor(valueRef.toString()); \ + } \ + } \ + } -#define CONNECTION_VALUE_EXISTS(v) \ - (v.type() != QJsonValue::Undefined && \ - v.type() != QJsonValue::Null) - -#define CONNECTION_STYLE_READ_COLOR(values, variable) { \ - auto valueRef = values[#variable]; \ - CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ - if (CONNECTION_VALUE_EXISTS(valueRef)) { \ - if (valueRef.isArray()) { \ - auto colorArray = valueRef.toArray(); \ - std::vector rgb; rgb.reserve(3); \ - for (auto it = colorArray.begin(); it != colorArray.end(); ++it) { \ - rgb.push_back((*it).toInt()); \ - } \ - variable = QColor(rgb[0], rgb[1], rgb[2]); \ - } else { \ - variable = QColor(valueRef.toString()); \ - } \ - } \ -} - -#define CONNECTION_STYLE_READ_FLOAT(values, variable) { \ - auto valueRef = values[#variable]; \ - CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ - if (CONNECTION_VALUE_EXISTS(valueRef)) \ - variable = valueRef.toDouble(); \ -} +#define CONNECTION_STYLE_READ_FLOAT(values, variable) \ + { \ + auto valueRef = values[#variable]; \ + CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ + if (CONNECTION_VALUE_EXISTS(valueRef)) \ + variable = valueRef.toDouble(); \ + } -#define CONNECTION_STYLE_READ_BOOL(values, variable) { \ - auto valueRef = values[#variable]; \ - CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ - if (CONNECTION_VALUE_EXISTS(valueRef)) \ - variable = valueRef.toBool(); \ -} +#define CONNECTION_STYLE_READ_BOOL(values, variable) \ + { \ + auto valueRef = values[#variable]; \ + CONNECTION_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ + if (CONNECTION_VALUE_EXISTS(valueRef)) \ + variable = valueRef.toBool(); \ + } void -ConnectionStyle:: -loadJsonFile(QString styleFile) +ConnectionStyle::loadJsonFile(QString styleFile) { QFile file(styleFile); - if (!file.open(QIODevice::ReadOnly)) - { + if (!file.open(QIODevice::ReadOnly)) { qWarning() << "Couldn't open file " << styleFile; return; @@ -108,18 +107,14 @@ loadJsonFile(QString styleFile) loadJsonFromByteArray(file.readAll()); } - void -ConnectionStyle:: -loadJsonText(QString jsonText) +ConnectionStyle::loadJsonText(QString jsonText) { loadJsonFromByteArray(jsonText.toUtf8()); } - void -ConnectionStyle:: -loadJsonFromByteArray(QByteArray const &byteArray) +ConnectionStyle::loadJsonFromByteArray(QByteArray const& byteArray) { QJsonDocument json(QJsonDocument::fromJson(byteArray)); @@ -142,26 +137,20 @@ loadJsonFromByteArray(QByteArray const &byteArray) CONNECTION_STYLE_READ_BOOL(obj, UseDataDefinedColors); } - QColor -ConnectionStyle:: -constructionColor() const +ConnectionStyle::constructionColor() const { return ConstructionColor; } - QColor -ConnectionStyle:: -normalColor() const +ConnectionStyle::normalColor() const { return NormalColor; } - QColor -ConnectionStyle:: -normalColor(QString typeId) const +ConnectionStyle::normalColor(QString typeId) const { std::size_t hash = qHash(typeId); @@ -172,63 +161,47 @@ normalColor(QString typeId) const std::size_t sat = 120 + hash % 129; - return QColor::fromHsl(hue, - sat, - 160); + return QColor::fromHsl(hue, sat, 160); } - QColor -ConnectionStyle:: -selectedColor() const +ConnectionStyle::selectedColor() const { return SelectedColor; } - QColor -ConnectionStyle:: -selectedHaloColor() const +ConnectionStyle::selectedHaloColor() const { return SelectedHaloColor; } - QColor -ConnectionStyle:: -hoveredColor() const +ConnectionStyle::hoveredColor() const { return HoveredColor; } - float -ConnectionStyle:: -lineWidth() const +ConnectionStyle::lineWidth() const { return LineWidth; } - float -ConnectionStyle:: -constructionLineWidth() const +ConnectionStyle::constructionLineWidth() const { return ConstructionLineWidth; } - float -ConnectionStyle:: -pointDiameter() const +ConnectionStyle::pointDiameter() const { return PointDiameter; } - bool -ConnectionStyle:: -useDataDefinedColors() const +ConnectionStyle::useDataDefinedColors() const { return UseDataDefinedColors; } diff --git a/src/DataFlowModel.cpp b/src/DataFlowModel.cpp index 22532cfdb..fc25b5249 100644 --- a/src/DataFlowModel.cpp +++ b/src/DataFlowModel.cpp @@ -1,67 +1,57 @@ #include "DataFlowModel.hpp" -#include "Node.hpp" #include "Connection.hpp" +#include "Node.hpp" +using QtNodes::Connection; +using QtNodes::ConnectionID; +using QtNodes::ConnectionPolicy; using QtNodes::DataFlowModel; -using QtNodes::NodeIndex; -using QtNodes::NodeValidationState; using QtNodes::DataModelRegistry; -using QtNodes::TypeConverterId; using QtNodes::Node; -using QtNodes::PortType; -using QtNodes::ConnectionID; using QtNodes::NodeDataModel; -using QtNodes::NodePainterDelegate; using QtNodes::NodeDataType; +using QtNodes::NodeIndex; +using QtNodes::NodePainterDelegate; +using QtNodes::NodeValidationState; using QtNodes::PortIndex; -using QtNodes::ConnectionPolicy; -using QtNodes::Connection; +using QtNodes::PortType; using QtNodes::TypeConverter; +using QtNodes::TypeConverterId; -DataFlowModel:: -DataFlowModel(std::shared_ptr registry) +DataFlowModel::DataFlowModel(std::shared_ptr registry) : _registry(std::move(registry)) -{ -} +{} // FlowSceneModel read interface QStringList -DataFlowModel:: -modelRegistry() const +DataFlowModel::modelRegistry() const { QStringList list; - for (const auto& item : _registry->registeredModelCreators()) - { + for (const auto& item : _registry->registeredModelCreators()) { list << item.first; } return list; } QString -DataFlowModel:: -nodeTypeCategory(QString const& name) const +DataFlowModel::nodeTypeCategory(QString const& name) const { auto iter = _registry->registeredModelsCategoryAssociation().find(name); - if (iter != _registry->registeredModelsCategoryAssociation().end()) - { + if (iter != _registry->registeredModelsCategoryAssociation().end()) { return iter->second; } return {}; } bool -DataFlowModel:: -getTypeConvertable(TypeConverterId const& id) const +DataFlowModel::getTypeConvertable(TypeConverterId const& id) const { return static_cast(_registry->getTypeConverter(id.first, id.second)); } - - QList -DataFlowModel:: -nodeUUids() const +DataFlowModel::nodeUUids() const { QList ret; @@ -69,15 +59,13 @@ nodeUUids() const std::transform(_nodes.begin(), _nodes.end(), std::back_inserter(ret), - [](const auto& pair) { - return pair.first; - }); + [](const auto& pair) { return pair.first; }); return ret; } + NodeIndex -DataFlowModel:: -nodeIndex(const QUuid& ID) const +DataFlowModel::nodeIndex(const QUuid& ID) const { auto iter = _nodes.find(ID); if (iter == _nodes.end()) @@ -86,8 +74,7 @@ nodeIndex(const QUuid& ID) const return createIndex(ID, iter->second.get()); } QString -DataFlowModel:: -nodeTypeIdentifier(NodeIndex const& index) const +DataFlowModel::nodeTypeIdentifier(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -96,8 +83,7 @@ nodeTypeIdentifier(NodeIndex const& index) const return node->nodeDataModel()->name(); } QString -DataFlowModel:: -nodeCaption(NodeIndex const& index) const +DataFlowModel::nodeCaption(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -108,9 +94,9 @@ nodeCaption(NodeIndex const& index) const return node->nodeDataModel()->caption(); } + QPointF -DataFlowModel:: -nodeLocation(NodeIndex const& index) const +DataFlowModel::nodeLocation(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -119,8 +105,7 @@ nodeLocation(NodeIndex const& index) const return node->position(); } QWidget* -DataFlowModel:: -nodeWidget(NodeIndex const& index) const +DataFlowModel::nodeWidget(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -129,8 +114,7 @@ nodeWidget(NodeIndex const& index) const return node->nodeDataModel()->embeddedWidget(); } bool -DataFlowModel:: -nodeResizable(NodeIndex const& index) const +DataFlowModel::nodeResizable(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -139,8 +123,7 @@ nodeResizable(NodeIndex const& index) const return node->nodeDataModel()->resizable(); } NodeValidationState -DataFlowModel:: -nodeValidationState(NodeIndex const& index) const +DataFlowModel::nodeValidationState(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -149,10 +132,8 @@ nodeValidationState(NodeIndex const& index) const return node->nodeDataModel()->validationState(); } - QString -DataFlowModel:: -nodeValidationMessage(NodeIndex const& index) const +DataFlowModel::nodeValidationMessage(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -161,10 +142,8 @@ nodeValidationMessage(NodeIndex const& index) const return node->nodeDataModel()->validationMessage(); } - NodePainterDelegate* -DataFlowModel:: -nodePainterDelegate(NodeIndex const& index) const +DataFlowModel::nodePainterDelegate(NodeIndex const& index) const { Q_ASSERT(index.isValid()); @@ -173,34 +152,32 @@ nodePainterDelegate(NodeIndex const& index) const return node->nodeDataModel()->painterDelegate(); } - unsigned int -DataFlowModel:: -nodePortCount(NodeIndex const& index, PortType portType) const +DataFlowModel::nodePortCount(NodeIndex const& index, PortType portType) const { Q_ASSERT(index.isValid()); - auto* node = static_cast(index.internalPointer()); + auto* node = reinterpret_cast(index.internalPointer()); return node->nodeDataModel()->nPorts(portType); } - QString -DataFlowModel:: -nodePortCaption(NodeIndex const& index, PortIndex pIndex, PortType portType) const +DataFlowModel::nodePortCaption(NodeIndex const& index, + PortIndex pIndex, + PortType portType) const { Q_ASSERT(index.isValid()); - auto* node = static_cast(index.internalPointer()); + auto* node = reinterpret_cast(index.internalPointer()); return node->nodeDataModel()->portCaption(portType, pIndex); } - NodeDataType -DataFlowModel:: -nodePortDataType(NodeIndex const& index, PortIndex pIndex, PortType portType) const +DataFlowModel::nodePortDataType(NodeIndex const& index, + PortIndex pIndex, + PortType portType) const { Q_ASSERT(index.isValid()); @@ -209,50 +186,50 @@ nodePortDataType(NodeIndex const& index, PortIndex pIndex, PortType portType) co return node->nodeDataModel()->dataType(portType, pIndex); } ConnectionPolicy -DataFlowModel:: -nodePortConnectionPolicy(NodeIndex const& index, PortIndex pIndex, PortType portType) const +DataFlowModel::nodePortConnectionPolicy(NodeIndex const& index, + PortIndex pIndex, + PortType portType) const { Q_ASSERT(index.isValid()); auto* node = static_cast(index.internalPointer()); - if (portType == PortType::In) - { + if (portType == PortType::In) { return ConnectionPolicy::One; } return node->nodeDataModel()->portOutConnectionPolicy(pIndex); } -std::vector > -DataFlowModel:: -nodePortConnections(NodeIndex const& index, PortIndex id, PortType portType) const + +std::vector> +DataFlowModel::nodePortConnections(NodeIndex const& index, + PortIndex id, + PortType portType) const { + std::vector> ret; Q_ASSERT(index.isValid()); - auto* node = static_cast(index.internalPointer()); + auto* node = reinterpret_cast(index.internalPointer()); - std::vector > ret; // construct connections - for (const auto& conn : node->connections(portType, id)) - { - ret.emplace_back(nodeIndex(conn->getNode(oppositePort(portType))->id()), conn->getPortIndex(oppositePort(portType))); + for (const auto& conn : node->connections(portType, id)) { + ret.emplace_back(nodeIndex(conn->getNode(oppositePort(portType))->id()), + conn->getPortIndex(oppositePort(portType))); } return ret; } // FlowSceneModel write interface bool - -DataFlowModel:: -removeConnection(NodeIndex const& leftNodeIdx, - PortIndex leftPortID, - NodeIndex const& rightNodeIdx, - PortIndex rightPortID) +DataFlowModel::removeConnection(NodeIndex const& leftNodeIdx, + PortIndex leftPortID, + NodeIndex const& rightNodeIdx, + PortIndex rightPortID) { Q_ASSERT(leftNodeIdx.isValid()); Q_ASSERT(rightNodeIdx.isValid()); - auto* leftNode = static_cast(leftNodeIdx.internalPointer()); - auto* rightNode = static_cast(rightNodeIdx.internalPointer()); + auto* leftNode = reinterpret_cast(leftNodeIdx.internalPointer()); + auto* rightNode = reinterpret_cast(rightNodeIdx.internalPointer()); ConnectionID connID; connID.lNodeID = leftNodeIdx.id(); @@ -264,16 +241,17 @@ removeConnection(NodeIndex const& leftNodeIdx, // remove it from the nodes auto& leftConns = leftNode->connections(PortType::Out, leftPortID); - auto iter = std::find_if(leftConns.begin(), leftConns.end(), [&](Connection* conn){ - return conn->id() == connID; - }); + auto iter = + std::find_if(leftConns.begin(), leftConns.end(), [&](Connection* conn) { + return conn->id() == connID; + }); Q_ASSERT(iter != leftConns.end()); leftConns.erase(iter); auto& rightConns = rightNode->connections(PortType::In, rightPortID); - iter = std::find_if(rightConns.begin(), rightConns.end(), [&](Connection* conn){ - return conn->id() == connID; - }); + iter = std::find_if(rightConns.begin(), + rightConns.end(), + [&](Connection* conn) { return conn->id() == connID; }); Q_ASSERT(iter != rightConns.end()); rightConns.erase(iter); @@ -286,27 +264,23 @@ removeConnection(NodeIndex const& leftNodeIdx, return true; } - bool - -DataFlowModel:: -addConnection(NodeIndex const& leftNodeIdx, - PortIndex leftPortID, - NodeIndex const& rightNodeIdx, - PortIndex rightPortID) +DataFlowModel::addConnection(NodeIndex const& leftNodeIdx, + PortIndex leftPortID, + NodeIndex const& rightNodeIdx, + PortIndex rightPortID) { Q_ASSERT(leftNodeIdx.isValid()); Q_ASSERT(rightNodeIdx.isValid()); - auto* leftNode = static_cast(leftNodeIdx.internalPointer()); + auto* leftNode = static_cast(leftNodeIdx.internalPointer()); auto* rightNode = static_cast(rightNodeIdx.internalPointer()); // type conversions TypeConverter conv = {}; - auto ltype = nodePortDataType(leftNodeIdx, leftPortID, PortType::Out); - auto rtype = nodePortDataType(rightNodeIdx, rightPortID, PortType::In); - if (ltype.id != rtype.id) - { + auto ltype = nodePortDataType(leftNodeIdx, leftPortID, PortType::Out); + auto rtype = nodePortDataType(rightNodeIdx, rightPortID, PortType::In); + if (ltype.id != rtype.id) { conv = _registry->getTypeConverter(ltype, rtype); } @@ -315,10 +289,8 @@ addConnection(NodeIndex const& leftNodeIdx, return true; } - bool -DataFlowModel:: -removeNode(NodeIndex const& index) +DataFlowModel::removeNode(NodeIndex const& index) { Q_ASSERT(index.isValid()); @@ -327,12 +299,12 @@ removeNode(NodeIndex const& index) auto* node = static_cast(index.internalPointer()); - for (auto idx = 0u; idx < node->nodeDataModel()->nPorts(PortType::In); ++idx) - { + for (auto idx = 0u; idx < node->nodeDataModel()->nPorts(PortType::In); + ++idx) { Q_ASSERT(node->connections(PortType::In, idx).empty()); } - for (auto idx = 0u; idx < node->nodeDataModel()->nPorts(PortType::Out); ++idx) - { + for (auto idx = 0u; idx < node->nodeDataModel()->nPorts(PortType::Out); + ++idx) { Q_ASSERT(node->connections(PortType::Out, idx).empty()); } #endif @@ -346,33 +318,35 @@ removeNode(NodeIndex const& index) return true; } QUuid -DataFlowModel:: -addNode(const QString& typeID, QPointF const& location) +DataFlowModel::addNode(const QString& typeID, QPointF const& location) { auto nodeid = QUuid::createUuid(); addNode(typeID, location, nodeid); return nodeid; } + QUuid -DataFlowModel:: -addNode(QString const& typeID, QPointF const& location, QUuid const& nodeid) +DataFlowModel::addNode(QString const& typeID, + QPointF const& location, + QUuid const& nodeid) { // create the NodeDataModel auto model = _registry->create(typeID); - if (!model) - { + if (!model) { return {}; } return addNode(std::move(model), location, nodeid); } + QUuid -DataFlowModel:: -addNode(std::unique_ptr&& model, QPointF const& location, QUuid const& nodeid) +DataFlowModel::addNode(std::unique_ptr&& model, + QPointF const& location, + QUuid const& nodeid) { - - connect(model.get(), &NodeDataModel::dataUpdated, this, [this, nodeid](PortIndex){ - emit nodeValidationUpdated(nodeIndex(nodeid)); - }); + connect( + model.get(), &NodeDataModel::dataUpdated, this, [this, nodeid](PortIndex) { + emit nodeValidationUpdated(nodeIndex(nodeid)); + }); // create a node auto node = std::make_unique(std::move(model), nodeid); @@ -386,9 +360,10 @@ addNode(std::unique_ptr&& model, QPointF const& location, QUuid c _nodes[nodeid] = std::move(node); // connect to the geometry gets updated - connect(nodePtr, &Node::positionChanged, this, [this, nodeid](QPointF const&){ - emit nodeMoved(nodeIndex(nodeid)); - }); + connect( + nodePtr, &Node::positionChanged, this, [this, nodeid](QPointF const&) { + emit nodeMoved(nodeIndex(nodeid)); + }); // tell the view emit nodeAdded(nodeid); @@ -396,10 +371,12 @@ addNode(std::unique_ptr&& model, QPointF const& location, QUuid c return nodeid; } - ConnectionID -DataFlowModel:: -addConnection(Node* leftNode, PortIndex leftPortID, Node* rightNode, PortIndex rightPortID, TypeConverter conv) +DataFlowModel::addConnection(Node* leftNode, + PortIndex leftPortID, + Node* rightNode, + PortIndex rightPortID, + TypeConverter conv) { ConnectionID connID; @@ -409,7 +386,8 @@ addConnection(Node* leftNode, PortIndex leftPortID, Node* rightNode, PortIndex r connID.rPortID = rightPortID; // create the connection - auto conn = std::make_shared(*rightNode, rightPortID, *leftNode, leftPortID, conv); + auto conn = std::make_shared( + *rightNode, rightPortID, *leftNode, leftPortID, conv); _connections[connID] = conn; // add it to the nodes @@ -417,17 +395,20 @@ addConnection(Node* leftNode, PortIndex leftPortID, Node* rightNode, PortIndex r rightNode->connections(PortType::In, rightPortID).push_back(conn.get()); // process data - conn->getNode(PortType::Out)->onDataUpdated(conn->getPortIndex(PortType::Out)); + conn->getNode(PortType::Out) + ->onDataUpdated(conn->getPortIndex(PortType::Out)); // tell the view the connection was added - emit connectionAdded(nodeIndex(leftNode->id()), leftPortID, nodeIndex(rightNode->id()), rightPortID); + emit connectionAdded(nodeIndex(leftNode->id()), + leftPortID, + nodeIndex(rightNode->id()), + rightPortID); return connID; } bool -DataFlowModel:: -moveNode(NodeIndex const& index, QPointF newLocation) +DataFlowModel::moveNode(NodeIndex const& index, QPointF newLocation) { Q_ASSERT(index.isValid()); diff --git a/src/DataFlowScene.cpp b/src/DataFlowScene.cpp index 4ba710dd3..36034cf29 100644 --- a/src/DataFlowScene.cpp +++ b/src/DataFlowScene.cpp @@ -1,56 +1,56 @@ #include "DataFlowScene.hpp" #include "Connection.hpp" -#include "Node.hpp" #include "DataFlowModel.hpp" +#include "Node.hpp" #include #include #include +using QtNodes::Connection; +using QtNodes::ConnectionID; +using QtNodes::DataFlowModel; using QtNodes::DataFlowScene; using QtNodes::DataModelRegistry; -using QtNodes::Connection; using QtNodes::Node; +using QtNodes::NodeDataModel; using QtNodes::PortIndex; using QtNodes::TypeConverter; -using QtNodes::ConnectionID; -using QtNodes::DataFlowModel; -using QtNodes::NodeDataModel; -DataFlowScene:: -DataFlowScene(std::shared_ptr registry, QObject* parent) +DataFlowScene::DataFlowScene(std::shared_ptr registry, + QObject* parent) : FlowScene(new DataFlowModel(std::move(registry)), parent) { _dataFlowModel = static_cast(model()); } +DataFlowScene::~DataFlowScene() +{ + delete _dataFlowModel; +} + std::shared_ptr -DataFlowScene:: -createConnection(Node& nodeIn, - PortIndex portIndexIn, - Node& nodeOut, - PortIndex portIndexOut, - TypeConverter const& converter) +DataFlowScene::createConnection(Node& nodeIn, + PortIndex portIndexIn, + Node& nodeOut, + PortIndex portIndexOut, + TypeConverter const& converter) { - auto connid = - _dataFlowModel->addConnection(&nodeOut, portIndexOut, - &nodeIn, portIndexIn, - converter); + auto connid = _dataFlowModel->addConnection( + &nodeOut, portIndexOut, &nodeIn, portIndexIn, converter); return _dataFlowModel->connections()[connid]; } std::shared_ptr -DataFlowScene:: -restoreConnection(QJsonObject const &connectionJson) +DataFlowScene::restoreConnection(QJsonObject const& connectionJson) { - QUuid nodeInId = QUuid(connectionJson["in_id"].toString()); + QUuid nodeInId = QUuid(connectionJson["in_id"].toString()); QUuid nodeOutId = QUuid(connectionJson["out_id"].toString()); - PortIndex portIndexIn = connectionJson["in_index"].toInt(); + PortIndex portIndexIn = connectionJson["in_index"].toInt(); PortIndex portIndexOut = connectionJson["out_index"].toInt(); - ConnectionID connId; connId.lNodeID = nodeOutId; connId.rNodeID = nodeInId; @@ -68,31 +68,28 @@ restoreConnection(QJsonObject const &connectionJson) } void -DataFlowScene:: -deleteConnection(Connection& connection) +DataFlowScene::deleteConnection(Connection& connection) { auto deleted = _dataFlowModel->removeConnection( _dataFlowModel->nodeIndex(connection.getNode(PortType::Out)->id()), connection.getPortIndex(PortType::Out), _dataFlowModel->nodeIndex(connection.getNode(PortType::In)->id()), connection.getPortIndex(PortType::Out)); - + Q_UNUSED(deleted); Q_ASSERT(deleted); } Node& -DataFlowScene:: -createNode(std::unique_ptr && dataModel) +DataFlowScene::createNode(std::unique_ptr&& dataModel) { - auto uid = _dataFlowModel->addNode(std::move(dataModel), {0.0, 0.0}); + auto uid = _dataFlowModel->addNode(std::move(dataModel), { 0.0, 0.0 }); return *_dataFlowModel->nodes()[uid]; } Node& -DataFlowScene:: -restoreNode(QJsonObject const& nodeJson) +DataFlowScene::restoreNode(QJsonObject const& nodeJson) { QString modelName = nodeJson["model"].toObject()["name"].toString(); @@ -108,113 +105,96 @@ restoreNode(QJsonObject const& nodeJson) } void -DataFlowScene:: -removeNode(Node& node) +DataFlowScene::removeNode(Node& node) { model()->removeNodeWithConnections(model()->nodeIndex(node.id())); } DataModelRegistry& -DataFlowScene:: -registry() const +DataFlowScene::registry() const { return _dataFlowModel->registry(); } void -DataFlowScene:: -setRegistry(std::shared_ptr registry) +DataFlowScene::setRegistry(std::shared_ptr registry) { _dataFlowModel->setRegistry(registry); } void -DataFlowScene:: -iterateOverNodes(std::function const& visitor) +DataFlowScene::iterateOverNodes(std::function const& visitor) { - for (auto const& node : _dataFlowModel->nodes()) - { + for (auto const& node : _dataFlowModel->nodes()) { visitor(node.second.get()); } } void -DataFlowScene:: -iterateOverNodeData(std::function const& visitor) +DataFlowScene::iterateOverNodeData( + std::function const& visitor) { - for (auto const& node : _dataFlowModel->nodes()) - { + for (auto const& node : _dataFlowModel->nodes()) { visitor(node.second->nodeDataModel()); } } void -DataFlowScene:: -iterateOverNodeDataDependentOrder(std::function const& visitor) +DataFlowScene::iterateOverNodeDataDependentOrder( + std::function const& visitor) { std::set visitedNodesSet; - //A leaf node is a node with no input ports, or all possible input ports empty - auto isNodeLeaf = - [](Node const &node, NodeDataModel const &model) - { - for (unsigned int i = 0; i < model.nPorts(PortType::In); ++i) - { - auto connections = node.connections(PortType::In, i); - if (!connections.empty()) - { - return false; - } + // A leaf node is a node with no input ports, or all possible input ports + // empty + auto isNodeLeaf = [](Node const& node, NodeDataModel const& model) { + for (unsigned int i = 0; i < model.nPorts(PortType::In); ++i) { + auto connections = node.connections(PortType::In, i); + if (!connections.empty()) { + return false; } + } - return true; - }; + return true; + }; - //Iterate over "leaf" nodes - for (auto const &_node : _dataFlowModel->nodes()) - { - auto const &node = _node.second; - auto model = node->nodeDataModel(); + // Iterate over "leaf" nodes + for (auto const& _node : _dataFlowModel->nodes()) { + auto const& node = _node.second; + auto model = node->nodeDataModel(); - if (isNodeLeaf(*node, *model)) - { + if (isNodeLeaf(*node, *model)) { visitor(model); visitedNodesSet.insert(node->id()); } } - auto areNodeInputsVisitedBefore = - [&](Node const &node, NodeDataModel const &model) - { - for (size_t i = 0; i < model.nPorts(PortType::In); ++i) - { - auto connections = node.connections(PortType::In, i); - - for (auto& conn : connections) - { - if (visitedNodesSet.find(conn->getNode(PortType::Out)->id()) == visitedNodesSet.end()) - { - return false; - } + auto areNodeInputsVisitedBefore = [&](Node const& node, + NodeDataModel const& model) { + for (size_t i = 0; i < model.nPorts(PortType::In); ++i) { + auto connections = node.connections(PortType::In, i); + + for (auto& conn : connections) { + if (visitedNodesSet.find(conn->getNode(PortType::Out)->id()) == + visitedNodesSet.end()) { + return false; } } + } - return true; - }; + return true; + }; - //Iterate over dependent nodes - while (_dataFlowModel->nodes().size() != visitedNodesSet.size()) - { - for (auto const &_node : _dataFlowModel->nodes()) - { - auto const &node = _node.second; + // Iterate over dependent nodes + while (_dataFlowModel->nodes().size() != visitedNodesSet.size()) { + for (auto const& _node : _dataFlowModel->nodes()) { + auto const& node = _node.second; if (visitedNodesSet.find(node->id()) != visitedNodesSet.end()) continue; auto model = node->nodeDataModel(); - if (areNodeInputsVisitedBefore(*node, *model)) - { + if (areNodeInputsVisitedBefore(*node, *model)) { visitor(model); visitedNodesSet.insert(node->id()); } @@ -223,62 +203,57 @@ iterateOverNodeDataDependentOrder(std::function const& vis } QPointF -DataFlowScene:: -getNodePosition(Node const& node) const +DataFlowScene::getNodePosition(Node const& node) const { return _dataFlowModel->nodeLocation(_dataFlowModel->nodeIndex(node.id())); } void -DataFlowScene:: -setNodePosition(Node& node, QPointF const& pos) const +DataFlowScene::setNodePosition(Node& node, QPointF const& pos) const { _dataFlowModel->moveNode(_dataFlowModel->nodeIndex(node.id()), pos); } - -std::unordered_map > const & -DataFlowScene:: -nodes() const +std::unordered_map> const& +DataFlowScene::nodes() const { return _dataFlowModel->nodes(); } -std::unordered_map > const & -DataFlowScene:: -connections() const +std::unordered_map> const& +DataFlowScene::connections() const { return _dataFlowModel->connections(); } std::vector -DataFlowScene:: -selectedNodes() const +DataFlowScene::selectedNodes() const { auto ids = FlowScene::selectedNodes(); std::vector ret; ret.reserve(ids.size()); - std::transform(ids.begin(), ids.end(), std::back_inserter(ret), - [this](NodeIndex const& id) - { return _dataFlowModel->nodes().find(id.id())->second.get(); }); + std::transform(ids.begin(), + ids.end(), + std::back_inserter(ret), + [this](NodeIndex const& id) { + return _dataFlowModel->nodes().find(id.id())->second.get(); + }); return ret; } void -DataFlowScene:: -clearScene() +DataFlowScene::clearScene() { // delete all the nodes - while(!_dataFlowModel->nodes().empty()) { + while (!_dataFlowModel->nodes().empty()) { removeNode(*_dataFlowModel->nodes().begin()->second); } } void -DataFlowScene:: -save() const +DataFlowScene::save() const { QString fileName = QFileDialog::getSaveFileName(nullptr, @@ -286,23 +261,19 @@ save() const QDir::homePath(), tr("Flow Scene Files (*.flow)")); - if (!fileName.isEmpty()) - { + if (!fileName.isEmpty()) { if (!fileName.endsWith("flow", Qt::CaseInsensitive)) fileName += ".flow"; QFile file(fileName); - if (file.open(QIODevice::WriteOnly)) - { + if (file.open(QIODevice::WriteOnly)) { file.write(saveToMemory()); } } } - void -DataFlowScene:: -load() +DataFlowScene::load() { clearScene(); @@ -327,18 +298,15 @@ load() loadFromMemory(wholeFile); } - QByteArray -DataFlowScene:: -saveToMemory() const +DataFlowScene::saveToMemory() const { QJsonObject sceneJson; QJsonArray nodesJsonArray; - for (auto const & pair : _dataFlowModel->nodes()) - { - auto const &node = pair.second; + for (auto const& pair : _dataFlowModel->nodes()) { + auto const& node = pair.second; nodesJsonArray.append(node->save()); } @@ -346,9 +314,8 @@ saveToMemory() const sceneJson["nodes"] = nodesJsonArray; QJsonArray connectionJsonArray; - for (auto const & pair : _dataFlowModel->connections()) - { - auto const &connection = pair.second; + for (auto const& pair : _dataFlowModel->connections()) { + auto const& connection = pair.second; QJsonObject connectionJson = connection->save(); @@ -363,24 +330,20 @@ saveToMemory() const return document.toJson(); } - void -DataFlowScene:: -loadFromMemory(const QByteArray& data) +DataFlowScene::loadFromMemory(const QByteArray& data) { QJsonObject const jsonDocument = QJsonDocument::fromJson(data).object(); QJsonArray nodesJsonArray = jsonDocument["nodes"].toArray(); - for (int i = 0; i < nodesJsonArray.size(); ++i) - { + for (int i = 0; i < nodesJsonArray.size(); ++i) { restoreNode(nodesJsonArray[i].toObject()); } QJsonArray connectionJsonArray = jsonDocument["connections"].toArray(); - for (int i = 0; i < connectionJsonArray.size(); ++i) - { + for (int i = 0; i < connectionJsonArray.size(); ++i) { restoreConnection(connectionJsonArray[i].toObject()); } } diff --git a/src/DataModelRegistry.cpp b/src/DataModelRegistry.cpp index 4a8b202d8..056aa706e 100644 --- a/src/DataModelRegistry.cpp +++ b/src/DataModelRegistry.cpp @@ -9,55 +9,44 @@ using QtNodes::NodeDataType; using QtNodes::TypeConverter; std::unique_ptr -DataModelRegistry:: -create(QString const &modelName) +DataModelRegistry::create(QString const& modelName) { auto it = _registeredItemCreators.find(modelName); - if (it != _registeredItemCreators.end()) - { + if (it != _registeredItemCreators.end()) { return it->second(); } return nullptr; } - -DataModelRegistry::RegisteredModelCreatorsMap const & -DataModelRegistry:: -registeredModelCreators() const +DataModelRegistry::RegisteredModelCreatorsMap const& +DataModelRegistry::registeredModelCreators() const { return _registeredItemCreators; } - -DataModelRegistry::RegisteredModelsCategoryMap const & -DataModelRegistry:: -registeredModelsCategoryAssociation() const +DataModelRegistry::RegisteredModelsCategoryMap const& +DataModelRegistry::registeredModelsCategoryAssociation() const { return _registeredModelsCategory; } - -DataModelRegistry::CategoriesSet const & -DataModelRegistry:: -categories() const +DataModelRegistry::CategoriesSet const& +DataModelRegistry::categories() const { return _categories; } - TypeConverter -DataModelRegistry:: -getTypeConverter(NodeDataType const & d1, - NodeDataType const & d2) const +DataModelRegistry::getTypeConverter(NodeDataType const& d1, + NodeDataType const& d2) const { TypeConverterId converterId = std::make_pair(d1, d2); auto it = _registeredTypeConverters.find(converterId); - if (it != _registeredTypeConverters.end()) - { + if (it != _registeredTypeConverters.end()) { return it->second; } diff --git a/src/FlowScene.cpp b/src/FlowScene.cpp index fea3fc407..85b767cbb 100644 --- a/src/FlowScene.cpp +++ b/src/FlowScene.cpp @@ -1,42 +1,46 @@ #include "FlowScene.hpp" -#include "NodeIndex.hpp" #include "ConnectionGraphicsObject.hpp" -#include "NodeGraphicsObject.hpp" #include "FlowSceneModel.hpp" +#include "NodeGraphicsObject.hpp" +#include "NodeIndex.hpp" #include using QtNodes::FlowScene; +using QtNodes::FlowSceneModel; using QtNodes::NodeGraphicsObject; using QtNodes::NodeIndex; -using QtNodes::FlowSceneModel; using QtNodes::PortIndex; -FlowScene:: -FlowScene(FlowSceneModel* model, - QObject * parent) +FlowScene::FlowScene(FlowSceneModel* model, QObject* parent) : QGraphicsScene(parent) - ,_model(model) + , _model(model) { Q_ASSERT(model != nullptr); connect(model, &FlowSceneModel::nodeRemoved, this, &FlowScene::nodeRemoved); connect(model, &FlowSceneModel::nodeAdded, this, &FlowScene::nodeAdded); - connect(model, &FlowSceneModel::nodePortUpdated, this, &FlowScene::nodePortUpdated); - connect(model, &FlowSceneModel::nodeValidationUpdated, this, &FlowScene::nodeValidationUpdated); - connect(model, &FlowSceneModel::connectionRemoved, this, &FlowScene::connectionRemoved); - connect(model, &FlowSceneModel::connectionAdded, this, &FlowScene::connectionAdded); + connect( + model, &FlowSceneModel::nodePortUpdated, this, &FlowScene::nodePortUpdated); + connect(model, + &FlowSceneModel::nodeValidationUpdated, + this, + &FlowScene::nodeValidationUpdated); + connect(model, + &FlowSceneModel::connectionRemoved, + this, + &FlowScene::connectionRemoved); + connect( + model, &FlowSceneModel::connectionAdded, this, &FlowScene::connectionAdded); connect(model, &FlowSceneModel::nodeMoved, this, &FlowScene::nodeMoved); // emit node added on all the existing nodes - for (const auto& n : model->nodeUUids()) - { + for (const auto& n : model->nodeUUids()) { nodeAdded(n); } // add connections - for (const auto& n : model->nodeUUids()) - { + for (const auto& n : model->nodeUUids()) { auto id = model->nodeIndex(n); Q_ASSERT(id.isValid()); @@ -44,24 +48,24 @@ FlowScene(FlowSceneModel* model, auto numPorts = model->nodePortCount(id, PortType::Out); // go through them and add the connections - for (auto portID = 0u; portID < numPorts; ++portID) - { + for (auto portID = 0u; portID < numPorts; ++portID) { // go through connections auto connections = model->nodePortConnections(id, portID, PortType::Out); - // validate the sanity of the model--make sure if it is marked as one connection per port then there is no more than one connection - Q_ASSERT(model->nodePortConnectionPolicy(id, portID, PortType::Out) == ConnectionPolicy::Many || connections.size() <= 1); + // validate the sanity of the model--make sure if it is marked as one + // connection per port then there is no more than one connection + Q_ASSERT(model->nodePortConnectionPolicy(id, portID, PortType::Out) == + ConnectionPolicy::Many || + connections.size() <= 1); - for (const auto& conn : connections) - { + for (const auto& conn : connections) { connectionAdded(id, portID, conn.first, conn.second); } } } // for some reason these end up in the wrong spot, fix that - for (const auto& n : model->nodeUUids()) - { + for (const auto& n : model->nodeUUids()) { auto ngo = nodeGraphicsObject(model->nodeIndex(n)); ngo->geometry().recalculateSize(); ngo->moveConnections(); @@ -71,57 +75,48 @@ FlowScene(FlowSceneModel* model, FlowScene::~FlowScene() = default; NodeGraphicsObject* -FlowScene:: -nodeGraphicsObject(const NodeIndex& index) +FlowScene::nodeGraphicsObject(const NodeIndex& index) { auto iter = _nodeGraphicsObjects.find(index.id()); - if (iter == _nodeGraphicsObjects.end()) - { + if (iter == _nodeGraphicsObjects.end()) { return nullptr; } return iter->second; } std::vector -FlowScene:: -selectedNodes() const +FlowScene::selectedNodes() const { QList graphicsItems = selectedItems(); std::vector ret; ret.reserve(graphicsItems.size()); - for (QGraphicsItem* item : graphicsItems) - { + for (QGraphicsItem* item : graphicsItems) { auto ngo = qgraphicsitem_cast(item); - if (ngo != nullptr) - { + if (ngo != nullptr) { ret.push_back(ngo->index()); } } return ret; - } // model slots void -FlowScene:: -nodeRemoved(const QUuid& id) +FlowScene::nodeRemoved(const QUuid& id) { Q_ASSERT(!id.isNull()); auto ngo = _nodeGraphicsObjects[id]; #ifndef QT_NO_DEBUG // make sure there are no connections left - for (const auto& connPtrSet : ngo->nodeState().getEntries(PortType::In)) - { + for (const auto& connPtrSet : ngo->nodeState().getEntries(PortType::In)) { Q_ASSERT(connPtrSet.size() == 0); } - for (const auto& connPtrSet : ngo->nodeState().getEntries(PortType::Out)) - { + for (const auto& connPtrSet : ngo->nodeState().getEntries(PortType::Out)) { Q_ASSERT(connPtrSet.size() == 0); } #endif @@ -134,8 +129,7 @@ nodeRemoved(const QUuid& id) } void -FlowScene:: -nodeAdded(const QUuid& newID) +FlowScene::nodeAdded(const QUuid& newID) { Q_ASSERT(!newID.isNull()); @@ -152,9 +146,9 @@ nodeAdded(const QUuid& newID) nodeMoved(index); } + void -FlowScene:: -nodePortUpdated(NodeIndex const& id) +FlowScene::nodePortUpdated(NodeIndex const& id) { Q_ASSERT(!id.id().isNull()); @@ -162,17 +156,17 @@ nodePortUpdated(NodeIndex const& id) Q_ASSERT(thisNodeNGO != Q_NULLPTR); // remove all the connections - for (auto ty : {PortType::In, PortType::Out}) - { - for (auto i = 0ull; i < thisNodeNGO->nodeState().getEntries(ty).size(); ++i) - { + for (auto ty : { PortType::In, PortType::Out }) { + for (auto i = 0ull; i < thisNodeNGO->nodeState().getEntries(ty).size(); + ++i) { while (!thisNodeNGO->nodeState().getEntries(ty)[i].empty()) { auto conn = thisNodeNGO->nodeState().getEntries(ty)[i][0]; // remove it from the nodes auto& otherNgo = *nodeGraphicsObject(conn->node(oppositePort(ty))); - otherNgo.nodeState().eraseConnection(oppositePort(ty), conn->portIndex(oppositePort(ty)), *conn); + otherNgo.nodeState().eraseConnection( + oppositePort(ty), conn->portIndex(oppositePort(ty)), *conn); auto& thisNgo = *nodeGraphicsObject(conn->node(ty)); thisNgo.nodeState().eraseConnection(ty, conn->portIndex(ty), *conn); @@ -203,73 +197,76 @@ nodePortUpdated(NodeIndex const& id) nodeMoved(id); // add the connections back - for (auto ty : { PortType::In, PortType::Out }) - { - + for (auto ty : { PortType::In, PortType::Out }) { // query the number of ports auto numPorts = model()->nodePortCount(id, ty); - for (auto portID = 0u; portID < numPorts; ++portID) - { + for (auto portID = 0u; portID < numPorts; ++portID) { // go through connections auto connections = model()->nodePortConnections(id, portID, ty); #ifndef QT_NO_DEBUG - for (auto conn : connections) - { - auto remoteConns = model()->nodePortConnections(conn.first, conn.second, oppositePort(ty)); + for (auto conn : connections) { + auto remoteConns = model()->nodePortConnections( + conn.first, conn.second, oppositePort(ty)); // if you fail here, your connections aren't self-consistent - Q_ASSERT(std::any_of(remoteConns.begin(), remoteConns.end(), [&](std::pair this_conn){ - return this_conn.first == id && (size_t)this_conn.second == portID; + Q_ASSERT(std::any_of(remoteConns.begin(), + remoteConns.end(), + [&](std::pair this_conn) { + return this_conn.first == id && + (size_t)this_conn.second == portID; })); } #endif - // validate the sanity of the model--make sure if it is marked as one connection per port then there is no more than one connection - Q_ASSERT(model()->nodePortConnectionPolicy(id, portID, ty) == ConnectionPolicy::Many || connections.size() <= 1); + // validate the sanity of the model--make sure if it is marked as one + // connection per port then there is no more than one connection + Q_ASSERT(model()->nodePortConnectionPolicy(id, portID, ty) == + ConnectionPolicy::Many || + connections.size() <= 1); - for (const auto& conn : connections) - { + for (const auto& conn : connections) { - if (ty == PortType::Out) - { + if (ty == PortType::Out) { connectionAdded(id, portID, conn.first, conn.second); - } - else { + } else { connectionAdded(conn.first, conn.second, id, portID); } } } } } + void -FlowScene:: -nodeValidationUpdated(NodeIndex const& id) +FlowScene::nodeValidationUpdated(NodeIndex const& id) { // repaint auto ngo = nodeGraphicsObject(id); - ngo->setGeometryChanged(); ngo->geometry().recalculateSize(); ngo->moveConnections(); ngo->update(); - } + void -FlowScene:: -connectionRemoved(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const& rightNode, PortIndex rightPortID) +FlowScene::connectionRemoved(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID) { // check the model's sanity #ifndef QT_NO_DEBUG - for (const auto& conn : model()->nodePortConnections(leftNode, leftPortID, PortType::Out)) - { - // if you fail here, then you're emitting connectionRemoved on a connection that is in the model - Q_ASSERT (conn.first != rightNode || conn.second != rightPortID); + for (const auto& conn : + model()->nodePortConnections(leftNode, leftPortID, PortType::Out)) { + // if you fail here, then you're emitting connectionRemoved on a connection + // that is in the model + Q_ASSERT(conn.first != rightNode || conn.second != rightPortID); } - for (const auto& conn : model()->nodePortConnections(rightNode, rightPortID, PortType::In)) - { - // if you fail here, then you're emitting connectionRemoved on a connection that is in the model - Q_ASSERT (conn.first != leftNode || conn.second != leftPortID); + for (const auto& conn : + model()->nodePortConnections(rightNode, rightPortID, PortType::In)) { + // if you fail here, then you're emitting connectionRemoved on a connection + // that is in the model + Q_ASSERT(conn.first != leftNode || conn.second != leftPortID); } #endif @@ -282,7 +279,6 @@ connectionRemoved(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex con // cgo auto& cgo = *_connGraphicsObjects[id]; - // remove it from the nodes auto& lngo = *nodeGraphicsObject(leftNode); lngo.nodeState().eraseConnection(PortType::Out, leftPortID, cgo); @@ -293,45 +289,56 @@ connectionRemoved(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex con // remove the ConnectionGraphicsObject delete &cgo; _connGraphicsObjects.erase(id); + + // update validation + nodeValidationUpdated(leftNode); + nodeValidationUpdated(rightNode); } + void -FlowScene:: -connectionAdded(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const& rightNode, PortIndex rightPortID) +FlowScene::connectionAdded(NodeIndex const& leftNode, + PortIndex leftPortID, + NodeIndex const& rightNode, + PortIndex rightPortID) { // check the model's sanity #ifndef QT_NO_DEBUG Q_ASSERT(leftPortID >= 0); Q_ASSERT(rightPortID >= 0); - // if you fail here, then you're emitting connectionAdded on a portID that doesn't exist - Q_ASSERT((size_t)leftPortID < model()->nodePortCount(leftNode, PortType::Out)); - Q_ASSERT((size_t)rightPortID < model()->nodePortCount(rightNode, PortType::In)); + // if you fail here, then you're emitting connectionAdded on a portID that + // doesn't exist + Q_ASSERT((size_t)leftPortID < + model()->nodePortCount(leftNode, PortType::Out)); + Q_ASSERT((size_t)rightPortID < + model()->nodePortCount(rightNode, PortType::In)); bool checkedOut = false; - for (const auto& conn : model()->nodePortConnections(leftNode, leftPortID, PortType::Out)) - { - if (conn.first == rightNode && conn.second == rightPortID) - { + for (const auto& conn : + model()->nodePortConnections(leftNode, leftPortID, PortType::Out)) { + if (conn.first == rightNode && conn.second == rightPortID) { checkedOut = true; break; } } - // if you fail here, then you're emitting connectionAdded on a connection that isn't in the model + // if you fail here, then you're emitting connectionAdded on a connection that + // isn't in the model Q_ASSERT(checkedOut); checkedOut = false; - for (const auto& conn : model()->nodePortConnections(rightNode, rightPortID, PortType::In)) - { - if (conn.first == leftNode && conn.second == leftPortID) - { + for (const auto& conn : + model()->nodePortConnections(rightNode, rightPortID, PortType::In)) { + if (conn.first == leftNode && conn.second == leftPortID) { checkedOut = true; break; } } - // if you fail here, then you're emitting connectionAdded on a connection that isn't in the model + // if you fail here, then you're emitting connectionAdded on a connection that + // isn't in the model Q_ASSERT(checkedOut); #endif // create the cgo - auto cgo = new ConnectionGraphicsObject(leftNode, leftPortID, rightNode, rightPortID, *this); + auto cgo = new ConnectionGraphicsObject( + leftNode, leftPortID, rightNode, rightPortID, *this); // add it to the nodes auto lngo = nodeGraphicsObject(leftNode); @@ -342,30 +349,25 @@ connectionAdded(NodeIndex const& leftNode, PortIndex leftPortID, NodeIndex const // add the cgo to the map _connGraphicsObjects[cgo->id()] = cgo; - } void -FlowScene:: -nodeMoved(NodeIndex const& index) +FlowScene::nodeMoved(NodeIndex const& index) { _nodeGraphicsObjects[index.id()]->setPos(model()->nodeLocation(index)); } //------------------------------------------------------------------------------ -namespace QtNodes -{ +namespace QtNodes { NodeGraphicsObject* -locateNodeAt(QPointF scenePoint, FlowScene &scene, - QTransform const & viewTransform) +locateNodeAt(QPointF scenePoint, + FlowScene& scene, + QTransform const& viewTransform) { // items under cursor - QList items = - scene.items(scenePoint, - Qt::IntersectsItemShape, - Qt::DescendingOrder, - viewTransform); + QList items = scene.items( + scenePoint, Qt::IntersectsItemShape, Qt::DescendingOrder, viewTransform); //// items convertable to NodeGraphicsObject std::vector filteredItems; @@ -373,15 +375,13 @@ locateNodeAt(QPointF scenePoint, FlowScene &scene, std::copy_if(items.begin(), items.end(), std::back_inserter(filteredItems), - [] (QGraphicsItem * item) - { + [](QGraphicsItem* item) { return (dynamic_cast(item) != nullptr); }); - if (!filteredItems.empty()) - { + if (!filteredItems.empty()) { QGraphicsItem* graphicsItem = filteredItems.front(); - auto ngo = dynamic_cast(graphicsItem); + auto ngo = dynamic_cast(graphicsItem); return ngo; } diff --git a/src/FlowSceneModel.cpp b/src/FlowSceneModel.cpp index ec8cc2637..83267b7b0 100644 --- a/src/FlowSceneModel.cpp +++ b/src/FlowSceneModel.cpp @@ -1,43 +1,33 @@ #include "FlowSceneModel.hpp" #include "NodeIndex.hpp" -namespace QtNodes -{ - +namespace QtNodes { bool -FlowSceneModel:: -removeNodeWithConnections(NodeIndex const& index) +FlowSceneModel::removeNodeWithConnections(NodeIndex const& index) { - // delete the conenctions that node has first - auto deleteConnections = - [&](PortType ty) -> bool - { - for (PortIndex portID = 0; (size_t)portID < nodePortCount(index, ty); ++portID) - { - auto inputConnections = nodePortConnections(index, portID, ty); - for (const auto& conn : inputConnections) - { - // try to remove it - bool success; - if (ty == PortType::In) - { - success = removeConnection(conn.first, conn.second, index, portID); - } - else { - success = removeConnection(index, portID, conn.first, conn.second); - } - - // failed, abort the node deletion - if (!success) - { - return false; - } + auto deleteConnections = [&](PortType ty) -> bool { + for (PortIndex portID = 0; (size_t)portID < nodePortCount(index, ty); + ++portID) { + auto inputConnections = nodePortConnections(index, portID, ty); + for (const auto& conn : inputConnections) { + // try to remove it + bool success; + if (ty == PortType::In) { + success = removeConnection(conn.first, conn.second, index, portID); + } else { + success = removeConnection(index, portID, conn.first, conn.second); + } + + // failed, abort the node deletion + if (!success) { + return false; } } - return true; - }; + } + return true; + }; bool success = deleteConnections(PortType::In); @@ -53,11 +43,9 @@ removeNodeWithConnections(NodeIndex const& index) } NodeIndex -FlowSceneModel:: -createIndex(const QUuid& id, void* internalPointer) const +FlowSceneModel::createIndex(const QUuid& id, void* internalPointer) const { return NodeIndex(id, internalPointer, this); } } // namespace QtNodes - diff --git a/src/FlowView.cpp b/src/FlowView.cpp index 5373d1df3..2e631305b 100644 --- a/src/FlowView.cpp +++ b/src/FlowView.cpp @@ -2,32 +2,31 @@ #include -#include #include +#include #include -#include #include +#include #include #include #include -#include #include +#include -#include "FlowScene.hpp" +#include "ConnectionGraphicsObject.hpp" #include "DataModelRegistry.hpp" +#include "FlowScene.hpp" #include "Node.hpp" #include "NodeGraphicsObject.hpp" -#include "ConnectionGraphicsObject.hpp" #include "StyleCollection.hpp" -using QtNodes::FlowView; using QtNodes::FlowScene; +using QtNodes::FlowView; -FlowView:: -FlowView(QWidget *parent) +FlowView::FlowView(QWidget* parent) : QGraphicsView(parent) , _clearSelectionAction(Q_NULLPTR) , _deleteSelectionAction(Q_NULLPTR) @@ -36,12 +35,12 @@ FlowView(QWidget *parent) setDragMode(QGraphicsView::ScrollHandDrag); setRenderHint(QPainter::Antialiasing); - auto const &flowViewStyle = StyleCollection::flowViewStyle(); + auto const& flowViewStyle = StyleCollection::flowViewStyle(); setBackgroundBrush(flowViewStyle.BackgroundColor); - //setViewportUpdateMode(QGraphicsView::FullViewportUpdate); - //setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); + // setViewportUpdateMode(QGraphicsView::FullViewportUpdate); + // setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -49,37 +48,29 @@ FlowView(QWidget *parent) setCacheMode(QGraphicsView::CacheBackground); - //setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); + // setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); } - -FlowView:: -FlowView(FlowScene *scene, QWidget *parent) +FlowView::FlowView(FlowScene* scene, QWidget* parent) : FlowView(parent) { setScene(scene); } - QAction* -FlowView:: -clearSelectionAction() const +FlowView::clearSelectionAction() const { return _clearSelectionAction; } - QAction* -FlowView:: -deleteSelectionAction() const +FlowView::deleteSelectionAction() const { return _deleteSelectionAction; } - void -FlowView:: -setScene(FlowScene *scene) +FlowView::setScene(FlowScene* scene) { _scene = scene; QGraphicsView::setScene(_scene); @@ -88,23 +79,27 @@ setScene(FlowScene *scene) delete _clearSelectionAction; _clearSelectionAction = new QAction(QStringLiteral("Clear Selection"), this); _clearSelectionAction->setShortcut(Qt::Key_Escape); - connect(_clearSelectionAction, &QAction::triggered, _scene, &QGraphicsScene::clearSelection); + connect(_clearSelectionAction, + &QAction::triggered, + _scene, + &QGraphicsScene::clearSelection); addAction(_clearSelectionAction); delete _deleteSelectionAction; - _deleteSelectionAction = new QAction(QStringLiteral("Delete Selection"), this); + _deleteSelectionAction = + new QAction(QStringLiteral("Delete Selection"), this); _deleteSelectionAction->setShortcut(Qt::Key_Delete); - connect(_deleteSelectionAction, &QAction::triggered, this, &FlowView::deleteSelectedNodes); + connect(_deleteSelectionAction, + &QAction::triggered, + this, + &FlowView::deleteSelectedNodes); addAction(_deleteSelectionAction); } - void -FlowView:: -contextMenuEvent(QContextMenuEvent *event) +FlowView::contextMenuEvent(QContextMenuEvent* event) { - if (itemAt(event->pos())) - { + if (itemAt(event->pos())) { QGraphicsView::contextMenuEvent(event); return; } @@ -113,29 +108,28 @@ contextMenuEvent(QContextMenuEvent *event) auto skipText = QStringLiteral("skip me"); - //Add filterbox to the context menu - auto *txtBox = new QLineEdit(&modelMenu); + // Add filterbox to the context menu + auto* txtBox = new QLineEdit(&modelMenu); txtBox->setPlaceholderText(QStringLiteral("Filter")); txtBox->setClearButtonEnabled(true); - auto *txtBoxAction = new QWidgetAction(&modelMenu); + auto* txtBoxAction = new QWidgetAction(&modelMenu); txtBoxAction->setDefaultWidget(txtBox); modelMenu.addAction(txtBoxAction); - //Add result treeview to the context menu - auto *treeView = new QTreeWidget(&modelMenu); + // Add result treeview to the context menu + auto* treeView = new QTreeWidget(&modelMenu); treeView->header()->close(); - auto *treeViewAction = new QWidgetAction(&modelMenu); + auto* treeViewAction = new QWidgetAction(&modelMenu); treeViewAction->setDefaultWidget(treeView); modelMenu.addAction(treeViewAction); QMap categoryItems; - for (auto const &modelName : _scene->model()->modelRegistry()) - { + for (auto const& modelName : _scene->model()->modelRegistry()) { // get the category auto category = _scene->model()->nodeTypeCategory(modelName); @@ -143,8 +137,7 @@ contextMenuEvent(QContextMenuEvent *event) auto iter = categoryItems.find(category); // add it if it doesn't exist - if (iter == categoryItems.end()) - { + if (iter == categoryItems.end()) { auto item = new QTreeWidgetItem(treeView); item->setText(0, category); @@ -158,7 +151,6 @@ contextMenuEvent(QContextMenuEvent *event) // add the item - auto item = new QTreeWidgetItem(parent); item->setText(0, modelName); item->setData(0, Qt::UserRole, modelName); @@ -166,46 +158,40 @@ contextMenuEvent(QContextMenuEvent *event) treeView->expandAll(); - connect(treeView, &QTreeWidget::itemClicked, [&](QTreeWidgetItem *item, int) - { - QString modelName = item->data(0, Qt::UserRole).toString(); - - if (modelName == skipText) - { - return; - } - - QPoint pos = event->pos(); - - QPointF posView = this->mapToScene(pos); - - // try to create the node - auto uuid = _scene->model()->addNode(modelName, posView); - - // if the node creation failed, then don't add it - if (!uuid.isNull()) - { - // move it to the cursor location - _scene->model()->moveNode(_scene->model()->nodeIndex(uuid), posView); - } - - modelMenu.close(); - }); - - //Setup filtering - connect(txtBox, &QLineEdit::textChanged, [&](const QString &text) - { - for (auto& topLvlItem : categoryItems) - { - for (int i = 0; i < topLvlItem->childCount(); ++i) - { - auto child = topLvlItem->child(i); - auto modelName = child->data(0, Qt::UserRole).toString(); - const bool match = (modelName.contains(text, Qt::CaseInsensitive)); - child->setHidden(!match); - } - } - }); + connect(treeView, &QTreeWidget::itemClicked, [&](QTreeWidgetItem* item, int) { + QString modelName = item->data(0, Qt::UserRole).toString(); + + if (modelName == skipText) { + return; + } + + QPoint pos = event->pos(); + + QPointF posView = this->mapToScene(pos); + + // try to create the node + auto uuid = _scene->model()->addNode(modelName, posView); + + // if the node creation failed, then don't add it + if (!uuid.isNull()) { + // move it to the cursor location + _scene->model()->moveNode(_scene->model()->nodeIndex(uuid), posView); + } + + modelMenu.close(); + }); + + // Setup filtering + connect(txtBox, &QLineEdit::textChanged, [&](const QString& text) { + for (auto& topLvlItem : categoryItems) { + for (int i = 0; i < topLvlItem->childCount(); ++i) { + auto child = topLvlItem->child(i); + auto modelName = child->data(0, Qt::UserRole).toString(); + const bool match = (modelName.contains(text, Qt::CaseInsensitive)); + child->setHidden(!match); + } + } + }); // make sure the text box gets focus so the user doesn't have to click on it txtBox->setFocus(); @@ -213,15 +199,12 @@ contextMenuEvent(QContextMenuEvent *event) modelMenu.exec(event->globalPos()); } - void -FlowView:: -wheelEvent(QWheelEvent *event) +FlowView::wheelEvent(QWheelEvent* event) { QPoint delta = event->angleDelta(); - if (delta.y() == 0) - { + if (delta.y() == 0) { event->ignore(); return; } @@ -234,12 +217,10 @@ wheelEvent(QWheelEvent *event) scaleDown(); } - void -FlowView:: -scaleUp() +FlowView::scaleUp() { - double const step = 1.2; + double const step = 1.2; double const factor = std::pow(step, 1.0); QTransform t = transform(); @@ -250,33 +231,29 @@ scaleUp() scale(factor, factor); } - void -FlowView:: -scaleDown() +FlowView::scaleDown() { - double const step = 1.2; + double const step = 1.2; double const factor = std::pow(step, -1.0); scale(factor, factor); } - void -FlowView:: -deleteSelectedNodes() +FlowView::deleteSelectedNodes() { // Delete the selected connections first, ensuring that they won't be // automatically deleted when selected nodes are deleted (deleting a node // deletes some connections as well) - for (QGraphicsItem * item : _scene->selectedItems()) - { - if (auto c = qgraphicsitem_cast(item)) - { + for (QGraphicsItem* item : _scene->selectedItems()) { + if (auto c = qgraphicsitem_cast(item)) { // does't matter if it works or doesn't, at least we tried - scene()->model()->removeConnection(c->node(PortType::Out), c->portIndex(PortType::Out), c->node(PortType::In), c->portIndex(PortType::In)); - + scene()->model()->removeConnection(c->node(PortType::Out), + c->portIndex(PortType::Out), + c->node(PortType::In), + c->portIndex(PortType::In)); } } @@ -284,10 +261,8 @@ deleteSelectedNodes() // Selected connections were already deleted prior to this loop, otherwise // qgraphicsitem_cast(item) could be a use-after-free // when a selected connection is deleted by deleting the node. - for (QGraphicsItem * item : _scene->selectedItems()) - { - if (auto n = qgraphicsitem_cast(item)) - { + for (QGraphicsItem* item : _scene->selectedItems()) { + if (auto n = qgraphicsitem_cast(item)) { auto index = n->index(); scene()->model()->removeNodeWithConnections(index); @@ -295,13 +270,10 @@ deleteSelectedNodes() } } - void -FlowView:: -keyPressEvent(QKeyEvent *event) +FlowView::keyPressEvent(QKeyEvent* event) { - switch (event->key()) - { + switch (event->key()) { case Qt::Key_Shift: setDragMode(QGraphicsView::RubberBandDrag); break; @@ -313,13 +285,10 @@ keyPressEvent(QKeyEvent *event) QGraphicsView::keyPressEvent(event); } - void -FlowView:: -keyReleaseEvent(QKeyEvent *event) +FlowView::keyReleaseEvent(QKeyEvent* event) { - switch (event->key()) - { + switch (event->key()) { case Qt::Key_Shift: setDragMode(QGraphicsView::ScrollHandDrag); break; @@ -330,73 +299,61 @@ keyReleaseEvent(QKeyEvent *event) QGraphicsView::keyReleaseEvent(event); } - void -FlowView:: -mousePressEvent(QMouseEvent *event) +FlowView::mousePressEvent(QMouseEvent* event) { QGraphicsView::mousePressEvent(event); - if (event->button() == Qt::LeftButton) - { + if (event->button() == Qt::LeftButton) { _clickPos = mapToScene(event->pos()); } } - void -FlowView:: -mouseMoveEvent(QMouseEvent *event) +FlowView::mouseMoveEvent(QMouseEvent* event) { QGraphicsView::mouseMoveEvent(event); - if (scene()->mouseGrabberItem() == nullptr && event->buttons() == Qt::LeftButton) - { + if (scene()->mouseGrabberItem() == nullptr && + event->buttons() == Qt::LeftButton) { // Make sure shift is not being pressed - if ((event->modifiers() & Qt::ShiftModifier) == 0) - { + if ((event->modifiers() & Qt::ShiftModifier) == 0) { QPointF difference = _clickPos - mapToScene(event->pos()); setSceneRect(sceneRect().translated(difference.x(), difference.y())); } } } - void -FlowView:: -drawBackground(QPainter* painter, const QRectF& r) +FlowView::drawBackground(QPainter* painter, const QRectF& r) { QGraphicsView::drawBackground(painter, r); - auto drawGrid = - [&](double gridStep) - { - QRect windowRect = rect(); - QPointF tl = mapToScene(windowRect.topLeft()); - QPointF br = mapToScene(windowRect.bottomRight()); - - double left = std::floor(tl.x() / gridStep - 0.5); - double right = std::floor(br.x() / gridStep + 1.0); - double bottom = std::floor(tl.y() / gridStep - 0.5); - double top = std::floor (br.y() / gridStep + 1.0); - - // vertical lines - for (int xi = int(left); xi <= int(right); ++xi) - { - QLineF line(xi * gridStep, bottom * gridStep, - xi * gridStep, top * gridStep ); - - painter->drawLine(line); - } + auto drawGrid = [&](double gridStep) { + QRect windowRect = rect(); + QPointF tl = mapToScene(windowRect.topLeft()); + QPointF br = mapToScene(windowRect.bottomRight()); - // horizontal lines - for (int yi = int(bottom); yi <= int(top); ++yi) - { - QLineF line(left * gridStep, yi * gridStep, - right * gridStep, yi * gridStep ); - painter->drawLine(line); - } - }; + double left = std::floor(tl.x() / gridStep - 0.5); + double right = std::floor(br.x() / gridStep + 1.0); + double bottom = std::floor(tl.y() / gridStep - 0.5); + double top = std::floor(br.y() / gridStep + 1.0); + + // vertical lines + for (int xi = int(left); xi <= int(right); ++xi) { + QLineF line( + xi * gridStep, bottom * gridStep, xi * gridStep, top * gridStep); + + painter->drawLine(line); + } - auto const &flowViewStyle = StyleCollection::flowViewStyle(); + // horizontal lines + for (int yi = int(bottom); yi <= int(top); ++yi) { + QLineF line( + left * gridStep, yi * gridStep, right * gridStep, yi * gridStep); + painter->drawLine(line); + } + }; + + auto const& flowViewStyle = StyleCollection::flowViewStyle(); QBrush bBrush = backgroundBrush(); @@ -411,19 +368,22 @@ drawBackground(QPainter* painter, const QRectF& r) drawGrid(150); } - void -FlowView:: -showEvent(QShowEvent *event) +FlowView::showEvent(QShowEvent* event) { _scene->setSceneRect(this->rect()); QGraphicsView::showEvent(event); } +void +FlowView::resizeEvent(QResizeEvent* event) +{ + _scene->setSceneRect(QRect{ QPoint{}, event->size() }); + QGraphicsView::resizeEvent(event); +} -FlowScene * -FlowView:: -scene() +FlowScene* +FlowView::scene() { return _scene; } diff --git a/src/FlowViewStyle.cpp b/src/FlowViewStyle.cpp index ba19e07a3..77cb764a3 100644 --- a/src/FlowViewStyle.cpp +++ b/src/FlowViewStyle.cpp @@ -1,10 +1,10 @@ #include "FlowViewStyle.hpp" #include +#include #include #include #include -#include #include @@ -13,70 +13,68 @@ using QtNodes::FlowViewStyle; inline void -initResources() { Q_INIT_RESOURCE(resources); } +initResources() +{ + Q_INIT_RESOURCE(resources); +} -FlowViewStyle:: -FlowViewStyle() +FlowViewStyle::FlowViewStyle() { // Explicit resources inialization for preventing the static initialization // order fiasco: https://isocpp.org/wiki/faq/ctors#static-init-order initResources(); - // This configuration is stored inside the compiled unit and is loaded statically + // This configuration is stored inside the compiled unit and is loaded + // statically loadJsonFile(":DefaultStyle.json"); } - -FlowViewStyle:: -FlowViewStyle(QString jsonText) +FlowViewStyle::FlowViewStyle(QString jsonText) { loadJsonText(jsonText); } - void -FlowViewStyle:: -setStyle(QString jsonText) +FlowViewStyle::setStyle(QString jsonText) { FlowViewStyle style(jsonText); StyleCollection::setFlowViewStyle(style); } - #ifdef STYLE_DEBUG - #define FLOW_VIEW_STYLE_CHECK_UNDEFINED_VALUE(v, variable) { \ - if (v.type() == QJsonValue::Undefined || \ - v.type() == QJsonValue::Null) \ - qWarning() << "Undefined value for parameter:" << #variable; \ -} +#define FLOW_VIEW_STYLE_CHECK_UNDEFINED_VALUE(v, variable) \ + { \ + if (v.type() == QJsonValue::Undefined || v.type() == QJsonValue::Null) \ + qWarning() << "Undefined value for parameter:" << #variable; \ + } #else - #define FLOW_VIEW_STYLE_CHECK_UNDEFINED_VALUE(v, variable) +#define FLOW_VIEW_STYLE_CHECK_UNDEFINED_VALUE(v, variable) #endif -#define FLOW_VIEW_STYLE_READ_COLOR(values, variable) { \ - auto valueRef = values[#variable]; \ - FLOW_VIEW_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ - if (valueRef.isArray()) { \ - auto colorArray = valueRef.toArray(); \ - std::vector rgb; rgb.reserve(3); \ - for (auto it = colorArray.begin(); it != colorArray.end(); ++it) { \ - rgb.push_back((*it).toInt()); \ - } \ - variable = QColor(rgb[0], rgb[1], rgb[2]); \ - } else { \ - variable = QColor(valueRef.toString()); \ - } \ -} +#define FLOW_VIEW_STYLE_READ_COLOR(values, variable) \ + { \ + auto valueRef = values[#variable]; \ + FLOW_VIEW_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ + if (valueRef.isArray()) { \ + auto colorArray = valueRef.toArray(); \ + std::vector rgb; \ + rgb.reserve(3); \ + for (auto it = colorArray.begin(); it != colorArray.end(); ++it) { \ + rgb.push_back((*it).toInt()); \ + } \ + variable = QColor(rgb[0], rgb[1], rgb[2]); \ + } else { \ + variable = QColor(valueRef.toString()); \ + } \ + } void -FlowViewStyle:: -loadJsonFile(QString styleFile) +FlowViewStyle::loadJsonFile(QString styleFile) { QFile file(styleFile); - if (!file.open(QIODevice::ReadOnly)) - { + if (!file.open(QIODevice::ReadOnly)) { qWarning() << "Couldn't open file " << styleFile; return; @@ -85,18 +83,14 @@ loadJsonFile(QString styleFile) loadJsonFromByteArray(file.readAll()); } - void -FlowViewStyle:: -loadJsonText(QString jsonText) +FlowViewStyle::loadJsonText(QString jsonText) { loadJsonFromByteArray(jsonText.toUtf8()); } - void -FlowViewStyle:: -loadJsonFromByteArray(QByteArray const &byteArray) +FlowViewStyle::loadJsonFromByteArray(QByteArray const& byteArray) { QJsonDocument json(QJsonDocument::fromJson(byteArray)); diff --git a/src/Node.cpp b/src/Node.cpp index 069c66b91..c7349a0e3 100644 --- a/src/Node.cpp +++ b/src/Node.cpp @@ -2,45 +2,43 @@ #include -#include #include +#include #include "FlowScene.hpp" -#include "NodeGraphicsObject.hpp" #include "NodeDataModel.hpp" +#include "NodeGraphicsObject.hpp" +#include "Connection.hpp" #include "ConnectionGraphicsObject.hpp" #include "ConnectionState.hpp" -#include "Connection.hpp" +using QtNodes::Connection; using QtNodes::Node; +using QtNodes::NodeData; using QtNodes::NodeDataModel; -using QtNodes::Connection; -using QtNodes::PortType; using QtNodes::PortIndex; -using QtNodes::NodeData; +using QtNodes::PortType; -Node:: -Node(std::unique_ptr && dataModel, QUuid const& id) +Node::Node(std::unique_ptr&& dataModel, QUuid const& id) : _uid(id) - ,_nodeDataModel(std::move(dataModel)) + , _nodeDataModel(std::move(dataModel)) { // propagate data: model => node - connect(_nodeDataModel.get(), &NodeDataModel::dataUpdated, - this, &Node::onDataUpdated); + connect(_nodeDataModel.get(), + &NodeDataModel::dataUpdated, + this, + &Node::onDataUpdated); _inConnections.resize(nodeDataModel()->nPorts(PortType::In)); _outConnections.resize(nodeDataModel()->nPorts(PortType::Out)); } - -Node:: -~Node() = default; +Node::~Node() = default; QJsonObject -Node:: -save() const +Node::save() const { QJsonObject nodeJson; @@ -49,52 +47,44 @@ save() const nodeJson["model"] = _nodeDataModel->save(); QJsonObject obj; - obj["x"] = _pos.x(); - obj["y"] = _pos.y(); + obj["x"] = _pos.x(); + obj["y"] = _pos.y(); nodeJson["position"] = obj; return nodeJson; } - void -Node:: -restore(QJsonObject const& json) +Node::restore(QJsonObject const& json) { QJsonObject positionJson = json["position"].toObject(); - QPointF point(positionJson["x"].toDouble(), - positionJson["y"].toDouble()); + QPointF point(positionJson["x"].toDouble(), positionJson["y"].toDouble()); setPosition(point); _nodeDataModel->restore(json["model"].toObject()); } - QUuid -Node:: -id() const +Node::id() const { return _uid; } NodeDataModel* -Node:: -nodeDataModel() const +Node::nodeDataModel() const { return _nodeDataModel.get(); } QPointF -Node:: -position() const +Node::position() const { return _pos; } void -Node:: -setPosition(QPointF const& newPos) +Node::setPosition(QPointF const& newPos) { _pos = newPos; @@ -102,42 +92,38 @@ setPosition(QPointF const& newPos) } std::vector const& -Node:: -connections(PortType pType, PortIndex idx) const +Node::connections(PortType pType, PortIndex idx) const { Q_ASSERT(idx >= 0); - Q_ASSERT(pType == PortType::In ? (size_t)idx < _inConnections.size() : (size_t)idx < _outConnections.size()); + Q_ASSERT(pType == PortType::In ? (size_t)idx < _inConnections.size() + : (size_t)idx < _outConnections.size()); return pType == PortType::In ? _inConnections[idx] : _outConnections[idx]; } -std::vector & -Node:: -connections(PortType pType, PortIndex idx) +std::vector& +Node::connections(PortType pType, PortIndex idx) { Q_ASSERT(idx >= 0); - Q_ASSERT(pType == PortType::In ? (size_t)idx < _inConnections.size() : (size_t)idx < _outConnections.size()); + Q_ASSERT(pType == PortType::In ? (size_t)idx < _inConnections.size() + : (size_t)idx < _outConnections.size()); return pType == PortType::In ? _inConnections[idx] : _outConnections[idx]; } void -Node:: -propagateData(std::shared_ptr nodeData, - PortIndex inPortIndex) const +Node::propagateData(std::shared_ptr nodeData, + PortIndex inPortIndex) const { _nodeDataModel->setInData(nodeData, inPortIndex); } - void -Node:: -onDataUpdated(PortIndex index) +Node::onDataUpdated(PortIndex index) { auto nodeData = _nodeDataModel->outData(index); - auto& conns = - connections(PortType::Out, index); + auto& conns = connections(PortType::Out, index); - for (auto const & c : conns) + for (auto const& c : conns) c->propagateData(nodeData); } diff --git a/src/NodeConnectionInteraction.cpp b/src/NodeConnectionInteraction.cpp index fdb37d34a..e4e988dc5 100644 --- a/src/NodeConnectionInteraction.cpp +++ b/src/NodeConnectionInteraction.cpp @@ -1,39 +1,36 @@ #include "NodeConnectionInteraction.hpp" #include "ConnectionGraphicsObject.hpp" -#include "NodeGraphicsObject.hpp" -#include "NodeDataModel.hpp" #include "DataModelRegistry.hpp" #include "FlowScene.hpp" +#include "NodeDataModel.hpp" +#include "NodeGraphicsObject.hpp" -using QtNodes::NodeConnectionInteraction; -using QtNodes::PortType; -using QtNodes::PortIndex; +using QtNodes::ConnectionGraphicsObject; using QtNodes::FlowScene; +using QtNodes::NodeConnectionInteraction; using QtNodes::NodeDataModel; -using QtNodes::TypeConverter; using QtNodes::NodeIndex; -using QtNodes::ConnectionGraphicsObject; +using QtNodes::PortIndex; +using QtNodes::PortType; +using QtNodes::TypeConverter; -NodeConnectionInteraction:: -NodeConnectionInteraction(NodeIndex const& node, - ConnectionGraphicsObject& connection) +NodeConnectionInteraction::NodeConnectionInteraction( + NodeIndex const& node, + ConnectionGraphicsObject& connection) : _node(node) , _connection(&connection) {} - bool -NodeConnectionInteraction:: -canConnect(PortIndex &portIndex, bool& converted) const +NodeConnectionInteraction::canConnect(PortIndex& portIndex, + bool& converted) const { // 1) Connection requires a port PortType requiredPort = connectionRequiredPort(); - - if (requiredPort == PortType::None) - { + if (requiredPort == PortType::None) { return false; } @@ -47,11 +44,9 @@ canConnect(PortIndex &portIndex, bool& converted) const QPointF connectionPoint = connectionEndScenePosition(requiredPort); - portIndex = nodePortIndexUnderScenePoint(requiredPort, - connectionPoint); + portIndex = nodePortIndexUnderScenePoint(requiredPort, connectionPoint); - if (portIndex == INVALID) - { + if (portIndex == INVALID) { return false; } @@ -61,25 +56,24 @@ canConnect(PortIndex &portIndex, bool& converted) const if (!nodePortIsEmpty(requiredPort, portIndex)) return false; - // 4) Connection type equals node port type, or there is a registered type conversion that can translate between the two + // 4) Connection type equals node port type, or there is a registered type + // conversion that can translate between the two - auto connectionDataType = - _connection->dataType(oppositePort(requiredPort)); + auto connectionDataType = _connection->dataType(oppositePort(requiredPort)); - auto const modelTarget = _node.model(); - NodeDataType candidateNodeDataType = modelTarget->nodePortDataType(_node, portIndex, requiredPort); + auto const modelTarget = _node.model(); + NodeDataType candidateNodeDataType = + modelTarget->nodePortDataType(_node, portIndex, requiredPort); // if the types don't match, try a conversion - if (connectionDataType.id != candidateNodeDataType.id) - { + if (connectionDataType.id != candidateNodeDataType.id) { converted = true; - if (requiredPort == PortType::In) - { - return modelTarget->getTypeConvertable({connectionDataType, candidateNodeDataType}); - } - else if (requiredPort == PortType::Out) - { - return modelTarget->getTypeConvertable({candidateNodeDataType, connectionDataType}); + if (requiredPort == PortType::In) { + return modelTarget->getTypeConvertable( + { connectionDataType, candidateNodeDataType }); + } else if (requiredPort == PortType::Out) { + return modelTarget->getTypeConvertable( + { candidateNodeDataType, connectionDataType }); } Q_UNREACHABLE(); } @@ -89,31 +83,27 @@ canConnect(PortIndex &portIndex, bool& converted) const return true; } - bool -NodeConnectionInteraction:: -tryConnect() const +NodeConnectionInteraction::tryConnect() const { // 1) Check conditions from 'canConnect' PortIndex portIndex = INVALID; bool converted; - if (!canConnect(portIndex, converted)) - { + if (!canConnect(portIndex, converted)) { return false; } - auto requiredPort = connectionRequiredPort(); + auto requiredPort = connectionRequiredPort(); auto connectedPort = oppositePort(requiredPort); auto outNodePortIndex = _connection->portIndex(connectedPort); - auto outNode = _connection->node(connectedPort); + auto outNode = _connection->node(connectedPort); auto model = _connection->flowScene().model(); - if (requiredPort == PortType::In) - { + if (requiredPort == PortType::In) { return model->addConnection(outNode, outNodePortIndex, _node, portIndex); } return model->addConnection(_node, portIndex, outNode, outNodePortIndex); @@ -122,18 +112,15 @@ tryConnect() const // ------------------ util functions below PortType -NodeConnectionInteraction:: -connectionRequiredPort() const +NodeConnectionInteraction::connectionRequiredPort() const { - auto const &state = _connection->state(); + auto const& state = _connection->state(); return state.requiredPort(); } - QPointF -NodeConnectionInteraction:: -connectionEndScenePosition(PortType portType) const +NodeConnectionInteraction::connectionEndScenePosition(PortType portType) const { ConnectionGeometry& geometry = _connection->geometry(); @@ -142,51 +129,50 @@ connectionEndScenePosition(PortType portType) const return _connection->mapToScene(endPoint); } - QPointF -NodeConnectionInteraction:: -nodePortScenePosition(PortType portType, PortIndex portIndex) const +NodeConnectionInteraction::nodePortScenePosition(PortType portType, + PortIndex portIndex) const { - NodeGraphicsObject const& ngo = *_connection->flowScene().nodeGraphicsObject(_node); + NodeGraphicsObject const& ngo = + *_connection->flowScene().nodeGraphicsObject(_node); - NodeGeometry const &geom = ngo.geometry(); + NodeGeometry const& geom = ngo.geometry(); QPointF p = geom.portScenePosition(portIndex, portType); return ngo.sceneTransform().map(p); } - PortIndex -NodeConnectionInteraction:: -nodePortIndexUnderScenePoint(PortType portType, - QPointF const & scenePoint) const +NodeConnectionInteraction::nodePortIndexUnderScenePoint( + PortType portType, + QPointF const& scenePoint) const { - NodeGraphicsObject const& ngo = *_connection->flowScene().nodeGraphicsObject(_node); - NodeGeometry const &nodeGeom = ngo.geometry(); + NodeGraphicsObject const& ngo = + *_connection->flowScene().nodeGraphicsObject(_node); + NodeGeometry const& nodeGeom = ngo.geometry(); - QTransform sceneTransform = - ngo.sceneTransform(); + QTransform sceneTransform = ngo.sceneTransform(); - PortIndex portIndex = nodeGeom.checkHitScenePoint(portType, - scenePoint, - sceneTransform); + PortIndex portIndex = + nodeGeom.checkHitScenePoint(portType, scenePoint, sceneTransform); return portIndex; } - bool -NodeConnectionInteraction:: -nodePortIsEmpty(PortType portType, PortIndex portIndex) const +NodeConnectionInteraction::nodePortIsEmpty(PortType portType, + PortIndex portIndex) const { - NodeState const & nodeState = _connection->flowScene().nodeGraphicsObject(_node)->nodeState(); + NodeState const& nodeState = + _connection->flowScene().nodeGraphicsObject(_node)->nodeState(); - auto const & entries = nodeState.getEntries(portType); + auto const& entries = nodeState.getEntries(portType); if (entries[portIndex].empty()) return true; - const auto outPolicy = _node.model()->nodePortConnectionPolicy(_node, portIndex, portType); + const auto outPolicy = + _node.model()->nodePortConnectionPolicy(_node, portIndex, portType); return outPolicy == ConnectionPolicy::Many; } diff --git a/src/NodeConnectionInteraction.hpp b/src/NodeConnectionInteraction.hpp index ae79ad4d3..0236475d9 100644 --- a/src/NodeConnectionInteraction.hpp +++ b/src/NodeConnectionInteraction.hpp @@ -1,10 +1,9 @@ #pragma once -#include "Node.hpp" #include "Connection.hpp" +#include "Node.hpp" -namespace QtNodes -{ +namespace QtNodes { /// Class performs various operations on the Node and Connection pair. /// An instance should be created on the stack and destroyed when @@ -19,39 +18,31 @@ class NodeConnectionInteraction /// 1) Connection 'requires' a port /// 2) Connection's vacant end is above the node port /// 3) Node port is vacant - /// 4) Connection type equals node port type, or there is a registered type conversion that can translate between the two - bool - canConnect(PortIndex & portIndex, bool& converted) const; + /// 4) Connection type equals node port type, or there is a registered type + /// conversion that can translate between the two + bool canConnect(PortIndex& portIndex, bool& converted) const; /// 1) Check conditions from 'canConnect' - /// 1.5) If the connection is possible but a type conversion is needed, add a converter node to the scene, and connect it properly - /// 2) Assign node to required port in Connection - /// 3) Assign Connection to empty port in NodeState - /// 4) Adjust Connection geometry - /// 5) Poke model to initiate data transfer - bool - tryConnect() const; + /// 1.5) If the connection is possible but a type conversion is needed, add a + /// converter node to the scene, and connect it properly 2) Assign node to + /// required port in Connection 3) Assign Connection to empty port in + /// NodeState 4) Adjust Connection geometry 5) Poke model to initiate data + /// transfer + bool tryConnect() const; private: - - PortType - connectionRequiredPort() const; + PortType connectionRequiredPort() const; QPointF connectionEndScenePosition(PortType) const; - QPointF - nodePortScenePosition(PortType portType, - PortIndex portIndex) const; + QPointF nodePortScenePosition(PortType portType, PortIndex portIndex) const; - PortIndex - nodePortIndexUnderScenePoint(PortType portType, - QPointF const &p) const; + PortIndex nodePortIndexUnderScenePoint(PortType portType, + QPointF const& p) const; - bool - nodePortIsEmpty(PortType portType, PortIndex portIndex) const; + bool nodePortIsEmpty(PortType portType, PortIndex portIndex) const; private: - NodeIndex _node; ConnectionGraphicsObject* _connection; diff --git a/src/NodeDataModel.cpp b/src/NodeDataModel.cpp index 9737b345d..da563519f 100644 --- a/src/NodeDataModel.cpp +++ b/src/NodeDataModel.cpp @@ -5,17 +5,14 @@ using QtNodes::NodeDataModel; using QtNodes::NodeStyle; -NodeDataModel:: -NodeDataModel() +NodeDataModel::NodeDataModel() : _nodeStyle(StyleCollection::nodeStyle()) { // Derived classes can initialize specific style here } - QJsonObject -NodeDataModel:: -save() const +NodeDataModel::save() const { QJsonObject modelJson; @@ -24,18 +21,14 @@ save() const return modelJson; } - NodeStyle const& -NodeDataModel:: -nodeStyle() const +NodeDataModel::nodeStyle() const { return _nodeStyle; } - void -NodeDataModel:: -setNodeStyle(NodeStyle const& style) +NodeDataModel::setNodeStyle(NodeStyle const& style) { _nodeStyle = style; } diff --git a/src/NodeGeometry.cpp b/src/NodeGeometry.cpp index 697270dc8..b68fb7110 100644 --- a/src/NodeGeometry.cpp +++ b/src/NodeGeometry.cpp @@ -1,24 +1,24 @@ #include "NodeGeometry.hpp" -#include #include +#include -#include "PortType.hpp" -#include "NodeIndex.hpp" -#include "NodeGraphicsObject.hpp" #include "FlowSceneModel.hpp" +#include "NodeGraphicsObject.hpp" +#include "NodeIndex.hpp" +#include "PortType.hpp" #include "StyleCollection.hpp" #include -namespace QtNodes -{ +namespace QtNodes { -NodeGeometry:: -NodeGeometry(const NodeIndex& index) - : _width(100) +NodeGeometry::NodeGeometry(const NodeIndex& index, NodeGraphicsObject& obj) + : _obj{ obj } + , _width(100) , _height(150) + , _entryWidth(0) , _inputPortWidth(70) , _outputPortWidth(70) , _entryHeight(20) @@ -31,84 +31,77 @@ NodeGeometry(const NodeIndex& index) , _fontMetrics(QFont()) , _boldFontMetrics(QFont()) { - QFont f; f.setBold(true); + QFont f; + f.setBold(true); _boldFontMetrics = QFontMetrics(f); -} + // TODO if style can change dynamicly, so it have to be unkomment + // connect(&StyleCollection::instance(), &StyleCollection::nodeStyleChanged, + // this, [&]() { + // _obj.prepareGeometryChange(); + // _obj.boundingRect(); + // }); +} QRectF -NodeGeometry:: -entryBoundingRect() const +NodeGeometry::entryBoundingRect() const { double const addon = 0.0; - return QRectF(0 - addon, - 0 - addon, - _entryWidth + 2 * addon, - _entryHeight + 2 * addon); + return QRectF( + 0 - addon, 0 - addon, _entryWidth + 2 * addon, _entryHeight + 2 * addon); } - QRectF -NodeGeometry:: -boundingRect() const +NodeGeometry::boundingRect() const { - auto const &nodeStyle = StyleCollection::nodeStyle(); + auto const& nodeStyle = StyleCollection::nodeStyle(); double addon = 4 * nodeStyle.ConnectionPointDiameter; - return QRectF(0 - addon, - 0 - addon, - _width + 2 * addon, - _height + 2 * addon); + return QRectF(0 - addon, 0 - addon, _width + 2 * addon, _height + 2 * addon); } - void -NodeGeometry:: -recalculateSize() const +NodeGeometry::recalculateSize() const { + _obj.prepareGeometryChange(); + _entryHeight = _fontMetrics.height(); { unsigned int maxNumOfEntries = std::max(_nSinks, _nSources); - unsigned int step = _entryHeight + _spacing; + unsigned int step = _entryHeight + _spacing; _height = step * maxNumOfEntries; } - if (auto w = _nodeIndex.model()->nodeWidget(_nodeIndex)) - { + if (auto w = _nodeIndex.model()->nodeWidget(_nodeIndex)) { _height = std::max(_height, static_cast(w->height())); } _height += captionHeight(); - _inputPortWidth = portWidth(PortType::In); + _inputPortWidth = portWidth(PortType::In); _outputPortWidth = portWidth(PortType::Out); - _width = _inputPortWidth + - _outputPortWidth + - 2 * _spacing; + _width = _inputPortWidth + _outputPortWidth + 2 * _spacing; - if (auto w = _nodeIndex.model()->nodeWidget(_nodeIndex)) - { + if (auto w = _nodeIndex.model()->nodeWidget(_nodeIndex)) { _width += w->width(); } _width = std::max(_width, captionWidth()); - if (_nodeIndex.model()->nodeValidationState(_nodeIndex) != NodeValidationState::Valid) - { - _width = std::max(_width, validationWidth()); + if (_nodeIndex.model()->nodeValidationState(_nodeIndex) != + NodeValidationState::Valid) { + _width = std::max(_width, validationWidth()); _height += validationHeight() + _spacing; } } - void -NodeGeometry:: -recalculateSize(QFont const & font) const +NodeGeometry::recalculateSize(QFont const& font) const { QFontMetrics fontMetrics(font); QFont boldFont = font; @@ -117,23 +110,20 @@ recalculateSize(QFont const & font) const QFontMetrics boldFontMetrics(boldFont); - if (_boldFontMetrics != boldFontMetrics) - { - _fontMetrics = fontMetrics; + if (_boldFontMetrics != boldFontMetrics) { + _fontMetrics = fontMetrics; _boldFontMetrics = boldFontMetrics; recalculateSize(); } } - QPointF -NodeGeometry:: -portScenePosition(PortIndex index, - PortType portType, - QTransform const & t) const +NodeGeometry::portScenePosition(PortIndex index, + PortType portType, + QTransform const& t) const { - auto const &nodeStyle = StyleCollection::nodeStyle(); + auto const& nodeStyle = StyleCollection::nodeStyle(); unsigned int step = _entryHeight + _spacing; @@ -148,18 +138,15 @@ portScenePosition(PortIndex index, // TODO: why? totalHeight += step / 2.0; - switch (portType) - { - case PortType::Out: - { + switch (portType) { + case PortType::Out: { double x = _width + nodeStyle.ConnectionPointDiameter; result = QPointF(x, totalHeight); break; } - case PortType::In: - { + case PortType::In: { double x = 0.0 - nodeStyle.ConnectionPointDiameter; result = QPointF(x, totalHeight); @@ -173,14 +160,12 @@ portScenePosition(PortIndex index, return t.map(result); } - PortIndex -NodeGeometry:: -checkHitScenePoint(PortType portType, - QPointF const scenePoint, - QTransform const & sceneTransform) const +NodeGeometry::checkHitScenePoint(PortType portType, + QPointF const scenePoint, + QTransform const& sceneTransform) const { - auto const &nodeStyle = StyleCollection::nodeStyle(); + auto const& nodeStyle = StyleCollection::nodeStyle(); PortIndex result = INVALID; @@ -191,15 +176,13 @@ checkHitScenePoint(PortType portType, size_t const nItems = _nodeIndex.model()->nodePortCount(_nodeIndex, portType); - for (unsigned int i = 0; i < nItems; ++i) - { + for (unsigned int i = 0; i < nItems; ++i) { auto pp = portScenePosition(i, portType, sceneTransform); - QPointF p = pp - scenePoint; + QPointF p = pp - scenePoint; auto distance = std::sqrt(QPointF::dotProduct(p, p)); - if (distance < tolerance) - { + if (distance < tolerance) { result = PortIndex(i); break; } @@ -208,30 +191,24 @@ checkHitScenePoint(PortType portType, return result; } - QRect -NodeGeometry:: -resizeRect() const +NodeGeometry::resizeRect() const { unsigned int rectSize = 7; - return QRect(_width - rectSize, - _height - rectSize, - rectSize, - rectSize); + return QRect(_width - rectSize, _height - rectSize, rectSize, rectSize); } - QPointF -NodeGeometry:: -widgetPosition() const +NodeGeometry::widgetPosition() const { - if (auto w = _nodeIndex.model()->nodeWidget(_nodeIndex)) - { - if (_nodeIndex.model()->nodeValidationState(_nodeIndex) != NodeValidationState::Valid) - { + if (auto w = _nodeIndex.model()->nodeWidget(_nodeIndex)) { + if (_nodeIndex.model()->nodeValidationState(_nodeIndex) != + NodeValidationState::Valid) { return QPointF(_spacing + portWidth(PortType::In), - (captionHeight() + _height - validationHeight() - _spacing - w->height()) / 2.0); + (captionHeight() + _height - validationHeight() - + _spacing - w->height()) / + 2.0); } return QPointF(_spacing + portWidth(PortType::In), @@ -241,10 +218,8 @@ widgetPosition() const return QPointF(); } - unsigned int -NodeGeometry:: -captionHeight() const +NodeGeometry::captionHeight() const { QString name = _nodeIndex.model()->nodeCaption(_nodeIndex); @@ -252,10 +227,8 @@ captionHeight() const return _boldFontMetrics.boundingRect(name).height(); } - unsigned int -NodeGeometry:: -captionWidth() const +NodeGeometry::captionWidth() const { QString name = _nodeIndex.model()->nodeCaption(_nodeIndex); @@ -263,62 +236,64 @@ captionWidth() const return _boldFontMetrics.boundingRect(name).width(); } - unsigned int -NodeGeometry:: -validationHeight() const +NodeGeometry::validationHeight() const { QString msg = _nodeIndex.model()->nodeValidationMessage(_nodeIndex); return _boldFontMetrics.boundingRect(msg).height(); } - unsigned int -NodeGeometry:: -validationWidth() const +NodeGeometry::validationWidth() const { QString msg = _nodeIndex.model()->nodeValidationMessage(_nodeIndex); return _boldFontMetrics.boundingRect(msg).width(); } - QPointF -NodeGeometry:: -calculateNodePositionBetweenNodePorts(PortIndex targetPortIndex, PortType targetPort, const NodeGraphicsObject& targetNode, - PortIndex sourcePortIndex, PortType sourcePort, const NodeGraphicsObject& sourceNode, - const NodeGeometry& newNodeGeom) +NodeGeometry::calculateNodePositionBetweenNodePorts( + PortIndex targetPortIndex, + PortType targetPort, + const NodeGraphicsObject& targetNode, + PortIndex sourcePortIndex, + PortType sourcePort, + const NodeGraphicsObject& sourceNode, + const NodeGeometry& newNodeGeom) { - //Calculating the nodes position in the scene. It'll be positioned half way between the two ports that it "connects". - //The first line calculates the halfway point between the ports (node position + port position on the node for both nodes averaged). - //The second line offsets this coordinate with the size of the new node, so that the new nodes center falls on the originally - //calculated coordinate, instead of it's upper left corner. - auto converterNodePos = (sourceNode.pos() + sourceNode.geometry().portScenePosition(sourcePortIndex, sourcePort) - + targetNode.pos() + targetNode.geometry().portScenePosition(targetPortIndex, targetPort)) / 2.0f; + // Calculating the nodes position in the scene. It'll be positioned half way + // between the two ports that it "connects". The first line calculates the + // halfway point between the ports (node position + port position on the node + // for both nodes averaged). The second line offsets this coordinate with the + // size of the new node, so that the new nodes center falls on the originally + // calculated coordinate, instead of it's upper left corner. + auto converterNodePos = + (sourceNode.pos() + + sourceNode.geometry().portScenePosition(sourcePortIndex, sourcePort) + + targetNode.pos() + + targetNode.geometry().portScenePosition(targetPortIndex, targetPort)) / + 2.0f; converterNodePos.setX(converterNodePos.x() - newNodeGeom.width() / 2.0f); converterNodePos.setY(converterNodePos.y() - newNodeGeom.height() / 2.0f); return converterNodePos; } - unsigned int -NodeGeometry:: -portWidth(PortType portType) const +NodeGeometry::portWidth(PortType portType) const { unsigned width = 0; - for (auto i = 0ul; i < _nodeIndex.model()->nodePortCount(_nodeIndex, portType); ++i) - { + for (auto i = 0ul; + i < _nodeIndex.model()->nodePortCount(_nodeIndex, portType); + ++i) { QString name = _nodeIndex.model()->nodePortCaption(_nodeIndex, i, portType); - if (name.isEmpty()) - { + if (name.isEmpty()) { name = _nodeIndex.model()->nodePortDataType(_nodeIndex, i, portType).name; } - width = std::max(unsigned(_fontMetrics.width(name)), - width); + width = std::max(unsigned(_fontMetrics.width(name)), width); } return width; diff --git a/src/NodeGraphicsObject.cpp b/src/NodeGraphicsObject.cpp index a9d14cafe..7fbc06cbd 100644 --- a/src/NodeGraphicsObject.cpp +++ b/src/NodeGraphicsObject.cpp @@ -1,10 +1,10 @@ #include "NodeGraphicsObject.hpp" -#include #include +#include -#include #include +#include #include "ConnectionGraphicsObject.hpp" #include "ConnectionState.hpp" @@ -12,28 +12,26 @@ #include "FlowScene.hpp" #include "NodePainter.hpp" -#include "NodeIndex.hpp" #include "FlowSceneModel.hpp" #include "NodeConnectionInteraction.hpp" +#include "NodeIndex.hpp" #include "StyleCollection.hpp" -using QtNodes::NodeGraphicsObject; -using QtNodes::Node; +using QtNodes::ConnectionPolicy; using QtNodes::FlowScene; -using QtNodes::NodeIndex; +using QtNodes::Node; +using QtNodes::NodeDataType; using QtNodes::NodeGeometry; +using QtNodes::NodeGraphicsObject; +using QtNodes::NodeIndex; using QtNodes::NodeState; -using QtNodes::ConnectionPolicy; using QtNodes::PortType; -using QtNodes::NodeDataType; -NodeGraphicsObject:: -NodeGraphicsObject(FlowScene &scene, - NodeIndex const& node) +NodeGraphicsObject::NodeGraphicsObject(FlowScene& scene, NodeIndex const& node) : _scene(scene) , _nodeIndex(node) - , _geometry(node) + , _geometry(node, *this) , _state(node) , _locked(false) , _proxyWidget(nullptr) @@ -46,9 +44,9 @@ NodeGraphicsObject(FlowScene &scene, setFlag(QGraphicsItem::ItemIsSelectable, true); setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); - setCacheMode( QGraphicsItem::DeviceCoordinateCache ); + setCacheMode(QGraphicsItem::DeviceCoordinateCache); - auto const &nodeStyle = flowScene().model()->nodeStyle(index()); + auto const& nodeStyle = flowScene().model()->nodeStyle(index()); { auto effect = new QGraphicsDropShadowEffect; @@ -63,93 +61,81 @@ NodeGraphicsObject(FlowScene &scene, setAcceptHoverEvents(true); - setZValue(0); + setZValue(0.); embedQWidget(); // connect to the move signals auto onMoveSlot = [this] { - // ask the model to move it - if (!flowScene().model()->moveNode(index(), pos())) - { - // set the location back - setPos(flowScene().model()->nodeLocation(index())); - moveConnections(); - } - }; + // ask the model to move it + if (!flowScene().model()->moveNode(index(), pos())) { + // set the location back + setPos(flowScene().model()->nodeLocation(index())); + moveConnections(); + } + }; connect(this, &QGraphicsObject::xChanged, this, onMoveSlot); connect(this, &QGraphicsObject::yChanged, this, onMoveSlot); - } - -NodeGraphicsObject:: -~NodeGraphicsObject() +NodeGraphicsObject::~NodeGraphicsObject() { - if (_proxyWidget) - { + // TODO I think it is dangerous - user have to delete widget if he allocated + // it + if (_proxyWidget) { delete _proxyWidget->widget(); } + // TODO here can be problem, when item have a parent, then parent remove item + // when it will be removed _scene.removeItem(this); } + NodeIndex -NodeGraphicsObject:: -index() const +NodeGraphicsObject::index() const { return _nodeIndex; } - FlowScene& -NodeGraphicsObject:: -flowScene() +NodeGraphicsObject::flowScene() { return _scene; } FlowScene const& -NodeGraphicsObject:: -flowScene() const +NodeGraphicsObject::flowScene() const { return _scene; } NodeGeometry& -NodeGraphicsObject:: -geometry() +NodeGraphicsObject::geometry() { return _geometry; } NodeGeometry const& -NodeGraphicsObject:: -geometry() const +NodeGraphicsObject::geometry() const { return _geometry; } - NodeState& -NodeGraphicsObject:: -nodeState() +NodeGraphicsObject::nodeState() { return _state; } NodeState const& -NodeGraphicsObject:: -nodeState() const +NodeGraphicsObject::nodeState() const { return _state; } void -NodeGraphicsObject:: -embedQWidget() +NodeGraphicsObject::embedQWidget() { - - if (auto w = flowScene().model()->nodeWidget(index())) - { + if (auto w = flowScene().model()->nodeWidget(index())) { _proxyWidget = new QGraphicsProxyWidget(this); _proxyWidget->setWidget(w); @@ -167,49 +153,29 @@ embedQWidget() } } - QRectF -NodeGraphicsObject:: -boundingRect() const +NodeGraphicsObject::boundingRect() const { return geometry().boundingRect(); } - void -NodeGraphicsObject:: -setGeometryChanged() +NodeGraphicsObject::moveConnections() const { - prepareGeometryChange(); -} + for (PortType portType : { PortType::In, PortType::Out }) { + auto const& connectionEntries = nodeState().getEntries(portType); - -void -NodeGraphicsObject:: -moveConnections() const -{ - for(PortType portType: {PortType::In, PortType::Out}) - { - auto const & connectionEntries = - nodeState().getEntries(portType); - - for (auto const & connections : connectionEntries) - { - for (auto & con : connections) + for (auto const& connections : connectionEntries) { + for (auto& con : connections) con->move(); } - } - ; + }; } - - void -NodeGraphicsObject:: -reactToPossibleConnection(PortType reactingPortType, - - NodeDataType reactingDataType, - QPointF const &scenePoint) +NodeGraphicsObject::reactToPossibleConnection(PortType reactingPortType, + NodeDataType reactingDataType, + QPointF const& scenePoint) { QTransform const t = sceneTransform(); @@ -219,23 +185,18 @@ reactToPossibleConnection(PortType reactingPortType, update(); - _state.setReaction(NodeState::REACTING, - reactingPortType, - reactingDataType); + _state.setReaction(NodeState::REACTING, reactingPortType, reactingDataType); } - void -NodeGraphicsObject:: -resetReactionToConnection() +NodeGraphicsObject::resetReactionToConnection() { _state.setReaction(NodeState::NOT_REACTING); update(); } void -NodeGraphicsObject:: -lock(bool locked) +NodeGraphicsObject::lock(bool locked) { _locked = locked; setFlag(QGraphicsItem::ItemIsMovable, !locked); @@ -243,97 +204,97 @@ lock(bool locked) setFlag(QGraphicsItem::ItemIsSelectable, !locked); } - void -NodeGraphicsObject:: -paint(QPainter * painter, - QStyleOptionGraphicsItem const* option, - QWidget* ) +NodeGraphicsObject::paint(QPainter* painter, + QStyleOptionGraphicsItem const* option, + QWidget*) { painter->setClipRect(option->exposedRect); NodePainter::paint(painter, *this); } - QVariant -NodeGraphicsObject:: -itemChange(GraphicsItemChange change, const QVariant &value) +NodeGraphicsObject::itemChange(GraphicsItemChange change, const QVariant& value) { - if (change == ItemPositionChange && scene()) - { + if (change == ItemPositionChange && scene()) { moveConnections(); } return QGraphicsItem::itemChange(change, value); } - void -NodeGraphicsObject:: -mousePressEvent(QGraphicsSceneMouseEvent * event) +NodeGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent* event) { - if(_locked) + if (_locked) return; // deselect all other items after this one is selected - if (!isSelected() && - !(event->modifiers() & Qt::ControlModifier)) - { + if (!isSelected() && !(event->modifiers() & Qt::ControlModifier)) { _scene.clearSelection(); } - for(PortType portToCheck: {PortType::In, PortType::Out}) - { + for (PortType portToCheck : { PortType::In, PortType::Out }) { // TODO do not pass sceneTransform - int portIndex = geometry().checkHitScenePoint(portToCheck, - event->scenePos(), - sceneTransform()); - if (portIndex != INVALID) - { + PortIndex portIndex = geometry().checkHitScenePoint( + portToCheck, event->scenePos(), sceneTransform()); + if (portIndex != INVALID) { std::vector connections = nodeState().connections(portToCheck, portIndex); // start dragging existing connection if (!connections.empty() && - flowScene().model()->nodePortConnectionPolicy(index(), portIndex, portToCheck) == ConnectionPolicy::One) - { + flowScene().model()->nodePortConnectionPolicy( + index(), portIndex, portToCheck) == ConnectionPolicy::One) { Q_ASSERT(connections.size() == 1); auto con = *connections.begin(); - // remove it - flowScene().model()->removeConnection( - con->node(PortType::Out), - con->portIndex(PortType::Out), - con->node(PortType::In), - con->portIndex(PortType::In)); - - // start connecting anew, except start with the port that this connection was already connected to + // start connecting anew, except start with the port that this + // connection was already connected to Q_ASSERT(_scene._temporaryConn == nullptr); - if (portToCheck == PortType::In) - { - _scene._temporaryConn = new ConnectionGraphicsObject(con->node(PortType::Out), con->portIndex(PortType::Out), NodeIndex{}, -1, _scene); - _scene._temporaryConn->geometry().setEndPoint(PortType::In, event->scenePos()); - } - else { - _scene._temporaryConn = new ConnectionGraphicsObject(NodeIndex{}, -1, con->node(PortType::In), con->portIndex(PortType::In), _scene); - _scene._temporaryConn->geometry().setEndPoint(PortType::Out, event->scenePos()); + if (portToCheck == PortType::In) { + _scene._temporaryConn = + new ConnectionGraphicsObject(con->node(PortType::Out), + con->portIndex(PortType::Out), + NodeIndex{}, + INVALID, + _scene); + _scene._temporaryConn->geometry().setEndPoint(PortType::In, + event->scenePos()); + } else { + _scene._temporaryConn = + new ConnectionGraphicsObject(NodeIndex{}, + INVALID, + con->node(PortType::In), + con->portIndex(PortType::In), + _scene); + _scene._temporaryConn->geometry().setEndPoint(PortType::Out, + event->scenePos()); } _scene._temporaryConn->grabMouse(); - } - else // initialize new Connection + + // remove it + flowScene().model()->removeConnection(con->node(PortType::Out), + con->portIndex(PortType::Out), + con->node(PortType::In), + con->portIndex(PortType::In)); + + } else // initialize new Connection { - if (portToCheck == PortType::In) - { + if (portToCheck == PortType::In) { Q_ASSERT(_scene._temporaryConn == nullptr); - _scene._temporaryConn = new ConnectionGraphicsObject(NodeIndex{}, -1, _nodeIndex, portIndex, _scene); - _scene._temporaryConn->geometry().setEndPoint(PortType::Out, event->scenePos()); - } - else { + _scene._temporaryConn = new ConnectionGraphicsObject( + NodeIndex{}, INVALID, _nodeIndex, portIndex, _scene); + _scene._temporaryConn->geometry().setEndPoint(PortType::Out, + event->scenePos()); + } else { Q_ASSERT(_scene._temporaryConn == nullptr); - _scene._temporaryConn = new ConnectionGraphicsObject(_nodeIndex, portIndex, NodeIndex{}, -1, _scene); - _scene._temporaryConn->geometry().setEndPoint(PortType::In, event->scenePos()); + _scene._temporaryConn = new ConnectionGraphicsObject( + _nodeIndex, portIndex, NodeIndex{}, INVALID, _scene); + _scene._temporaryConn->geometry().setEndPoint(PortType::In, + event->scenePos()); } _scene._temporaryConn->grabMouse(); @@ -344,46 +305,36 @@ mousePressEvent(QGraphicsSceneMouseEvent * event) auto pos = event->pos(); if (flowScene().model()->nodeResizable(index()) && - geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) - { + geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) { nodeState().setResizing(true); } } - void -NodeGraphicsObject:: -mouseMoveEvent(QGraphicsSceneMouseEvent * event) +NodeGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { - - if (nodeState().resizing()) - { + if (nodeState().resizing()) { auto diff = event->pos() - event->lastPos(); - if (auto w = flowScene().model()->nodeWidget(index())) - { - prepareGeometryChange(); - + if (auto w = flowScene().model()->nodeWidget(index())) { auto oldSize = w->size(); oldSize += QSize(diff.x(), diff.y()); w->setFixedSize(oldSize); + // We have to recalculdate size before set widgetPosition in proxyWidget + geometry().recalculateSize(); + _proxyWidget->setMinimumSize(oldSize); _proxyWidget->setMaximumSize(oldSize); _proxyWidget->setPos(geometry().widgetPosition()); - geometry().recalculateSize(); - update(); - moveConnections(); event->accept(); } - } - else - { + } else { QGraphicsObject::mouseMoveEvent(event); if (event->lastPos() != event->pos()) @@ -392,17 +343,14 @@ mouseMoveEvent(QGraphicsSceneMouseEvent * event) event->ignore(); } - QRectF r = scene()->sceneRect(); - - r = r.united(mapToScene(boundingRect()).boundingRect()); - - scene()->setSceneRect(r); + // TODO I think we have to set scene rect not here, but in view + // QRectF r = scene()->sceneRect(); + // r = r.united(mapToScene(boundingRect()).boundingRect()); + // scene()->setSceneRect(r); } - void -NodeGraphicsObject:: -mouseReleaseEvent(QGraphicsSceneMouseEvent* event) +NodeGraphicsObject::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { nodeState().setResizing(false); @@ -412,18 +360,14 @@ mouseReleaseEvent(QGraphicsSceneMouseEvent* event) moveConnections(); } - void -NodeGraphicsObject:: -hoverEnterEvent(QGraphicsSceneHoverEvent * event) +NodeGraphicsObject::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { // bring all the colliding nodes to background - QList overlapItems = collidingItems(); + QList overlapItems = collidingItems(); - for (QGraphicsItem *item : overlapItems) - { - if (item->zValue() > 0.0) - { + for (QGraphicsItem* item : overlapItems) { + if (item->zValue() > 0.0) { item->setZValue(0.0); } } @@ -436,10 +380,8 @@ hoverEnterEvent(QGraphicsSceneHoverEvent * event) event->accept(); } - void -NodeGraphicsObject:: -hoverLeaveEvent(QGraphicsSceneHoverEvent * event) +NodeGraphicsObject::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { geometry().setHovered(false); update(); @@ -448,28 +390,22 @@ hoverLeaveEvent(QGraphicsSceneHoverEvent * event) } void -NodeGraphicsObject:: -hoverMoveEvent(QGraphicsSceneHoverEvent * event) +NodeGraphicsObject::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { auto pos = event->pos(); if (flowScene().model()->nodeResizable(index()) && - geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) - { + geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) { setCursor(QCursor(Qt::SizeFDiagCursor)); - } - else - { + } else { setCursor(QCursor()); } event->accept(); } - void -NodeGraphicsObject:: -mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) +NodeGraphicsObject::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { QGraphicsItem::mouseDoubleClickEvent(event); @@ -477,8 +413,7 @@ mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) } void -NodeGraphicsObject:: -contextMenuEvent(QGraphicsSceneContextMenuEvent* event) +NodeGraphicsObject::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) { QGraphicsItem::contextMenuEvent(event); diff --git a/src/NodePainter.cpp b/src/NodePainter.cpp index 5de3d0b14..8d0cb2012 100644 --- a/src/NodePainter.cpp +++ b/src/NodePainter.cpp @@ -4,27 +4,25 @@ #include -#include "StyleCollection.hpp" -#include "PortType.hpp" -#include "NodeGraphicsObject.hpp" +#include "FlowScene.hpp" +#include "FlowSceneModel.hpp" #include "NodeGeometry.hpp" -#include "NodeState.hpp" +#include "NodeGraphicsObject.hpp" #include "NodeIndex.hpp" -#include "FlowSceneModel.hpp" #include "NodePainterDelegate.hpp" -#include "FlowScene.hpp" +#include "NodeState.hpp" +#include "PortType.hpp" +#include "StyleCollection.hpp" -using QtNodes::NodePainter; -using QtNodes::NodeIndex; +using QtNodes::ConnectionPolicy; using QtNodes::NodeGeometry; using QtNodes::NodeGraphicsObject; +using QtNodes::NodeIndex; +using QtNodes::NodePainter; using QtNodes::NodeState; -using QtNodes::ConnectionPolicy; void -NodePainter:: -paint(QPainter* painter, - NodeGraphicsObject const & graphicsObject) +NodePainter::paint(QPainter* painter, NodeGraphicsObject const& graphicsObject) { NodeGeometry const& geom = graphicsObject.geometry(); @@ -47,38 +45,34 @@ paint(QPainter* painter, drawValidationRect(painter, graphicsObject); /// call custom painter - if (auto painterDelegate = graphicsObject.index().model()->nodePainterDelegate(graphicsObject.index())) - { - painterDelegate->paint(painter, graphicsObject.geometry(), graphicsObject.index()); + if (auto painterDelegate = + graphicsObject.index().model()->nodePainterDelegate( + graphicsObject.index())) { + painterDelegate->paint( + painter, graphicsObject.geometry(), graphicsObject.index()); } } - void -NodePainter:: -drawNodeRect(QPainter* painter, NodeGraphicsObject const & graphicsObject) +NodePainter::drawNodeRect(QPainter* painter, + NodeGraphicsObject const& graphicsObject) { - FlowSceneModel& model = *graphicsObject.flowScene().model(); + FlowSceneModel& model = *graphicsObject.flowScene().model(); NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); - NodeGeometry const& geom = graphicsObject.geometry(); + NodeGeometry const& geom = graphicsObject.geometry(); - auto color = graphicsObject.isSelected() - ? nodeStyle.SelectedBoundaryColor - : nodeStyle.NormalBoundaryColor; + auto color = graphicsObject.isSelected() ? nodeStyle.SelectedBoundaryColor + : nodeStyle.NormalBoundaryColor; - if (geom.hovered()) - { + if (geom.hovered()) { QPen p(color, nodeStyle.HoveredPenWidth); painter->setPen(p); - } - else - { + } else { QPen p(color, nodeStyle.PenWidth); painter->setPen(p); } - QLinearGradient gradient(QPointF(0.0, 0.0), - QPointF(2.0, geom.height())); + QLinearGradient gradient(QPointF(0.0, 0.0), QPointF(2.0, geom.height())); gradient.setColorAt(0.0, nodeStyle.GradientColor0); gradient.setColorAt(0.03, nodeStyle.GradientColor1); @@ -89,154 +83,129 @@ drawNodeRect(QPainter* painter, NodeGraphicsObject const & graphicsObject) float diam = nodeStyle.ConnectionPointDiameter; - QRectF boundary( -diam, -diam, 2.0 * diam + geom.width(), 2.0 * diam + geom.height()); + QRectF boundary( + -diam, -diam, 2.0 * diam + geom.width(), 2.0 * diam + geom.height()); double const radius = 3.0; painter->drawRoundedRect(boundary, radius, radius); } - void -NodePainter:: -drawConnectionPoints(QPainter* painter, NodeGraphicsObject const & graphicsObject) +NodePainter::drawConnectionPoints(QPainter* painter, + NodeGraphicsObject const& graphicsObject) { - const FlowSceneModel& model = *graphicsObject.flowScene().model(); - NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); - auto const &connectionStyle = StyleCollection::connectionStyle(); - NodeState const& state = graphicsObject.nodeState(); - NodeGeometry const& geom = graphicsObject.geometry(); + const FlowSceneModel& model = *graphicsObject.flowScene().model(); + NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); + auto const& connectionStyle = StyleCollection::connectionStyle(); + NodeState const& state = graphicsObject.nodeState(); + NodeGeometry const& geom = graphicsObject.geometry(); - float diameter = nodeStyle.ConnectionPointDiameter; + float diameter = nodeStyle.ConnectionPointDiameter; auto reducedDiameter = diameter * 0.6; - for(PortType portType: {PortType::Out, PortType::In}) - { + for (PortType portType : { PortType::Out, PortType::In }) { size_t n = state.getEntries(portType).size(); - for (unsigned int i = 0; i < n; ++i) - { + for (unsigned int i = 0; i < n; ++i) { QPointF p = geom.portScenePosition(i, portType); - auto const & dataType = model.nodePortDataType(graphicsObject.index(), i, portType); + auto const& dataType = + model.nodePortDataType(graphicsObject.index(), i, portType); bool canConnect = (state.getEntries(portType)[i].empty() || (portType == PortType::Out && - model.nodePortConnectionPolicy(graphicsObject.index(), i, PortType::Out) == ConnectionPolicy::Many) ); + model.nodePortConnectionPolicy( + graphicsObject.index(), i, PortType::Out) == + ConnectionPolicy::Many)); double r = 1.0; - if (state.isReacting() && - canConnect && - portType == state.reactingPortType()) - { + if (state.isReacting() && canConnect && + portType == state.reactingPortType()) { - auto diff = geom.draggingPos() - p; - double dist = std::sqrt(QPointF::dotProduct(diff, diff)); + auto diff = geom.draggingPos() - p; + double dist = std::sqrt(QPointF::dotProduct(diff, diff)); bool typeConvertable = false; { - if (portType == PortType::In) - { - typeConvertable = model.getTypeConvertable({state.reactingDataType(), dataType}); - } - else - { - typeConvertable = model.getTypeConvertable({dataType, state.reactingDataType()}); + if (portType == PortType::In) { + typeConvertable = + model.getTypeConvertable({ state.reactingDataType(), dataType }); + } else { + typeConvertable = + model.getTypeConvertable({ dataType, state.reactingDataType() }); } } - if (state.reactingDataType().id == dataType.id || typeConvertable) - { + if (state.reactingDataType().id == dataType.id || typeConvertable) { double const thres = 40.0; - r = (dist < thres) ? - (2.0 - dist / thres ) : - 1.0; - } - else - { + r = (dist < thres) ? (2.0 - dist / thres) : 1.0; + } else { double const thres = 80.0; - r = (dist < thres) ? - (dist / thres) : - 1.0; + r = (dist < thres) ? (dist / thres) : 1.0; } } - if (connectionStyle.useDataDefinedColors()) - { + if (connectionStyle.useDataDefinedColors()) { painter->setBrush(connectionStyle.normalColor(dataType.id)); - } - else - { + } else { painter->setBrush(nodeStyle.ConnectionPointColor); } - painter->drawEllipse(p, - reducedDiameter * r, - reducedDiameter * r); + painter->drawEllipse(p, reducedDiameter * r, reducedDiameter * r); } - } - ; + }; } - void -NodePainter:: -drawFilledConnectionPoints(QPainter * painter, NodeGraphicsObject const & graphicsObject) +NodePainter::drawFilledConnectionPoints( + QPainter* painter, + NodeGraphicsObject const& graphicsObject) { - FlowSceneModel const& model = *graphicsObject.index().model(); - NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); - auto const& connectionStyle = StyleCollection::connectionStyle(); - NodeState const& state = graphicsObject.nodeState(); - NodeGeometry const& geom = graphicsObject.geometry(); + FlowSceneModel const& model = *graphicsObject.index().model(); + NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); + auto const& connectionStyle = StyleCollection::connectionStyle(); + NodeState const& state = graphicsObject.nodeState(); + NodeGeometry const& geom = graphicsObject.geometry(); auto diameter = nodeStyle.ConnectionPointDiameter; - for(PortType portType: {PortType::Out, PortType::In}) - { + for (PortType portType : { PortType::Out, PortType::In }) { size_t n = state.getEntries(portType).size(); - for (size_t i = 0; i < n; ++i) - { + for (size_t i = 0; i < n; ++i) { QPointF p = geom.portScenePosition(i, portType); - if (!state.getEntries(portType)[i].empty()) - { - auto const & dataType = model.nodePortDataType(graphicsObject.index(), i, portType); + if (!state.getEntries(portType)[i].empty()) { + auto const& dataType = + model.nodePortDataType(graphicsObject.index(), i, portType); - if (connectionStyle.useDataDefinedColors()) - { + if (connectionStyle.useDataDefinedColors()) { QColor const c = connectionStyle.normalColor(dataType.id); painter->setPen(c); painter->setBrush(c); - } - else - { + } else { painter->setPen(nodeStyle.FilledConnectionPointColor); painter->setBrush(nodeStyle.FilledConnectionPointColor); } - painter->drawEllipse(p, - diameter * 0.4, - diameter * 0.4); + painter->drawEllipse(p, diameter * 0.4, diameter * 0.4); } } } } - void -NodePainter:: -drawModelName(QPainter * painter, NodeGraphicsObject const & graphicsObject) +NodePainter::drawModelName(QPainter* painter, + NodeGraphicsObject const& graphicsObject) { - FlowSceneModel const& model = *graphicsObject.index().model(); - NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); - NodeGeometry const& geom = graphicsObject.geometry(); + NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); + NodeGeometry const& geom = graphicsObject.geometry(); - QString const &name = model.nodeCaption(graphicsObject.index()); + QString const& name = model.nodeCaption(graphicsObject.index()); - if (name.isEmpty()) - { + if (name.isEmpty()) { return; } @@ -245,9 +214,7 @@ drawModelName(QPainter * painter, NodeGraphicsObject const & graphicsObject) f.setBold(true); QFontMetrics metrics(f); - auto rect = metrics.boundingRect(name); - QPointF position((geom.width() - rect.width()) / 2.0, (geom.spacing() + geom.entryHeight()) / 3.0); @@ -259,27 +226,23 @@ drawModelName(QPainter * painter, NodeGraphicsObject const & graphicsObject) painter->setFont(f); } - void -NodePainter:: -drawEntryLabels(QPainter * painter, NodeGraphicsObject const & graphicsObject) +NodePainter::drawEntryLabels(QPainter* painter, + NodeGraphicsObject const& graphicsObject) { - NodeState const& state = graphicsObject.nodeState(); - NodeGeometry const& geom = graphicsObject.geometry(); - FlowSceneModel const& model = *graphicsObject.index().model(); - QFontMetrics const & metrics = - painter->fontMetrics(); + NodeState const& state = graphicsObject.nodeState(); + NodeGeometry const& geom = graphicsObject.geometry(); + FlowSceneModel const& model = *graphicsObject.index().model(); + QFontMetrics const& metrics = painter->fontMetrics(); - for(PortType portType: {PortType::Out, PortType::In}) - { - auto const &nodeStyle = model.nodeStyle(graphicsObject.index()); + for (PortType portType : { PortType::Out, PortType::In }) { + auto const& nodeStyle = model.nodeStyle(graphicsObject.index()); auto& entries = state.getEntries(portType); size_t n = entries.size(); - for (size_t i = 0; i < n; ++i) - { + for (size_t i = 0; i < n; ++i) { QPointF p = geom.portScenePosition(i, portType); if (entries[i].empty()) @@ -289,8 +252,7 @@ drawEntryLabels(QPainter * painter, NodeGraphicsObject const & graphicsObject) QString s = model.nodePortCaption(graphicsObject.index(), i, portType); - if (s.isEmpty()) - { + if (s.isEmpty()) { s = model.nodePortDataType(graphicsObject.index(), i, portType).name; } @@ -298,8 +260,7 @@ drawEntryLabels(QPainter * painter, NodeGraphicsObject const & graphicsObject) p.setY(p.y() + rect.height() / 4.0); - switch (portType) - { + switch (portType) { case PortType::In: p.setX(5.0); break; @@ -317,58 +278,46 @@ drawEntryLabels(QPainter * painter, NodeGraphicsObject const & graphicsObject) } } - void -NodePainter:: -drawResizeRect(QPainter * painter, - NodeGraphicsObject const & graphicsObject) +NodePainter::drawResizeRect(QPainter* painter, + NodeGraphicsObject const& graphicsObject) { FlowSceneModel const& model = *graphicsObject.index().model(); - if (model.nodeResizable(graphicsObject.index())) - { + if (model.nodeResizable(graphicsObject.index())) { painter->setBrush(Qt::gray); painter->drawEllipse(graphicsObject.geometry().resizeRect()); } } - void -NodePainter:: -drawValidationRect(QPainter * painter, NodeGraphicsObject const & graphicsObject) +NodePainter::drawValidationRect(QPainter* painter, + NodeGraphicsObject const& graphicsObject) { FlowSceneModel const& model = *graphicsObject.index().model(); - NodeGeometry const& geom = graphicsObject.geometry(); + NodeGeometry const& geom = graphicsObject.geometry(); auto modelValidationState = model.nodeValidationState(graphicsObject.index()); - if (modelValidationState != NodeValidationState::Valid) - { + if (modelValidationState != NodeValidationState::Valid) { NodeStyle const& nodeStyle = model.nodeStyle(graphicsObject.index()); - auto color = graphicsObject.isSelected() - ? nodeStyle.SelectedBoundaryColor - : nodeStyle.NormalBoundaryColor; + auto color = graphicsObject.isSelected() ? nodeStyle.SelectedBoundaryColor + : nodeStyle.NormalBoundaryColor; - if (geom.hovered()) - { + if (geom.hovered()) { QPen p(color, nodeStyle.HoveredPenWidth); painter->setPen(p); - } - else - { + } else { QPen p(color, nodeStyle.PenWidth); painter->setPen(p); } - //Drawing the validation message background - if (modelValidationState == NodeValidationState::Error) - { + // Drawing the validation message background + if (modelValidationState == NodeValidationState::Error) { painter->setBrush(nodeStyle.ErrorColor); - } - else - { + } else { painter->setBrush(nodeStyle.WarningColor); } @@ -385,8 +334,9 @@ drawValidationRect(QPainter * painter, NodeGraphicsObject const & graphicsObject painter->setBrush(Qt::gray); - //Drawing the validation message itself - QString const &errorMsg = model.nodeValidationMessage(graphicsObject.index()); + // Drawing the validation message itself + QString const& errorMsg = + model.nodeValidationMessage(graphicsObject.index()); QFont f = painter->font(); diff --git a/src/NodePainter.hpp b/src/NodePainter.hpp index 7c47348e5..05d01c127 100644 --- a/src/NodePainter.hpp +++ b/src/NodePainter.hpp @@ -2,8 +2,7 @@ #include -namespace QtNodes -{ +namespace QtNodes { class NodeState; class NodeGeometry; @@ -14,49 +13,32 @@ class FlowScene; class NodePainter { public: - NodePainter(); public: + static void paint(QPainter* painter, + NodeGraphicsObject const& graphicsObject); + + static void drawNodeRect(QPainter* painter, + NodeGraphicsObject const& graphicsObject); + + static void drawModelName(QPainter* painter, + NodeGraphicsObject const& graphicsObject); + + static void drawEntryLabels(QPainter* painter, + NodeGraphicsObject const& graphicsObject); + + static void drawConnectionPoints(QPainter* painter, + NodeGraphicsObject const& graphicsObject); + + static void drawFilledConnectionPoints( + QPainter* painter, + NodeGraphicsObject const& graphicsObject); + + static void drawResizeRect(QPainter* painter, + NodeGraphicsObject const& graphicsObject); - static - void - paint(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawNodeRect(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawModelName(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawEntryLabels(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawConnectionPoints(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawFilledConnectionPoints(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawResizeRect(QPainter* painter, - NodeGraphicsObject const & graphicsObject); - - static - void - drawValidationRect(QPainter * painter, - NodeGraphicsObject const & graphicsObject); + static void drawValidationRect(QPainter* painter, + NodeGraphicsObject const& graphicsObject); }; } diff --git a/src/NodeState.cpp b/src/NodeState.cpp index 7846c0618..2be86f928 100644 --- a/src/NodeState.cpp +++ b/src/NodeState.cpp @@ -1,23 +1,22 @@ #include "NodeState.hpp" +#include "FlowSceneModel.hpp" #include "NodeDataModel.hpp" #include "NodeIndex.hpp" -#include "FlowSceneModel.hpp" #include "QUuidStdHash.hpp" #include "Connection.hpp" -using QtNodes::NodeState; -using QtNodes::NodeDataType; -using QtNodes::NodeDataModel; -using QtNodes::PortType; -using QtNodes::PortIndex; using QtNodes::Connection; -using QtNodes::NodeIndex; using QtNodes::ConnectionGraphicsObject; +using QtNodes::NodeDataModel; +using QtNodes::NodeDataType; +using QtNodes::NodeIndex; +using QtNodes::NodeState; +using QtNodes::PortIndex; +using QtNodes::PortType; -NodeState:: -NodeState(NodeIndex const &index) +NodeState::NodeState(NodeIndex const& index) : _inConnections(index.model()->nodePortCount(index, PortType::In)) , _outConnections(index.model()->nodePortCount(index, PortType::Out)) , _reaction(NOT_REACTING) @@ -25,10 +24,8 @@ NodeState(NodeIndex const &index) , _resizing(false) {} - -std::vector const & -NodeState:: -getEntries(PortType portType) const +std::vector const& +NodeState::getEntries(PortType portType) const { if (portType == PortType::In) return _inConnections; @@ -36,10 +33,8 @@ getEntries(PortType portType) const return _outConnections; } - -std::vector & -NodeState:: -getEntries(PortType portType) +std::vector& +NodeState::getEntries(PortType portType) { if (portType == PortType::In) return _inConnections; @@ -47,74 +42,58 @@ getEntries(PortType portType) return _outConnections; } - NodeState::ConnectionPtrVec -NodeState:: -connections(PortType portType, PortIndex portIndex) const +NodeState::connections(PortType portType, PortIndex portIndex) const { - auto const &connections = getEntries(portType); + auto const& connections = getEntries(portType); return connections[portIndex]; } - void -NodeState:: -setConnection(PortType portType, - PortIndex portIndex, - ConnectionGraphicsObject& connection) +NodeState::setConnection(PortType portType, + PortIndex portIndex, + ConnectionGraphicsObject& connection) { - auto &connections = getEntries(portType); + auto& connections = getEntries(portType); connections[portIndex].push_back(&connection); } - void -NodeState:: -eraseConnection(PortType portType, - PortIndex portIndex, - ConnectionGraphicsObject& conn) +NodeState::eraseConnection(PortType portType, + PortIndex portIndex, + ConnectionGraphicsObject& conn) { auto& ptrSet = getEntries(portType)[portIndex]; - auto iter = std::find(ptrSet.begin(), ptrSet.end(), &conn); - if (iter != ptrSet.end()) - { + auto iter = std::find(ptrSet.begin(), ptrSet.end(), &conn); + if (iter != ptrSet.end()) { ptrSet.erase(iter); } - } - NodeState::ReactToConnectionState -NodeState:: -reaction() const +NodeState::reaction() const { return _reaction; } - PortType -NodeState:: -reactingPortType() const +NodeState::reactingPortType() const { return _reactingPortType; } - NodeDataType -NodeState:: -reactingDataType() const +NodeState::reactingDataType() const { return _reactingDataType; } - void -NodeState:: -setReaction(ReactToConnectionState reaction, - PortType reactingPortType, - NodeDataType reactingDataType) +NodeState::setReaction(ReactToConnectionState reaction, + PortType reactingPortType, + NodeDataType reactingDataType) { _reaction = reaction; @@ -123,26 +102,20 @@ setReaction(ReactToConnectionState reaction, _reactingDataType = std::move(reactingDataType); } - bool -NodeState:: -isReacting() const +NodeState::isReacting() const { return _reaction == REACTING; } - void -NodeState:: -setResizing(bool resizing) +NodeState::setResizing(bool resizing) { _resizing = resizing; } - bool -NodeState:: -resizing() const +NodeState::resizing() const { return _resizing; } diff --git a/src/NodeStyle.cpp b/src/NodeStyle.cpp index 8af22a183..9d6b04b25 100644 --- a/src/NodeStyle.cpp +++ b/src/NodeStyle.cpp @@ -3,10 +3,10 @@ #include #include +#include #include #include #include -#include #include @@ -15,77 +15,75 @@ using QtNodes::NodeStyle; inline void -initResources() { Q_INIT_RESOURCE(resources); } +initResources() +{ + Q_INIT_RESOURCE(resources); +} -NodeStyle:: -NodeStyle() +NodeStyle::NodeStyle() { // Explicit resources inialization for preventing the static initialization // order fiasco: https://isocpp.org/wiki/faq/ctors#static-init-order initResources(); - // This configuration is stored inside the compiled unit and is loaded statically + // This configuration is stored inside the compiled unit and is loaded + // statically loadJsonFile(":DefaultStyle.json"); } - -NodeStyle:: -NodeStyle(QString jsonText) +NodeStyle::NodeStyle(QString jsonText) { loadJsonText(jsonText); } - void -NodeStyle:: -setNodeStyle(QString jsonText) +NodeStyle::setNodeStyle(QString jsonText) { NodeStyle style(jsonText); - StyleCollection::setNodeStyle(style); } - #ifdef STYLE_DEBUG - #define NODE_STYLE_CHECK_UNDEFINED_VALUE(v, variable) { \ - if (v.type() == QJsonValue::Undefined || \ - v.type() == QJsonValue::Null) \ - qWarning() << "Undefined value for parameter:" << #variable; \ -} +#define NODE_STYLE_CHECK_UNDEFINED_VALUE(v, variable) \ + { \ + if (v.type() == QJsonValue::Undefined || v.type() == QJsonValue::Null) \ + qWarning() << "Undefined value for parameter:" << #variable; \ + } #else - #define NODE_STYLE_CHECK_UNDEFINED_VALUE(v, variable) +#define NODE_STYLE_CHECK_UNDEFINED_VALUE(v, variable) #endif -#define NODE_STYLE_READ_COLOR(values, variable) { \ - auto valueRef = values[#variable]; \ - NODE_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ - if (valueRef.isArray()) { \ - auto colorArray = valueRef.toArray(); \ - std::vector rgb; rgb.reserve(3); \ - for (auto it = colorArray.begin(); it != colorArray.end(); ++it) { \ - rgb.push_back((*it).toInt()); \ - } \ - variable = QColor(rgb[0], rgb[1], rgb[2]); \ - } else { \ - variable = QColor(valueRef.toString()); \ - } \ -} +#define NODE_STYLE_READ_COLOR(values, variable) \ + { \ + auto valueRef = values[#variable]; \ + NODE_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ + if (valueRef.isArray()) { \ + auto colorArray = valueRef.toArray(); \ + std::vector rgb; \ + rgb.reserve(3); \ + for (auto it = colorArray.begin(); it != colorArray.end(); ++it) { \ + rgb.push_back((*it).toInt()); \ + } \ + variable = QColor(rgb[0], rgb[1], rgb[2]); \ + } else { \ + variable = QColor(valueRef.toString()); \ + } \ + } -#define NODE_STYLE_READ_FLOAT(values, variable) { \ - auto valueRef = values[#variable]; \ - NODE_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ - variable = valueRef.toDouble(); \ -} +#define NODE_STYLE_READ_FLOAT(values, variable) \ + { \ + auto valueRef = values[#variable]; \ + NODE_STYLE_CHECK_UNDEFINED_VALUE(valueRef, variable) \ + variable = valueRef.toDouble(); \ + } void -NodeStyle:: -loadJsonFile(QString styleFile) +NodeStyle::loadJsonFile(QString styleFile) { QFile file(styleFile); - if (!file.open(QIODevice::ReadOnly)) - { + if (!file.open(QIODevice::ReadOnly)) { qWarning() << "Couldn't open file " << styleFile; return; @@ -94,18 +92,14 @@ loadJsonFile(QString styleFile) loadJsonFromByteArray(file.readAll()); } - void -NodeStyle:: -loadJsonText(QString jsonText) +NodeStyle::loadJsonText(QString jsonText) { loadJsonFromByteArray(jsonText.toUtf8()); } - void -NodeStyle:: -loadJsonFromByteArray(QByteArray const &byteArray) +NodeStyle::loadJsonFromByteArray(QByteArray const& byteArray) { QJsonDocument json(QJsonDocument::fromJson(byteArray)); diff --git a/src/Properties.cpp b/src/Properties.cpp index 422e6aa10..71498f140 100644 --- a/src/Properties.cpp +++ b/src/Properties.cpp @@ -3,10 +3,7 @@ using QtNodes::Properties; void -Properties:: -put(QString const &name, QVariant const &v) +Properties::put(QString const& name, QVariant const& v) { _values.insert(name, v); } - - diff --git a/src/Properties.hpp b/src/Properties.hpp index 35bb95e27..1f781a22d 100644 --- a/src/Properties.hpp +++ b/src/Properties.hpp @@ -6,24 +6,19 @@ #include "Export.hpp" -namespace QtNodes -{ +namespace QtNodes { class NODE_EDITOR_PUBLIC Properties { public: + void put(QString const& name, QVariant const& v); - void - put(QString const &name, QVariant const &v); - - template - bool - get(QString name, T* v) const + template + bool get(QString name, T* v) const { - QVariant const &var = _values[name]; + QVariant const& var = _values[name]; - if (var.canConvert()) - { + if (var.canConvert()) { *v = _values[name].value(); return true; @@ -32,16 +27,11 @@ class NODE_EDITOR_PUBLIC Properties return false; } - QVariantMap const & - values() const - { return _values; } + QVariantMap const& values() const { return _values; } - QVariantMap & - values() - { return _values; } + QVariantMap& values() { return _values; } private: - QVariantMap _values; }; } diff --git a/src/StyleCollection.cpp b/src/StyleCollection.cpp index 3f1d3d628..f9ffdc42f 100644 --- a/src/StyleCollection.cpp +++ b/src/StyleCollection.cpp @@ -1,62 +1,48 @@ #include "StyleCollection.hpp" -using QtNodes::StyleCollection; -using QtNodes::NodeStyle; using QtNodes::ConnectionStyle; using QtNodes::FlowViewStyle; +using QtNodes::NodeStyle; +using QtNodes::StyleCollection; NodeStyle const& -StyleCollection:: -nodeStyle() +StyleCollection::nodeStyle() { return instance()._nodeStyle; } - ConnectionStyle const& -StyleCollection:: -connectionStyle() +StyleCollection::connectionStyle() { return instance()._connectionStyle; } - FlowViewStyle const& -StyleCollection:: -flowViewStyle() +StyleCollection::flowViewStyle() { return instance()._flowViewStyle; } - void -StyleCollection:: -setNodeStyle(NodeStyle nodeStyle) +StyleCollection::setNodeStyle(NodeStyle nodeStyle) { instance()._nodeStyle = nodeStyle; } - void -StyleCollection:: -setConnectionStyle(ConnectionStyle connectionStyle) +StyleCollection::setConnectionStyle(ConnectionStyle connectionStyle) { instance()._connectionStyle = connectionStyle; } - void -StyleCollection:: -setFlowViewStyle(FlowViewStyle flowViewStyle) +StyleCollection::setFlowViewStyle(FlowViewStyle flowViewStyle) { instance()._flowViewStyle = flowViewStyle; } - - StyleCollection& -StyleCollection:: -instance() +StyleCollection::instance() { static StyleCollection collection; diff --git a/src/StyleCollection.hpp b/src/StyleCollection.hpp index 71eb29024..d5cabffe7 100644 --- a/src/StyleCollection.hpp +++ b/src/StyleCollection.hpp @@ -1,57 +1,37 @@ #pragma once -#include "NodeStyle.hpp" #include "ConnectionStyle.hpp" #include "FlowViewStyle.hpp" +#include "NodeStyle.hpp" -namespace QtNodes -{ +namespace QtNodes { class StyleCollection { public: + static NodeStyle const& nodeStyle(); - static - NodeStyle const& - nodeStyle(); - - static - ConnectionStyle const& - connectionStyle(); + static ConnectionStyle const& connectionStyle(); - static - FlowViewStyle const& - flowViewStyle(); + static FlowViewStyle const& flowViewStyle(); public: + static void setNodeStyle(NodeStyle); - static - void - setNodeStyle(NodeStyle); + static void setConnectionStyle(ConnectionStyle); - static - void - setConnectionStyle(ConnectionStyle); - - static - void - setFlowViewStyle(FlowViewStyle); + static void setFlowViewStyle(FlowViewStyle); private: - StyleCollection() = default; StyleCollection(StyleCollection const&) = delete; - StyleCollection& - operator=(StyleCollection const&) = delete; + StyleCollection& operator=(StyleCollection const&) = delete; - static - StyleCollection& - instance(); + static StyleCollection& instance(); private: - NodeStyle _nodeStyle; ConnectionStyle _connectionStyle; diff --git a/test/include/ApplicationSetup.hpp b/test/include/ApplicationSetup.hpp index 9e94928cf..bbb5e83ee 100644 --- a/test/include/ApplicationSetup.hpp +++ b/test/include/ApplicationSetup.hpp @@ -4,14 +4,13 @@ #include - inline std::unique_ptr applicationSetup() { - static int Argc = 0; - static char ArgvVal = '\0'; - static char* ArgvValPtr = &ArgvVal; - static char** Argv = &ArgvValPtr; + static int Argc = 0; + static char ArgvVal = '\0'; + static char* ArgvValPtr = &ArgvVal; + static char** Argv = &ArgvValPtr; auto app = std::make_unique(Argc, Argv); app->setAttribute(Qt::AA_Use96Dpi, true); diff --git a/test/include/Stringify.hpp b/test/include/Stringify.hpp index 39e87fab6..6fadc08fe 100644 --- a/test/include/Stringify.hpp +++ b/test/include/Stringify.hpp @@ -7,23 +7,20 @@ #include -namespace Catch -{ -template <> +namespace Catch { +template<> struct StringMaker { - static std::string - convert(QPointF const& p) + static std::string convert(QPointF const& p) { return std::string(QTest::toString(p)); } }; -template <> +template<> struct StringMaker { - static std::string - convert(QPoint const& p) + static std::string convert(QPoint const& p) { return std::string(QTest::toString(p)); } diff --git a/test/include/StubNodeDataModel.hpp b/test/include/StubNodeDataModel.hpp index b10b18e29..7d79877bd 100644 --- a/test/include/StubNodeDataModel.hpp +++ b/test/include/StubNodeDataModel.hpp @@ -7,57 +7,34 @@ class StubNodeDataModel : public QtNodes::NodeDataModel { public: - QString - name() const override - { - return _name; - } + QString name() const override { return _name; } - QString - caption() const override - { - return _caption; - } + QString caption() const override { return _caption; } - unsigned int - nPorts(QtNodes::PortType) const override { return 0; } + unsigned int nPorts(QtNodes::PortType) const override { return 0; } - QWidget* - embeddedWidget() override - { - return nullptr; - } + QWidget* embeddedWidget() override { return nullptr; } - QtNodes::NodeDataType - dataType(QtNodes::PortType, QtNodes::PortIndex) const override + QtNodes::NodeDataType dataType(QtNodes::PortType, + QtNodes::PortIndex) const override { return QtNodes::NodeDataType(); } - std::shared_ptr - outData(QtNodes::PortIndex) override + std::shared_ptr outData(QtNodes::PortIndex) override { return nullptr; } - void - setInData(std::shared_ptr, QtNodes::PortIndex) override - { - } + void setInData(std::shared_ptr, + QtNodes::PortIndex) override + {} - void - name(QString name) - { - _name = std::move(name); - } + void name(QString name) { _name = std::move(name); } - void - caption(QString caption) - { - _caption = std::move(caption); - } + void caption(QString caption) { _caption = std::move(caption); } private: - QString _name = "name"; + QString _name = "name"; QString _caption = "caption"; }; diff --git a/test/src/TestDataModelRegistry.cpp b/test/src/TestDataModelRegistry.cpp index 3651ac223..114345e74 100644 --- a/test/src/TestDataModelRegistry.cpp +++ b/test/src/TestDataModelRegistry.cpp @@ -11,16 +11,11 @@ using QtNodes::NodeDataType; using QtNodes::PortIndex; using QtNodes::PortType; -namespace -{ +namespace { class StubModelStaticName : public StubNodeDataModel { public: - static QString - Name() - { - return "Name"; - } + static QString Name() { return "Name"; } }; } diff --git a/test/src/TestNodeGraphicsObject.cpp b/test/src/TestNodeGraphicsObject.cpp index d72cfafcb..e1aa68d58 100644 --- a/test/src/TestNodeGraphicsObject.cpp +++ b/test/src/TestNodeGraphicsObject.cpp @@ -10,13 +10,13 @@ #include "ApplicationSetup.hpp" #include "StubNodeDataModel.hpp" +using QtNodes::ConnectionPolicy; using QtNodes::DataFlowScene; using QtNodes::FlowView; using QtNodes::Node; using QtNodes::NodeDataModel; using QtNodes::NodeGraphicsObject; using QtNodes::PortType; -using QtNodes::ConnectionPolicy; TEST_CASE("NodeDataModel::portOutConnectionPolicy(...) isn't called for input " "connections (issue #127)", @@ -24,12 +24,10 @@ TEST_CASE("NodeDataModel::portOutConnectionPolicy(...) isn't called for input " { class MockModel : public StubNodeDataModel { -public: - unsigned int - nPorts(PortType) const override { return 1; } + public: + unsigned int nPorts(PortType) const override { return 1; } - ConnectionPolicy - portOutConnectionPolicy(int index) const override + ConnectionPolicy portOutConnectionPolicy(int index) const override { portOutConnectionPolicyCalledCount++; return ConnectionPolicy::One; @@ -49,20 +47,22 @@ TEST_CASE("NodeDataModel::portOutConnectionPolicy(...) isn't called for input " view.show(); REQUIRE(QTest::qWaitForWindowExposed(&view)); - auto& node = scene.createNode(std::make_unique()); + auto& node = scene.createNode(std::make_unique()); auto& model = dynamic_cast(*node.nodeDataModel()); - auto& ngo = *scene.nodeGraphicsObject(scene.model()->nodeIndex(node.id())); + auto& ngo = *scene.nodeGraphicsObject(scene.model()->nodeIndex(node.id())); auto& ngeom = ngo.geometry(); // Move the node to somewhere in the middle of the screen ngo.setPos(QPointF(50, 50)); // Compute the on-screen position of the input port - QPointF scInPortPos = ngeom.portScenePosition(0, PortType::In, ngo.sceneTransform()); - QPoint vwInPortPos = view.mapFromScene(scInPortPos); + QPointF scInPortPos = + ngeom.portScenePosition(0, PortType::In, ngo.sceneTransform()); + QPoint vwInPortPos = view.mapFromScene(scInPortPos); // Create a partial connection by clicking on the input port of the node - QTest::mousePress(view.windowHandle(), Qt::LeftButton, Qt::NoModifier, vwInPortPos); + QTest::mousePress( + view.windowHandle(), Qt::LeftButton, Qt::NoModifier, vwInPortPos); CHECK(model.portOutConnectionPolicyCalledCount == 0); } diff --git a/test/src/test_dragging.cpp b/test/src/test_dragging.cpp index e53753c21..88d30c192 100644 --- a/test/src/test_dragging.cpp +++ b/test/src/test_dragging.cpp @@ -15,8 +15,8 @@ #include "StubNodeDataModel.hpp" using QtNodes::Connection; -using QtNodes::DataModelRegistry; using QtNodes::DataFlowScene; +using QtNodes::DataModelRegistry; using QtNodes::FlowView; using QtNodes::Node; using QtNodes::NodeData; @@ -47,7 +47,7 @@ TEST_CASE("Dragging node changes position", "[gui]") scClickPos = QPointF(ngo.sceneTransform().map(scClickPos).toPoint()); QPoint vwClickPos = view.mapFromScene(scClickPos); - QPoint vwDestPos = vwClickPos + QPoint(10, 20); + QPoint vwDestPos = vwClickPos + QPoint(10, 20); QPointF scExpectedDelta = view.mapToScene(vwDestPos) - scClickPos; @@ -57,11 +57,12 @@ TEST_CASE("Dragging node changes position", "[gui]") CAPTURE(scExpectedDelta); QTest::mouseMove(view.windowHandle(), vwClickPos); - QTest::mousePress(view.windowHandle(), Qt::LeftButton, Qt::NoModifier, vwClickPos); + QTest::mousePress( + view.windowHandle(), Qt::LeftButton, Qt::NoModifier, vwClickPos); QTest::mouseMove(view.windowHandle(), vwDestPos); - QPointF scDelta = node.position() - scPosBefore; - QPoint roundDelta = scDelta.toPoint(); + QPointF scDelta = node.position() - scPosBefore; + QPoint roundDelta = scDelta.toPoint(); QPoint roundExpectedDelta = scExpectedDelta.toPoint(); CHECK(roundDelta == roundExpectedDelta);