diff --git a/sources/QetGraphicsItemModeler/qetgraphicshandleritem.h b/sources/QetGraphicsItemModeler/qetgraphicshandleritem.h index 270b30123..51b7b00fc 100644 --- a/sources/QetGraphicsItemModeler/qetgraphicshandleritem.h +++ b/sources/QetGraphicsItemModeler/qetgraphicshandleritem.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef QETGRAPHICSHANDLERITEM_H #define QETGRAPHICSHANDLERITEM_H @@ -22,43 +22,43 @@ #include /** - @brief The QetGraphicsHandlerItem class - This graphics item represents a point, - destined to be used as an handler, - for modifie the geometrie of a another graphics item (like shapes). - The graphics item to be modified, - must call "installSceneEventFilter" - of this item with itself for argument,. - The ghraphics item to be modified, - need to reimplement "sceneEventFilter" - for create the modification behavior. + @brief The QetGraphicsHandlerItem class + This graphics item represents a point, + destined to be used as an handler, + for modifie the geometrie of a another graphics item (like shapes). + The graphics item to be modified, + must call "installSceneEventFilter" + of this item with itself for argument,. + The ghraphics item to be modified, + need to reimplement "sceneEventFilter" + for create the modification behavior. */ class QetGraphicsHandlerItem : public QGraphicsItem { - public: - QetGraphicsHandlerItem(qreal size = 10); - QRectF boundingRect() const override; - - enum { Type = UserType + 1200}; - int type() const override {return Type;} - - void setColor(QColor color); + public: + QetGraphicsHandlerItem(qreal size = 10); + QRectF boundingRect() const override; + + enum { Type = UserType + 1200}; + int type() const override {return Type;} + + void setColor(QColor color); - protected: - void paint(QPainter *painter, - const QStyleOptionGraphicsItem *option, - QWidget *widget) override; + protected: + void paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, + QWidget *widget) override; - private: - QRectF m_handler_rect, - m_br; - qreal m_size; - QColor m_color; - QPen m_pen; - - public: - static QVector handlerForPoint( - const QVector &points, int size = 10); + private: + QRectF m_handler_rect, + m_br; + qreal m_size; + QColor m_color; + QPen m_pen; + + public: + static QVector handlerForPoint( + const QVector &points, int size = 10); }; #endif // QETGRAPHICSHANDLERITEM_H diff --git a/sources/borderproperties.cpp b/sources/borderproperties.cpp index a2aa3de5f..c16186504 100644 --- a/sources/borderproperties.cpp +++ b/sources/borderproperties.cpp @@ -1,180 +1,180 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "borderproperties.h" /** - @brief BorderProperties::BorderProperties - constructor - Initializes a BorderProperties object with default properties + @brief BorderProperties::BorderProperties + constructor + Initializes a BorderProperties object with default properties - Initializes a BorderProperties object - with the following default properties: - - 17 columns of 60.0 px wide by 20.0px high - - 8 lines of 80.0 px high by 20.0px wide + Initializes a BorderProperties object + with the following default properties: + - 17 columns of 60.0 px wide by 20.0px high + - 8 lines of 80.0 px high by 20.0px wide - \~French Initialise un objet BorderProperties avec les proprietes par - defaut suivantes : - - 17 colonnes affichees de 60.0 px de large pour 20.0px de haut - - 8 lignes affichees de 80.0 px de haut pour 20.0px de large + \~French Initialise un objet BorderProperties avec les proprietes par + defaut suivantes : + - 17 colonnes affichees de 60.0 px de large pour 20.0px de haut + - 8 lignes affichees de 80.0 px de haut pour 20.0px de large */ BorderProperties::BorderProperties() : - columns_count(17), - columns_width(60.0), - columns_header_height(20.0), - display_columns(true), - rows_count(8), - rows_height(80.0), - rows_header_width(20.0), - display_rows(true) + columns_count(17), + columns_width(60.0), + columns_header_height(20.0), + display_columns(true), + rows_count(8), + rows_height(80.0), + rows_header_width(20.0), + display_rows(true) { } /** - @brief BorderProperties::~BorderProperties - destructor + @brief BorderProperties::~BorderProperties + destructor */ BorderProperties::~BorderProperties() { } /** - @brief BorderProperties::operator == + @brief BorderProperties::operator == - \~ @param bp : Other BorderProperties container/class. - \~French Autre conteneur BorderProperties - \~ @return True if it and this container are identical, false otherwise. - \~French True si ip et ce conteneur sont identiques, false sinon + \~ @param bp : Other BorderProperties container/class. + \~French Autre conteneur BorderProperties + \~ @return True if it and this container are identical, false otherwise. + \~French True si ip et ce conteneur sont identiques, false sinon */ bool BorderProperties::operator==(const BorderProperties &bp) { - return( - bp.columns_count == columns_count &&\ - bp.columns_width == columns_width &&\ - bp.columns_header_height == columns_header_height &&\ - bp.display_columns == display_columns &&\ - bp.rows_count == rows_count &&\ - bp.rows_height == rows_height &&\ - bp.rows_header_width == rows_header_width &&\ - bp.display_rows == display_rows - ); + return( + bp.columns_count == columns_count &&\ + bp.columns_width == columns_width &&\ + bp.columns_header_height == columns_header_height &&\ + bp.display_columns == display_columns &&\ + bp.rows_count == rows_count &&\ + bp.rows_height == rows_height &&\ + bp.rows_header_width == rows_header_width &&\ + bp.display_rows == display_rows + ); } /** - @brief BorderProperties::operator != + @brief BorderProperties::operator != - \~ @param bp : - Other BorderProperties container/class. - \~French Autre conteneur BorderProperties - \~ @return - False if it and this container are identical, true otherwise. - \~French False si bp et ce conteneur sont identiques, true sinon + \~ @param bp : + Other BorderProperties container/class. + \~French Autre conteneur BorderProperties + \~ @return + False if it and this container are identical, true otherwise. + \~French False si bp et ce conteneur sont identiques, true sinon */ bool BorderProperties::operator!=(const BorderProperties &bp) { - return(!(*this == bp)); + return(!(*this == bp)); } /** - @brief BorderProperties::toXml - Exports dimensions as XML attributes added to element e. - \~French Exporte les dimensions sous formes d'attributs XML ajoutes a l'element e. + @brief BorderProperties::toXml + Exports dimensions as XML attributes added to element e. + \~French Exporte les dimensions sous formes d'attributs XML ajoutes a l'element e. - \~ @param e : - XML element to which attributes will be added - \~French Element XML auquel seront ajoutes des attributs + \~ @param e : + XML element to which attributes will be added + \~French Element XML auquel seront ajoutes des attributs */ void BorderProperties::toXml(QDomElement &e) const { - e.setAttribute("cols", columns_count); - e.setAttribute("colsize", QString("%1").arg(columns_width)); - e.setAttribute("rows", rows_count); - e.setAttribute("rowsize", QString("%1").arg(rows_height)); - e.setAttribute("displaycols", display_columns ? "true" : "false"); - e.setAttribute("displayrows", display_rows ? "true" : "false"); + e.setAttribute("cols", columns_count); + e.setAttribute("colsize", QString("%1").arg(columns_width)); + e.setAttribute("rows", rows_count); + e.setAttribute("rowsize", QString("%1").arg(rows_height)); + e.setAttribute("displaycols", display_columns ? "true" : "false"); + e.setAttribute("displayrows", display_rows ? "true" : "false"); } /** - @brief BorderProperties::fromXml - Import dimensions from XML attributes of element e - \~French Importe les dimensions a partir des attributs XML de l'element e + @brief BorderProperties::fromXml + Import dimensions from XML attributes of element e + \~French Importe les dimensions a partir des attributs XML de l'element e - \~ @param e : - XML element whose attributes will be read - \~French Element XML dont les attributs seront lus + \~ @param e : + XML element whose attributes will be read + \~French Element XML dont les attributs seront lus */ void BorderProperties::fromXml(QDomElement &e) { - if (e.hasAttribute("cols")) columns_count = e.attribute("cols").toInt(); - if (e.hasAttribute("colsize")) columns_width = e.attribute("colsize").toInt(); - if (e.hasAttribute("rows")) rows_count = e.attribute("rows").toInt(); - if (e.hasAttribute("rowsize")) rows_height = e.attribute("rowsize").toInt(); - if (e.hasAttribute("displaycols")) display_columns = e.attribute("displaycols") == "true"; - if (e.hasAttribute("displayrows")) display_rows = e.attribute("displayrows") == "true"; + if (e.hasAttribute("cols")) columns_count = e.attribute("cols").toInt(); + if (e.hasAttribute("colsize")) columns_width = e.attribute("colsize").toInt(); + if (e.hasAttribute("rows")) rows_count = e.attribute("rows").toInt(); + if (e.hasAttribute("rowsize")) rows_height = e.attribute("rowsize").toInt(); + if (e.hasAttribute("displaycols")) display_columns = e.attribute("displaycols") == "true"; + if (e.hasAttribute("displayrows")) display_rows = e.attribute("displayrows") == "true"; } /** - @brief BorderProperties::toSettings - Export dimensions in a QSettings object. - \~French Exporte les dimensions dans une configuration. + @brief BorderProperties::toSettings + Export dimensions in a QSettings object. + \~French Exporte les dimensions dans une configuration. - \~ @param settings : - QSettings object to write - \~French Parametres a ecrire - \~ @param prefix : - prefix to be added before the names of the parameters - \~French prefixe a ajouter devant les noms des parametres + \~ @param settings : + QSettings object to write + \~French Parametres a ecrire + \~ @param prefix : + prefix to be added before the names of the parameters + \~French prefixe a ajouter devant les noms des parametres */ void BorderProperties::toSettings(QSettings &settings, const QString &prefix) const { - settings.setValue(prefix + "cols", columns_count); - settings.setValue(prefix + "colsize", columns_width); - settings.setValue(prefix + "displaycols", display_columns); - settings.setValue(prefix + "rows", rows_count); - settings.setValue(prefix + "rowsize", rows_height); - settings.setValue(prefix + "displayrows", display_rows); + settings.setValue(prefix + "cols", columns_count); + settings.setValue(prefix + "colsize", columns_width); + settings.setValue(prefix + "displaycols", display_columns); + settings.setValue(prefix + "rows", rows_count); + settings.setValue(prefix + "rowsize", rows_height); + settings.setValue(prefix + "displayrows", display_rows); } /** - @brief BorderProperties::fromSettings - Import dimensions from a QSettings object. - \~French Importe les dimensions depuis une configuration. - \~ @param settings : QSettings object to read - \~French Parametres a lire - \~ @param prefix : prefix to be added before the names of the parameters - \~French prefixe a ajouter devant les noms des parametres + @brief BorderProperties::fromSettings + Import dimensions from a QSettings object. + \~French Importe les dimensions depuis une configuration. + \~ @param settings : QSettings object to read + \~French Parametres a lire + \~ @param prefix : prefix to be added before the names of the parameters + \~French prefixe a ajouter devant les noms des parametres */ void BorderProperties::fromSettings(QSettings &settings, const QString &prefix) { - columns_count = settings.value(prefix + "cols", columns_count).toInt(); - columns_width = qRound(settings.value(prefix + "colsize", columns_width).toDouble()); - display_columns = settings.value(prefix + "displaycols", display_columns).toBool(); - - rows_count = settings.value(prefix + "rows", rows_count).toInt(); - rows_height = qRound(settings.value(prefix + "rowsize", rows_height).toDouble()); - display_rows = settings.value(prefix + "displayrows", display_rows).toBool(); + columns_count = settings.value(prefix + "cols", columns_count).toInt(); + columns_width = qRound(settings.value(prefix + "colsize", columns_width).toDouble()); + display_columns = settings.value(prefix + "displaycols", display_columns).toBool(); + + rows_count = settings.value(prefix + "rows", rows_count).toInt(); + rows_height = qRound(settings.value(prefix + "rowsize", rows_height).toDouble()); + display_rows = settings.value(prefix + "displayrows", display_rows).toBool(); } /** - @brief BorderProperties::defaultProperties - @return the default properties stored in the setting file + @brief BorderProperties::defaultProperties + @return the default properties stored in the setting file */ BorderProperties BorderProperties::defaultProperties() { - QSettings settings; + QSettings settings; - BorderProperties def; - def.fromSettings(settings, "diagrameditor/default"); + BorderProperties def; + def.fromSettings(settings, "diagrameditor/default"); - return(def); + return(def); } diff --git a/sources/borderproperties.h b/sources/borderproperties.h index 74df1e8bb..a8429a332 100644 --- a/sources/borderproperties.h +++ b/sources/borderproperties.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef BORDER_PROPERTIES_H #define BORDER_PROPERTIES_H @@ -21,36 +21,36 @@ #include /** - @brief The BorderProperties class - This class is a container for dimensions and display properties of a - diagram. - @remark Attributes are public + @brief The BorderProperties class + This class is a container for dimensions and display properties of a + diagram. + @remark Attributes are public */ class BorderProperties { - public: - // constructor, destructor, operators - BorderProperties(); - virtual ~BorderProperties(); - - bool operator==(const BorderProperties &); - bool operator!=(const BorderProperties &); - - void toXml(QDomElement &) const; - void fromXml(QDomElement &); - void toSettings(QSettings &, const QString & = QString()) const; - void fromSettings(QSettings &, const QString & = QString()); + public: + // constructor, destructor, operators + BorderProperties(); + virtual ~BorderProperties(); + + bool operator==(const BorderProperties &); + bool operator!=(const BorderProperties &); + + void toXml(QDomElement &) const; + void fromXml(QDomElement &); + void toSettings(QSettings &, const QString & = QString()) const; + void fromSettings(QSettings &, const QString & = QString()); - static BorderProperties defaultProperties(); - - // attributes - int columns_count; ///< Columns count - qreal columns_width; ///< Columns width - qreal columns_header_height; ///< Column headers height - bool display_columns; ///< Whether to display column headers - - int rows_count; ///< Rows count - qreal rows_height; ///< Rows height - qreal rows_header_width; ///< Row headers width - bool display_rows; ///< Whether to display row headers + static BorderProperties defaultProperties(); + + // attributes + int columns_count; ///< Columns count + qreal columns_width; ///< Columns width + qreal columns_header_height; ///< Column headers height + bool display_columns; ///< Whether to display column headers + + int rows_count; ///< Rows count + qreal rows_height; ///< Rows height + qreal rows_header_width; ///< Row headers width + bool display_rows; ///< Whether to display row headers }; #endif diff --git a/sources/bordertitleblock.cpp b/sources/bordertitleblock.cpp index 026bab62f..9f509f044 100644 --- a/sources/bordertitleblock.cpp +++ b/sources/bordertitleblock.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include #include @@ -34,1066 +34,1066 @@ #define MIN_ROW_HEIGHT 5.0 /** - @brief BorderTitleBlock::BorderTitleBlock - Simple constructor: - build a border by recovering the dimensions - in the application configuration. + @brief BorderTitleBlock::BorderTitleBlock + Simple constructor: + build a border by recovering the dimensions + in the application configuration. - \~French Constructeur simple : - construit une bordure en recuperant les dimensions - dans la configuration de l'application. - \~ @param parent : - \~French QObject parent de ce BorderTitleBlock + \~French Constructeur simple : + construit une bordure en recuperant les dimensions + dans la configuration de l'application. + \~ @param parent : + \~French QObject parent de ce BorderTitleBlock */ BorderTitleBlock::BorderTitleBlock(QObject *parent) : - QObject(parent) + QObject(parent) { - // at first, the internal titleblock template renderer uses the default titleblock template - m_titleblock_template_renderer = new TitleBlockTemplateRenderer(this); - m_titleblock_template_renderer -> setTitleBlockTemplate(QETApp::defaultTitleBlockTemplate()); + // at first, the internal titleblock template renderer uses the default titleblock template + m_titleblock_template_renderer = new TitleBlockTemplateRenderer(this); + m_titleblock_template_renderer -> setTitleBlockTemplate(QETApp::defaultTitleBlockTemplate()); - // disable the QPicture-based cache from Qt 4.8 to avoid rendering errors and crashes -#if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) // ### Qt 6: remove + // disable the QPicture-based cache from Qt 4.8 to avoid rendering errors and crashes +#if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) // ### Qt 6: remove #else - m_titleblock_template_renderer -> setUseCache(false); + m_titleblock_template_renderer -> setUseCache(false); #endif - // dimensions par defaut du schema - importBorder(BorderProperties()); + // dimensions par defaut du schema + importBorder(BorderProperties()); - // contenu par defaut du cartouche - importTitleBlock(TitleBlockProperties()); + // contenu par defaut du cartouche + importTitleBlock(TitleBlockProperties()); - display_titleblock_ = true; - display_border_ = true; - setFolioData(1, 1); - updateRectangles(); + display_titleblock_ = true; + display_border_ = true; + setFolioData(1, 1); + updateRectangles(); } /** - @brief BorderTitleBlock::~BorderTitleBlock - \~French Destructeur - ne fait rien + @brief BorderTitleBlock::~BorderTitleBlock + \~French Destructeur - ne fait rien */ BorderTitleBlock::~BorderTitleBlock() { } /** - @brief BorderTitleBlock::titleBlockRect - @return the rectangle of the titleblock in scene coordinate. + @brief BorderTitleBlock::titleBlockRect + @return the rectangle of the titleblock in scene coordinate. */ QRectF BorderTitleBlock::titleBlockRect() const { - if (m_edge == Qt::BottomEdge) - return QRectF(diagram_rect_.bottomLeft(), - QSize(diagram_rect_.width(), - m_titleblock_template_renderer -> height() - )); - else - return QRectF(diagram_rect_.topRight(), - QSize(m_titleblock_template_renderer -> height(), - diagram_rect_.height() - )); + if (m_edge == Qt::BottomEdge) + return QRectF(diagram_rect_.bottomLeft(), + QSize(diagram_rect_.width(), + m_titleblock_template_renderer -> height() + )); + else + return QRectF(diagram_rect_.topRight(), + QSize(m_titleblock_template_renderer -> height(), + diagram_rect_.height() + )); } /** - @brief BorderTitleBlock::titleblockInformation - @return + @brief BorderTitleBlock::titleblockInformation + @return */ DiagramContext BorderTitleBlock::titleblockInformation() const { - return m_titleblock_template_renderer->context(); + return m_titleblock_template_renderer->context(); } /** - @brief BorderTitleBlock::titleBlockRectForQPainter - @return The title block rect to use with the QPainter in the method draw. - The returned rect is alway horizontal - (like displayed at the bottom of rect) only the top left change of pos - according to the edge where the title block need to be displayed. - Rect according to edge: - Bottom : top left is at the bottom left edge of the diagram rect. - Right : top left is at the bottom right of diagram rect. - Befor use this rect you need to rotate the QPainter by -90° - for snap the rect at the right edge of diagram. + @brief BorderTitleBlock::titleBlockRectForQPainter + @return The title block rect to use with the QPainter in the method draw. + The returned rect is alway horizontal + (like displayed at the bottom of rect) only the top left change of pos + according to the edge where the title block need to be displayed. + Rect according to edge: + Bottom : top left is at the bottom left edge of the diagram rect. + Right : top left is at the bottom right of diagram rect. + Befor use this rect you need to rotate the QPainter by -90° + for snap the rect at the right edge of diagram. */ QRectF BorderTitleBlock::titleBlockRectForQPainter() const { - //Rect at bottom have same position and dimension of displayed rect - if (m_edge == Qt::BottomEdge) - return titleBlockRect(); - else - return QRectF (diagram_rect_.bottomRight(), - QSize(diagram_rect_.height(), - m_titleblock_template_renderer -> height() - )); + //Rect at bottom have same position and dimension of displayed rect + if (m_edge == Qt::BottomEdge) + return titleBlockRect(); + else + return QRectF (diagram_rect_.bottomRight(), + QSize(diagram_rect_.height(), + m_titleblock_template_renderer -> height() + )); } /** - @brief BorderTitleBlock::borderAndTitleBlockRect - @return the bounding rectangle of diagram and titleblock. - It's like unite outsideBorderRect and titleBlockRect. - The rect is in scene coordinate + @brief BorderTitleBlock::borderAndTitleBlockRect + @return the bounding rectangle of diagram and titleblock. + It's like unite outsideBorderRect and titleBlockRect. + The rect is in scene coordinate */ QRectF BorderTitleBlock::borderAndTitleBlockRect() const { - return diagram_rect_ | titleBlockRect(); + return diagram_rect_ | titleBlockRect(); } /** - @brief BorderTitleBlock::columnsRect - @return The columns rect in scene coordinate. - If column is not displayed, return a null QRectF + @brief BorderTitleBlock::columnsRect + @return The columns rect in scene coordinate. + If column is not displayed, return a null QRectF */ QRectF BorderTitleBlock::columnsRect() const { - if (!display_columns_) return QRectF(); - return QRectF (Diagram::margin, - Diagram::margin, - (columns_count_*columns_width_) + rows_header_width_, - columns_header_height_); + if (!display_columns_) return QRectF(); + return QRectF (Diagram::margin, + Diagram::margin, + (columns_count_*columns_width_) + rows_header_width_, + columns_header_height_); } /** - @brief BorderTitleBlock::rowsRect - @return The rows rect in scene coordinate. - If row is not displayed, return a null QRectF + @brief BorderTitleBlock::rowsRect + @return The rows rect in scene coordinate. + If row is not displayed, return a null QRectF */ QRectF BorderTitleBlock::rowsRect() const { - if (!display_rows_) return QRectF(); - return QRectF (Diagram::margin, - Diagram::margin, - rows_header_width_, - (rows_count_*rows_height_) + columns_header_height_); + if (!display_rows_) return QRectF(); + return QRectF (Diagram::margin, + Diagram::margin, + rows_header_width_, + (rows_count_*rows_height_) + columns_header_height_); } /** - @brief BorderTitleBlock::outsideBorderRect - @return The rect of outside border (diagram with columns and rows) - The rect is in scene coordinate + @brief BorderTitleBlock::outsideBorderRect + @return The rect of outside border (diagram with columns and rows) + The rect is in scene coordinate */ QRectF BorderTitleBlock::outsideBorderRect() const { - return QRectF (Diagram::margin, - Diagram::margin, - (columns_width_*columns_count_) + rows_header_width_, - (rows_height_*rows_count_) + columns_header_height_); + return QRectF (Diagram::margin, + Diagram::margin, + (columns_width_*columns_count_) + rows_header_width_, + (rows_height_*rows_count_) + columns_header_height_); } /** - @brief BorderTitleBlock::insideBorderRect - @return The rect of the inside border, in other word, the drawing area. - This method take care about if rows or columns are displayed or not. - The rect is in scene coordinate + @brief BorderTitleBlock::insideBorderRect + @return The rect of the inside border, in other word, the drawing area. + This method take care about if rows or columns are displayed or not. + The rect is in scene coordinate */ QRectF BorderTitleBlock::insideBorderRect() const { - qreal left = Diagram::margin; - qreal top = Diagram::margin; - qreal width = columns_width_*columns_count_; - qreal height = rows_height_*rows_count_; + qreal left = Diagram::margin; + qreal top = Diagram::margin; + qreal width = columns_width_*columns_count_; + qreal height = rows_height_*rows_count_; - display_rows_ ? left += rows_header_width_ : width += rows_header_width_; - display_columns_ ? top += columns_header_height_ : height += columns_header_height_; + display_rows_ ? left += rows_header_width_ : width += rows_header_width_; + display_columns_ ? top += columns_header_height_ : height += columns_header_height_; - return QRectF (left, top, width, height); + return QRectF (left, top, width, height); } /** - @brief BorderTitleBlock::titleBlockToXml - Exports the title block current values to XML. - @param xml_elmt the XML element attributes will be added to + @brief BorderTitleBlock::titleBlockToXml + Exports the title block current values to XML. + @param xml_elmt the XML element attributes will be added to */ void BorderTitleBlock::titleBlockToXml(QDomElement &xml_elmt) { - exportTitleBlock().toXml(xml_elmt); + exportTitleBlock().toXml(xml_elmt); } /** - @brief BorderTitleBlock::titleBlockFromXml - Reads the title block values from XML. - @param xml_elmt the XML element values will be read from + @brief BorderTitleBlock::titleBlockFromXml + Reads the title block values from XML. + @param xml_elmt the XML element values will be read from */ void BorderTitleBlock::titleBlockFromXml(const QDomElement &xml_elmt) { - TitleBlockProperties tbp; - tbp.fromXml(xml_elmt); - importTitleBlock(tbp); + TitleBlockProperties tbp; + tbp.fromXml(xml_elmt); + importTitleBlock(tbp); } /** - @brief BorderTitleBlock::borderToXml - Exports the border current settings to XML. - @param xml_elmt the XML element attributes will be added to + @brief BorderTitleBlock::borderToXml + Exports the border current settings to XML. + @param xml_elmt the XML element attributes will be added to */ void BorderTitleBlock::borderToXml(QDomElement &xml_elmt) { - xml_elmt.setAttribute("cols", columnsCount()); - xml_elmt.setAttribute("colsize", QString("%1").arg(columnsWidth())); - xml_elmt.setAttribute("displaycols", columnsAreDisplayed() ? "true" : "false"); + xml_elmt.setAttribute("cols", columnsCount()); + xml_elmt.setAttribute("colsize", QString("%1").arg(columnsWidth())); + xml_elmt.setAttribute("displaycols", columnsAreDisplayed() ? "true" : "false"); - xml_elmt.setAttribute("rows", rowsCount()); - xml_elmt.setAttribute("rowsize", QString("%1").arg(rowsHeight())); - xml_elmt.setAttribute("displayrows", rowsAreDisplayed() ? "true" : "false"); + xml_elmt.setAttribute("rows", rowsCount()); + xml_elmt.setAttribute("rowsize", QString("%1").arg(rowsHeight())); + xml_elmt.setAttribute("displayrows", rowsAreDisplayed() ? "true" : "false"); - // attribut datant de la version 0.1 - laisse pour retrocompatibilite - xml_elmt.setAttribute("height", QString("%1").arg(diagramHeight())); + // attribut datant de la version 0.1 - laisse pour retrocompatibilite + xml_elmt.setAttribute("height", QString("%1").arg(diagramHeight())); } /** - @brief BorderTitleBlock::borderFromXml - Reads the border settings from XML. - @param xml_elmt the XML element values will be read from + @brief BorderTitleBlock::borderFromXml + Reads the border settings from XML. + @param xml_elmt the XML element values will be read from */ void BorderTitleBlock::borderFromXml(const QDomElement &xml_elmt) { - bool ok; - // columns count - int cols_count = xml_elmt.attribute("cols").toInt(&ok); - if (ok) setColumnsCount(cols_count); + bool ok; + // columns count + int cols_count = xml_elmt.attribute("cols").toInt(&ok); + if (ok) setColumnsCount(cols_count); - // columns width - double cols_width = xml_elmt.attribute("colsize").toDouble(&ok); - if (ok) setColumnsWidth(cols_width); + // columns width + double cols_width = xml_elmt.attribute("colsize").toDouble(&ok); + if (ok) setColumnsWidth(cols_width); - // backward compatibility: - // diagrams saved with 0.1 version have a "height" attribute - if (xml_elmt.hasAttribute("rows") && xml_elmt.hasAttribute("rowsize")) { - // rows counts - int rows_count = xml_elmt.attribute("rows").toInt(&ok); - if (ok) setRowsCount(rows_count); + // backward compatibility: + // diagrams saved with 0.1 version have a "height" attribute + if (xml_elmt.hasAttribute("rows") && xml_elmt.hasAttribute("rowsize")) { + // rows counts + int rows_count = xml_elmt.attribute("rows").toInt(&ok); + if (ok) setRowsCount(rows_count); - // taille des lignes - double rows_size = xml_elmt.attribute("rowsize").toDouble(&ok); - if (ok) setRowsHeight(rows_size); - } else { - // hauteur du schema - double height = xml_elmt.attribute("height").toDouble(&ok); - if (ok) setDiagramHeight(height); - } + // taille des lignes + double rows_size = xml_elmt.attribute("rowsize").toDouble(&ok); + if (ok) setRowsHeight(rows_size); + } else { + // hauteur du schema + double height = xml_elmt.attribute("height").toDouble(&ok); + if (ok) setDiagramHeight(height); + } - // rows and columns display - displayColumns(xml_elmt.attribute("displaycols") != "false"); - displayRows(xml_elmt.attribute("displayrows") != "false"); + // rows and columns display + displayColumns(xml_elmt.attribute("displaycols") != "false"); + displayRows(xml_elmt.attribute("displayrows") != "false"); - updateRectangles(); + updateRectangles(); } /** - @brief BorderTitleBlock::exportTitleBlock - @return the properties of the titleblock - \~French les proprietes du cartouches + @brief BorderTitleBlock::exportTitleBlock + @return the properties of the titleblock + \~French les proprietes du cartouches */ TitleBlockProperties BorderTitleBlock::exportTitleBlock() { - TitleBlockProperties ip; + TitleBlockProperties ip; - ip.author = author(); - ip.date = date(); - ip.title = title(); - ip.filename = fileName(); - ip.plant = plant(); - ip.locmach = locmach(); - ip.indexrev = indexrev(); - ip.version = version(); - ip.folio = folio(); - ip.template_name = titleBlockTemplateName(); - ip.display_at = m_edge; - ip.auto_page_num = autoPageNum(); - ip.context = additional_fields_; - ip.collection = QET::QetCollection::Embedded; + ip.author = author(); + ip.date = date(); + ip.title = title(); + ip.filename = fileName(); + ip.plant = plant(); + ip.locmach = locmach(); + ip.indexrev = indexrev(); + ip.version = version(); + ip.folio = folio(); + ip.template_name = titleBlockTemplateName(); + ip.display_at = m_edge; + ip.auto_page_num = autoPageNum(); + ip.context = additional_fields_; + ip.collection = QET::QetCollection::Embedded; - return(ip); + return(ip); } /** - @brief BorderTitleBlock::importTitleBlock - @param ip the new properties of titleblock + @brief BorderTitleBlock::importTitleBlock + @param ip the new properties of titleblock */ void BorderTitleBlock::importTitleBlock(const TitleBlockProperties &ip) { - setAuthor(ip.author); - setDate(ip.date); - setTitle(ip.title); - setFileName(ip.filename); - setPlant(ip.plant); - setLocMach(ip.locmach); - setIndicerev(ip.indexrev); - setVersion(QET::displayedVersion); - setFolio(ip.folio); - setAutoPageNum(ip.auto_page_num); - if (m_edge != ip.display_at) - { - m_edge = ip.display_at; - emit(displayChanged()); - } - additional_fields_ = ip.context; + setAuthor(ip.author); + setDate(ip.date); + setTitle(ip.title); + setFileName(ip.filename); + setPlant(ip.plant); + setLocMach(ip.locmach); + setIndicerev(ip.indexrev); + setVersion(QET::displayedVersion); + setFolio(ip.folio); + setAutoPageNum(ip.auto_page_num); + if (m_edge != ip.display_at) + { + m_edge = ip.display_at; + emit(displayChanged()); + } + additional_fields_ = ip.context; - emit(needFolioData()); // Note: we expect additional data to be provided - // through setFolioData(), - // which in turn calls updateDiagramContextForTitleBlock(). - emit(needTitleBlockTemplate(ip.template_name)); + emit(needFolioData()); // Note: we expect additional data to be provided + // through setFolioData(), + // which in turn calls updateDiagramContextForTitleBlock(). + emit(needTitleBlockTemplate(ip.template_name)); } /** - @brief BorderTitleBlock::exportBorder - @return border properties - \~French les proprietes de la bordure + @brief BorderTitleBlock::exportBorder + @return border properties + \~French les proprietes de la bordure */ BorderProperties BorderTitleBlock::exportBorder() { - BorderProperties bp; - bp.columns_count = columnsCount(); - bp.columns_width = columnsWidth(); - bp.columns_header_height = columnsHeaderHeight(); - bp.display_columns = columnsAreDisplayed(); - bp.rows_count = rowsCount(); - bp.rows_height = rowsHeight(); - bp.rows_header_width = rowsHeaderWidth(); - bp.display_rows = rowsAreDisplayed(); - return(bp); + BorderProperties bp; + bp.columns_count = columnsCount(); + bp.columns_width = columnsWidth(); + bp.columns_header_height = columnsHeaderHeight(); + bp.display_columns = columnsAreDisplayed(); + bp.rows_count = rowsCount(); + bp.rows_height = rowsHeight(); + bp.rows_header_width = rowsHeaderWidth(); + bp.display_rows = rowsAreDisplayed(); + return(bp); } /** - @brief BorderTitleBlock::importBorder - @param bp : the new properties of the border - \~French les nouvelles proprietes de la bordure + @brief BorderTitleBlock::importBorder + @param bp : the new properties of the border + \~French les nouvelles proprietes de la bordure */ void BorderTitleBlock::importBorder(const BorderProperties &bp) { - setColumnsHeaderHeight(bp.columns_header_height); - setColumnsCount(bp.columns_count); - setColumnsWidth(bp.columns_width); - displayColumns(bp.display_columns); - setRowsHeaderWidth(bp.rows_header_width); - setRowsCount(bp.rows_count); - setRowsHeight(bp.rows_height); - displayRows(bp.display_rows); + setColumnsHeaderHeight(bp.columns_header_height); + setColumnsCount(bp.columns_count); + setColumnsWidth(bp.columns_width); + displayColumns(bp.display_columns); + setRowsHeaderWidth(bp.rows_header_width); + setRowsCount(bp.rows_count); + setRowsHeight(bp.rows_height); + displayRows(bp.display_rows); } /** - @brief BorderTitleBlock::titleBlockTemplate - @return the titleblock template used to render the titleblock - @see TitleBlockTemplateRenderer::titleBlockTemplate() + @brief BorderTitleBlock::titleBlockTemplate + @return the titleblock template used to render the titleblock + @see TitleBlockTemplateRenderer::titleBlockTemplate() */ const TitleBlockTemplate *BorderTitleBlock::titleBlockTemplate() { - return(m_titleblock_template_renderer -> titleBlockTemplate()); + return(m_titleblock_template_renderer -> titleBlockTemplate()); } /** - @brief BorderTitleBlock::setTitleBlockTemplate - @param titleblock_template: - The new titleblock template to use to render the titleblock - @see TitleBlockTemplateRenderer::setTitleBlockTemplate() + @brief BorderTitleBlock::setTitleBlockTemplate + @param titleblock_template: + The new titleblock template to use to render the titleblock + @see TitleBlockTemplateRenderer::setTitleBlockTemplate() */ void BorderTitleBlock::setTitleBlockTemplate( - const TitleBlockTemplate *titleblock_template) { - m_titleblock_template_renderer -> setTitleBlockTemplate( - titleblock_template); + const TitleBlockTemplate *titleblock_template) { + m_titleblock_template_renderer -> setTitleBlockTemplate( + titleblock_template); } /** - @brief BorderTitleBlock::titleBlockTemplateName - @return The name of the template used to render the titleblock. + @brief BorderTitleBlock::titleBlockTemplateName + @return The name of the template used to render the titleblock. */ QString BorderTitleBlock::titleBlockTemplateName() const { - QString tbt_name = m_titleblock_template_renderer -> titleBlockTemplate() -> name(); - return((tbt_name == "default") ? "" : tbt_name); + QString tbt_name = m_titleblock_template_renderer -> titleBlockTemplate() -> name(); + return((tbt_name == "default") ? "" : tbt_name); } /** - @brief BorderTitleBlock::titleBlockTemplateChanged - This slot may be used to inform this class that the given title block - template has changed. - The title block-dedicated rendering cache will thus be flushed. - @param template_name : Name of the title block template that has changed + @brief BorderTitleBlock::titleBlockTemplateChanged + This slot may be used to inform this class that the given title block + template has changed. + The title block-dedicated rendering cache will thus be flushed. + @param template_name : Name of the title block template that has changed */ void BorderTitleBlock::titleBlockTemplateChanged(const QString &template_name) { - if (titleBlockTemplateName() != template_name) return; - m_titleblock_template_renderer -> invalidateRenderedTemplate(); + if (titleBlockTemplateName() != template_name) return; + m_titleblock_template_renderer -> invalidateRenderedTemplate(); } /** - @brief BorderTitleBlock::titleBlockTemplateRemoved - This slot has to be used to inform this class that the given title block - template is about to be removed and is no longer accessible. This class - will either use the provided optional TitleBlockTemplate or the default - title block provided by QETApp::defaultTitleBlockTemplate() - @param removed_template_name : - Name of the title block template that has changed - @param new_template (Optional) title block template to use instead + @brief BorderTitleBlock::titleBlockTemplateRemoved + This slot has to be used to inform this class that the given title block + template is about to be removed and is no longer accessible. This class + will either use the provided optional TitleBlockTemplate or the default + title block provided by QETApp::defaultTitleBlockTemplate() + @param removed_template_name : + Name of the title block template that has changed + @param new_template (Optional) title block template to use instead */ void BorderTitleBlock::titleBlockTemplateRemoved( - const QString &removed_template_name, - const TitleBlockTemplate *new_template) { - if (titleBlockTemplateName() != removed_template_name) return; + const QString &removed_template_name, + const TitleBlockTemplate *new_template) { + if (titleBlockTemplateName() != removed_template_name) return; - if (new_template) { - setTitleBlockTemplate(new_template); - } else { - setTitleBlockTemplate(QETApp::defaultTitleBlockTemplate()); - } + if (new_template) { + setTitleBlockTemplate(new_template); + } else { + setTitleBlockTemplate(QETApp::defaultTitleBlockTemplate()); + } } /** - @brief BorderTitleBlock::displayTitleBlock - @param di : true to display the title block, false otherwise - \~French true pour afficher le cartouche, false sinon + @brief BorderTitleBlock::displayTitleBlock + @param di : true to display the title block, false otherwise + \~French true pour afficher le cartouche, false sinon */ void BorderTitleBlock::displayTitleBlock(bool di) { - bool change = (di != display_titleblock_); - display_titleblock_ = di; - if (change) emit(displayChanged()); + bool change = (di != display_titleblock_); + display_titleblock_ = di; + if (change) emit(displayChanged()); } /** - @brief BorderTitleBlock::displayColumns - @param dc : true to display the column headers, false otherwise - \~French true pour afficher les entetes des colonnes, false sinon + @brief BorderTitleBlock::displayColumns + @param dc : true to display the column headers, false otherwise + \~French true pour afficher les entetes des colonnes, false sinon */ void BorderTitleBlock::displayColumns(bool dc) { - bool change = (dc != display_columns_); - display_columns_ = dc; - if (change) emit(displayChanged()); + bool change = (dc != display_columns_); + display_columns_ = dc; + if (change) emit(displayChanged()); } /** - @brief BorderTitleBlock::displayRows - @param dr : true to display line headers, false otherwise - \~French true pour afficher les entetes des lignes, false sinon + @brief BorderTitleBlock::displayRows + @param dr : true to display line headers, false otherwise + \~French true pour afficher les entetes des lignes, false sinon */ void BorderTitleBlock::displayRows(bool dr) { - bool change = (dr != display_rows_); - display_rows_ = dr; - if (change) emit(displayChanged()); + bool change = (dr != display_rows_); + display_rows_ = dr; + if (change) emit(displayChanged()); } /** - @brief BorderTitleBlock::displayBorder - @param db : true to display the border of the diagram, false otherwise - \~French true pour afficher la bordure du schema, false sinon - \~ @note : if the border display is deactivated, - the rows and columns will not be drawn. - \~French si l'affichage de la bordure est ainsi desactivee, - les lignes et colonnes ne seront pas dessinees. + @brief BorderTitleBlock::displayBorder + @param db : true to display the border of the diagram, false otherwise + \~French true pour afficher la bordure du schema, false sinon + \~ @note : if the border display is deactivated, + the rows and columns will not be drawn. + \~French si l'affichage de la bordure est ainsi desactivee, + les lignes et colonnes ne seront pas dessinees. */ void BorderTitleBlock::displayBorder(bool db) { - bool change = (db != display_border_); - display_border_ = db; - if (change) emit(displayChanged()); + bool change = (db != display_border_); + display_border_ = db; + if (change) emit(displayChanged()); } /** - @brief BorderTitleBlock::slot_setAutoPageNum - @param pageAutoNum : - Set Page (Folio) Auto Num + @brief BorderTitleBlock::slot_setAutoPageNum + @param pageAutoNum : + Set Page (Folio) Auto Num */ void BorderTitleBlock::slot_setAutoPageNum(QString pageAutoNum) { - btb_auto_page_num_=std::move(pageAutoNum); + btb_auto_page_num_=std::move(pageAutoNum); } /** - @brief BorderTitleBlock::updateRectangles - This method update the diagram rect according - to the value of rows and columns (number and size) + @brief BorderTitleBlock::updateRectangles + This method update the diagram rect according + to the value of rows and columns (number and size) */ void BorderTitleBlock::updateRectangles() { - QRectF previous_diagram = diagram_rect_; - diagram_rect_ = QRectF(Diagram::margin, - Diagram::margin, - diagramWidth(), - diagramHeight()); - if (diagram_rect_ != previous_diagram) - emit(borderChanged(previous_diagram, diagram_rect_)); + QRectF previous_diagram = diagram_rect_; + diagram_rect_ = QRectF(Diagram::margin, + Diagram::margin, + diagramWidth(), + diagramHeight()); + if (diagram_rect_ != previous_diagram) + emit(borderChanged(previous_diagram, diagram_rect_)); } /** - @brief BorderTitleBlock::draw - Draw the border and the titleblock. - @param painter : QPainter to use for draw this. + @brief BorderTitleBlock::draw + Draw the border and the titleblock. + @param painter : QPainter to use for draw this. */ void BorderTitleBlock::draw(QPainter *painter) { - //Set the QPainter - painter -> save(); - QPen pen(Qt::black); - pen.setCosmetic(true); - painter -> setPen(pen); - painter -> setBrush(Qt::NoBrush); + //Set the QPainter + painter -> save(); + QPen pen(Qt::black); + pen.setCosmetic(true); + painter -> setPen(pen); + painter -> setBrush(Qt::NoBrush); - QSettings settings; + QSettings settings; - //Draw the borer - if (display_border_) painter -> drawRect(diagram_rect_); + //Draw the borer + if (display_border_) painter -> drawRect(diagram_rect_); - painter -> setFont(QETApp::diagramTextsFont()); + painter -> setFont(QETApp::diagramTextsFont()); - //Draw the empty case at the top left of diagram when there is header - if (display_border_ && (display_columns_ || display_rows_)) - { - QRectF first_rectangle( - diagram_rect_.topLeft().x(), - diagram_rect_.topLeft().y(), - rows_header_width_, - columns_header_height_ - ); - painter -> drawRect(first_rectangle); - } + //Draw the empty case at the top left of diagram when there is header + if (display_border_ && (display_columns_ || display_rows_)) + { + QRectF first_rectangle( + diagram_rect_.topLeft().x(), + diagram_rect_.topLeft().y(), + rows_header_width_, + columns_header_height_ + ); + painter -> drawRect(first_rectangle); + } - //Draw the nums of columns - if (display_border_ && display_columns_) { - for (int i = 1 ; i <= columns_count_ ; ++ i) { - QRectF numbered_rectangle = QRectF( - diagram_rect_.topLeft().x() - + (rows_header_width_ - + ((i - 1) * columns_width_)), - diagram_rect_.topLeft().y(), - columns_width_, - columns_header_height_ - ); - painter -> drawRect(numbered_rectangle); - if (settings.value("border-columns_0", true).toBool()){ - painter -> drawText(numbered_rectangle, - Qt::AlignVCenter - | Qt::AlignCenter, - QString("%1").arg(i - 1)); - }else{ - painter -> drawText(numbered_rectangle, - Qt::AlignVCenter - | Qt::AlignCenter, - QString("%1").arg(i)); - } - } - } + //Draw the nums of columns + if (display_border_ && display_columns_) { + for (int i = 1 ; i <= columns_count_ ; ++ i) { + QRectF numbered_rectangle = QRectF( + diagram_rect_.topLeft().x() + + (rows_header_width_ + + ((i - 1) * columns_width_)), + diagram_rect_.topLeft().y(), + columns_width_, + columns_header_height_ + ); + painter -> drawRect(numbered_rectangle); + if (settings.value("border-columns_0", true).toBool()){ + painter -> drawText(numbered_rectangle, + Qt::AlignVCenter + | Qt::AlignCenter, + QString("%1").arg(i - 1)); + }else{ + painter -> drawText(numbered_rectangle, + Qt::AlignVCenter + | Qt::AlignCenter, + QString("%1").arg(i)); + } + } + } - //Draw the nums of rows - if (display_border_ && display_rows_) { - QString row_string("A"); - for (int i = 1 ; i <= rows_count_ ; ++ i) { - QRectF lettered_rectangle = QRectF( - diagram_rect_.topLeft().x(), - diagram_rect_.topLeft().y() - + ( - columns_header_height_ - + ((i - 1)* rows_height_) - ), - rows_header_width_, - rows_height_ - ); - painter -> drawRect(lettered_rectangle); - painter -> drawText(lettered_rectangle, - Qt::AlignVCenter - | Qt::AlignCenter, - row_string); - row_string = incrementLetters(row_string); - } - } + //Draw the nums of rows + if (display_border_ && display_rows_) { + QString row_string("A"); + for (int i = 1 ; i <= rows_count_ ; ++ i) { + QRectF lettered_rectangle = QRectF( + diagram_rect_.topLeft().x(), + diagram_rect_.topLeft().y() + + ( + columns_header_height_ + + ((i - 1)* rows_height_) + ), + rows_header_width_, + rows_height_ + ); + painter -> drawRect(lettered_rectangle); + painter -> drawText(lettered_rectangle, + Qt::AlignVCenter + | Qt::AlignCenter, + row_string); + row_string = incrementLetters(row_string); + } + } - // render the titleblock, using the TitleBlockTemplate object - if (display_titleblock_) { - QRectF tbt_rect = titleBlockRectForQPainter(); - if (m_edge == Qt::BottomEdge) - { - painter -> translate(tbt_rect.topLeft()); - m_titleblock_template_renderer -> render( - painter, - tbt_rect.width()); - painter -> translate(-tbt_rect.topLeft()); - } - else - { - painter->translate(tbt_rect.topLeft()); - painter->rotate(-90); - m_titleblock_template_renderer -> render( - painter, - tbt_rect.width()); - painter->rotate(90); - painter -> translate(-tbt_rect.topLeft()); - } - } + // render the titleblock, using the TitleBlockTemplate object + if (display_titleblock_) { + QRectF tbt_rect = titleBlockRectForQPainter(); + if (m_edge == Qt::BottomEdge) + { + painter -> translate(tbt_rect.topLeft()); + m_titleblock_template_renderer -> render( + painter, + tbt_rect.width()); + painter -> translate(-tbt_rect.topLeft()); + } + else + { + painter->translate(tbt_rect.topLeft()); + painter->rotate(-90); + m_titleblock_template_renderer -> render( + painter, + tbt_rect.width()); + painter->rotate(90); + painter -> translate(-tbt_rect.topLeft()); + } + } - painter -> restore(); + painter -> restore(); } /** - @brief BorderTitleBlock::drawDxf - @param file_path - @param color + @brief BorderTitleBlock::drawDxf + @param file_path + @param color */ void BorderTitleBlock::drawDxf( - QString &file_path, - int color) + QString &file_path, + int color) { - // Transform to DXF scale. - columns_header_height_ *= Createdxf::yScale; - rows_height_ *= Createdxf::yScale; - rows_header_width_ *= Createdxf::xScale; - columns_width_ *= Createdxf::xScale; + // Transform to DXF scale. + columns_header_height_ *= Createdxf::yScale; + rows_height_ *= Createdxf::yScale; + rows_header_width_ *= Createdxf::xScale; + columns_width_ *= Createdxf::xScale; - // draw the empty box that appears as soon as there is a header - // dessine la case vide qui apparait des qu'il y a un entete - if (display_border_ && - (display_columns_ || - display_rows_) - ) { - Createdxf::drawRectangle( - file_path, - double(diagram_rect_.topLeft().x()) * Createdxf::xScale, - Createdxf::sheetHeight - - double(diagram_rect_.topLeft().y()) - * Createdxf::yScale - - columns_header_height_, - rows_header_width_, - columns_header_height_, - color - ); - } + // draw the empty box that appears as soon as there is a header + // dessine la case vide qui apparait des qu'il y a un entete + if (display_border_ && + (display_columns_ || + display_rows_) + ) { + Createdxf::drawRectangle( + file_path, + double(diagram_rect_.topLeft().x()) * Createdxf::xScale, + Createdxf::sheetHeight + - double(diagram_rect_.topLeft().y()) + * Createdxf::yScale + - columns_header_height_, + rows_header_width_, + columns_header_height_, + color + ); + } - QSettings settings; + QSettings settings; - // draw the numbering of the columns - // dessine la numerotation des colonnes - if (display_border_ && - display_columns_) { - int offset = settings.value("border-columns_0", true).toBool() ? -1 : 0; - for (int i = 1 ; i <= columns_count_ ; ++ i) { - double xCoord = diagram_rect_.topLeft().x() * Createdxf::xScale + - (rows_header_width_ + ((i - 1) * - columns_width_)); - double yCoord = Createdxf::sheetHeight - - diagram_rect_.topLeft().y()*Createdxf::yScale - - columns_header_height_; - double recWidth = columns_width_; - double recHeight = columns_header_height_; - Createdxf::drawRectangle(file_path, xCoord, yCoord, - recWidth, recHeight, color); + // draw the numbering of the columns + // dessine la numerotation des colonnes + if (display_border_ && + display_columns_) { + int offset = settings.value("border-columns_0", true).toBool() ? -1 : 0; + for (int i = 1 ; i <= columns_count_ ; ++ i) { + double xCoord = diagram_rect_.topLeft().x() * Createdxf::xScale + + (rows_header_width_ + ((i - 1) * + columns_width_)); + double yCoord = Createdxf::sheetHeight + - diagram_rect_.topLeft().y()*Createdxf::yScale + - columns_header_height_; + double recWidth = columns_width_; + double recHeight = columns_header_height_; + Createdxf::drawRectangle(file_path, xCoord, yCoord, + recWidth, recHeight, color); - Createdxf::drawTextAligned(file_path, - QString::number(i + offset), - xCoord+recWidth/4, - yCoord + recHeight*0.5, - recHeight*0.7, - 0, - 0, - 1, - 2, - xCoord+recWidth/2, - 1, - color); - } - } + Createdxf::drawTextAligned(file_path, + QString::number(i + offset), + xCoord+recWidth/4, + yCoord + recHeight*0.5, + recHeight*0.7, + 0, + 0, + 1, + 2, + xCoord+recWidth/2, + 1, + color); + } + } - // draw line numbering - // dessine la numerotation des lignes - if (display_border_ && display_rows_) { - QString row_string("A"); - for (int i = 1 ; i <= rows_count_ ; ++ i) { - double xCoord = diagram_rect_.topLeft().x() - * Createdxf::xScale; - double yCoord = Createdxf::sheetHeight - - diagram_rect_.topLeft().y() - *Createdxf::yScale - - ( - columns_header_height_ - + ((i - 1) - * rows_height_) ) - - rows_height_; - double recWidth = rows_header_width_; - double recHeight = rows_height_; - Createdxf::drawRectangle(file_path, xCoord, yCoord, - recWidth, recHeight, color); - Createdxf::drawTextAligned(file_path, - row_string, - xCoord+recWidth*0.1, - yCoord + recHeight*0.4, - recWidth*0.7, - 0, - 0, - 1, - 2, - xCoord+recWidth/2, - 1, - color); - row_string = incrementLetters(row_string); - } - } + // draw line numbering + // dessine la numerotation des lignes + if (display_border_ && display_rows_) { + QString row_string("A"); + for (int i = 1 ; i <= rows_count_ ; ++ i) { + double xCoord = diagram_rect_.topLeft().x() + * Createdxf::xScale; + double yCoord = Createdxf::sheetHeight + - diagram_rect_.topLeft().y() + *Createdxf::yScale + - ( + columns_header_height_ + + ((i - 1) + * rows_height_) ) + - rows_height_; + double recWidth = rows_header_width_; + double recHeight = rows_height_; + Createdxf::drawRectangle(file_path, xCoord, yCoord, + recWidth, recHeight, color); + Createdxf::drawTextAligned(file_path, + row_string, + xCoord+recWidth*0.1, + yCoord + recHeight*0.4, + recWidth*0.7, + 0, + 0, + 1, + 2, + xCoord+recWidth/2, + 1, + color); + row_string = incrementLetters(row_string); + } + } - // render the titleblock, using the TitleBlockTemplate object - if (display_titleblock_) { - //qp -> translate(titleblock_rect_.topLeft()); - QRectF rect = titleBlockRect(); - m_titleblock_template_renderer -> renderDxf(rect, - rect.width(), - file_path, - color); - //qp -> translate(-titleblock_rect_.topLeft()); - } + // render the titleblock, using the TitleBlockTemplate object + if (display_titleblock_) { + //qp -> translate(titleblock_rect_.topLeft()); + QRectF rect = titleBlockRect(); + m_titleblock_template_renderer -> renderDxf(rect, + rect.width(), + file_path, + color); + //qp -> translate(-titleblock_rect_.topLeft()); + } - // Transform back to QET scale - columns_header_height_ /= Createdxf::yScale; - rows_height_ /= Createdxf::yScale; - rows_header_width_ /= Createdxf::xScale; - columns_width_ /= Createdxf::xScale; + // Transform back to QET scale + columns_header_height_ /= Createdxf::yScale; + rows_height_ /= Createdxf::yScale; + rows_header_width_ /= Createdxf::xScale; + columns_width_ /= Createdxf::xScale; } /** - @brief BorderTitleBlock::setColumnsCount - Allows you to change the number of columns. - If this number of columns is less than the minimum required, - it is this minimum which is used. + @brief BorderTitleBlock::setColumnsCount + Allows you to change the number of columns. + If this number of columns is less than the minimum required, + it is this minimum which is used. - \~French Permet de changer le nombre de colonnes. - Si ce nombre de colonnes est inferieur au minimum requis, - c'est ce minimum qui est utilise. - \~ @param nb_c : new number of columns - \~French nouveau nombre de colonnes - \~ @see minNbColumns() + \~French Permet de changer le nombre de colonnes. + Si ce nombre de colonnes est inferieur au minimum requis, + c'est ce minimum qui est utilise. + \~ @param nb_c : new number of columns + \~French nouveau nombre de colonnes + \~ @see minNbColumns() */ void BorderTitleBlock::setColumnsCount(int nb_c) { - if (nb_c == columnsCount()) return; - columns_count_ = qMax(MIN_COLUMN_COUNT , nb_c); - updateRectangles(); + if (nb_c == columnsCount()) return; + columns_count_ = qMax(MIN_COLUMN_COUNT , nb_c); + updateRectangles(); } /** - @brief BorderTitleBlock::setColumnsWidth - Change the width of the columns. - If the width indicated is less than the minimum required, - it is this minimum which is used. + @brief BorderTitleBlock::setColumnsWidth + Change the width of the columns. + If the width indicated is less than the minimum required, + it is this minimum which is used. - \~French Change la largeur des colonnes. - Si la largeur indiquee est inferieure au minimum requis, - c'est ce minimum qui est utilise. - \~ @param new_cw : new column width - \~French nouvelle largeur des colonnes - \~ @see minColumnsWidth() + \~French Change la largeur des colonnes. + Si la largeur indiquee est inferieure au minimum requis, + c'est ce minimum qui est utilise. + \~ @param new_cw : new column width + \~French nouvelle largeur des colonnes + \~ @see minColumnsWidth() */ void BorderTitleBlock::setColumnsWidth(const qreal &new_cw) { - if (new_cw == columnsWidth()) return; - columns_width_ = qMax(MIN_COLUMN_WIDTH , new_cw); - updateRectangles(); + if (new_cw == columnsWidth()) return; + columns_width_ = qMax(MIN_COLUMN_WIDTH , new_cw); + updateRectangles(); } /** - @brief BorderTitleBlock::setColumnsHeaderHeight - Change the height of the headers containing the column numbers. - This must remain between 5 and 50 px. + @brief BorderTitleBlock::setColumnsHeaderHeight + Change the height of the headers containing the column numbers. + This must remain between 5 and 50 px. - \~French Change la hauteur des en-tetes contenant les numeros de colonnes. - Celle-ci doit rester comprise entre 5 et 50 px. - \~ @param new_chh : new height of column headers - \~French nouvelle hauteur des en-tetes de colonnes + \~French Change la hauteur des en-tetes contenant les numeros de colonnes. + Celle-ci doit rester comprise entre 5 et 50 px. + \~ @param new_chh : new height of column headers + \~French nouvelle hauteur des en-tetes de colonnes */ void BorderTitleBlock::setColumnsHeaderHeight(const qreal &new_chh) { - columns_header_height_ = qBound(qreal(5.0), new_chh, qreal(50.0)); - updateRectangles(); + columns_header_height_ = qBound(qreal(5.0), new_chh, qreal(50.0)); + updateRectangles(); } /** - @brief BorderTitleBlock::setRowsCount - Allows you to change the number of lines. - If this number of lines is lower than the minimum required, - this function does nothing + @brief BorderTitleBlock::setRowsCount + Allows you to change the number of lines. + If this number of lines is lower than the minimum required, + this function does nothing - \~French Permet de changer le nombre de lignes. - Si ce nombre de lignes est inferieur au minimum requis, - cette fonction ne fait rien - \~ @param nb_r : new number of lines - \~French nouveau nombre de lignes - \~ @see minNbRows() + \~French Permet de changer le nombre de lignes. + Si ce nombre de lignes est inferieur au minimum requis, + cette fonction ne fait rien + \~ @param nb_r : new number of lines + \~French nouveau nombre de lignes + \~ @see minNbRows() */ void BorderTitleBlock::setRowsCount(int nb_r) { - if (nb_r == rowsCount()) return; - rows_count_ = qMax(MIN_ROW_COUNT, nb_r); - updateRectangles(); + if (nb_r == rowsCount()) return; + rows_count_ = qMax(MIN_ROW_COUNT, nb_r); + updateRectangles(); } /** - @brief BorderTitleBlock::setRowsHeight - Change the height of the lines. - If the indicated height is lower than the minimum required, - it is this minimum which is used. + @brief BorderTitleBlock::setRowsHeight + Change the height of the lines. + If the indicated height is lower than the minimum required, + it is this minimum which is used. - \~French Change la hauteur des lignes. - Si la hauteur indiquee est inferieure au minimum requis, - c'est ce minimum qui est utilise. - \~ @param new_rh : new row height - \~French nouvelle hauteur des lignes - \~ @see minRowsHeight() + \~French Change la hauteur des lignes. + Si la hauteur indiquee est inferieure au minimum requis, + c'est ce minimum qui est utilise. + \~ @param new_rh : new row height + \~French nouvelle hauteur des lignes + \~ @see minRowsHeight() */ void BorderTitleBlock::setRowsHeight(const qreal &new_rh) { - if (new_rh == rowsHeight()) return; - rows_height_ = qMax(MIN_ROW_HEIGHT, new_rh); - updateRectangles(); + if (new_rh == rowsHeight()) return; + rows_height_ = qMax(MIN_ROW_HEIGHT, new_rh); + updateRectangles(); } /** - @brief BorderTitleBlock::setRowsHeaderWidth - Change the width of the headers containing the line numbers. - This must remain between 5 and 50 px. + @brief BorderTitleBlock::setRowsHeaderWidth + Change the width of the headers containing the line numbers. + This must remain between 5 and 50 px. - \~French Change la largeur des en-tetes contenant les numeros de lignes. - Celle-ci doit rester comprise entre 5 et 50 px. - \~ @param new_rhw : new width of line headers - \~French nouvelle largeur des en-tetes des lignes + \~French Change la largeur des en-tetes contenant les numeros de lignes. + Celle-ci doit rester comprise entre 5 et 50 px. + \~ @param new_rhw : new width of line headers + \~French nouvelle largeur des en-tetes des lignes */ void BorderTitleBlock::setRowsHeaderWidth(const qreal &new_rhw) { - rows_header_width_ = qBound(qreal(5.0), new_rhw, qreal(50.0)); - updateRectangles(); + rows_header_width_ = qBound(qreal(5.0), new_rhw, qreal(50.0)); + updateRectangles(); } /** - @brief BorderTitleBlock::setDiagramHeight - This method tries to get as close as possible to the given height - as a parameter by modifying the number of rows in progress. + @brief BorderTitleBlock::setDiagramHeight + This method tries to get as close as possible to the given height + as a parameter by modifying the number of rows in progress. - \~French Cette methode essaye de se rapprocher le plus possible de la - hauteur donnee en parametre en modifiant le nombre de lignes en cours. - \~ @param height : + \~French Cette methode essaye de se rapprocher le plus possible de la + hauteur donnee en parametre en modifiant le nombre de lignes en cours. + \~ @param height : */ void BorderTitleBlock::setDiagramHeight(const qreal &height) { - // size of rows to use = rows_height - // taille des lignes a utiliser = rows_height - setRowsCount(qRound(ceil(height / rows_height_))); + // size of rows to use = rows_height + // taille des lignes a utiliser = rows_height + setRowsCount(qRound(ceil(height / rows_height_))); } /** - @brief BorderTitleBlock::convertPosition - Convert a Point in cartesian coordinate (x : 12.5, 56.9) - to a point in grid coordinate (ex : B2) - @param pos : position to convert - @return the converted point in grid coordinate. + @brief BorderTitleBlock::convertPosition + Convert a Point in cartesian coordinate (x : 12.5, 56.9) + to a point in grid coordinate (ex : B2) + @param pos : position to convert + @return the converted point in grid coordinate. */ DiagramPosition BorderTitleBlock::convertPosition(const QPointF &pos) { - if(!insideBorderRect().contains(pos)) - return (DiagramPosition("", 0)); + if(!insideBorderRect().contains(pos)) + return (DiagramPosition("", 0)); - QPointF relative_pos = pos - insideBorderRect().topLeft(); - int row_number = int(ceil(relative_pos.x() / columnsWidth())); - int column_number = int(ceil(relative_pos.y() / rowsHeight())); + QPointF relative_pos = pos - insideBorderRect().topLeft(); + int row_number = int(ceil(relative_pos.x() / columnsWidth())); + int column_number = int(ceil(relative_pos.y() / rowsHeight())); - QString letter = "A"; - for (int i = 1 ; i < column_number ; ++ i) - letter = incrementLetters(letter); + QString letter = "A"; + for (int i = 1 ; i < column_number ; ++ i) + letter = incrementLetters(letter); - return(DiagramPosition(letter, row_number)); + return(DiagramPosition(letter, row_number)); } /** - @brief BorderTitleBlock::setAuthor - @param author the new value of the "Author" field + @brief BorderTitleBlock::setAuthor + @param author the new value of the "Author" field */ void BorderTitleBlock::setAuthor(const QString &author) { - btb_author_ = author; + btb_author_ = author; } /** - @brief BorderTitleBlock::setDate - @param date the new value of the "Date" field + @brief BorderTitleBlock::setDate + @param date the new value of the "Date" field */ void BorderTitleBlock::setDate(const QDate &date) { - btb_date_ = date; + btb_date_ = date; } /** - @brief BorderTitleBlock::setTitle - @param title the new value of the "Title" field + @brief BorderTitleBlock::setTitle + @param title the new value of the "Title" field */ void BorderTitleBlock::setTitle(const QString &title) { - if (btb_title_ != title) - { - btb_title_ = title; - emit(diagramTitleChanged(title)); - } + if (btb_title_ != title) + { + btb_title_ = title; + emit(diagramTitleChanged(title)); + } } /** - @brief BorderTitleBlock::setFolio - @param folio the new value of the "Folio" field + @brief BorderTitleBlock::setFolio + @param folio the new value of the "Folio" field */ void BorderTitleBlock::setFolio(const QString &folio) { - btb_folio_ = folio; - emit (titleBlockFolioChanged(folio)); + btb_folio_ = folio; + emit (titleBlockFolioChanged(folio)); } /** - @brief BorderTitleBlock::updateDiagramContextForTitleBlock - Update the informations given to the titleblock template - by regenerating a DiagramContext object. - @param initial_context : - Base diagram context that will be overridden by diagram-wide values + @brief BorderTitleBlock::updateDiagramContextForTitleBlock + Update the informations given to the titleblock template + by regenerating a DiagramContext object. + @param initial_context : + Base diagram context that will be overridden by diagram-wide values */ void BorderTitleBlock::updateDiagramContextForTitleBlock( - const DiagramContext &initial_context) { - // Our final DiagramContext is the initial one (which is supposed to bring - // project-wide properties), overridden by the "additional fields" one... - DiagramContext context = initial_context; - foreach (QString key, additional_fields_.keys()) { - context.addValue(key, additional_fields_[key]); - } + const DiagramContext &initial_context) { + // Our final DiagramContext is the initial one (which is supposed to bring + // project-wide properties), overridden by the "additional fields" one... + DiagramContext context = initial_context; + foreach (QString key, additional_fields_.keys()) { + context.addValue(key, additional_fields_[key]); + } - // ... overridden by the historical and/or dynamically generated fields - QLocale var; - var.dateFormat(QLocale::ShortFormat); - context.addValue("author", btb_author_); - context.addValue( - "date", - QLocale::system().toString(btb_date_, QLocale::ShortFormat)); - context.addValue("title", btb_title_); - context.addValue("filename", btb_filename_); - context.addValue("plant", btb_plant_); - context.addValue("locmach", btb_locmach_); - context.addValue("indexrev", btb_indexrev_); - context.addValue("version", btb_version_); - context.addValue("folio", btb_final_folio_); - context.addValue("folio-id", folio_index_); - context.addValue("folio-total", folio_total_); - context.addValue("auto_page_num", btb_auto_page_num_); - context.addValue("previous-folio-num", m_previous_folio_num); - context.addValue("next-folio-num", m_next_folio_num); + // ... overridden by the historical and/or dynamically generated fields + QLocale var; + var.dateFormat(QLocale::ShortFormat); + context.addValue("author", btb_author_); + context.addValue( + "date", + QLocale::system().toString(btb_date_, QLocale::ShortFormat)); + context.addValue("title", btb_title_); + context.addValue("filename", btb_filename_); + context.addValue("plant", btb_plant_); + context.addValue("locmach", btb_locmach_); + context.addValue("indexrev", btb_indexrev_); + context.addValue("version", btb_version_); + context.addValue("folio", btb_final_folio_); + context.addValue("folio-id", folio_index_); + context.addValue("folio-total", folio_total_); + context.addValue("auto_page_num", btb_auto_page_num_); + context.addValue("previous-folio-num", m_previous_folio_num); + context.addValue("next-folio-num", m_next_folio_num); - m_titleblock_template_renderer -> setContext(context); + m_titleblock_template_renderer -> setContext(context); } /** - @brief BorderTitleBlock::incrementLetters - increments string with Letters A to Z - @param string - @return string ++Letters - eg: - - A-> B - - Z -> AA + @brief BorderTitleBlock::incrementLetters + increments string with Letters A to Z + @param string + @return string ++Letters + eg: + - A-> B + - Z -> AA */ QString BorderTitleBlock::incrementLetters(const QString &string) { - if (string.isEmpty()) { - return("A"); - } else { - // separate previous digits from last digit - // separe les digits precedents du dernier digit - QString first_digits(string.left(string.count() - 1)); - QChar last_digit(string.at(string.count() - 1)); - if (last_digit != 'Z') { - // increments the last digit - // incremente le dernier digit - last_digit = last_digit.toLatin1() + 1; - return(first_digits + QString(last_digit)); - } else { - return(incrementLetters(first_digits) + "A"); - } - } + if (string.isEmpty()) { + return("A"); + } else { + // separate previous digits from last digit + // separe les digits precedents du dernier digit + QString first_digits(string.left(string.count() - 1)); + QChar last_digit(string.at(string.count() - 1)); + if (last_digit != 'Z') { + // increments the last digit + // incremente le dernier digit + last_digit = last_digit.toLatin1() + 1; + return(first_digits + QString(last_digit)); + } else { + return(incrementLetters(first_digits) + "A"); + } + } } /** - @brief BorderTitleBlock::setFolioData + @brief BorderTitleBlock::setFolioData - \~ @param index : schema number (from 1 to total) - \~French numero du schema (de 1 a total) + \~ @param index : schema number (from 1 to total) + \~French numero du schema (de 1 a total) - \~ @param total : total number of diagrams in the project - \~French nombre total de schemas dans le projet + \~ @param total : total number of diagrams in the project + \~French nombre total de schemas dans le projet - \~ @param autonum : + \~ @param autonum : - \~ @param project_properties : Project-wide properties, - to be merged with diagram-wide ones. + \~ @param project_properties : Project-wide properties, + to be merged with diagram-wide ones. */ void BorderTitleBlock::setFolioData( - int index, - int total, - const QString& autonum, - const DiagramContext &project_properties) { - if (index < 1 || total < 1 || index > total) return; + int index, + int total, + const QString& autonum, + const DiagramContext &project_properties) { + if (index < 1 || total < 1 || index > total) return; - // memorize information - // memorise les informations - folio_index_ = index; - folio_total_ = total; + // memorize information + // memorise les informations + folio_index_ = index; + folio_total_ = total; - // regenerate the content of the folio field - // regenere le contenu du champ folio - btb_final_folio_ = btb_folio_; + // regenerate the content of the folio field + // regenere le contenu du champ folio + btb_final_folio_ = btb_folio_; - if (btb_final_folio_.contains("%autonum")){ - btb_final_folio_.replace("%autonum", autonum); - btb_folio_ = btb_final_folio_; - } - btb_final_folio_.replace("%id", QString::number(folio_index_)); - btb_final_folio_.replace("%total", QString::number(folio_total_)); + if (btb_final_folio_.contains("%autonum")){ + btb_final_folio_.replace("%autonum", autonum); + btb_folio_ = btb_final_folio_; + } + btb_final_folio_.replace("%id", QString::number(folio_index_)); + btb_final_folio_.replace("%total", QString::number(folio_total_)); - updateDiagramContextForTitleBlock(project_properties); + updateDiagramContextForTitleBlock(project_properties); } /** - @brief BorderTitleBlock::setPlant - @param plant the new value of the "plant" field + @brief BorderTitleBlock::setPlant + @param plant the new value of the "plant" field */ void BorderTitleBlock::setPlant(const QString &plant) { - btb_plant_ = plant; + btb_plant_ = plant; } /** - @brief BorderTitleBlock::setLocMach - @param locmach the new value of the "locmach" field + @brief BorderTitleBlock::setLocMach + @param locmach the new value of the "locmach" field */ void BorderTitleBlock::setLocMach(const QString &locmach) { - btb_locmach_ = locmach; + btb_locmach_ = locmach; } /** - @brief BorderTitleBlock::setIndicerev - @param indexrev the new value of the "indexrev" field + @brief BorderTitleBlock::setIndicerev + @param indexrev the new value of the "indexrev" field */ void BorderTitleBlock::setIndicerev(const QString &indexrev) { - btb_indexrev_ = indexrev; + btb_indexrev_ = indexrev; } /** - @brief BorderTitleBlock::setFileName - @param filename the new value of the "filename" field + @brief BorderTitleBlock::setFileName + @param filename the new value of the "filename" field */ void BorderTitleBlock::setFileName(const QString &filename) { - btb_filename_ = filename; + btb_filename_ = filename; } /** - @brief BorderTitleBlock::setVersion - @param version the new value of the "version" field + @brief BorderTitleBlock::setVersion + @param version the new value of the "version" field */ void BorderTitleBlock::setVersion(const QString &version) { - btb_version_ = version; + btb_version_ = version; } /** - @brief BorderTitleBlock::setAutoPageNum - @param auto_page_num the new value of the "auto_page_num" field + @brief BorderTitleBlock::setAutoPageNum + @param auto_page_num the new value of the "auto_page_num" field */ void BorderTitleBlock::setAutoPageNum(const QString &auto_page_num) { - btb_auto_page_num_ = auto_page_num; + btb_auto_page_num_ = auto_page_num; } /** - @brief BorderTitleBlock::setPreviousFolioNum - @param previous the new value of the "previous-folio-num" field + @brief BorderTitleBlock::setPreviousFolioNum + @param previous the new value of the "previous-folio-num" field */ void BorderTitleBlock::setPreviousFolioNum(const QString &previous) { - m_previous_folio_num = previous; - DiagramContext context = m_titleblock_template_renderer->context(); - context.addValue("previous-folio-num", m_previous_folio_num); - m_titleblock_template_renderer->setContext(context); + m_previous_folio_num = previous; + DiagramContext context = m_titleblock_template_renderer->context(); + context.addValue("previous-folio-num", m_previous_folio_num); + m_titleblock_template_renderer->setContext(context); } /** - @brief BorderTitleBlock::setNextFolioNum - @param next the new value of the "next-folio-num" field + @brief BorderTitleBlock::setNextFolioNum + @param next the new value of the "next-folio-num" field */ void BorderTitleBlock::setNextFolioNum(const QString &next) { - m_next_folio_num = next; - DiagramContext context = m_titleblock_template_renderer->context(); - context.addValue("next-folio-num", m_next_folio_num); - m_titleblock_template_renderer->setContext(context); + m_next_folio_num = next; + DiagramContext context = m_titleblock_template_renderer->context(); + context.addValue("next-folio-num", m_next_folio_num); + m_titleblock_template_renderer->setContext(context); } diff --git a/sources/bordertitleblock.h b/sources/bordertitleblock.h index 39a7f93a6..779b2f005 100644 --- a/sources/bordertitleblock.h +++ b/sources/bordertitleblock.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef BORDERTITLEBLOCK_H #define BORDERTITLEBLOCK_H @@ -29,266 +29,266 @@ class DiagramPosition; class TitleBlockTemplate; class TitleBlockTemplateRenderer; /** - @brief The BorderTitleBlock class - This class represents the border and the titleblock which frame a - particular electric diagram. + @brief The BorderTitleBlock class + This class represents the border and the titleblock which frame a + particular electric diagram. */ class BorderTitleBlock : public QObject { - Q_OBJECT - - public: - BorderTitleBlock(QObject * = nullptr); - ~BorderTitleBlock() override; - - private: - BorderTitleBlock(const BorderTitleBlock &); - - //METHODS - public: - void draw(QPainter *painter); - void drawDxf(QString &, int); - - //METHODS TO GET DIMENSION - //COLUMNS - /// @return the number of columns - int columnsCount() const { return(columns_count_); } - /// @return the columns width, in pixels - qreal columnsWidth() const { return(columns_width_); } - /// @return the total width of all columns, headers excluded - qreal columnsTotalWidth() const { - return(columns_count_ * columns_width_); } - /// @return the column headers height, in pixels - qreal columnsHeaderHeight() const { - return(columns_header_height_); } - - //ROWS - /// @return the number of rows - int rowsCount() const { return(rows_count_); } - /// @return the rows height, in pixels - qreal rowsHeight() const { return(rows_height_); } - /// @return the total height of all rows, headers excluded - qreal rowsTotalHeight() const { - return(rows_count_ * rows_height_); } - /// @return la rows header width, in pixels - qreal rowsHeaderWidth() const { return(rows_header_width_); } - - // border - title block = diagram - /** - @brief diagramWidth - @return the diagram width, - i.e. the width of the border without title block - */ - qreal diagramWidth() const + Q_OBJECT + + public: + BorderTitleBlock(QObject * = nullptr); + ~BorderTitleBlock() override; + + private: + BorderTitleBlock(const BorderTitleBlock &); + + //METHODS + public: + void draw(QPainter *painter); + void drawDxf(QString &, int); + + //METHODS TO GET DIMENSION + //COLUMNS + /// @return the number of columns + int columnsCount() const { return(columns_count_); } + /// @return the columns width, in pixels + qreal columnsWidth() const { return(columns_width_); } + /// @return the total width of all columns, headers excluded + qreal columnsTotalWidth() const { + return(columns_count_ * columns_width_); } + /// @return the column headers height, in pixels + qreal columnsHeaderHeight() const { + return(columns_header_height_); } + + //ROWS + /// @return the number of rows + int rowsCount() const { return(rows_count_); } + /// @return the rows height, in pixels + qreal rowsHeight() const { return(rows_height_); } + /// @return the total height of all rows, headers excluded + qreal rowsTotalHeight() const { + return(rows_count_ * rows_height_); } + /// @return la rows header width, in pixels + qreal rowsHeaderWidth() const { return(rows_header_width_); } + + // border - title block = diagram + /** + @brief diagramWidth + @return the diagram width, + i.e. the width of the border without title block + */ + qreal diagramWidth() const { - return(columnsTotalWidth() + rowsHeaderWidth()); } - /** - @brief diagramHeight - @return the diagram height, - i.e. the height of the border without title block - */ - qreal diagramHeight() const + return(columnsTotalWidth() + rowsHeaderWidth()); } + /** + @brief diagramHeight + @return the diagram height, + i.e. the height of the border without title block + */ + qreal diagramHeight() const { - return(rowsTotalHeight() + columnsHeaderHeight()); } + return(rowsTotalHeight() + columnsHeaderHeight()); } - QRectF titleBlockRect () const; + QRectF titleBlockRect () const; - DiagramContext titleblockInformation() const; - private: - QRectF titleBlockRectForQPainter () const; + DiagramContext titleblockInformation() const; + private: + QRectF titleBlockRectForQPainter () const; - public: - QRectF borderAndTitleBlockRect () const; - QRectF columnsRect () const; - QRectF rowsRect () const; - QRectF outsideBorderRect() const; - QRectF insideBorderRect() const; - - // methods to get title block basic data - /// @return the value of the title block "Author" field - QString author() const { return(btb_author_); } - /// @return the value of the title block "Date" field - QDate date() const { return(btb_date_); } - /// @return the value of the title block "Title" field - QString title() const { return(btb_title_); } - /// @return the value of the title block "Folio" field - QString folio() const { return(btb_folio_); } - /// @return the value of the title block "Folio" field as displayed - QString finalfolio() const { return(btb_final_folio_); } - /// @return the value of the title block "Plant" field - QString plant() const { return(btb_plant_); } - /// @return the value of the title block "Locmach" field - QString locmach() const { return(btb_locmach_); } - /// @return the value of the revision index block "Folio" field - QString indexrev() const { return(btb_indexrev_); } - /// @return the value of the title block "File" field - QString fileName() const { return(btb_filename_); } - /// @return the value of the title block Additional Fields - QString version() const { return(btb_version_); } - /// @return the value of the title block Additional Fields - DiagramContext additionalFields() const { - return (additional_fields_); } - /// @return the value of the title block - QString autoPageNum() const { return(btb_auto_page_num_); } - /// @return the value of the total number of folios - int folioTotal() const { return(folio_total_);} - - // methods to get display options - /// @return true si le cartouche est affiche, false sinon - bool titleBlockIsDisplayed() const { - return(display_titleblock_); } - /// @return true si les entetes des colonnes sont affiches, - /// false sinon - bool columnsAreDisplayed() const { return(display_columns_); } - /// @return true si les entetes des lignes sont affiches, - /// false sinon - bool rowsAreDisplayed() const { return(display_rows_); } - /// @return true si la bordure est affichee, false sinon - bool borderIsDisplayed() const { return(display_border_); } - - // methods to set dimensions - void setColumnsCount(int); - void setRowsCount(int); - void setColumnsWidth(const qreal &); - void setRowsHeight(const qreal &); - void setColumnsHeaderHeight(const qreal &); - void setRowsHeaderWidth(const qreal &); - void setDiagramHeight(const qreal &); - - DiagramPosition convertPosition(const QPointF &); - - // methods to set title block basic data - void setAuthor(const QString &author); - void setDate(const QDate &date); - void setTitle(const QString &title); - void setFolio(const QString &folio); - void setFolioData(int, int, const QString& = nullptr, - const DiagramContext & = DiagramContext()); - void setPlant(const QString &plant); - void setLocMach(const QString &locmach); - void setIndicerev(const QString &indexrev); - void setFileName(const QString &filename); - void setVersion(const QString &version); - void setAutoPageNum(const QString &auto_page_num); - void setPreviousFolioNum(const QString &previous); - void setNextFolioNum(const QString &next); - - void titleBlockToXml(QDomElement &); - void titleBlockFromXml(const QDomElement &); - void borderToXml(QDomElement &); - void borderFromXml(const QDomElement &); - - TitleBlockProperties exportTitleBlock(); - void importTitleBlock(const TitleBlockProperties &); - BorderProperties exportBorder(); - void importBorder(const BorderProperties &); - - const TitleBlockTemplate *titleBlockTemplate(); - void setTitleBlockTemplate(const TitleBlockTemplate *); - QString titleBlockTemplateName() const; - - public slots: - void titleBlockTemplateChanged(const QString &); - void titleBlockTemplateRemoved( - const QString &, - const TitleBlockTemplate * = nullptr); - - // methods to set display options - void displayTitleBlock(bool); - void displayColumns(bool); - void displayRows(bool); - void displayBorder(bool); - void slot_setAutoPageNum (QString); - - private: - void updateRectangles(); - void updateDiagramContextForTitleBlock( - const DiagramContext & = DiagramContext()); - QString incrementLetters(const QString &); - - signals: - /** - @brief borderChanged - Signal emitted after the border has changed - @param old_border Former border - @param new_border New border - */ - void borderChanged(QRectF old_border, QRectF new_border); - /** - @brief displayChanged - Signal emitted after display options have changed - */ - void displayChanged(); - /** - @brief diagramTitleChanged - Signal emitted after the title has changed - */ - void diagramTitleChanged(const QString &); - /** - @brief titleBlockFolioChanged - Signal emitted after Folio has changed - */ - void titleBlockFolioChanged(const QString &); - /** - @brief needFolioData - Signal emitted when the title block - requires its data to be updated - in order to generate the folio field. - */ - void needFolioData(); - /** - @brief needTitleBlockTemplate - Signal emitted when this object needs to - set a specific title block template. - This object cannot handle the job - since it does not know of its parent project. - */ - void needTitleBlockTemplate(const QString &); - - // attributes - private: - // titleblock basic data - QString btb_author_; ///< titleblock author - QDate btb_date_; ///< titleblock date - QString btb_title_; ///< titleblock title - QString btb_folio_; ///< titleblock folio - QString btb_plant_; ///< titleblock plant - QString btb_locmach_; ///< titleblock locmach - QString btb_indexrev_; ///< titleblock index rev - QString btb_final_folio_; ///< titleblock final folio - QString btb_auto_page_num_; ///< titleblock auto page num - int folio_index_; ///< titleblock index - int folio_total_; ///< titleblock total - QString btb_filename_; ///< titleblock filename - QString btb_version_; ///< titleblock version - /// titleblock additional fields - DiagramContext additional_fields_; - Qt::Edge m_edge; ///< titleblock edge - QString m_next_folio_num; ///< titleblock next folio num - QString m_previous_folio_num; ///< titleblock previous folio num - - // border dimensions (rows and columns) - // columns: number and dimensions - int columns_count_; ///< columns count - qreal columns_width_; ///< columns width - qreal columns_header_height_; ///< columns header height - - // rows: number and dimensions - int rows_count_; ///< rows count - qreal rows_height_; ///< rows height - qreal rows_header_width_; ///< rows header width - - // title block dimensions - qreal titleblock_height_; - - // rectangles used for drawing operations - QRectF diagram_rect_; - - // display options - bool display_titleblock_; - bool display_columns_; - bool display_rows_; - bool display_border_; - TitleBlockTemplateRenderer *m_titleblock_template_renderer; + public: + QRectF borderAndTitleBlockRect () const; + QRectF columnsRect () const; + QRectF rowsRect () const; + QRectF outsideBorderRect() const; + QRectF insideBorderRect() const; + + // methods to get title block basic data + /// @return the value of the title block "Author" field + QString author() const { return(btb_author_); } + /// @return the value of the title block "Date" field + QDate date() const { return(btb_date_); } + /// @return the value of the title block "Title" field + QString title() const { return(btb_title_); } + /// @return the value of the title block "Folio" field + QString folio() const { return(btb_folio_); } + /// @return the value of the title block "Folio" field as displayed + QString finalfolio() const { return(btb_final_folio_); } + /// @return the value of the title block "Plant" field + QString plant() const { return(btb_plant_); } + /// @return the value of the title block "Locmach" field + QString locmach() const { return(btb_locmach_); } + /// @return the value of the revision index block "Folio" field + QString indexrev() const { return(btb_indexrev_); } + /// @return the value of the title block "File" field + QString fileName() const { return(btb_filename_); } + /// @return the value of the title block Additional Fields + QString version() const { return(btb_version_); } + /// @return the value of the title block Additional Fields + DiagramContext additionalFields() const { + return (additional_fields_); } + /// @return the value of the title block + QString autoPageNum() const { return(btb_auto_page_num_); } + /// @return the value of the total number of folios + int folioTotal() const { return(folio_total_);} + + // methods to get display options + /// @return true si le cartouche est affiche, false sinon + bool titleBlockIsDisplayed() const { + return(display_titleblock_); } + /// @return true si les entetes des colonnes sont affiches, + /// false sinon + bool columnsAreDisplayed() const { return(display_columns_); } + /// @return true si les entetes des lignes sont affiches, + /// false sinon + bool rowsAreDisplayed() const { return(display_rows_); } + /// @return true si la bordure est affichee, false sinon + bool borderIsDisplayed() const { return(display_border_); } + + // methods to set dimensions + void setColumnsCount(int); + void setRowsCount(int); + void setColumnsWidth(const qreal &); + void setRowsHeight(const qreal &); + void setColumnsHeaderHeight(const qreal &); + void setRowsHeaderWidth(const qreal &); + void setDiagramHeight(const qreal &); + + DiagramPosition convertPosition(const QPointF &); + + // methods to set title block basic data + void setAuthor(const QString &author); + void setDate(const QDate &date); + void setTitle(const QString &title); + void setFolio(const QString &folio); + void setFolioData(int, int, const QString& = nullptr, + const DiagramContext & = DiagramContext()); + void setPlant(const QString &plant); + void setLocMach(const QString &locmach); + void setIndicerev(const QString &indexrev); + void setFileName(const QString &filename); + void setVersion(const QString &version); + void setAutoPageNum(const QString &auto_page_num); + void setPreviousFolioNum(const QString &previous); + void setNextFolioNum(const QString &next); + + void titleBlockToXml(QDomElement &); + void titleBlockFromXml(const QDomElement &); + void borderToXml(QDomElement &); + void borderFromXml(const QDomElement &); + + TitleBlockProperties exportTitleBlock(); + void importTitleBlock(const TitleBlockProperties &); + BorderProperties exportBorder(); + void importBorder(const BorderProperties &); + + const TitleBlockTemplate *titleBlockTemplate(); + void setTitleBlockTemplate(const TitleBlockTemplate *); + QString titleBlockTemplateName() const; + + public slots: + void titleBlockTemplateChanged(const QString &); + void titleBlockTemplateRemoved( + const QString &, + const TitleBlockTemplate * = nullptr); + + // methods to set display options + void displayTitleBlock(bool); + void displayColumns(bool); + void displayRows(bool); + void displayBorder(bool); + void slot_setAutoPageNum (QString); + + private: + void updateRectangles(); + void updateDiagramContextForTitleBlock( + const DiagramContext & = DiagramContext()); + QString incrementLetters(const QString &); + + signals: + /** + @brief borderChanged + Signal emitted after the border has changed + @param old_border Former border + @param new_border New border + */ + void borderChanged(QRectF old_border, QRectF new_border); + /** + @brief displayChanged + Signal emitted after display options have changed + */ + void displayChanged(); + /** + @brief diagramTitleChanged + Signal emitted after the title has changed + */ + void diagramTitleChanged(const QString &); + /** + @brief titleBlockFolioChanged + Signal emitted after Folio has changed + */ + void titleBlockFolioChanged(const QString &); + /** + @brief needFolioData + Signal emitted when the title block + requires its data to be updated + in order to generate the folio field. + */ + void needFolioData(); + /** + @brief needTitleBlockTemplate + Signal emitted when this object needs to + set a specific title block template. + This object cannot handle the job + since it does not know of its parent project. + */ + void needTitleBlockTemplate(const QString &); + + // attributes + private: + // titleblock basic data + QString btb_author_; ///< titleblock author + QDate btb_date_; ///< titleblock date + QString btb_title_; ///< titleblock title + QString btb_folio_; ///< titleblock folio + QString btb_plant_; ///< titleblock plant + QString btb_locmach_; ///< titleblock locmach + QString btb_indexrev_; ///< titleblock index rev + QString btb_final_folio_; ///< titleblock final folio + QString btb_auto_page_num_; ///< titleblock auto page num + int folio_index_; ///< titleblock index + int folio_total_; ///< titleblock total + QString btb_filename_; ///< titleblock filename + QString btb_version_; ///< titleblock version + /// titleblock additional fields + DiagramContext additional_fields_; + Qt::Edge m_edge; ///< titleblock edge + QString m_next_folio_num; ///< titleblock next folio num + QString m_previous_folio_num; ///< titleblock previous folio num + + // border dimensions (rows and columns) + // columns: number and dimensions + int columns_count_; ///< columns count + qreal columns_width_; ///< columns width + qreal columns_header_height_; ///< columns header height + + // rows: number and dimensions + int rows_count_; ///< rows count + qreal rows_height_; ///< rows height + qreal rows_header_width_; ///< rows header width + + // title block dimensions + qreal titleblock_height_; + + // rectangles used for drawing operations + QRectF diagram_rect_; + + // display options + bool display_titleblock_; + bool display_columns_; + bool display_rows_; + bool display_border_; + TitleBlockTemplateRenderer *m_titleblock_template_renderer; }; #endif diff --git a/sources/conductorproperties.cpp b/sources/conductorproperties.cpp index b26853f8b..bd1b3f999 100644 --- a/sources/conductorproperties.cpp +++ b/sources/conductorproperties.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "conductorproperties.h" #include @@ -21,13 +21,13 @@ #include #include /** - Constructeur par defaut + Constructeur par defaut */ SingleLineProperties::SingleLineProperties() : - hasGround(true), - hasNeutral(true), - is_pen(false), - phases(1) + hasGround(true), + hasNeutral(true), + is_pen(false), + phases(1) { } @@ -37,224 +37,224 @@ SingleLineProperties::~SingleLineProperties() } /** - Definit le nombre de phases (0, 1, 2, ou 3) - @param n Nombre de phases + Definit le nombre de phases (0, 1, 2, ou 3) + @param n Nombre de phases */ void SingleLineProperties::setPhasesCount(int n) { - phases = qBound(0, n, 3); + phases = qBound(0, n, 3); } /// @return le nombre de phases (0, 1, 2, ou 3) unsigned short int SingleLineProperties::phasesCount() { - return(phases); + return(phases); } /** - @return true if the singleline conductor should be drawn using the PEN - (Protective Earth Neutral) representation and if it features the ground and - the neutral. + @return true if the singleline conductor should be drawn using the PEN + (Protective Earth Neutral) representation and if it features the ground and + the neutral. */ bool SingleLineProperties::isPen() const { - return(hasNeutral && hasGround && is_pen); + return(hasNeutral && hasGround && is_pen); } /** - Dessine les symboles propres a un conducteur unifilaire - @param painter QPainter a utiliser pour dessiner les symboles - @param direction direction du segment sur lequel les symboles apparaitront - @param rect rectangle englobant le dessin ; utilise pour specifier a la fois la position et la taille du dessin + Dessine les symboles propres a un conducteur unifilaire + @param painter QPainter a utiliser pour dessiner les symboles + @param direction direction du segment sur lequel les symboles apparaitront + @param rect rectangle englobant le dessin ; utilise pour specifier a la fois la position et la taille du dessin */ void SingleLineProperties::draw(QPainter *painter, - QET::ConductorSegmentType direction, - const QRectF &rect) { - // s'il n'y a rien a dessiner, on retourne immediatement - if (!hasNeutral && !hasGround && !phases) return; + QET::ConductorSegmentType direction, + const QRectF &rect) { + // s'il n'y a rien a dessiner, on retourne immediatement + if (!hasNeutral && !hasGround && !phases) return; - // prepare le QPainter - painter -> save(); - QPen pen(painter -> pen()); - pen.setCapStyle(Qt::FlatCap); - pen.setJoinStyle(Qt::MiterJoin); - pen.setStyle(Qt::SolidLine); - pen.setWidthF(1); - painter -> setPen(pen); - painter -> setRenderHint(QPainter::Antialiasing, true); + // prepare le QPainter + painter -> save(); + QPen pen(painter -> pen()); + pen.setCapStyle(Qt::FlatCap); + pen.setJoinStyle(Qt::MiterJoin); + pen.setStyle(Qt::SolidLine); + pen.setWidthF(1); + painter -> setPen(pen); + painter -> setRenderHint(QPainter::Antialiasing, true); - uint symbols_count = (hasNeutral ? 1 : 0) + (hasGround ? 1 : 0) - (isPen() ? 1 : 0) + phases; - qreal interleave_base = (direction == QET::Horizontal ? rect.width() : rect.height()); - qreal interleave = interleave_base / (symbols_count + 1);; - qreal symbol_width = interleave_base / 12; + uint symbols_count = (hasNeutral ? 1 : 0) + (hasGround ? 1 : 0) - (isPen() ? 1 : 0) + phases; + qreal interleave_base = (direction == QET::Horizontal ? rect.width() : rect.height()); + qreal interleave = interleave_base / (symbols_count + 1);; + qreal symbol_width = interleave_base / 12; - for (uint i = 1 ; i <= symbols_count ; ++ i) { - // dessine le tronc du symbole - QPointF symbol_p1, symbol_p2; - if (direction == QET::Horizontal) { - symbol_p1 = QPointF(rect.x() + (i * interleave) + symbol_width, rect.y() + rect.height() * 0.75); - symbol_p2 = QPointF(rect.x() + (i * interleave) - symbol_width, rect.y() + rect.height() * 0.25); - } else { - symbol_p2 = QPointF(rect.x() + rect.width() * 0.75, rect.y() + (i * interleave) - symbol_width); - symbol_p1 = QPointF(rect.x() + rect.width() * 0.25, rect.y() + (i * interleave) + symbol_width); - } - painter -> drawLine(QLineF(symbol_p1, symbol_p2)); + for (uint i = 1 ; i <= symbols_count ; ++ i) { + // dessine le tronc du symbole + QPointF symbol_p1, symbol_p2; + if (direction == QET::Horizontal) { + symbol_p1 = QPointF(rect.x() + (i * interleave) + symbol_width, rect.y() + rect.height() * 0.75); + symbol_p2 = QPointF(rect.x() + (i * interleave) - symbol_width, rect.y() + rect.height() * 0.25); + } else { + symbol_p2 = QPointF(rect.x() + rect.width() * 0.75, rect.y() + (i * interleave) - symbol_width); + symbol_p1 = QPointF(rect.x() + rect.width() * 0.25, rect.y() + (i * interleave) + symbol_width); + } + painter -> drawLine(QLineF(symbol_p1, symbol_p2)); - // dessine le reste des symboles terre et neutre - if (isPen()) { - if (i == 1) { - drawPen(painter, direction, symbol_p2, symbol_width); - } - } else { - if (hasGround && i == 1) { - drawGround(painter, direction, symbol_p2, symbol_width * 2.0); - } else if (hasNeutral && ((i == 1 && !hasGround) || (i == 2 && hasGround))) { - drawNeutral(painter, symbol_p2, symbol_width * 1.5); - } - } - } - painter -> restore(); + // dessine le reste des symboles terre et neutre + if (isPen()) { + if (i == 1) { + drawPen(painter, direction, symbol_p2, symbol_width); + } + } else { + if (hasGround && i == 1) { + drawGround(painter, direction, symbol_p2, symbol_width * 2.0); + } else if (hasNeutral && ((i == 1 && !hasGround) || (i == 2 && hasGround))) { + drawNeutral(painter, symbol_p2, symbol_width * 1.5); + } + } + } + painter -> restore(); } /** - Dessine le segment correspondant au symbole de la terre sur un conducteur unifilaire - @param painter QPainter a utiliser pour dessiner le segment - @param direction direction du segment sur lequel le symbole apparaitra - @param center centre du segment - @param size taille du segment + Dessine le segment correspondant au symbole de la terre sur un conducteur unifilaire + @param painter QPainter a utiliser pour dessiner le segment + @param direction direction du segment sur lequel le symbole apparaitra + @param center centre du segment + @param size taille du segment */ void SingleLineProperties::drawGround(QPainter *painter, - QET::ConductorSegmentType direction, - QPointF center, - qreal size) { - painter -> save(); + QET::ConductorSegmentType direction, + QPointF center, + qreal size) { + painter -> save(); - // prepare le QPainter - painter -> setRenderHint(QPainter::Antialiasing, false); - QPen pen2(painter -> pen()); - pen2.setCapStyle(Qt::SquareCap); - painter -> setPen(pen2); + // prepare le QPainter + painter -> setRenderHint(QPainter::Antialiasing, false); + QPen pen2(painter -> pen()); + pen2.setCapStyle(Qt::SquareCap); + painter -> setPen(pen2); - // dessine le segment representant la terre - qreal half_size = size / 2.0; - QPointF offset_point( - (direction == QET::Horizontal) ? half_size : 0.0, - (direction == QET::Horizontal) ? 0.0 : half_size - ); - painter -> drawLine( - QLineF( - center + offset_point, - center - offset_point - ) - ); + // dessine le segment representant la terre + qreal half_size = size / 2.0; + QPointF offset_point( + (direction == QET::Horizontal) ? half_size : 0.0, + (direction == QET::Horizontal) ? 0.0 : half_size + ); + painter -> drawLine( + QLineF( + center + offset_point, + center - offset_point + ) + ); - painter -> restore(); + painter -> restore(); } /** - Dessine le cercle correspondant au symbole du neutre sur un conducteur unifilaire - @param painter QPainter a utiliser pour dessiner le segment - @param center centre du cercle - @param size diametre du cercle + Dessine le cercle correspondant au symbole du neutre sur un conducteur unifilaire + @param painter QPainter a utiliser pour dessiner le segment + @param center centre du cercle + @param size diametre du cercle */ void SingleLineProperties::drawNeutral( - QPainter *painter, - QPointF center, - qreal size) + QPainter *painter, + QPointF center, + qreal size) { - painter -> save(); + painter -> save(); - // prepare le QPainter - if (painter -> brush() == Qt::NoBrush) painter -> setBrush(Qt::black); - painter -> setPen(Qt::NoPen); + // prepare le QPainter + if (painter -> brush() == Qt::NoBrush) painter -> setBrush(Qt::black); + painter -> setPen(Qt::NoPen); - // desine le cercle representant le neutre - painter -> drawEllipse( - QRectF( - center - QPointF(size / 2.0, size / 2.0), - QSizeF(size, size) - ) - ); + // desine le cercle representant le neutre + painter -> drawEllipse( + QRectF( + center - QPointF(size / 2.0, size / 2.0), + QSizeF(size, size) + ) + ); - painter -> restore(); + painter -> restore(); } /** - @brief SingleLineProperties::drawPen - Draw the PEN (Protective Earth Neutral) symbol using - \a painter at position \a center, using a size hint of \a size. - @param painter - @param direction : - Indicate the direction of the underlying conductor segment - @param center - @param size + @brief SingleLineProperties::drawPen + Draw the PEN (Protective Earth Neutral) symbol using + \a painter at position \a center, using a size hint of \a size. + @param painter + @param direction : + Indicate the direction of the underlying conductor segment + @param center + @param size */ void SingleLineProperties::drawPen(QPainter *painter, - QET::ConductorSegmentType direction, - QPointF center, - qreal size) { - painter -> save(); + QET::ConductorSegmentType direction, + QPointF center, + qreal size) { + painter -> save(); - //painter -> setBrush(Qt::white); - // desine le cercle representant le neutre - //painter -> drawEllipse( - // QRectF( - // center - QPointF(size * 1.5 / 2.0, size * 1.5 / 2.0), - // QSizeF(size * 1.5, size * 1.5) - // ) - //); - drawNeutral(painter, center, size * 1.5); + //painter -> setBrush(Qt::white); + // desine le cercle representant le neutre + //painter -> drawEllipse( + // QRectF( + // center - QPointF(size * 1.5 / 2.0, size * 1.5 / 2.0), + // QSizeF(size * 1.5, size * 1.5) + // ) + //); + drawNeutral(painter, center, size * 1.5); - int offset = (size * 1.5 / 2.0); - QPointF pos = center + (direction == QET::Horizontal ? QPointF(0.0, -offset - 0.5) : QPointF(offset + 0.5, 0.0)); - drawGround(painter, direction, pos, 2.0 * size); - painter -> restore(); + int offset = (size * 1.5 / 2.0); + QPointF pos = center + (direction == QET::Horizontal ? QPointF(0.0, -offset - 0.5) : QPointF(offset + 0.5, 0.0)); + drawGround(painter, direction, pos, 2.0 * size); + painter -> restore(); } /** - Exporte les parametres du conducteur unifilaire sous formes d'attributs XML - ajoutes a l'element e. - @param e Element XML auquel seront ajoutes des attributs + Exporte les parametres du conducteur unifilaire sous formes d'attributs XML + ajoutes a l'element e. + @param e Element XML auquel seront ajoutes des attributs */ void SingleLineProperties::toXml(QDomElement &e) const { - e.setAttribute("ground", hasGround ? "true" : "false"); - e.setAttribute("neutral", hasNeutral ? "true" : "false"); - e.setAttribute("phase", phases); - if (isPen()) e.setAttribute("pen", "true"); + e.setAttribute("ground", hasGround ? "true" : "false"); + e.setAttribute("neutral", hasNeutral ? "true" : "false"); + e.setAttribute("phase", phases); + if (isPen()) e.setAttribute("pen", "true"); } /** - Importe les parametres du conducteur unifilaire a partir des attributs XML - de l'element e - @param e Element XML dont les attributs seront lus + Importe les parametres du conducteur unifilaire a partir des attributs XML + de l'element e + @param e Element XML dont les attributs seront lus */ void SingleLineProperties::fromXml(QDomElement &e) { - hasGround = e.attribute("ground") == "true"; - hasNeutral = e.attribute("neutral") == "true"; - setPhasesCount(e.attribute("phase").toInt()); - is_pen = (hasGround && hasNeutral && e.attribute("pen", "false") == "true"); + hasGround = e.attribute("ground") == "true"; + hasNeutral = e.attribute("neutral") == "true"; + setPhasesCount(e.attribute("phase").toInt()); + is_pen = (hasGround && hasNeutral && e.attribute("pen", "false") == "true"); } /** - Constructeur : par defaut, les proprietes font un conducteur - multifilaire noir dont le texte est "_" + Constructeur : par defaut, les proprietes font un conducteur + multifilaire noir dont le texte est "_" */ ConductorProperties::ConductorProperties() : - type(Multi), - color(Qt::black), - text_color(Qt::black), - text("_"), - text_size(9), - cond_size(1), - verti_rotate_text(270), - horiz_rotate_text(0), - m_show_text(true), - m_one_text_per_folio(false), - style(Qt::SolidLine) + type(Multi), + color(Qt::black), + text_color(Qt::black), + text("_"), + text_size(9), + cond_size(1), + verti_rotate_text(270), + horiz_rotate_text(0), + m_show_text(true), + m_one_text_per_folio(false), + style(Qt::SolidLine) {} /** - Destructeur + Destructeur */ ConductorProperties::~ConductorProperties() { @@ -262,662 +262,662 @@ ConductorProperties::~ConductorProperties() /** - @brief ConductorProperties::toXml - Export conductor propertie, in the XML element 'e' - @param e the xml element + @brief ConductorProperties::toXml + Export conductor propertie, in the XML element 'e' + @param e the xml element */ void ConductorProperties::toXml(QDomElement &e) const { - e.setAttribute("type", typeToString(type)); + e.setAttribute("type", typeToString(type)); - if (color != QColor(Qt::black)) - e.setAttribute("color", color.name()); + if (color != QColor(Qt::black)) + e.setAttribute("color", color.name()); - e.setAttribute("bicolor", m_bicolor? "true" : "false"); - e.setAttribute("color2", m_color_2.name()); - e.setAttribute("dash-size", QString::number(m_dash_size)); + e.setAttribute("bicolor", m_bicolor? "true" : "false"); + e.setAttribute("color2", m_color_2.name()); + e.setAttribute("dash-size", QString::number(m_dash_size)); - if (type == Single) - singleLineProperties.toXml(e); + if (type == Single) + singleLineProperties.toXml(e); - e.setAttribute("num", text); - e.setAttribute("text_color", text_color.name()); - e.setAttribute("formula", m_formula); - e.setAttribute("cable", m_cable); - e.setAttribute("bus", m_bus); - e.setAttribute("function", m_function); - e.setAttribute("tension_protocol", m_tension_protocol); - e.setAttribute("conductor_color", m_wire_color); - e.setAttribute("conductor_section", m_wire_section); - e.setAttribute("numsize", QString::number(text_size)); - e.setAttribute("condsize", QString::number(cond_size)); - e.setAttribute("displaytext", m_show_text); - e.setAttribute("onetextperfolio", m_one_text_per_folio); - e.setAttribute("vertirotatetext", QString::number(verti_rotate_text)); - e.setAttribute("horizrotatetext", QString::number(horiz_rotate_text)); + e.setAttribute("num", text); + e.setAttribute("text_color", text_color.name()); + e.setAttribute("formula", m_formula); + e.setAttribute("cable", m_cable); + e.setAttribute("bus", m_bus); + e.setAttribute("function", m_function); + e.setAttribute("tension_protocol", m_tension_protocol); + e.setAttribute("conductor_color", m_wire_color); + e.setAttribute("conductor_section", m_wire_section); + e.setAttribute("numsize", QString::number(text_size)); + e.setAttribute("condsize", QString::number(cond_size)); + e.setAttribute("displaytext", m_show_text); + e.setAttribute("onetextperfolio", m_one_text_per_folio); + e.setAttribute("vertirotatetext", QString::number(verti_rotate_text)); + e.setAttribute("horizrotatetext", QString::number(horiz_rotate_text)); - QMetaEnum me = QMetaEnum::fromType(); - e.setAttribute("horizontal-alignment", me.valueToKey(m_horizontal_alignment)); - e.setAttribute("vertical-alignment", me.valueToKey(m_vertical_alignment)); + QMetaEnum me = QMetaEnum::fromType(); + e.setAttribute("horizontal-alignment", me.valueToKey(m_horizontal_alignment)); + e.setAttribute("vertical-alignment", me.valueToKey(m_vertical_alignment)); - QString conductor_style = writeStyle(); - if (!conductor_style.isEmpty()) - e.setAttribute("style", conductor_style); + QString conductor_style = writeStyle(); + if (!conductor_style.isEmpty()) + e.setAttribute("style", conductor_style); } /** - @brief ConductorProperties::fromXml - Import conductor propertie, from the attribute of the xml element 'e' - @param e the xml document + @brief ConductorProperties::fromXml + Import conductor propertie, from the attribute of the xml element 'e' + @param e the xml document */ void ConductorProperties::fromXml(QDomElement &e) { - // get conductor color - QColor xml_color= QColor(e.attribute("color")); - color = (xml_color.isValid()? xml_color : QColor(Qt::black)); + // get conductor color + QColor xml_color= QColor(e.attribute("color")); + color = (xml_color.isValid()? xml_color : QColor(Qt::black)); - QString bicolor_str = e.attribute("bicolor", "false"); - m_bicolor = bicolor_str == "true"? true : false; + QString bicolor_str = e.attribute("bicolor", "false"); + m_bicolor = bicolor_str == "true"? true : false; - QColor xml_color_2 = QColor(e.attribute("color2")); - m_color_2 = xml_color_2.isValid()? xml_color_2 : QColor(Qt::black); + QColor xml_color_2 = QColor(e.attribute("color2")); + m_color_2 = xml_color_2.isValid()? xml_color_2 : QColor(Qt::black); - m_dash_size = e.attribute("dash-size", QString::number(1)).toInt(); + m_dash_size = e.attribute("dash-size", QString::number(1)).toInt(); - // read style of conductor - readStyle(e.attribute("style")); + // read style of conductor + readStyle(e.attribute("style")); - if (e.attribute("type") == typeToString(Single)) - { - // get specific properties for single conductor - singleLineProperties.fromXml(e); - type = Single; - } - else - type = Multi; + if (e.attribute("type") == typeToString(Single)) + { + // get specific properties for single conductor + singleLineProperties.fromXml(e); + type = Single; + } + else + type = Multi; - text = e.attribute("num"); - // get text color - QColor xml_text_color= QColor(e.attribute("text_color")); - text_color = (xml_text_color.isValid()? xml_text_color : QColor(Qt::black)); - m_formula = e.attribute("formula"); - m_cable = e.attribute("cable"); - m_bus = e.attribute("bus"); - m_function = e.attribute("function"); - m_tension_protocol = e.attribute("tension_protocol"); - m_wire_color = e.attribute("conductor_color"); - m_wire_section = e.attribute("conductor_section"); - text_size = e.attribute("numsize", QString::number(9)).toInt(); - cond_size = e.attribute("condsize", QString::number(1)).toDouble(); - m_show_text = e.attribute("displaytext", QString::number(1)).toInt(); - m_one_text_per_folio = e.attribute("onetextperfolio", QString::number(0)).toInt(); - verti_rotate_text = e.attribute("vertirotatetext").toDouble(); - horiz_rotate_text = e.attribute("horizrotatetext").toDouble(); + text = e.attribute("num"); + // get text color + QColor xml_text_color= QColor(e.attribute("text_color")); + text_color = (xml_text_color.isValid()? xml_text_color : QColor(Qt::black)); + m_formula = e.attribute("formula"); + m_cable = e.attribute("cable"); + m_bus = e.attribute("bus"); + m_function = e.attribute("function"); + m_tension_protocol = e.attribute("tension_protocol"); + m_wire_color = e.attribute("conductor_color"); + m_wire_section = e.attribute("conductor_section"); + text_size = e.attribute("numsize", QString::number(9)).toInt(); + cond_size = e.attribute("condsize", QString::number(1)).toDouble(); + m_show_text = e.attribute("displaytext", QString::number(1)).toInt(); + m_one_text_per_folio = e.attribute("onetextperfolio", QString::number(0)).toInt(); + verti_rotate_text = e.attribute("vertirotatetext").toDouble(); + horiz_rotate_text = e.attribute("horizrotatetext").toDouble(); - QMetaEnum me = QMetaEnum::fromType(); - m_horizontal_alignment = Qt::Alignment( - me.keyToValue( - e.attribute( - "horizontal-alignment", - "AlignBottom" - ).toStdString().data())); - m_vertical_alignment = Qt::Alignment( - me.keyToValue( - e.attribute( - "vertical-alignment", - "AlignRight" - ).toStdString().data())); + QMetaEnum me = QMetaEnum::fromType(); + m_horizontal_alignment = Qt::Alignment( + me.keyToValue( + e.attribute( + "horizontal-alignment", + "AlignBottom" + ).toStdString().data())); + m_vertical_alignment = Qt::Alignment( + me.keyToValue( + e.attribute( + "vertical-alignment", + "AlignRight" + ).toStdString().data())); - //Keep retrocompatible with version older than 0,4 - //If the propertie @type is simple (removed since QET 0,4), we set text no visible. - //@TODO remove this code for qet 0.6 or later + //Keep retrocompatible with version older than 0,4 + //If the propertie @type is simple (removed since QET 0,4), we set text no visible. + //@TODO remove this code for qet 0.6 or later #if TODO_LIST #pragma message("@TODO remove this code for qet 0.6 or later") #endif - if (e.attribute("type") == "simple") m_show_text = false; + if (e.attribute("type") == "simple") m_show_text = false; } /** - @param settings Parametres a ecrire - @param prefix prefixe a ajouter devant les noms des parametres + @param settings Parametres a ecrire + @param prefix prefixe a ajouter devant les noms des parametres */ void ConductorProperties::toSettings(QSettings &settings, const QString &prefix) const { - settings.setValue(prefix + "color", color.name()); - settings.setValue(prefix + "bicolor", m_bicolor); - settings.setValue(prefix + "color2", m_color_2.name()); - settings.setValue(prefix + "dash-size", m_dash_size); - settings.setValue(prefix + "style", writeStyle()); - settings.setValue(prefix + "type", typeToString(type)); - settings.setValue(prefix + "text", text); - settings.setValue(prefix + "text_color", text_color.name()); - settings.setValue(prefix + "formula", m_formula); - settings.setValue(prefix + "cable", m_cable); - settings.setValue(prefix + "bus", m_bus); - settings.setValue(prefix + "function", m_function); - settings.setValue(prefix + "tension_protocol", m_tension_protocol); - settings.setValue(prefix + "conductor_color", m_wire_color); - settings.setValue(prefix + "conductor_section", m_wire_section); - settings.setValue(prefix + "textsize", QString::number(text_size)); - settings.setValue(prefix + "size", QString::number(cond_size)); - settings.setValue(prefix + "displaytext", m_show_text); - settings.setValue(prefix + "onetextperfolio", m_one_text_per_folio); - settings.setValue(prefix + "vertirotatetext", QString::number(verti_rotate_text)); - settings.setValue(prefix + "horizrotatetext", QString::number(horiz_rotate_text)); + settings.setValue(prefix + "color", color.name()); + settings.setValue(prefix + "bicolor", m_bicolor); + settings.setValue(prefix + "color2", m_color_2.name()); + settings.setValue(prefix + "dash-size", m_dash_size); + settings.setValue(prefix + "style", writeStyle()); + settings.setValue(prefix + "type", typeToString(type)); + settings.setValue(prefix + "text", text); + settings.setValue(prefix + "text_color", text_color.name()); + settings.setValue(prefix + "formula", m_formula); + settings.setValue(prefix + "cable", m_cable); + settings.setValue(prefix + "bus", m_bus); + settings.setValue(prefix + "function", m_function); + settings.setValue(prefix + "tension_protocol", m_tension_protocol); + settings.setValue(prefix + "conductor_color", m_wire_color); + settings.setValue(prefix + "conductor_section", m_wire_section); + settings.setValue(prefix + "textsize", QString::number(text_size)); + settings.setValue(prefix + "size", QString::number(cond_size)); + settings.setValue(prefix + "displaytext", m_show_text); + settings.setValue(prefix + "onetextperfolio", m_one_text_per_folio); + settings.setValue(prefix + "vertirotatetext", QString::number(verti_rotate_text)); + settings.setValue(prefix + "horizrotatetext", QString::number(horiz_rotate_text)); - QMetaEnum me = QMetaEnum::fromType(); - settings.setValue(prefix + "horizontal-alignment", me.valueToKey(m_horizontal_alignment)); - settings.setValue(prefix + "vertical-alignment", me.valueToKey(m_vertical_alignment)); + QMetaEnum me = QMetaEnum::fromType(); + settings.setValue(prefix + "horizontal-alignment", me.valueToKey(m_horizontal_alignment)); + settings.setValue(prefix + "vertical-alignment", me.valueToKey(m_vertical_alignment)); - singleLineProperties.toSettings(settings, prefix); + singleLineProperties.toSettings(settings, prefix); } /** - @param settings Parametres a lire - @param prefix prefixe a ajouter devant les noms des parametres + @param settings Parametres a lire + @param prefix prefixe a ajouter devant les noms des parametres */ void ConductorProperties::fromSettings(QSettings &settings, const QString &prefix) { - QColor settings_color = QColor(settings.value(prefix + "color").toString()); - color = (settings_color.isValid()? settings_color : QColor(Qt::black)); + QColor settings_color = QColor(settings.value(prefix + "color").toString()); + color = (settings_color.isValid()? settings_color : QColor(Qt::black)); - QColor settings_color_2 = QColor(settings.value(prefix + "color2").toString()); - m_color_2 = (settings_color_2.isValid()? settings_color_2 : QColor(Qt::black)); + QColor settings_color_2 = QColor(settings.value(prefix + "color2").toString()); + m_color_2 = (settings_color_2.isValid()? settings_color_2 : QColor(Qt::black)); - m_bicolor = settings.value(prefix + "bicolor", false).toBool(); - m_dash_size = settings.value(prefix + "dash-size", 1).toInt(); + m_bicolor = settings.value(prefix + "bicolor", false).toBool(); + m_dash_size = settings.value(prefix + "dash-size", 1).toInt(); - QString setting_type = settings.value(prefix + "type", typeToString(Multi)).toString(); - type = (setting_type == typeToString(Single)? Single : Multi); + QString setting_type = settings.value(prefix + "type", typeToString(Multi)).toString(); + type = (setting_type == typeToString(Single)? Single : Multi); - singleLineProperties.fromSettings(settings, prefix); + singleLineProperties.fromSettings(settings, prefix); - text = settings.value(prefix + "text", "_").toString(); - QColor settings_text_color = QColor(settings.value(prefix + "text_color").toString()); - text_color = (settings_text_color.isValid()? settings_text_color : QColor(Qt::black)); - m_formula = settings.value(prefix + "formula", "").toString(); - m_cable = settings.value(prefix + "cable", "").toString(); - m_bus = settings.value(prefix + "bus", "").toString(); - m_function = settings.value(prefix + "function", "").toString(); - m_tension_protocol = settings.value(prefix + "tension_protocol", "").toString(); - m_wire_color = settings.value(prefix + "conductor_color", "").toString(); - m_wire_section = settings.value(prefix + "conductor_section", "").toString(); - text_size = settings.value(prefix + "textsize", "7").toInt(); - cond_size = settings.value(prefix + "size", "1").toInt(); - m_show_text = settings.value(prefix + "displaytext", true).toBool(); - m_one_text_per_folio = settings.value(prefix + "onetextperfolio", false).toBool(); - verti_rotate_text = settings.value((prefix + "vertirotatetext"), "270").toDouble(); - horiz_rotate_text = settings.value((prefix + "horizrotatetext"), "0").toDouble(); + text = settings.value(prefix + "text", "_").toString(); + QColor settings_text_color = QColor(settings.value(prefix + "text_color").toString()); + text_color = (settings_text_color.isValid()? settings_text_color : QColor(Qt::black)); + m_formula = settings.value(prefix + "formula", "").toString(); + m_cable = settings.value(prefix + "cable", "").toString(); + m_bus = settings.value(prefix + "bus", "").toString(); + m_function = settings.value(prefix + "function", "").toString(); + m_tension_protocol = settings.value(prefix + "tension_protocol", "").toString(); + m_wire_color = settings.value(prefix + "conductor_color", "").toString(); + m_wire_section = settings.value(prefix + "conductor_section", "").toString(); + text_size = settings.value(prefix + "textsize", "7").toInt(); + cond_size = settings.value(prefix + "size", "1").toInt(); + m_show_text = settings.value(prefix + "displaytext", true).toBool(); + m_one_text_per_folio = settings.value(prefix + "onetextperfolio", false).toBool(); + verti_rotate_text = settings.value((prefix + "vertirotatetext"), "270").toDouble(); + horiz_rotate_text = settings.value((prefix + "horizrotatetext"), "0").toDouble(); - QMetaEnum me = QMetaEnum::fromType(); - m_horizontal_alignment = Qt::Alignment(me.keyToValue(settings.value(prefix + "horizontal-alignment", "AlignBottom").toString().toStdString().data())); - m_vertical_alignment = Qt::Alignment(me.keyToValue(settings.value(prefix + "vertical-alignment", "AlignRight").toString().toStdString().data())); + QMetaEnum me = QMetaEnum::fromType(); + m_horizontal_alignment = Qt::Alignment(me.keyToValue(settings.value(prefix + "horizontal-alignment", "AlignBottom").toString().toStdString().data())); + m_vertical_alignment = Qt::Alignment(me.keyToValue(settings.value(prefix + "vertical-alignment", "AlignRight").toString().toStdString().data())); - readStyle(settings.value(prefix + "style").toString()); + readStyle(settings.value(prefix + "style").toString()); } /** - @param t type du conducteur + @param t type du conducteur */ QString ConductorProperties::typeToString(ConductorType t) { - switch(t) - { - case Single: return("single"); - case Multi: return("multi"); - } - return QString(); + switch(t) + { + case Single: return("single"); + case Multi: return("multi"); + } + return QString(); } /** - @brief ConductorProperties::applyForEqualAttributes - Test each attribute of properties in the list separatly. - For each attributes, if is equal, the attribute is apply to this. - @param list + @brief ConductorProperties::applyForEqualAttributes + Test each attribute of properties in the list separatly. + For each attributes, if is equal, the attribute is apply to this. + @param list */ void ConductorProperties::applyForEqualAttributes(QList list) { - const QList clist = std::move(list); + const QList clist = std::move(list); - if (clist.isEmpty()) - return; + if (clist.isEmpty()) + return; - if (clist.size() == 1) - { - ConductorProperties cp = clist.first(); - color = cp.color; - m_bicolor = cp.m_bicolor; - m_color_2 = cp.m_color_2; - m_dash_size = cp.m_dash_size; - text = cp.text; - text_color = cp.text_color; - m_formula = cp.m_formula; - m_cable = cp.m_cable; - m_bus = cp.m_bus; - m_function = cp.m_function; - m_tension_protocol = cp.m_tension_protocol; - m_wire_color = cp.m_wire_color; - m_wire_section = cp.m_wire_section; - text_size = cp.text_size; - cond_size = cp.cond_size; - m_show_text = cp.m_show_text; - m_one_text_per_folio = cp.m_one_text_per_folio; - verti_rotate_text = cp.verti_rotate_text; - horiz_rotate_text = cp.horiz_rotate_text; - m_vertical_alignment = cp.m_vertical_alignment; - m_horizontal_alignment = cp.m_horizontal_alignment; + if (clist.size() == 1) + { + ConductorProperties cp = clist.first(); + color = cp.color; + m_bicolor = cp.m_bicolor; + m_color_2 = cp.m_color_2; + m_dash_size = cp.m_dash_size; + text = cp.text; + text_color = cp.text_color; + m_formula = cp.m_formula; + m_cable = cp.m_cable; + m_bus = cp.m_bus; + m_function = cp.m_function; + m_tension_protocol = cp.m_tension_protocol; + m_wire_color = cp.m_wire_color; + m_wire_section = cp.m_wire_section; + text_size = cp.text_size; + cond_size = cp.cond_size; + m_show_text = cp.m_show_text; + m_one_text_per_folio = cp.m_one_text_per_folio; + verti_rotate_text = cp.verti_rotate_text; + horiz_rotate_text = cp.horiz_rotate_text; + m_vertical_alignment = cp.m_vertical_alignment; + m_horizontal_alignment = cp.m_horizontal_alignment; - return; - } + return; + } - bool equal = true; - QColor c_value; - bool b_value; - QString s_value; - int i_value; - double d_value; - Qt::Alignment align_value; + bool equal = true; + QColor c_value; + bool b_value; + QString s_value; + int i_value; + double d_value; + Qt::Alignment align_value; - //Color - c_value = clist.first().color; - for(ConductorProperties cp : clist) - { - if (cp.color != c_value) - equal = false; - } - if (equal) - color = c_value; - equal = true; + //Color + c_value = clist.first().color; + for(ConductorProperties cp : clist) + { + if (cp.color != c_value) + equal = false; + } + if (equal) + color = c_value; + equal = true; - //bicolor - b_value = clist.first().m_bicolor; - for(ConductorProperties cp : clist) - { - if (cp.m_bicolor != b_value) - equal = false; - } - if (equal) - m_bicolor = b_value; - equal = true; + //bicolor + b_value = clist.first().m_bicolor; + for(ConductorProperties cp : clist) + { + if (cp.m_bicolor != b_value) + equal = false; + } + if (equal) + m_bicolor = b_value; + equal = true; - //second color - c_value = clist.first().m_color_2; - for(ConductorProperties cp : clist) - { - if (cp.m_color_2 != c_value) - equal = false; - } - if (equal) - m_color_2 = c_value; - equal = true; + //second color + c_value = clist.first().m_color_2; + for(ConductorProperties cp : clist) + { + if (cp.m_color_2 != c_value) + equal = false; + } + if (equal) + m_color_2 = c_value; + equal = true; - //Dash size - i_value = clist.first().m_dash_size; - for(ConductorProperties cp : clist) - { - if (cp.m_dash_size != i_value) - equal = false; - } - if (equal) - m_dash_size = i_value; - equal = true; + //Dash size + i_value = clist.first().m_dash_size; + for(ConductorProperties cp : clist) + { + if (cp.m_dash_size != i_value) + equal = false; + } + if (equal) + m_dash_size = i_value; + equal = true; - //text - s_value = clist.first().text; - for(ConductorProperties cp : clist) - { - if (cp.text != s_value) - equal = false; - } - if (equal) - text = s_value; - equal = true; + //text + s_value = clist.first().text; + for(ConductorProperties cp : clist) + { + if (cp.text != s_value) + equal = false; + } + if (equal) + text = s_value; + equal = true; - //text color - c_value = clist.first().text_color; - for(ConductorProperties cp : clist) - { - if (cp.text_color != c_value) - equal = false; - } - if (equal) - text_color = c_value; - equal = true; + //text color + c_value = clist.first().text_color; + for(ConductorProperties cp : clist) + { + if (cp.text_color != c_value) + equal = false; + } + if (equal) + text_color = c_value; + equal = true; - //formula - s_value = clist.first().m_formula; - for(ConductorProperties cp : clist) - { - if (cp.m_formula != s_value) - equal = false; - } - if (equal) - m_formula = s_value; - equal = true; + //formula + s_value = clist.first().m_formula; + for(ConductorProperties cp : clist) + { + if (cp.m_formula != s_value) + equal = false; + } + if (equal) + m_formula = s_value; + equal = true; - //cable - s_value = clist.first().m_cable; - for(ConductorProperties cp : clist) - { - if (cp.m_cable != s_value) - equal = false; - } - if (equal) - m_cable = s_value; - equal = true; + //cable + s_value = clist.first().m_cable; + for(ConductorProperties cp : clist) + { + if (cp.m_cable != s_value) + equal = false; + } + if (equal) + m_cable = s_value; + equal = true; - //bus - s_value = clist.first().m_bus; - for(ConductorProperties cp : clist) - { - if (cp.m_bus != s_value) - equal = false; - } - if (equal) - m_bus = s_value; - equal = true; + //bus + s_value = clist.first().m_bus; + for(ConductorProperties cp : clist) + { + if (cp.m_bus != s_value) + equal = false; + } + if (equal) + m_bus = s_value; + equal = true; - //function - s_value = clist.first().m_function; - for(ConductorProperties cp : clist) - { - if (cp.m_function != s_value) - equal = false; - } - if (equal) - m_function = s_value; - equal = true; + //function + s_value = clist.first().m_function; + for(ConductorProperties cp : clist) + { + if (cp.m_function != s_value) + equal = false; + } + if (equal) + m_function = s_value; + equal = true; - //Tension protocol - s_value = clist.first().m_tension_protocol; - for(ConductorProperties cp : clist) - { - if (cp.m_tension_protocol != s_value) - equal = false; - } - if (equal) - m_tension_protocol = s_value; - equal = true; + //Tension protocol + s_value = clist.first().m_tension_protocol; + for(ConductorProperties cp : clist) + { + if (cp.m_tension_protocol != s_value) + equal = false; + } + if (equal) + m_tension_protocol = s_value; + equal = true; - //conductor_color - s_value = clist.first().m_wire_color; - for(ConductorProperties cp : clist) - { - if (cp.m_wire_color != s_value) - equal = false; - } - if (equal) - m_wire_color = s_value; - equal = true; + //conductor_color + s_value = clist.first().m_wire_color; + for(ConductorProperties cp : clist) + { + if (cp.m_wire_color != s_value) + equal = false; + } + if (equal) + m_wire_color = s_value; + equal = true; - //conductor_section - s_value = clist.first().m_wire_section; - for(ConductorProperties cp : clist) - { - if (cp.m_wire_section != s_value) - equal = false; - } - if (equal) - m_wire_section = s_value; - equal = true; + //conductor_section + s_value = clist.first().m_wire_section; + for(ConductorProperties cp : clist) + { + if (cp.m_wire_section != s_value) + equal = false; + } + if (equal) + m_wire_section = s_value; + equal = true; - //text size - i_value = clist.first().text_size; - for(ConductorProperties cp : clist) - { - if (cp.text_size != i_value) - equal = false; - } - if (equal) - text_size = i_value; - equal = true; + //text size + i_value = clist.first().text_size; + for(ConductorProperties cp : clist) + { + if (cp.text_size != i_value) + equal = false; + } + if (equal) + text_size = i_value; + equal = true; - //conductor size - d_value = clist.first().cond_size; - for(ConductorProperties cp : clist) - { - if (cp.cond_size != d_value) - equal = false; - } - if (equal) - cond_size = d_value; - equal = true; + //conductor size + d_value = clist.first().cond_size; + for(ConductorProperties cp : clist) + { + if (cp.cond_size != d_value) + equal = false; + } + if (equal) + cond_size = d_value; + equal = true; - //show text - b_value = clist.first().m_show_text; - for(ConductorProperties cp : clist) - { - if (cp.m_show_text != b_value) - equal = false; - } - if (equal) - m_show_text = b_value; - equal = true; + //show text + b_value = clist.first().m_show_text; + for(ConductorProperties cp : clist) + { + if (cp.m_show_text != b_value) + equal = false; + } + if (equal) + m_show_text = b_value; + equal = true; - //One text per folio - b_value = clist.first().m_one_text_per_folio; - for(ConductorProperties cp : clist) - { - if (cp.m_one_text_per_folio != b_value) - equal = false; - } - if (equal) - m_one_text_per_folio = b_value; - equal = true; + //One text per folio + b_value = clist.first().m_one_text_per_folio; + for(ConductorProperties cp : clist) + { + if (cp.m_one_text_per_folio != b_value) + equal = false; + } + if (equal) + m_one_text_per_folio = b_value; + equal = true; - //Text rotation for vertical conducor - d_value = clist.first().verti_rotate_text; - for(ConductorProperties cp : clist) - { - if (cp.verti_rotate_text != d_value) - equal = false; - } - if (equal) - verti_rotate_text = d_value; - equal = true; + //Text rotation for vertical conducor + d_value = clist.first().verti_rotate_text; + for(ConductorProperties cp : clist) + { + if (cp.verti_rotate_text != d_value) + equal = false; + } + if (equal) + verti_rotate_text = d_value; + equal = true; - //Text rotation for horizontal conducor - d_value = clist.first().horiz_rotate_text; - for(ConductorProperties cp : clist) - { - if (cp.horiz_rotate_text != d_value) - equal = false; - } - if (equal) - horiz_rotate_text = d_value; - equal = true; + //Text rotation for horizontal conducor + d_value = clist.first().horiz_rotate_text; + for(ConductorProperties cp : clist) + { + if (cp.horiz_rotate_text != d_value) + equal = false; + } + if (equal) + horiz_rotate_text = d_value; + equal = true; - //Text alignment for horizontal conducor - align_value = clist.first().m_horizontal_alignment; - for(ConductorProperties cp : clist) - { - if (cp.m_horizontal_alignment != align_value) - equal = false; - } - if (equal) - m_horizontal_alignment = align_value; - equal = true; + //Text alignment for horizontal conducor + align_value = clist.first().m_horizontal_alignment; + for(ConductorProperties cp : clist) + { + if (cp.m_horizontal_alignment != align_value) + equal = false; + } + if (equal) + m_horizontal_alignment = align_value; + equal = true; - //Text alignment for vertical conducor - align_value = clist.first().m_vertical_alignment; - for(ConductorProperties cp : clist) - { - if (cp.m_vertical_alignment != align_value) - equal = false; - } - if (equal) - m_vertical_alignment = align_value; - equal = true; + //Text alignment for vertical conducor + align_value = clist.first().m_vertical_alignment; + for(ConductorProperties cp : clist) + { + if (cp.m_vertical_alignment != align_value) + equal = false; + } + if (equal) + m_vertical_alignment = align_value; + equal = true; } /** - @brief ConductorProperties::defaultProperties - @return the default properties stored in the setting file + @brief ConductorProperties::defaultProperties + @return the default properties stored in the setting file */ ConductorProperties ConductorProperties::defaultProperties() { - QSettings settings; + QSettings settings; - ConductorProperties def; - def.fromSettings(settings, "diagrameditor/defaultconductor"); + ConductorProperties def; + def.fromSettings(settings, "diagrameditor/defaultconductor"); - return(def); + return(def); } /** - @brief ConductorProperties::operator == - @param other - @return true if other == this + @brief ConductorProperties::operator == + @param other + @return true if other == this */ bool ConductorProperties::operator==(const ConductorProperties &other) const { - return( - other.type == type &&\ - other.color == color &&\ - other.m_bicolor == m_bicolor &&\ - other.m_color_2 == m_color_2 &&\ - other.m_dash_size == m_dash_size &&\ - other.style == style &&\ - other.text == text &&\ - other.text_color == text_color &&\ - other.m_formula == m_formula &&\ - other.m_cable == m_cable &&\ - other.m_bus == m_bus &&\ - other.m_function == m_function &&\ - other.m_tension_protocol == m_tension_protocol &&\ - other.m_wire_color == m_wire_color && \ - other.m_wire_section == m_wire_section && \ - other.m_show_text == m_show_text &&\ - other.text_size == text_size &&\ - other.cond_size == cond_size &&\ - other.verti_rotate_text == verti_rotate_text &&\ - other.horiz_rotate_text == horiz_rotate_text &&\ - other.singleLineProperties == singleLineProperties &&\ - other.m_one_text_per_folio == m_one_text_per_folio &&\ - other.m_horizontal_alignment == m_horizontal_alignment &&\ - other.m_vertical_alignment == m_vertical_alignment - ); + return( + other.type == type &&\ + other.color == color &&\ + other.m_bicolor == m_bicolor &&\ + other.m_color_2 == m_color_2 &&\ + other.m_dash_size == m_dash_size &&\ + other.style == style &&\ + other.text == text &&\ + other.text_color == text_color &&\ + other.m_formula == m_formula &&\ + other.m_cable == m_cable &&\ + other.m_bus == m_bus &&\ + other.m_function == m_function &&\ + other.m_tension_protocol == m_tension_protocol &&\ + other.m_wire_color == m_wire_color && \ + other.m_wire_section == m_wire_section && \ + other.m_show_text == m_show_text &&\ + other.text_size == text_size &&\ + other.cond_size == cond_size &&\ + other.verti_rotate_text == verti_rotate_text &&\ + other.horiz_rotate_text == horiz_rotate_text &&\ + other.singleLineProperties == singleLineProperties &&\ + other.m_one_text_per_folio == m_one_text_per_folio &&\ + other.m_horizontal_alignment == m_horizontal_alignment &&\ + other.m_vertical_alignment == m_vertical_alignment + ); } /** - @param other l'autre ensemble de proprietes avec lequel il faut effectuer la comparaison - @return true si les deux ensembles de proprietes sont differents, false sinon + @param other l'autre ensemble de proprietes avec lequel il faut effectuer la comparaison + @return true si les deux ensembles de proprietes sont differents, false sinon */ bool ConductorProperties::operator!=(const ConductorProperties &other) const{ - return(!(*this == other)); + return(!(*this == other)); } /** - Applique les styles passes en parametre dans cet objet - @param style_string Chaine decrivant le style du conducteur + Applique les styles passes en parametre dans cet objet + @param style_string Chaine decrivant le style du conducteur */ void ConductorProperties::readStyle(const QString &style_string) { - style = Qt::SolidLine; // style par defaut + style = Qt::SolidLine; // style par defaut - if (style_string.isEmpty()) return; + if (style_string.isEmpty()) return; - // recupere la liste des couples style / valeur -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove - QStringList styles = style_string.split(";", QString::SkipEmptyParts); + // recupere la liste des couples style / valeur +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove + QStringList styles = style_string.split(";", QString::SkipEmptyParts); #else #if TODO_LIST #pragma message("@TODO remove code QString::SkipEmptyParts for QT 5.14 or later") #endif - QStringList styles = style_string.split(";", Qt::SkipEmptyParts); + QStringList styles = style_string.split(";", Qt::SkipEmptyParts); #endif - QRegularExpression Rx("^(?[a-z-]+): (?[a-z-]+)$"); - if (!Rx.isValid()) - { - qWarning() <[a-z-]+): (?[a-z-]+)$"); + if (!Rx.isValid()) + { + qWarning() <. + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef CONDUCTOR_PROPERTIES_H #define CONDUCTOR_PROPERTIES_H @@ -25,117 +25,117 @@ class QPainter; /** - @brief The SingleLineProperties class - This class represents the properties of a singleline conductor. + @brief The SingleLineProperties class + This class represents the properties of a singleline conductor. */ class SingleLineProperties { - public: - SingleLineProperties(); - virtual ~SingleLineProperties(); + public: + SingleLineProperties(); + virtual ~SingleLineProperties(); - void setPhasesCount(int); - unsigned short int phasesCount(); - bool isPen() const; - void draw(QPainter *, QET::ConductorSegmentType, const QRectF &); - void toXml(QDomElement &) const; - void fromXml(QDomElement &); - void toSettings(QSettings &, const QString & = QString()) const; - void fromSettings(QSettings &, const QString & = QString()); + void setPhasesCount(int); + unsigned short int phasesCount(); + bool isPen() const; + void draw(QPainter *, QET::ConductorSegmentType, const QRectF &); + void toXml(QDomElement &) const; + void fromXml(QDomElement &); + void toSettings(QSettings &, const QString & = QString()) const; + void fromSettings(QSettings &, const QString & = QString()); - /// Whether the singleline conductor should display the ground symbol - bool hasGround; - /// Whether the singleline conductor should display the neutral symbol - bool hasNeutral; - /// Protective Earth Neutral: visually merge neutral and ground - bool is_pen; + /// Whether the singleline conductor should display the ground symbol + bool hasGround; + /// Whether the singleline conductor should display the neutral symbol + bool hasNeutral; + /// Protective Earth Neutral: visually merge neutral and ground + bool is_pen; - int operator==(const SingleLineProperties &) const; - int operator!=(const SingleLineProperties &) const; + int operator==(const SingleLineProperties &) const; + int operator!=(const SingleLineProperties &) const; - private: - unsigned short int phases; - void drawGround (QPainter *, QET::ConductorSegmentType, QPointF, qreal); - void drawNeutral(QPainter *, QPointF, qreal); - void drawPen(QPainter *, QET::ConductorSegmentType, QPointF, qreal); + private: + unsigned short int phases; + void drawGround (QPainter *, QET::ConductorSegmentType, QPointF, qreal); + void drawNeutral(QPainter *, QPointF, qreal); + void drawPen(QPainter *, QET::ConductorSegmentType, QPointF, qreal); }; /** - @brief The ConductorProperties class - This class represents the functional properties of a particular conductor, - i.e. properties other than path and terminals. + @brief The ConductorProperties class + This class represents the functional properties of a particular conductor, + i.e. properties other than path and terminals. */ class ConductorProperties { - public: - ConductorProperties(); - virtual ~ConductorProperties(); + public: + ConductorProperties(); + virtual ~ConductorProperties(); - /** - @brief The ConductorType enum Represents - the kind of a particular conductor: - Single: singleline symbols, no text input - Multi: text input, no symbol - */ - enum ConductorType { Single, Multi }; + /** + @brief The ConductorType enum Represents + the kind of a particular conductor: + Single: singleline symbols, no text input + Multi: text input, no symbol + */ + enum ConductorType { Single, Multi }; - //Attributes - ConductorType type; + //Attributes + ConductorType type; - QColor - color, - m_color_2, - text_color; + QColor + color, + m_color_2, + text_color; - QString - text, - m_function, - m_tension_protocol, - m_wire_color, - m_wire_section, - m_formula, - m_bus, - m_cable; + QString + text, + m_function, + m_tension_protocol, + m_wire_color, + m_wire_section, + m_formula, + m_bus, + m_cable; - int - text_size, - m_dash_size = 1; + int + text_size, + m_dash_size = 1; - double - cond_size, - verti_rotate_text, - horiz_rotate_text; + double + cond_size, + verti_rotate_text, + horiz_rotate_text; - bool - m_show_text, - m_one_text_per_folio, - m_bicolor = false; + bool + m_show_text, + m_one_text_per_folio, + m_bicolor = false; - Qt::Alignment - m_horizontal_alignment = Qt::AlignBottom, - m_vertical_alignment = Qt::AlignRight; + Qt::Alignment + m_horizontal_alignment = Qt::AlignBottom, + m_vertical_alignment = Qt::AlignRight; - Qt::PenStyle style; + Qt::PenStyle style; - SingleLineProperties singleLineProperties; + SingleLineProperties singleLineProperties; - // methods - void toXml(QDomElement &) const; - void fromXml(QDomElement &); - void toSettings(QSettings &, const QString & = QString()) const; - void fromSettings(QSettings &, const QString & = QString()); - static QString typeToString(ConductorType); - void applyForEqualAttributes(QList list); + // methods + void toXml(QDomElement &) const; + void fromXml(QDomElement &); + void toSettings(QSettings &, const QString & = QString()) const; + void fromSettings(QSettings &, const QString & = QString()); + static QString typeToString(ConductorType); + void applyForEqualAttributes(QList list); - static ConductorProperties defaultProperties(); + static ConductorProperties defaultProperties(); - // operators - bool operator==(const ConductorProperties &) const; - bool operator!=(const ConductorProperties &) const; + // operators + bool operator==(const ConductorProperties &) const; + bool operator!=(const ConductorProperties &) const; - private: - void readStyle(const QString &); - QString writeStyle() const; + private: + void readStyle(const QString &); + QString writeStyle() const; }; Q_DECLARE_METATYPE(ConductorProperties) diff --git a/sources/diagram.cpp b/sources/diagram.cpp index 5414c35bb..9b3e981ac 100644 --- a/sources/diagram.cpp +++ b/sources/diagram.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include #include @@ -51,2346 +51,2346 @@ int Diagram::yKeyGridFine = 1; const qreal Diagram::margin = 5.0; /** - @brief Diagram::background_color - static variable to keep track of present background color of the diagram. + @brief Diagram::background_color + static variable to keep track of present background color of the diagram. */ -QColor Diagram::background_color = Qt::white; +QColor Diagram::background_color = Qt::white; /** - @brief Diagram::Diagram - Constructor - @param project : The project of this diagram and also parent QObject + @brief Diagram::Diagram + Constructor + @param project : The project of this diagram and also parent QObject */ Diagram::Diagram(QETProject *project) : - QGraphicsScene (project), - m_project (project), - draw_grid_ (true), - use_border_ (true), - draw_terminals_ (true), - draw_colored_conductors_ (true), - m_event_interface (nullptr), - m_freeze_new_elements (false), - m_freeze_new_conductors_ (false) + QGraphicsScene (project), + m_project (project), + draw_grid_ (true), + use_border_ (true), + draw_terminals_ (true), + draw_colored_conductors_ (true), + m_event_interface (nullptr), + m_freeze_new_elements (false), + m_freeze_new_conductors_ (false) { - setItemIndexMethod(QGraphicsScene::NoIndex); - /* Set to no index, - * because they can be the source of the crash with conductor and shape ghost. - * https://forum.qt.io/topic/71316/qgraphicsscenefinditembsptreevisitor-visit-crashes-due-to-an-obsolete-paintevent-after-qgraphicsscene-removeitem - * https://stackoverflow.com/questions/38458830/crash-after-qgraphicssceneremoveitem-with-custom-item-class - * http://www.qtcentre.org/archive/index.php/t-33730.html - * http://tech-artists.org/t/qt-properly-removing-qgraphicitems/3063 - */ + setItemIndexMethod(QGraphicsScene::NoIndex); + /* Set to no index, + * because they can be the source of the crash with conductor and shape ghost. + * https://forum.qt.io/topic/71316/qgraphicsscenefinditembsptreevisitor-visit-crashes-due-to-an-obsolete-paintevent-after-qgraphicsscene-removeitem + * https://stackoverflow.com/questions/38458830/crash-after-qgraphicssceneremoveitem-with-custom-item-class + * http://www.qtcentre.org/archive/index.php/t-33730.html + * http://tech-artists.org/t/qt-properly-removing-qgraphicitems/3063 + */ - qgi_manager_ = new QGIManager(this); - setBackgroundBrush(Qt::white); - conductor_setter_ = new QGraphicsLineItem(nullptr); - conductor_setter_ -> setZValue(1000000); + qgi_manager_ = new QGIManager(this); + setBackgroundBrush(Qt::white); + conductor_setter_ = new QGraphicsLineItem(nullptr); + conductor_setter_ -> setZValue(1000000); - QPen pen(Qt::NoBrush, 1.5, Qt::DashLine); - pen.setColor(Qt::black); - conductor_setter_ -> setPen(pen); + QPen pen(Qt::NoBrush, 1.5, Qt::DashLine); + pen.setColor(Qt::black); + conductor_setter_ -> setPen(pen); - connect(&border_and_titleblock, - &BorderTitleBlock::needTitleBlockTemplate, - this, &Diagram::setTitleBlockTemplate); - connect(&border_and_titleblock, - &BorderTitleBlock::diagramTitleChanged, - this, &Diagram::titleChanged); - connect(&border_and_titleblock, - &BorderTitleBlock::titleBlockFolioChanged, - this, &Diagram::titleChanged); - connect(&border_and_titleblock, - &BorderTitleBlock::borderChanged, - this, &Diagram::adjustSceneRect); - connect(&border_and_titleblock, - &BorderTitleBlock::titleBlockFolioChanged, - this, &Diagram::updateLabels); - connect(this, &Diagram::diagramActivated, - this, &Diagram::loadElmtFolioSeq); - connect(this, &Diagram::diagramActivated, - this, &Diagram::loadCndFolioSeq); - adjustSceneRect(); + connect(&border_and_titleblock, + &BorderTitleBlock::needTitleBlockTemplate, + this, &Diagram::setTitleBlockTemplate); + connect(&border_and_titleblock, + &BorderTitleBlock::diagramTitleChanged, + this, &Diagram::titleChanged); + connect(&border_and_titleblock, + &BorderTitleBlock::titleBlockFolioChanged, + this, &Diagram::titleChanged); + connect(&border_and_titleblock, + &BorderTitleBlock::borderChanged, + this, &Diagram::adjustSceneRect); + connect(&border_and_titleblock, + &BorderTitleBlock::titleBlockFolioChanged, + this, &Diagram::updateLabels); + connect(this, &Diagram::diagramActivated, + this, &Diagram::loadElmtFolioSeq); + connect(this, &Diagram::diagramActivated, + this, &Diagram::loadCndFolioSeq); + adjustSceneRect(); } /** - @brief Diagram::~Diagram - Destructor + @brief Diagram::~Diagram + Destructor */ Diagram::~Diagram() { - //First clear every selection to close an hypothetical editor - clearSelection(); - // clear undo stack to prevent errors, - // because contains pointers to this diagram and is elements. - undoStack().clear(); - //delete of QGIManager, every elements he knows are removed - delete qgi_manager_; - // remove of conductor setter - delete conductor_setter_; + //First clear every selection to close an hypothetical editor + clearSelection(); + // clear undo stack to prevent errors, + // because contains pointers to this diagram and is elements. + undoStack().clear(); + //delete of QGIManager, every elements he knows are removed + delete qgi_manager_; + // remove of conductor setter + delete conductor_setter_; - if (m_event_interface) - delete m_event_interface; + if (m_event_interface) + delete m_event_interface; - // list removable items - QList deletable_items; - for(QGraphicsItem *qgi : items()) - { - if (qgi -> parentItem()) continue; - if (qgraphicsitem_cast(qgi)) continue; - deletable_items << qgi; - } + // list removable items + QList deletable_items; + for(QGraphicsItem *qgi : items()) + { + if (qgi -> parentItem()) continue; + if (qgraphicsitem_cast(qgi)) continue; + deletable_items << qgi; + } - qDeleteAll (deletable_items); + qDeleteAll (deletable_items); } /** - @brief Diagram::drawBackground - Draw the background of the diagram, ie the grid. - \~French Dessine l'arriere-plan du schema, cad la grille. - \~ @param p : - The QPainter to use for drawing - \~French Le QPainter a utiliser pour dessiner - \~ @param r : - The rectangle of the area to be drawn - \~French Le rectangle de la zone a dessiner + @brief Diagram::drawBackground + Draw the background of the diagram, ie the grid. + \~French Dessine l'arriere-plan du schema, cad la grille. + \~ @param p : + The QPainter to use for drawing + \~French Le QPainter a utiliser pour dessiner + \~ @param r : + The rectangle of the area to be drawn + \~French Le rectangle de la zone a dessiner */ void Diagram::drawBackground(QPainter *p, const QRectF &r) { - p -> save(); + p -> save(); - // disable all antialiasing, except for text - // desactive tout antialiasing, sauf pour le texte - p -> setRenderHint(QPainter::Antialiasing, false); - p -> setRenderHint(QPainter::TextAntialiasing, true); - p -> setRenderHint(QPainter::SmoothPixmapTransform, false); + // disable all antialiasing, except for text + // desactive tout antialiasing, sauf pour le texte + p -> setRenderHint(QPainter::Antialiasing, false); + p -> setRenderHint(QPainter::TextAntialiasing, true); + p -> setRenderHint(QPainter::SmoothPixmapTransform, false); - // draw a white background - // dessine un fond blanc - p -> setPen(Qt::NoPen); - //set brush color to present background color. - p -> setBrush(Diagram::background_color); - p -> drawRect(r); + // draw a white background + // dessine un fond blanc + p -> setPen(Qt::NoPen); + //set brush color to present background color. + p -> setBrush(Diagram::background_color); + p -> drawRect(r); - if (draw_grid_) { - /* Draw the point of the grid - * if background color is black, - * then grid spots shall be white, - * else they shall be black in color. - */ - QPen pen; - Diagram::background_color == Qt::black? pen.setColor(Qt::white) - : pen.setColor(Qt::black); - pen.setCosmetic(true); - p->setPen(pen); + if (draw_grid_) { + /* Draw the point of the grid + * if background color is black, + * then grid spots shall be white, + * else they shall be black in color. + */ + QPen pen; + Diagram::background_color == Qt::black? pen.setColor(Qt::white) + : pen.setColor(Qt::black); + pen.setCosmetic(true); + p->setPen(pen); - p -> setBrush(Qt::NoBrush); + p -> setBrush(Qt::NoBrush); - // If user allow zoom out beyond of folio, - // we draw grid outside of border. - QSettings settings; - int xGrid = settings.value("diagrameditor/Xgrid", - Diagram::xGrid).toInt(); - int yGrid = settings.value("diagrameditor/Ygrid", - Diagram::yGrid).toInt(); - QRectF rect = settings.value( - "diagrameditor/zoom-out-beyond-of-folio", - false).toBool() ? r - : border_and_titleblock - .insideBorderRect() - .intersected(r); + // If user allow zoom out beyond of folio, + // we draw grid outside of border. + QSettings settings; + int xGrid = settings.value("diagrameditor/Xgrid", + Diagram::xGrid).toInt(); + int yGrid = settings.value("diagrameditor/Ygrid", + Diagram::yGrid).toInt(); + QRectF rect = settings.value( + "diagrameditor/zoom-out-beyond-of-folio", + false).toBool() ? r + : border_and_titleblock + .insideBorderRect() + .intersected(r); - qreal limite_x = rect.x() + rect.width(); - qreal limite_y = rect.y() + rect.height(); + qreal limite_x = rect.x() + rect.width(); + qreal limite_y = rect.y() + rect.height(); - int g_x = (int)ceil(rect.x()); - while (g_x % xGrid) ++ g_x; - int g_y = (int)ceil(rect.y()); - while (g_y % yGrid) ++ g_y; + int g_x = (int)ceil(rect.x()); + while (g_x % xGrid) ++ g_x; + int g_y = (int)ceil(rect.y()); + while (g_y % yGrid) ++ g_y; - QPolygon points; - for (int gx = g_x ; gx < limite_x ; gx += xGrid) { - for (int gy = g_y ; gy < limite_y ; gy += yGrid) { - points << QPoint(gx, gy); - } - } - p -> drawPoints(points); - } + QPolygon points; + for (int gx = g_x ; gx < limite_x ; gx += xGrid) { + for (int gy = g_y ; gy < limite_y ; gy += yGrid) { + points << QPoint(gx, gy); + } + } + p -> drawPoints(points); + } - if (use_border_) border_and_titleblock.draw(p); - p -> restore(); + if (use_border_) border_and_titleblock.draw(p); + p -> restore(); } /** - @brief Diagram::mouseDoubleClickEvent - This event is managed by diagram event interface if any. - @param event : + @brief Diagram::mouseDoubleClickEvent + This event is managed by diagram event interface if any. + @param event : */ void Diagram::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { - event->setAccepted(false); + event->setAccepted(false); - if (m_event_interface) { - m_event_interface->mouseDoubleClickEvent(event); - if (event->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->mouseDoubleClickEvent(event); + if (event->isAccepted()) { + return; + } + } - QGraphicsScene::mouseDoubleClickEvent(event); + QGraphicsScene::mouseDoubleClickEvent(event); } /** - @brief Diagram::mousePressEvent - This event is managed by diagram event interface if any. - @param event + @brief Diagram::mousePressEvent + This event is managed by diagram event interface if any. + @param event */ void Diagram::mousePressEvent(QGraphicsSceneMouseEvent *event) { - event->setAccepted(false); + event->setAccepted(false); - if (m_event_interface) { - m_event_interface->mousePressEvent(event); - if (event->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->mousePressEvent(event); + if (event->isAccepted()) { + return; + } + } - QGraphicsScene::mousePressEvent(event); + QGraphicsScene::mousePressEvent(event); } /** - @brief Diagram::mouseMoveEvent - This event is managed by diagram event interface if any. - @param event + @brief Diagram::mouseMoveEvent + This event is managed by diagram event interface if any. + @param event */ void Diagram::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - event->setAccepted(false); + event->setAccepted(false); - if (m_event_interface) { - m_event_interface->mouseMoveEvent(event); - if (event->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->mouseMoveEvent(event); + if (event->isAccepted()) { + return; + } + } - QGraphicsScene::mouseMoveEvent(event); + QGraphicsScene::mouseMoveEvent(event); } /** - @brief Diagram::mouseReleaseEvent - This event is managed by diagram event interface if any. - @param event + @brief Diagram::mouseReleaseEvent + This event is managed by diagram event interface if any. + @param event */ void Diagram::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - event->setAccepted(false); + event->setAccepted(false); - if (m_event_interface) { - m_event_interface->mouseReleaseEvent(event); - if (event->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->mouseReleaseEvent(event); + if (event->isAccepted()) { + return; + } + } - QGraphicsScene::mouseReleaseEvent(event); + QGraphicsScene::mouseReleaseEvent(event); } /** - @brief Diagram::wheelEvent - This event is managed by diagram event interface if any. - @param event + @brief Diagram::wheelEvent + This event is managed by diagram event interface if any. + @param event */ void Diagram::wheelEvent(QGraphicsSceneWheelEvent *event) { - event->setAccepted(false); + event->setAccepted(false); - if (m_event_interface) { - m_event_interface->wheelEvent(event); - if (event->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->wheelEvent(event); + if (event->isAccepted()) { + return; + } + } - QGraphicsScene::wheelEvent(event); + QGraphicsScene::wheelEvent(event); } /** - @brief Diagram::keyPressEvent - This event is managed by diagram event interface if any. - Else move selected elements - @param event + @brief Diagram::keyPressEvent + This event is managed by diagram event interface if any. + Else move selected elements + @param event */ void Diagram::keyPressEvent(QKeyEvent *event) { - QSettings settings; - int xKeyGrid = settings.value("diagrameditor/key_Xgrid", - Diagram::xKeyGrid).toInt(); - int yKeyGrid = settings.value("diagrameditor/key_Ygrid", - Diagram::yKeyGrid).toInt(); - int xKeyGridFine = settings.value("diagrameditor/key_fine_Xgrid", - Diagram::xKeyGridFine).toInt(); - int yKeyGridFine = settings.value("diagrameditor/key_fine_Ygrid", - Diagram::yKeyGridFine).toInt(); - event->setAccepted(false); + QSettings settings; + int xKeyGrid = settings.value("diagrameditor/key_Xgrid", + Diagram::xKeyGrid).toInt(); + int yKeyGrid = settings.value("diagrameditor/key_Ygrid", + Diagram::yKeyGrid).toInt(); + int xKeyGridFine = settings.value("diagrameditor/key_fine_Xgrid", + Diagram::xKeyGridFine).toInt(); + int yKeyGridFine = settings.value("diagrameditor/key_fine_Ygrid", + Diagram::yKeyGridFine).toInt(); + event->setAccepted(false); - if (m_event_interface) { - m_event_interface->keyPressEvent(event); - if (event->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->keyPressEvent(event); + if (event->isAccepted()) { + return; + } + } - if (isReadOnly()) return; + if (isReadOnly()) return; - QPointF movement; - qreal top_position = 0; - qreal left_position = 0; - DiagramContent dc(this); - if (dc.items(DiagramContent::All).isEmpty()) - { - event->ignore(); - QGraphicsScene::keyPressEvent(event); - return; - } + QPointF movement; + qreal top_position = 0; + qreal left_position = 0; + DiagramContent dc(this); + if (dc.items(DiagramContent::All).isEmpty()) + { + event->ignore(); + QGraphicsScene::keyPressEvent(event); + return; + } #if TODO_LIST #pragma message("@TODO move code to new function") #endif - //Move item with the keyboard arrow - if(event->modifiers() == Qt::NoModifier) - { - switch(event->key()) - { - case Qt::Key_Left: - for (Element *item : dc.m_elements) - { - left_position = item->sceneBoundingRect().x(); - if(left_position <= 5) - return; - } - movement = QPointF(-xKeyGrid, 0.0); - break; - case Qt::Key_Right: - movement = QPointF(+xKeyGrid, 0.0); - break; - case Qt::Key_Up: - for(Element *item : dc.m_elements) - { - top_position = item->sceneBoundingRect().y(); - if(top_position <= 5) - return; - } - movement = QPointF(0.0, -yKeyGrid); - break; - case Qt::Key_Down: - movement = QPointF(0.0, +yKeyGrid); - break; - } + //Move item with the keyboard arrow + if(event->modifiers() == Qt::NoModifier) + { + switch(event->key()) + { + case Qt::Key_Left: + for (Element *item : dc.m_elements) + { + left_position = item->sceneBoundingRect().x(); + if(left_position <= 5) + return; + } + movement = QPointF(-xKeyGrid, 0.0); + break; + case Qt::Key_Right: + movement = QPointF(+xKeyGrid, 0.0); + break; + case Qt::Key_Up: + for(Element *item : dc.m_elements) + { + top_position = item->sceneBoundingRect().y(); + if(top_position <= 5) + return; + } + movement = QPointF(0.0, -yKeyGrid); + break; + case Qt::Key_Down: + movement = QPointF(0.0, +yKeyGrid); + break; + } - if (!movement.isNull() && !focusItem()) - { - m_elements_mover.beginMovement(this); - m_elements_mover.continueMovement(movement); - event->accept(); - return; - } - } - else if(event->modifiers() == Qt::AltModifier) - { - switch(event->key()) - { - case Qt::Key_Left: - for (Element *item : dc.m_elements) - { - left_position = item->sceneBoundingRect().x(); - if(left_position <= 5) - return; - } - movement = QPointF(-xKeyGridFine, 0.0); - break; - case Qt::Key_Right: - movement = QPointF(+xKeyGridFine, 0.0); - break; - case Qt::Key_Up: - for(Element *item : dc.m_elements) - { - top_position = item->sceneBoundingRect().y(); - if(top_position <= 5) - return; - } - movement = QPointF(0.0, -yKeyGridFine); - break; - case Qt::Key_Down: - movement = QPointF(0.0, +yKeyGridFine); - break; - } + if (!movement.isNull() && !focusItem()) + { + m_elements_mover.beginMovement(this); + m_elements_mover.continueMovement(movement); + event->accept(); + return; + } + } + else if(event->modifiers() == Qt::AltModifier) + { + switch(event->key()) + { + case Qt::Key_Left: + for (Element *item : dc.m_elements) + { + left_position = item->sceneBoundingRect().x(); + if(left_position <= 5) + return; + } + movement = QPointF(-xKeyGridFine, 0.0); + break; + case Qt::Key_Right: + movement = QPointF(+xKeyGridFine, 0.0); + break; + case Qt::Key_Up: + for(Element *item : dc.m_elements) + { + top_position = item->sceneBoundingRect().y(); + if(top_position <= 5) + return; + } + movement = QPointF(0.0, -yKeyGridFine); + break; + case Qt::Key_Down: + movement = QPointF(0.0, +yKeyGridFine); + break; + } - if (!movement.isNull() && !focusItem()) - { - m_elements_mover.beginMovement(this); - m_elements_mover.continueMovement(movement); - event->accept(); - return; - } - } - else if(event->modifiers() == Qt::ControlModifier) - { - //Adjust the alignment of a texts group - if(selectedItems().size() == 1 - && selectedItems().first()->type() - == QGraphicsItemGroup::Type) - { - if(ElementTextItemGroup *etig = - dynamic_cast - (selectedItems().first())) - { - if(event->key() == Qt::Key_Left - && etig->alignment() != Qt::AlignLeft) - undoStack().push( - new AlignmentTextsGroupCommand( - etig, - Qt::AlignLeft)); + if (!movement.isNull() && !focusItem()) + { + m_elements_mover.beginMovement(this); + m_elements_mover.continueMovement(movement); + event->accept(); + return; + } + } + else if(event->modifiers() == Qt::ControlModifier) + { + //Adjust the alignment of a texts group + if(selectedItems().size() == 1 + && selectedItems().first()->type() + == QGraphicsItemGroup::Type) + { + if(ElementTextItemGroup *etig = + dynamic_cast + (selectedItems().first())) + { + if(event->key() == Qt::Key_Left + && etig->alignment() != Qt::AlignLeft) + undoStack().push( + new AlignmentTextsGroupCommand( + etig, + Qt::AlignLeft)); - else if (event->key() == Qt::Key_Up - && etig->alignment() != Qt::AlignVCenter) - undoStack().push( - new AlignmentTextsGroupCommand( - etig, - Qt::AlignVCenter)); + else if (event->key() == Qt::Key_Up + && etig->alignment() != Qt::AlignVCenter) + undoStack().push( + new AlignmentTextsGroupCommand( + etig, + Qt::AlignVCenter)); - else if (event->key() == Qt::Key_Right - && etig->alignment() != Qt::AlignRight) - undoStack().push( - new AlignmentTextsGroupCommand( - etig, - Qt::AlignRight)); - } - } - } - event->ignore(); - QGraphicsScene::keyPressEvent(event); + else if (event->key() == Qt::Key_Right + && etig->alignment() != Qt::AlignRight) + undoStack().push( + new AlignmentTextsGroupCommand( + etig, + Qt::AlignRight)); + } + } + } + event->ignore(); + QGraphicsScene::keyPressEvent(event); } /** - @brief Diagram::keyReleaseEvent - This event is managed by diagram event interface if any. - Else move selected element - @param e + @brief Diagram::keyReleaseEvent + This event is managed by diagram event interface if any. + Else move selected element + @param e */ void Diagram::keyReleaseEvent(QKeyEvent *e) { - e->setAccepted(false); + e->setAccepted(false); - if (m_event_interface) { - m_event_interface->keyReleaseEvent(e); - if (e->isAccepted()) { - return; - } - } + if (m_event_interface) { + m_event_interface->keyReleaseEvent(e); + if (e->isAccepted()) { + return; + } + } - bool transmit_event = true; - if (!isReadOnly()) { - /* detects the release of a direction key - * (= movement of elements) - * detecte le relachement d'une touche de direction - * ( = deplacement d'elements) - */ - if ( - ( - e -> key() == Qt::Key_Left - || e -> key() == Qt::Key_Right - || e -> key() == Qt::Key_Up - || e -> key() == Qt::Key_Down - ) && !e -> isAutoRepeat() - ) { - m_elements_mover.endMovement(); - e -> accept(); - transmit_event = false; - } - } - if (transmit_event) { - QGraphicsScene::keyReleaseEvent(e); - } + bool transmit_event = true; + if (!isReadOnly()) { + /* detects the release of a direction key + * (= movement of elements) + * detecte le relachement d'une touche de direction + * ( = deplacement d'elements) + */ + if ( + ( + e -> key() == Qt::Key_Left + || e -> key() == Qt::Key_Right + || e -> key() == Qt::Key_Up + || e -> key() == Qt::Key_Down + ) && !e -> isAutoRepeat() + ) { + m_elements_mover.endMovement(); + e -> accept(); + transmit_event = false; + } + } + if (transmit_event) { + QGraphicsScene::keyReleaseEvent(e); + } } /** - @brief Diagram::uuid - @return the uuid of this diagram + @brief Diagram::uuid + @return the uuid of this diagram */ QUuid Diagram::uuid() { - return m_uuid; + return m_uuid; } /** - @brief Diagram::setEventInterface - Set event_interface has current interface. - Diagram become the ownership of event_interface - If there is a previous interface, they will be delete before - and call init() to the new interface. - @param event_interface + @brief Diagram::setEventInterface + Set event_interface has current interface. + Diagram become the ownership of event_interface + If there is a previous interface, they will be delete before + and call init() to the new interface. + @param event_interface */ void Diagram::setEventInterface(DiagramEventInterface *event_interface) { - if (m_event_interface) - { - delete m_event_interface; - event_interface -> init(); - } - m_event_interface = event_interface; + if (m_event_interface) + { + delete m_event_interface; + event_interface -> init(); + } + m_event_interface = event_interface; - connect(m_event_interface, &DiagramEventInterface::finish, [this]() - { - delete this->m_event_interface; - this->m_event_interface = nullptr; - }); + connect(m_event_interface, &DiagramEventInterface::finish, [this]() + { + delete this->m_event_interface; + this->m_event_interface = nullptr; + }); } /** - @brief Diagram::clearEventInterface - Clear the current event interface. + @brief Diagram::clearEventInterface + Clear the current event interface. */ void Diagram::clearEventInterface() { - if(m_event_interface) - { - delete m_event_interface; - m_event_interface = nullptr; - } + if(m_event_interface) + { + delete m_event_interface; + m_event_interface = nullptr; + } } /** - @brief Diagram::conductorsAutonumName - @return the name of autonum to use. + @brief Diagram::conductorsAutonumName + @return the name of autonum to use. */ QString Diagram::conductorsAutonumName() const { - return m_conductors_autonum_name; + return m_conductors_autonum_name; } /** - @brief Diagram::setConductorsAutonumName - @param name : name of autonum to use. + @brief Diagram::setConductorsAutonumName + @param name : name of autonum to use. */ void Diagram::setConductorsAutonumName(const QString &name) { - m_conductors_autonum_name= name; + m_conductors_autonum_name= name; } /** - Exporte le schema vers une image - @return Une QImage representant le schema + Exporte le schema vers une image + @return Une QImage representant le schema */ bool Diagram::toPaintDevice(QPaintDevice &pix, - int width, - int height, - Qt::AspectRatioMode aspectRatioMode) { - // determine the source area = schema content + margins - // determine la zone source = contenu du schema + marges - QRectF source_area; - if (!use_border_) { - source_area = itemsBoundingRect(); - source_area.translate(-margin, -margin); - source_area.setWidth (source_area.width () + 2.0 * margin); - source_area.setHeight(source_area.height() + 2.0 * margin); - } else { - source_area = QRectF( - 0.0, - 0.0, - border_and_titleblock.borderAndTitleBlockRect().width() - + 2.0 * margin, - border_and_titleblock.borderAndTitleBlockRect().height() - + 2.0 * margin - ); - } + int width, + int height, + Qt::AspectRatioMode aspectRatioMode) { + // determine the source area = schema content + margins + // determine la zone source = contenu du schema + marges + QRectF source_area; + if (!use_border_) { + source_area = itemsBoundingRect(); + source_area.translate(-margin, -margin); + source_area.setWidth (source_area.width () + 2.0 * margin); + source_area.setHeight(source_area.height() + 2.0 * margin); + } else { + source_area = QRectF( + 0.0, + 0.0, + border_and_titleblock.borderAndTitleBlockRect().width() + + 2.0 * margin, + border_and_titleblock.borderAndTitleBlockRect().height() + + 2.0 * margin + ); + } - /* if the dimensions are not specified, - * the image is exported at 1: 1 scale - * si les dimensions ne sont pas precisees, - * l'image est exportee a l'echelle 1:1 - */ - QSize image_size = (width == -1 && height == -1) - ? source_area.size().toSize() : QSize(width, height); + /* if the dimensions are not specified, + * the image is exported at 1: 1 scale + * si les dimensions ne sont pas precisees, + * l'image est exportee a l'echelle 1:1 + */ + QSize image_size = (width == -1 && height == -1) + ? source_area.size().toSize() : QSize(width, height); - // prepare the rendering - // prepare le rendu - QPainter p; - if (!p.begin(&pix)) return(false); + // prepare the rendering + // prepare le rendu + QPainter p; + if (!p.begin(&pix)) return(false); - // anti-aliasis rendering - // rendu antialiase - p.setRenderHint(QPainter::Antialiasing, true); - p.setRenderHint(QPainter::TextAntialiasing, true); - p.setRenderHint(QPainter::SmoothPixmapTransform, true); + // anti-aliasis rendering + // rendu antialiase + p.setRenderHint(QPainter::Antialiasing, true); + p.setRenderHint(QPainter::TextAntialiasing, true); + p.setRenderHint(QPainter::SmoothPixmapTransform, true); - // deselect all elements - // deselectionne tous les elements - QList selected_elmts = selectedItems(); - foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(false); + // deselect all elements + // deselectionne tous les elements + QList selected_elmts = selectedItems(); + foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(false); - // renders itself - // effectue le rendu lui-meme - render(&p, - QRect(QPoint(0, 0),image_size), - source_area, - aspectRatioMode); - p.end(); + // renders itself + // effectue le rendu lui-meme + render(&p, + QRect(QPoint(0, 0),image_size), + source_area, + aspectRatioMode); + p.end(); - // restore selected items - // restaure les elements selectionnes - foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(true); + // restore selected items + // restaure les elements selectionnes + foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(true); - return(true); + return(true); } /** - @brief Diagram::imageSize - Allows you to know the dimensions - that the image generated by the toImage() method will have - \~French Permet de connaitre les dimensions - qu'aura l'image generee par la methode toImage() - \~ @return The size of the image generated by toImage() - \~French La taille de l'image generee par toImage() + @brief Diagram::imageSize + Allows you to know the dimensions + that the image generated by the toImage() method will have + \~French Permet de connaitre les dimensions + qu'aura l'image generee par la methode toImage() + \~ @return The size of the image generated by toImage() + \~French La taille de l'image generee par toImage() */ QSize Diagram::imageSize() const { - // determine la zone source = contenu du schema + marges - qreal image_width, image_height; - if (!use_border_) { - QRectF items_rect = itemsBoundingRect(); - image_width = items_rect.width(); - image_height = items_rect.height(); - } else { - image_width = border_and_titleblock - .borderAndTitleBlockRect().width(); - image_height = border_and_titleblock - .borderAndTitleBlockRect().height(); - } + // determine la zone source = contenu du schema + marges + qreal image_width, image_height; + if (!use_border_) { + QRectF items_rect = itemsBoundingRect(); + image_width = items_rect.width(); + image_height = items_rect.height(); + } else { + image_width = border_and_titleblock + .borderAndTitleBlockRect().width(); + image_height = border_and_titleblock + .borderAndTitleBlockRect().height(); + } - image_width += 2.0 * margin; - image_height += 2.0 * margin; + image_width += 2.0 * margin; + image_height += 2.0 * margin; - // returns the size of the source area - // renvoie la taille de la zone source - return(QSizeF(image_width, image_height).toSize()); + // returns the size of the source area + // renvoie la taille de la zone source + return(QSizeF(image_width, image_height).toSize()); } /** - @brief Diagram::isEmpty - An empty schema contains no element, conductor, or text field - @return true if the schema is considered empty, false otherwise. - \~French true si le schema est considere comme vide, false sinon. - Un schema vide ne contient ni element, ni conducteur, ni champ de texte + @brief Diagram::isEmpty + An empty schema contains no element, conductor, or text field + @return true if the schema is considered empty, false otherwise. + \~French true si le schema est considere comme vide, false sinon. + Un schema vide ne contient ni element, ni conducteur, ni champ de texte */ bool Diagram::isEmpty() const { - return(!items().count()); + return(!items().count()); } /** - @brief Diagram::potential - @return all potential in the diagram - each potential are in the QList - and each conductors of one potential are in the QSet + @brief Diagram::potential + @return all potential in the diagram + each potential are in the QList + and each conductors of one potential are in the QSet */ QList < QSet > Diagram::potentials() { - QList < QSet > potential_List; - if (content().conductors().size() == 0) - return (potential_List); //return an empty potential - QList conductors_list = content().conductors(); + QList < QSet > potential_List; + if (content().conductors().size() == 0) + return (potential_List); //return an empty potential + QList conductors_list = content().conductors(); - do { - QSet one_potential = - conductors_list.first() - -> relatedPotentialConductors(); - one_potential << conductors_list.takeFirst(); - foreach (Conductor *c, one_potential) - conductors_list.removeOne(c); - potential_List << one_potential; - } while (!conductors_list.empty()); + do { + QSet one_potential = + conductors_list.first() + -> relatedPotentialConductors(); + one_potential << conductors_list.takeFirst(); + foreach (Conductor *c, one_potential) + conductors_list.removeOne(c); + potential_List << one_potential; + } while (!conductors_list.empty()); - return (potential_List); + return (potential_List); } /** - @brief Diagram::toXml - Exports all or part of the schema - \~French Exporte tout ou partie du schema - \~ @param whole_content : - Boolean (to true by default) indicating if the generated XML must - represent the entire schema or only the selected content - \~French Booleen (a vrai par defaut) indiquant si le XML genere doit - representer l'integralite du schema ou seulement le contenu selectionne - \~ @return An XML Document (QDomDocument) - \~French Un Document XML (QDomDocument) + @brief Diagram::toXml + Exports all or part of the schema + \~French Exporte tout ou partie du schema + \~ @param whole_content : + Boolean (to true by default) indicating if the generated XML must + represent the entire schema or only the selected content + \~French Booleen (a vrai par defaut) indiquant si le XML genere doit + representer l'integralite du schema ou seulement le contenu selectionne + \~ @return An XML Document (QDomDocument) + \~French Un Document XML (QDomDocument) */ QDomDocument Diagram::toXml(bool whole_content) { - // document - QDomDocument document; + // document + QDomDocument document; - // XML tree root - // racine de l'arbre XML - auto dom_root = document.createElement("diagram"); + // XML tree root + // racine de l'arbre XML + auto dom_root = document.createElement("diagram"); - // schema properties - // proprietes du schema - if (whole_content) { - border_and_titleblock.titleBlockToXml(dom_root); - border_and_titleblock.borderToXml(dom_root); + // schema properties + // proprietes du schema + if (whole_content) { + border_and_titleblock.titleBlockToXml(dom_root); + border_and_titleblock.borderToXml(dom_root); - // Default conductor properties - QDomElement default_conductor = - document.createElement("defaultconductor"); - defaultConductorProperties.toXml(default_conductor); - dom_root.appendChild(default_conductor); + // Default conductor properties + QDomElement default_conductor = + document.createElement("defaultconductor"); + defaultConductorProperties.toXml(default_conductor); + dom_root.appendChild(default_conductor); - // Conductor autonum - if (!m_conductors_autonum_name.isEmpty()) { - dom_root.setAttribute("conductorAutonum", - m_conductors_autonum_name); - } + // Conductor autonum + if (!m_conductors_autonum_name.isEmpty()) { + dom_root.setAttribute("conductorAutonum", + m_conductors_autonum_name); + } - //Default New Element - dom_root.setAttribute("freezeNewElement", - m_freeze_new_elements ? "true" : "false"); + //Default New Element + dom_root.setAttribute("freezeNewElement", + m_freeze_new_elements ? "true" : "false"); - //Default New Conductor - dom_root.setAttribute("freezeNewConductor", - m_freeze_new_conductors_ - ? "true" : "false"); + //Default New Conductor + dom_root.setAttribute("freezeNewConductor", + m_freeze_new_conductors_ + ? "true" : "false"); - //Element Folio Sequential Variables - if (!m_elmt_unitfolio_max.isEmpty() - || !m_elmt_tenfolio_max.isEmpty() - || !m_elmt_hundredfolio_max.isEmpty()) { - QDomElement elmtfoliosequential = - document.createElement( - "elementautonumfoliosequentials"); - if (!m_elmt_unitfolio_max.isEmpty()) { - QDomElement elmtfolioseq = - document.createElement( - "elementunitfolioseq"); - folioSequentialsToXml(&m_elmt_unitfolio_max, - &elmtfolioseq, - "sequf_", - "unitfolioseq", - &document); - elmtfoliosequential.appendChild(elmtfolioseq); - } - if (!m_elmt_tenfolio_max.isEmpty()) { - QDomElement elmtfolioseq = - document.createElement( - "elementtenfolioseq"); - folioSequentialsToXml(&m_elmt_tenfolio_max, - &elmtfolioseq, - "seqtf_", - "tenfolioseq", - &document); - elmtfoliosequential.appendChild(elmtfolioseq); - } - if (!m_elmt_hundredfolio_max.isEmpty()) { - QDomElement elmtfolioseq = - document.createElement( - "elementhundredfolioseq"); - folioSequentialsToXml(&m_elmt_hundredfolio_max, - &elmtfolioseq, - "seqhf_", - "hundredfolioseq", - &document); - elmtfoliosequential.appendChild(elmtfolioseq); - } - dom_root.appendChild(elmtfoliosequential); - } - // Conductor Folio Sequential Variables - if (!m_cnd_unitfolio_max.isEmpty() - || !m_cnd_tenfolio_max.isEmpty() || - !m_cnd_hundredfolio_max.isEmpty()) { - QDomElement cndfoliosequential = - document.createElement( - "conductorautonumfoliosequentials"); - QHash::iterator i; - if (!m_cnd_unitfolio_max.isEmpty()) { - QDomElement cndfolioseq = - document.createElement( - "conductorunitfolioseq"); - folioSequentialsToXml(&m_cnd_unitfolio_max, - &cndfolioseq, - "sequf_", - "unitfolioseq", - &document); - cndfoliosequential.appendChild(cndfolioseq); - } - if (!m_cnd_tenfolio_max.isEmpty()) { - QDomElement cndfolioseq = - document.createElement( - "conductortenfolioseq"); - folioSequentialsToXml(&m_cnd_tenfolio_max, - &cndfolioseq, - "seqtf_", - "tenfolioseq", - &document); - cndfoliosequential.appendChild(cndfolioseq); - } - if (!m_cnd_hundredfolio_max.isEmpty()) { - QDomElement cndfolioseq = - document.createElement( - "conductorhundredfolioseq"); - folioSequentialsToXml(&m_cnd_hundredfolio_max, - &cndfolioseq, - "seqhf_", - "hundredfolioseq", - &document); - cndfoliosequential.appendChild(cndfolioseq); - } - dom_root.appendChild(cndfoliosequential); - } - } - else { - //this method with whole_content to false, - //is often use to copy and paste the current selection - //so we add the id of the project where copy occur. - dom_root.setAttribute("projectId", QETApp::projectId(m_project)); - } - document.appendChild(dom_root); + //Element Folio Sequential Variables + if (!m_elmt_unitfolio_max.isEmpty() + || !m_elmt_tenfolio_max.isEmpty() + || !m_elmt_hundredfolio_max.isEmpty()) { + QDomElement elmtfoliosequential = + document.createElement( + "elementautonumfoliosequentials"); + if (!m_elmt_unitfolio_max.isEmpty()) { + QDomElement elmtfolioseq = + document.createElement( + "elementunitfolioseq"); + folioSequentialsToXml(&m_elmt_unitfolio_max, + &elmtfolioseq, + "sequf_", + "unitfolioseq", + &document); + elmtfoliosequential.appendChild(elmtfolioseq); + } + if (!m_elmt_tenfolio_max.isEmpty()) { + QDomElement elmtfolioseq = + document.createElement( + "elementtenfolioseq"); + folioSequentialsToXml(&m_elmt_tenfolio_max, + &elmtfolioseq, + "seqtf_", + "tenfolioseq", + &document); + elmtfoliosequential.appendChild(elmtfolioseq); + } + if (!m_elmt_hundredfolio_max.isEmpty()) { + QDomElement elmtfolioseq = + document.createElement( + "elementhundredfolioseq"); + folioSequentialsToXml(&m_elmt_hundredfolio_max, + &elmtfolioseq, + "seqhf_", + "hundredfolioseq", + &document); + elmtfoliosequential.appendChild(elmtfolioseq); + } + dom_root.appendChild(elmtfoliosequential); + } + // Conductor Folio Sequential Variables + if (!m_cnd_unitfolio_max.isEmpty() + || !m_cnd_tenfolio_max.isEmpty() || + !m_cnd_hundredfolio_max.isEmpty()) { + QDomElement cndfoliosequential = + document.createElement( + "conductorautonumfoliosequentials"); + QHash::iterator i; + if (!m_cnd_unitfolio_max.isEmpty()) { + QDomElement cndfolioseq = + document.createElement( + "conductorunitfolioseq"); + folioSequentialsToXml(&m_cnd_unitfolio_max, + &cndfolioseq, + "sequf_", + "unitfolioseq", + &document); + cndfoliosequential.appendChild(cndfolioseq); + } + if (!m_cnd_tenfolio_max.isEmpty()) { + QDomElement cndfolioseq = + document.createElement( + "conductortenfolioseq"); + folioSequentialsToXml(&m_cnd_tenfolio_max, + &cndfolioseq, + "seqtf_", + "tenfolioseq", + &document); + cndfoliosequential.appendChild(cndfolioseq); + } + if (!m_cnd_hundredfolio_max.isEmpty()) { + QDomElement cndfolioseq = + document.createElement( + "conductorhundredfolioseq"); + folioSequentialsToXml(&m_cnd_hundredfolio_max, + &cndfolioseq, + "seqhf_", + "hundredfolioseq", + &document); + cndfoliosequential.appendChild(cndfolioseq); + } + dom_root.appendChild(cndfoliosequential); + } + } + else { + //this method with whole_content to false, + //is often use to copy and paste the current selection + //so we add the id of the project where copy occur. + dom_root.setAttribute("projectId", QETApp::projectId(m_project)); + } + document.appendChild(dom_root); - if (items().isEmpty()) - return(document); + if (items().isEmpty()) + return(document); - QVector list_elements; - QVector list_conductors; - QVector list_texts; - QVector list_images; - QVector list_shapes; - QVector table_vector; + QVector list_elements; + QVector list_conductors; + QVector list_texts; + QVector list_images; + QVector list_shapes; + QVector table_vector; - //Ckeck graphics item to "XMLise" - for(QGraphicsItem *qgi : items()) - { - switch (qgi->type()) - { - case Element::Type: { - auto elmt = static_cast(qgi); - if (whole_content || elmt->isSelected()) - list_elements << elmt; - break; - } - case Conductor::Type: { - auto cond = static_cast(qgi); - if (whole_content) - list_conductors << cond; - /* When we did not export the whole diagram, - * we must to remove the non selected conductors. - * At this step that mean a conductor which one - * of these two element are not selected - */ - else if (cond->terminal1->parentItem()->isSelected() - && cond->terminal2->parentItem()->isSelected()) - list_conductors << cond; - break; - } - case DiagramImageItem::Type: { - auto image = static_cast(qgi); - if (whole_content || image->isSelected()) - list_images << image; - break; - } - case IndependentTextItem::Type: { - auto indi_text = static_cast(qgi); - if (whole_content || indi_text->isSelected()) - list_texts << indi_text; - break; - } - case QetShapeItem::Type: { - auto shape = static_cast(qgi); - if (whole_content || shape->isSelected()) - list_shapes << shape; - break; - } - case QetGraphicsTableItem::Type: { - auto table = static_cast(qgi); - if (whole_content || table->isSelected()) - table_vector << table; - } - } - } + //Ckeck graphics item to "XMLise" + for(QGraphicsItem *qgi : items()) + { + switch (qgi->type()) + { + case Element::Type: { + auto elmt = static_cast(qgi); + if (whole_content || elmt->isSelected()) + list_elements << elmt; + break; + } + case Conductor::Type: { + auto cond = static_cast(qgi); + if (whole_content) + list_conductors << cond; + /* When we did not export the whole diagram, + * we must to remove the non selected conductors. + * At this step that mean a conductor which one + * of these two element are not selected + */ + else if (cond->terminal1->parentItem()->isSelected() + && cond->terminal2->parentItem()->isSelected()) + list_conductors << cond; + break; + } + case DiagramImageItem::Type: { + auto image = static_cast(qgi); + if (whole_content || image->isSelected()) + list_images << image; + break; + } + case IndependentTextItem::Type: { + auto indi_text = static_cast(qgi); + if (whole_content || indi_text->isSelected()) + list_texts << indi_text; + break; + } + case QetShapeItem::Type: { + auto shape = static_cast(qgi); + if (whole_content || shape->isSelected()) + list_shapes << shape; + break; + } + case QetGraphicsTableItem::Type: { + auto table = static_cast(qgi); + if (whole_content || table->isSelected()) + table_vector << table; + } + } + } - // correspondence table between the addresses of the terminals and their ids - // table de correspondance entre les adresses des bornes et leurs ids - QHash table_adr_id; + // correspondence table between the addresses of the terminals and their ids + // table de correspondance entre les adresses des bornes et leurs ids + QHash table_adr_id; - if (!list_elements.isEmpty()) { - auto dom_elements = document.createElement("elements"); - for (auto elmt : list_elements) { - dom_elements.appendChild(elmt->toXml(document, - table_adr_id)); - } - dom_root.appendChild(dom_elements); - } + if (!list_elements.isEmpty()) { + auto dom_elements = document.createElement("elements"); + for (auto elmt : list_elements) { + dom_elements.appendChild(elmt->toXml(document, + table_adr_id)); + } + dom_root.appendChild(dom_elements); + } - if (!list_conductors.isEmpty()) { - auto dom_conductors = document.createElement("conductors"); - for (auto cond : list_conductors) { - dom_conductors.appendChild(cond->toXml(document, - table_adr_id)); - } - dom_root.appendChild(dom_conductors); - } + if (!list_conductors.isEmpty()) { + auto dom_conductors = document.createElement("conductors"); + for (auto cond : list_conductors) { + dom_conductors.appendChild(cond->toXml(document, + table_adr_id)); + } + dom_root.appendChild(dom_conductors); + } - if (!list_texts.isEmpty()) { - auto dom_texts = document.createElement("inputs"); - for (auto dti : list_texts) { - dom_texts.appendChild(dti->toXml(document)); - } - dom_root.appendChild(dom_texts); - } + if (!list_texts.isEmpty()) { + auto dom_texts = document.createElement("inputs"); + for (auto dti : list_texts) { + dom_texts.appendChild(dti->toXml(document)); + } + dom_root.appendChild(dom_texts); + } - if (!list_images.isEmpty()) { - auto dom_images = document.createElement("images"); - for (auto dii : list_images) { - dom_images.appendChild(dii->toXml(document)); - } - dom_root.appendChild(dom_images); - } + if (!list_images.isEmpty()) { + auto dom_images = document.createElement("images"); + for (auto dii : list_images) { + dom_images.appendChild(dii->toXml(document)); + } + dom_root.appendChild(dom_images); + } - if (!list_shapes.isEmpty()) { - auto dom_shapes = document.createElement("shapes"); - for (auto dii : list_shapes) { - dom_shapes.appendChild(dii -> toXml(document)); - } - dom_root.appendChild(dom_shapes); - } + if (!list_shapes.isEmpty()) { + auto dom_shapes = document.createElement("shapes"); + for (auto dii : list_shapes) { + dom_shapes.appendChild(dii -> toXml(document)); + } + dom_root.appendChild(dom_shapes); + } - if (table_vector.size()) { - auto tables = document.createElement("tables"); - for (auto table : table_vector) { - tables.appendChild(table->toXml(document)); - } - dom_root.appendChild(tables); - } + if (table_vector.size()) { + auto tables = document.createElement("tables"); + for (auto table : table_vector) { + tables.appendChild(table->toXml(document)); + } + dom_root.appendChild(tables); + } - return(document); + return(document); } /** - @brief Diagram::folioSequentialsToXml - Add folio sequential to QDomElement - @param hash to retrieve content with content - @param domElement to add attributes - @param seq_type type - @param type - @param doc + @brief Diagram::folioSequentialsToXml + Add folio sequential to QDomElement + @param hash to retrieve content with content + @param domElement to add attributes + @param seq_type type + @param type + @param doc */ void Diagram::folioSequentialsToXml(QHash *hash, - QDomElement *domElement, - const QString& seq_type, - const QString& type, - QDomDocument *doc) { - QHash::iterator i; - for (i = hash->begin(); i != hash->end(); i++) { - QDomElement folioseq = doc->createElement(type); - folioseq.setAttribute("title", i.key()); - for (int j = 0; j < i.value().size(); j++) { - folioseq.setAttribute(seq_type + QString::number(j+1), - i.value().at(j)); - } - domElement->appendChild(folioseq); - } + QStringList> *hash, + QDomElement *domElement, + const QString& seq_type, + const QString& type, + QDomDocument *doc) { + QHash::iterator i; + for (i = hash->begin(); i != hash->end(); i++) { + QDomElement folioseq = doc->createElement(type); + folioseq.setAttribute("title", i.key()); + for (int j = 0; j < i.value().size(); j++) { + folioseq.setAttribute(seq_type + QString::number(j+1), + i.value().at(j)); + } + domElement->appendChild(folioseq); + } } /** - @brief Diagram::fromXml - Imports the described schema into an XML document. - If a position is specified, - the imported elements are positioned so that the upper left corner - of the smallest rectangle that can surround them all - (the bounding rect) is at this position. - \~French Importe le schema decrit dans un document XML. - Si une position estprecisee, - les elements importes sont positionnes de maniere a ce que le coin - superieur gauche du plus petit rectangle pouvant les entourant tous - (le bounding rect) soit a cette position. - \~ @param document : - The XML document to analyze - \~French Le document XML a analyser - \~ @param position : - The position of the diagram matters - \~French La position du schema importe - \~ @param consider_informations : - If true, additional information - (author, title, ...) will be taken into account - \~French Si vrai, les informations complementaires - (auteur, titre, ...) seront prises en compte - \~ @param content_ptr : - if this pointer to a DiagramContent is different from 0, - it will be filled with the content added to the schema by the fromXml - \~French si ce pointeur vers un DiagramContent est different de 0, - il sera rempli avec le contenu ajoute au schema par le fromXml - \~ @return true if the import was successful, false otherwise - \~French true si l'import a reussi, false sinon + @brief Diagram::fromXml + Imports the described schema into an XML document. + If a position is specified, + the imported elements are positioned so that the upper left corner + of the smallest rectangle that can surround them all + (the bounding rect) is at this position. + \~French Importe le schema decrit dans un document XML. + Si une position estprecisee, + les elements importes sont positionnes de maniere a ce que le coin + superieur gauche du plus petit rectangle pouvant les entourant tous + (le bounding rect) soit a cette position. + \~ @param document : + The XML document to analyze + \~French Le document XML a analyser + \~ @param position : + The position of the diagram matters + \~French La position du schema importe + \~ @param consider_informations : + If true, additional information + (author, title, ...) will be taken into account + \~French Si vrai, les informations complementaires + (auteur, titre, ...) seront prises en compte + \~ @param content_ptr : + if this pointer to a DiagramContent is different from 0, + it will be filled with the content added to the schema by the fromXml + \~French si ce pointeur vers un DiagramContent est different de 0, + il sera rempli avec le contenu ajoute au schema par le fromXml + \~ @return true if the import was successful, false otherwise + \~French true si l'import a reussi, false sinon */ bool Diagram::fromXml(QDomDocument &document, - QPointF position, - bool consider_informations, - DiagramContent *content_ptr) { - QDomElement root = document.documentElement(); - return(fromXml(root, position, consider_informations, content_ptr)); + QPointF position, + bool consider_informations, + DiagramContent *content_ptr) { + QDomElement root = document.documentElement(); + return(fromXml(root, position, consider_informations, content_ptr)); } /** - @brief Diagram::initFromXml - Imports the described schema in an XML element. - This method delegates its work to Diagram :: fromXml - If the import is successful, - this method also initializes the XML document internal allowing to - manage the recording of this diagram in the project to which it belongs. - @see Diagram::fromXml - \~French Importe le schema decrit dans un element XML. - Cette methode delegue son travail a Diagram::fromXml - Si l'import reussit, cette methode initialise egalement le document XML - interne permettant de bien gerer l'enregistrement de ce schema dans le - projet auquel il appartient. - \~ @param document : The XML document to analyze - \~French Le document XML a analyser - \~ @param position : The position of the diagram matters - \~French La position du schema importe - \~ @param consider_informations : - If true, additional information - (author, title, ...) will be taken into account - \~French Si vrai, les informations complementaires - (auteur, titre, ...) seront prises en compte - \~ @param content_ptr : - if this pointer to a DiagramContent is different from 0, - it will be filled with the content added to the schema by the fromXml - \~French si ce pointeur vers un DiagramContent est different de 0, - il sera rempli avec le contenu ajoute au schema par le fromXml - \~ @return true if the import was successful, false otherwise - \~French true si l'import a reussi, false sinon + @brief Diagram::initFromXml + Imports the described schema in an XML element. + This method delegates its work to Diagram :: fromXml + If the import is successful, + this method also initializes the XML document internal allowing to + manage the recording of this diagram in the project to which it belongs. + @see Diagram::fromXml + \~French Importe le schema decrit dans un element XML. + Cette methode delegue son travail a Diagram::fromXml + Si l'import reussit, cette methode initialise egalement le document XML + interne permettant de bien gerer l'enregistrement de ce schema dans le + projet auquel il appartient. + \~ @param document : The XML document to analyze + \~French Le document XML a analyser + \~ @param position : The position of the diagram matters + \~French La position du schema importe + \~ @param consider_informations : + If true, additional information + (author, title, ...) will be taken into account + \~French Si vrai, les informations complementaires + (auteur, titre, ...) seront prises en compte + \~ @param content_ptr : + if this pointer to a DiagramContent is different from 0, + it will be filled with the content added to the schema by the fromXml + \~French si ce pointeur vers un DiagramContent est different de 0, + il sera rempli avec le contenu ajoute au schema par le fromXml + \~ @return true if the import was successful, false otherwise + \~French true si l'import a reussi, false sinon */ bool Diagram::initFromXml(QDomElement &document, - QPointF position, - bool consider_informations, - DiagramContent *content_ptr) { - /* import the content and properties of the schema - * from the XML element provided as a parameter - * import le contenu et les proprietes du schema - * depuis l'element XML fourni en parametre - */ - bool from_xml = fromXml(document, - position, - consider_informations, - content_ptr); + QPointF position, + bool consider_informations, + DiagramContent *content_ptr) { + /* import the content and properties of the schema + * from the XML element provided as a parameter + * import le contenu et les proprietes du schema + * depuis l'element XML fourni en parametre + */ + bool from_xml = fromXml(document, + position, + consider_informations, + content_ptr); - return(from_xml); + return(from_xml); } /** - @brief findTerminal - Find terminal to which the conductor should be connected - @param conductor_index 1 or 2 depending on which terminal is searched - @param f Conductor xml element - @param table_adr_id Hash table to all terminal id assignement (legacy) - @param added_elements Elements found in the xml file - @return + @brief findTerminal + Find terminal to which the conductor should be connected + @param conductor_index 1 or 2 depending on which terminal is searched + @param f Conductor xml element + @param table_adr_id Hash table to all terminal id assignement (legacy) + @param added_elements Elements found in the xml file + @return */ Terminal* findTerminal(int conductor_index, - QDomElement& f, - QHash& table_adr_id, - QList& added_elements) { - assert(conductor_index == 1 || conductor_index == 2); + QDomElement& f, + QHash& table_adr_id, + QList& added_elements) { + assert(conductor_index == 1 || conductor_index == 2); - QString element_index = "element" + QString::number(conductor_index); - QString terminal_index = "terminal" + QString::number(conductor_index); + QString element_index = "element" + QString::number(conductor_index); + QString terminal_index = "terminal" + QString::number(conductor_index); - if (f.hasAttribute(element_index)) { - QUuid element_uuid = QUuid(f.attribute(element_index)); - // element1 did not exist in the conductor part of the xml until prior 0.7 - // It is used as an indicator that uuid's are used to identify terminals - bool element_found = false; - for (auto element: added_elements) { - if (element->uuid() != element_uuid) - continue; - element_found = true; - QUuid terminal_uuid = QUuid(f.attribute(terminal_index)); - for (auto terminal: element->terminals()) { - if (terminal->uuid() != terminal_uuid) - continue; + if (f.hasAttribute(element_index)) { + QUuid element_uuid = QUuid(f.attribute(element_index)); + // element1 did not exist in the conductor part of the xml until prior 0.7 + // It is used as an indicator that uuid's are used to identify terminals + bool element_found = false; + for (auto element: added_elements) { + if (element->uuid() != element_uuid) + continue; + element_found = true; + QUuid terminal_uuid = QUuid(f.attribute(terminal_index)); + for (auto terminal: element->terminals()) { + if (terminal->uuid() != terminal_uuid) + continue; - return terminal; - } - qDebug() << "Diagram::fromXml() : " - << terminal_index - << ":" - << terminal_uuid - << "not found in " - << element_index - << ":" - << element_uuid; - break; - } - if (!element_found) - qDebug() << "Diagram::fromXml() : " - << element_index - << ": " - << element_uuid - << "not found"; - } else { - // Backward compatibility. - // Until version 0.7 a generated id is used to link the terminal. - int id_p1 = f.attribute(terminal_index).toInt(); - if (!table_adr_id.contains(id_p1)) { - qDebug() << "Diagram::fromXml() : terminal id " - << id_p1 - << " not found"; - } else - return table_adr_id.value(id_p1); - } - return nullptr; + return terminal; + } + qDebug() << "Diagram::fromXml() : " + << terminal_index + << ":" + << terminal_uuid + << "not found in " + << element_index + << ":" + << element_uuid; + break; + } + if (!element_found) + qDebug() << "Diagram::fromXml() : " + << element_index + << ": " + << element_uuid + << "not found"; + } else { + // Backward compatibility. + // Until version 0.7 a generated id is used to link the terminal. + int id_p1 = f.attribute(terminal_index).toInt(); + if (!table_adr_id.contains(id_p1)) { + qDebug() << "Diagram::fromXml() : terminal id " + << id_p1 + << " not found"; + } else + return table_adr_id.value(id_p1); + } + return nullptr; } /** - @brief Diagram::fromXml - Imports the described schema in an XML element. If a position is - specified, the imported elements are positioned in such a way that the - upper left corner of the smallest rectangle that can surround them all - (the bounding rect) either at this position. - \~French Importe le schema decrit dans un element XML. - Si une position est precisee, - les elements importes sont positionnes de maniere a ce que le - coin superieur gauche du plus petit rectangle pouvant les entourant tous - (le bounding rect) soit a cette position. - \~ @param document : - The XML document to analyze - \~French Le document XML a analyser - \~ @param position : - The position of the diagram matters - \~French La position du schema importe - \~ @param consider_informations : - If true, additional information - (author, title, ...) will be taken into account - \~French Si vrai, les informations complementaires - (auteur, titre, ...) seront prises en compte - \~ @param content_ptr : - if this pointer to a DiagramContent is different from 0, - it will be filled with the content added to the schema by the fromXml - \~French si ce pointeur vers un DiagramContent est different de 0, - il sera rempli avec le contenu ajoute au schema par le fromXml - \~ @return - true if the import was successful, false otherwise - \~French true si l'import a reussi, false sinon + @brief Diagram::fromXml + Imports the described schema in an XML element. If a position is + specified, the imported elements are positioned in such a way that the + upper left corner of the smallest rectangle that can surround them all + (the bounding rect) either at this position. + \~French Importe le schema decrit dans un element XML. + Si une position est precisee, + les elements importes sont positionnes de maniere a ce que le + coin superieur gauche du plus petit rectangle pouvant les entourant tous + (le bounding rect) soit a cette position. + \~ @param document : + The XML document to analyze + \~French Le document XML a analyser + \~ @param position : + The position of the diagram matters + \~French La position du schema importe + \~ @param consider_informations : + If true, additional information + (author, title, ...) will be taken into account + \~French Si vrai, les informations complementaires + (auteur, titre, ...) seront prises en compte + \~ @param content_ptr : + if this pointer to a DiagramContent is different from 0, + it will be filled with the content added to the schema by the fromXml + \~French si ce pointeur vers un DiagramContent est different de 0, + il sera rempli avec le contenu ajoute au schema par le fromXml + \~ @return + true if the import was successful, false otherwise + \~French true si l'import a reussi, false sinon */ bool Diagram::fromXml(QDomElement &document, - QPointF position, - bool consider_informations, - DiagramContent *content_ptr) { - const QDomElement& root = document; - // The first element must be a diagram - if (root.tagName() != "diagram") return(false); + QPointF position, + bool consider_informations, + DiagramContent *content_ptr) { + const QDomElement& root = document; + // The first element must be a diagram + if (root.tagName() != "diagram") return(false); - // Read attributes of this diagram - if (consider_informations) - { - // Load border and titleblock - border_and_titleblock.titleBlockFromXml(root); - border_and_titleblock.borderFromXml(root); + // Read attributes of this diagram + if (consider_informations) + { + // Load border and titleblock + border_and_titleblock.titleBlockFromXml(root); + border_and_titleblock.borderFromXml(root); - // Find the element "defaultconductor". - // If found, load default conductor properties. - QDomElement default_conductor_elmt = - root.firstChildElement("defaultconductor"); - if (!default_conductor_elmt.isNull()) { - defaultConductorProperties.fromXml(default_conductor_elmt); - } + // Find the element "defaultconductor". + // If found, load default conductor properties. + QDomElement default_conductor_elmt = + root.firstChildElement("defaultconductor"); + if (!default_conductor_elmt.isNull()) { + defaultConductorProperties.fromXml(default_conductor_elmt); + } - // Load the autonum - m_conductors_autonum_name = root.attribute("conductorAutonum"); + // Load the autonum + m_conductors_autonum_name = root.attribute("conductorAutonum"); - // Load Freeze New Element - m_freeze_new_elements = root.attribute("freezeNewElement").toInt(); + // Load Freeze New Element + m_freeze_new_elements = root.attribute("freezeNewElement").toInt(); - // Load Freeze New Conductor - m_freeze_new_conductors_ = root.attribute("freezeNewConductor").toInt(); + // Load Freeze New Conductor + m_freeze_new_conductors_ = root.attribute("freezeNewConductor").toInt(); - //Load Element Folio Sequential - folioSequentialsFromXml(root, - &m_elmt_unitfolio_max, - "elementunitfolioseq", - "sequf_", - "unitfolioseq", - "elementautonumfoliosequentials"); - folioSequentialsFromXml(root, &m_elmt_tenfolio_max, - "elementtenfolioseq", - "seqtf_", - "tenfolioseq", - "elementautonumfoliosequentials"); - folioSequentialsFromXml(root, &m_elmt_hundredfolio_max, - "elementhundredfolioseq", - "seqhf_", - "hundredfolioseq", - "elementautonumfoliosequentials"); + //Load Element Folio Sequential + folioSequentialsFromXml(root, + &m_elmt_unitfolio_max, + "elementunitfolioseq", + "sequf_", + "unitfolioseq", + "elementautonumfoliosequentials"); + folioSequentialsFromXml(root, &m_elmt_tenfolio_max, + "elementtenfolioseq", + "seqtf_", + "tenfolioseq", + "elementautonumfoliosequentials"); + folioSequentialsFromXml(root, &m_elmt_hundredfolio_max, + "elementhundredfolioseq", + "seqhf_", + "hundredfolioseq", + "elementautonumfoliosequentials"); - //Load Conductor Folio Sequential - folioSequentialsFromXml(root, &m_cnd_unitfolio_max, - "conductorunitfolioseq", - "sequf_", - "unitfolioseq", - "conductorautonumfoliosequentials"); - folioSequentialsFromXml(root, &m_cnd_tenfolio_max, - "conductortenfolioseq", - "seqtf_","tenfolioseq", - "conductorautonumfoliosequentials"); - folioSequentialsFromXml(root, &m_cnd_hundredfolio_max, - "conductorhundredfolioseq", - "seqhf_", - "hundredfolioseq", - "conductorautonumfoliosequentials"); - } + //Load Conductor Folio Sequential + folioSequentialsFromXml(root, &m_cnd_unitfolio_max, + "conductorunitfolioseq", + "sequf_", + "unitfolioseq", + "conductorautonumfoliosequentials"); + folioSequentialsFromXml(root, &m_cnd_tenfolio_max, + "conductortenfolioseq", + "seqtf_","tenfolioseq", + "conductorautonumfoliosequentials"); + folioSequentialsFromXml(root, &m_cnd_hundredfolio_max, + "conductorhundredfolioseq", + "seqhf_", + "hundredfolioseq", + "conductorautonumfoliosequentials"); + } - // if child haven't got a child, loading is finish (diagram is empty) - if (root.firstChild().isNull()) { - return(true); - } + // if child haven't got a child, loading is finish (diagram is empty) + if (root.firstChild().isNull()) { + return(true); + } - //If paste from another project - if (root.hasAttribute("projectId")) { - QETProject *other_project = QETApp::project( - root.attribute("projectId", - "-1").toInt()); + //If paste from another project + if (root.hasAttribute("projectId")) { + QETProject *other_project = QETApp::project( + root.attribute("projectId", + "-1").toInt()); - /* We try to paste from another project, - * then befor paste elements, - * we must to import the definition of the pasted elements - * (owned by other project) - * in the embedded collection of this project - */ - if (other_project && other_project != m_project) { - ElementCollectionHandler ech; - foreach (QDomElement element_xml, - QET::findInDomElement(root, - "elements", - "element")) { - if (!Element::valideXml(element_xml)) continue; + /* We try to paste from another project, + * then befor paste elements, + * we must to import the definition of the pasted elements + * (owned by other project) + * in the embedded collection of this project + */ + if (other_project && other_project != m_project) { + ElementCollectionHandler ech; + foreach (QDomElement element_xml, + QET::findInDomElement(root, + "elements", + "element")) { + if (!Element::valideXml(element_xml)) continue; - QString type_id = element_xml.attribute("type"); + QString type_id = element_xml.attribute("type"); - if (type_id.startsWith("embed://")) { - ElementsLocation location( - type_id, - other_project); - ech.importFromProject(m_project, - location); - } - } - } - } - //Load all elements from the XML - QList added_elements; - QHash table_adr_id; - foreach (QDomElement element_xml, - QET::findInDomElement(root, "elements", "element")) - { - if (!Element::valideXml(element_xml)) continue; + if (type_id.startsWith("embed://")) { + ElementsLocation location( + type_id, + other_project); + ech.importFromProject(m_project, + location); + } + } + } + } + //Load all elements from the XML + QList added_elements; + QHash table_adr_id; + foreach (QDomElement element_xml, + QET::findInDomElement(root, "elements", "element")) + { + if (!Element::valideXml(element_xml)) continue; - // cree un element dont le type correspond a l'id type - QString type_id = element_xml.attribute("type"); - ElementsLocation element_location; - if (type_id.startsWith("embed://")) { - element_location = ElementsLocation(type_id, m_project); - } - else { - element_location = ElementsLocation(type_id); - } + // cree un element dont le type correspond a l'id type + QString type_id = element_xml.attribute("type"); + ElementsLocation element_location; + if (type_id.startsWith("embed://")) { + element_location = ElementsLocation(type_id, m_project); + } + else { + element_location = ElementsLocation(type_id); + } - int state = 0; - Element *nvel_elmt = - ElementFactory::Instance() -> createElement( - element_location, nullptr, &state); - if (state) - { - QString debug_message = - QString("Diagram::fromXml() : Le chargement de " - "la description de l'element %1 a " - "echoue avec le code d'erreur %2").arg( - element_location.path()).arg(state); - qDebug() << qPrintable(debug_message); - delete nvel_elmt; - continue; - } + int state = 0; + Element *nvel_elmt = + ElementFactory::Instance() -> createElement( + element_location, nullptr, &state); + if (state) + { + QString debug_message = + QString("Diagram::fromXml() : Le chargement de " + "la description de l'element %1 a " + "echoue avec le code d'erreur %2").arg( + element_location.path()).arg(state); + qDebug() << qPrintable(debug_message); + delete nvel_elmt; + continue; + } - addItem(nvel_elmt); - //Loading fail, remove item from the diagram - if (!nvel_elmt->fromXml(element_xml, table_adr_id)) - { - removeItem(nvel_elmt); - delete nvel_elmt; - qDebug() << "Diagram::fromXml() : Le chargement des " - "parametres d'un element a echoue"; - } else { - added_elements << nvel_elmt; - } - } + addItem(nvel_elmt); + //Loading fail, remove item from the diagram + if (!nvel_elmt->fromXml(element_xml, table_adr_id)) + { + removeItem(nvel_elmt); + delete nvel_elmt; + qDebug() << "Diagram::fromXml() : Le chargement des " + "parametres d'un element a echoue"; + } else { + added_elements << nvel_elmt; + } + } - // Load text - QList added_texts; - foreach (QDomElement text_xml, QET::findInDomElement(root, - "inputs", - "input")) { - IndependentTextItem *iti = new IndependentTextItem(); - iti -> fromXml(text_xml); - addItem(iti); - added_texts << iti; - } + // Load text + QList added_texts; + foreach (QDomElement text_xml, QET::findInDomElement(root, + "inputs", + "input")) { + IndependentTextItem *iti = new IndependentTextItem(); + iti -> fromXml(text_xml); + addItem(iti); + added_texts << iti; + } - // Load image - QList added_images; - foreach (QDomElement image_xml, QET::findInDomElement(root, - "images", - "image")) { - DiagramImageItem *dii = new DiagramImageItem (); - dii -> fromXml(image_xml); - addItem(dii); - added_images << dii; - } + // Load image + QList added_images; + foreach (QDomElement image_xml, QET::findInDomElement(root, + "images", + "image")) { + DiagramImageItem *dii = new DiagramImageItem (); + dii -> fromXml(image_xml); + addItem(dii); + added_images << dii; + } - // Load shape - QList added_shapes; - foreach (QDomElement shape_xml, QET::findInDomElement(root, - "shapes", - "shape")) { - QetShapeItem *dii = new QetShapeItem (QPointF(0,0)); - dii -> fromXml(shape_xml); - addItem(dii); - added_shapes << dii; - } + // Load shape + QList added_shapes; + foreach (QDomElement shape_xml, QET::findInDomElement(root, + "shapes", + "shape")) { + QetShapeItem *dii = new QetShapeItem (QPointF(0,0)); + dii -> fromXml(shape_xml); + addItem(dii); + added_shapes << dii; + } - // Load conductor - QList added_conductors; - foreach (QDomElement f, QET::findInDomElement(root, - "conductors", - "conductor")) - { - if (!Conductor::valideXml(f)) continue; + // Load conductor + QList added_conductors; + foreach (QDomElement f, QET::findInDomElement(root, + "conductors", + "conductor")) + { + if (!Conductor::valideXml(f)) continue; - //Check if terminal that conductor must be linked is know + //Check if terminal that conductor must be linked is know - Terminal* p1 = findTerminal(1, f, table_adr_id, added_elements); - Terminal* p2 = findTerminal(2, f, table_adr_id, added_elements); + Terminal* p1 = findTerminal(1, f, table_adr_id, added_elements); + Terminal* p2 = findTerminal(2, f, table_adr_id, added_elements); - if (p1 && p2 && p1 != p2) - { - Conductor *c = new Conductor(p1, p2); - if (c->isValid()) - { - addItem(c); - c -> fromXml(f); - added_conductors << c; - } - else - delete c; - } - } + if (p1 && p2 && p1 != p2) + { + Conductor *c = new Conductor(p1, p2); + if (c->isValid()) + { + addItem(c); + c -> fromXml(f); + added_conductors << c; + } + else + delete c; + } + } - //Load tables - QVector added_tables; - for (auto dom_table - : QETXML::subChild(root, - "tables", - QetGraphicsTableItem::xmlTagName())) - { - auto table = new QetGraphicsTableItem(); - addItem(table); - table->fromXml(dom_table); - added_tables << table; - } + //Load tables + QVector added_tables; + for (auto dom_table + : QETXML::subChild(root, + "tables", + QetGraphicsTableItem::xmlTagName())) + { + auto table = new QetGraphicsTableItem(); + addItem(table); + table->fromXml(dom_table); + added_tables << table; + } - //Translate items if a new position was given in parameter - if (position != QPointF()) - { - QVector added_items; - for (auto element : added_elements ) added_items << element; - for (auto cond : added_conductors) added_items << cond; - for (auto shape : added_shapes ) added_items << shape; - for (auto text : added_texts ) added_items << text; - for (auto image : added_images ) added_items << image; - for (auto table : added_tables ) added_items << table; + //Translate items if a new position was given in parameter + if (position != QPointF()) + { + QVector added_items; + for (auto element : added_elements ) added_items << element; + for (auto cond : added_conductors) added_items << cond; + for (auto shape : added_shapes ) added_items << shape; + for (auto text : added_texts ) added_items << text; + for (auto image : added_images ) added_items << image; + for (auto table : added_tables ) added_items << table; - //Get the top left corner of the rectangle that contain all added items - QRectF items_rect; - for (auto item : added_items) { - items_rect = items_rect.united( - item->mapToScene( - item->boundingRect() - ).boundingRect()); - } + //Get the top left corner of the rectangle that contain all added items + QRectF items_rect; + for (auto item : added_items) { + items_rect = items_rect.united( + item->mapToScene( + item->boundingRect() + ).boundingRect()); + } - QPointF point_ = items_rect.topLeft(); - QPointF pos_ = Diagram::snapToGrid(QPointF (position.x() - point_.x(), - position.y() - point_.y())); + QPointF point_ = items_rect.topLeft(); + QPointF pos_ = Diagram::snapToGrid(QPointF (position.x() - point_.x(), + position.y() - point_.y())); - //Translate all added items - for (auto qgi : added_items) - qgi->setPos(qgi->pos() += pos_); - } + //Translate all added items + for (auto qgi : added_items) + qgi->setPos(qgi->pos() += pos_); + } - //Filling of falculatory lists - if (content_ptr) { - content_ptr -> m_elements = added_elements; - content_ptr -> m_conductors_to_move = added_conductors; -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove - content_ptr -> m_text_fields = added_texts.toSet(); - content_ptr -> m_images = added_images.toSet(); - content_ptr -> m_shapes = added_shapes.toSet(); + //Filling of falculatory lists + if (content_ptr) { + content_ptr -> m_elements = added_elements; + content_ptr -> m_conductors_to_move = added_conductors; +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove + content_ptr -> m_text_fields = added_texts.toSet(); + content_ptr -> m_images = added_images.toSet(); + content_ptr -> m_shapes = added_shapes.toSet(); #else #if TODO_LIST #pragma message("@TODO remove code for QT 5.14 or later") #endif - content_ptr -> m_text_fields = QSet( - added_texts.begin(), - added_texts.end()); - content_ptr -> m_images = QSet( - added_images.begin(), - added_images.end()); - content_ptr -> m_shapes = QSet( - added_shapes.begin(), - added_shapes.end()); + content_ptr -> m_text_fields = QSet( + added_texts.begin(), + added_texts.end()); + content_ptr -> m_images = QSet( + added_images.begin(), + added_images.end()); + content_ptr -> m_shapes = QSet( + added_shapes.begin(), + added_shapes.end()); #endif - content_ptr -> m_tables = added_tables; - } + content_ptr -> m_tables = added_tables; + } - adjustSceneRect(); - return(true); + adjustSceneRect(); + return(true); } /** - @brief Diagram::folioSequentialsFromXml - Load folio sequential from QDomElement - @param root containing all folio sequentials - @param hash : to be loaded with content - @param folioSeq type - @param seq type - @param type of sequential - @param autonumFolioSeqType + @brief Diagram::folioSequentialsFromXml + Load folio sequential from QDomElement + @param root containing all folio sequentials + @param hash : to be loaded with content + @param folioSeq type + @param seq type + @param type of sequential + @param autonumFolioSeqType */ void Diagram::folioSequentialsFromXml(const QDomElement &root, - QHash* hash, - const QString& folioSeq, - const QString& seq, - const QString& type, - const QString& autonumFolioSeqType) { - foreach (QDomElement folioSeqAutoNum, - QET::findInDomElement(root, autonumFolioSeqType, folioSeq)) { - for(QDomElement folioseq - = folioSeqAutoNum.firstChildElement(type); - !folioseq.isNull(); - folioseq = folioseq.nextSiblingElement(type)) { - QString title = folioseq.attribute("title"); - QStringList list; - int i = 1; - while (folioseq.hasAttribute(seq - + QString::number(i))) { - list << folioseq.attribute( - seq + QString::number(i)); - i++; - } - hash->insert(title,list); - } - } + QHash* hash, + const QString& folioSeq, + const QString& seq, + const QString& type, + const QString& autonumFolioSeqType) { + foreach (QDomElement folioSeqAutoNum, + QET::findInDomElement(root, autonumFolioSeqType, folioSeq)) { + for(QDomElement folioseq + = folioSeqAutoNum.firstChildElement(type); + !folioseq.isNull(); + folioseq = folioseq.nextSiblingElement(type)) { + QString title = folioseq.attribute("title"); + QStringList list; + int i = 1; + while (folioseq.hasAttribute(seq + + QString::number(i))) { + list << folioseq.attribute( + seq + QString::number(i)); + i++; + } + hash->insert(title,list); + } + } } /** - @brief Diagram::refreshContents - refresh all content of diagram. - - refresh conductor text. - - linking the elements waiting to be linked - - Refresh the connection of the dynamic element text item - (use for text with source of text label) + @brief Diagram::refreshContents + refresh all content of diagram. + - refresh conductor text. + - linking the elements waiting to be linked + - Refresh the connection of the dynamic element text item + (use for text with source of text label) */ void Diagram::refreshContents() { - ElementProvider provider_(this); + ElementProvider provider_(this); - for (Element *elmt : elements()) - { - elmt->initLink(project()); - for (DynamicElementTextItem *deti : elmt->dynamicTextItems()) - deti->refreshLabelConnection(); - } + for (Element *elmt : elements()) + { + elmt->initLink(project()); + for (DynamicElementTextItem *deti : elmt->dynamicTextItems()) + deti->refreshLabelConnection(); + } - for (Conductor *conductor : conductors()) - conductor->refreshText(); + for (Conductor *conductor : conductors()) + conductor->refreshText(); - for (auto table : provider_.table()) - table->initLink(); + for (auto table : provider_.table()) + table->initLink(); } /** - @brief Diagram::addItem - Réimplemented from QGraphicsScene::addItem(QGraphicsItem *item) - Do some specific operation if item need it (for exemple an element) - @param item + @brief Diagram::addItem + R??implemented from QGraphicsScene::addItem(QGraphicsItem *item) + Do some specific operation if item need it (for exemple an element) + @param item */ void Diagram::addItem(QGraphicsItem *item) { - if (!item || isReadOnly() || item->scene() == this) return; - QGraphicsScene::addItem(item); + if (!item || isReadOnly() || item->scene() == this) return; + QGraphicsScene::addItem(item); - switch (item->type()) - { - case Element::Type: - { - m_project->dataBase()->addElement( - static_cast(item)); - break; - } - case Conductor::Type: - { - Conductor *conductor = static_cast(item); - conductor->terminal1->addConductor(conductor); - conductor->terminal2->addConductor(conductor); - conductor->calculateTextItemPosition(); - break; - } - default: {break;} - } + switch (item->type()) + { + case Element::Type: + { + m_project->dataBase()->addElement( + static_cast(item)); + break; + } + case Conductor::Type: + { + Conductor *conductor = static_cast(item); + conductor->terminal1->addConductor(conductor); + conductor->terminal2->addConductor(conductor); + conductor->calculateTextItemPosition(); + break; + } + default: {break;} + } } /** - @brief Diagram::removeItem - Reimplemented from QGraphicsScene::removeItem(QGraphicsItem *item) - Do some specific operation if item need it (for exemple an element) - @param item + @brief Diagram::removeItem + Reimplemented from QGraphicsScene::removeItem(QGraphicsItem *item) + Do some specific operation if item need it (for exemple an element) + @param item */ void Diagram::removeItem(QGraphicsItem *item) { - if (!item || isReadOnly()) return; + if (!item || isReadOnly()) return; - switch (item->type()) - { - case Element::Type: - { - auto elmt = static_cast(item); - elmt->unlinkAllElements(); - m_project->dataBase()->removeElement(elmt); - break; - } - case Conductor::Type: - { - Conductor *conductor = static_cast(item); - conductor->terminal1->removeConductor(conductor); - conductor->terminal2->removeConductor(conductor); - break; - } - default: {break;} - } + switch (item->type()) + { + case Element::Type: + { + auto elmt = static_cast(item); + elmt->unlinkAllElements(); + m_project->dataBase()->removeElement(elmt); + break; + } + case Conductor::Type: + { + Conductor *conductor = static_cast(item); + conductor->terminal1->removeConductor(conductor); + conductor->terminal2->removeConductor(conductor); + break; + } + default: {break;} + } - QGraphicsScene::removeItem(item); + QGraphicsScene::removeItem(item); } /** - @brief Diagram::titleChanged - emit(diagramTitleChanged(this, title)); - @param title + @brief Diagram::titleChanged + emit(diagramTitleChanged(this, title)); + @param title */ void Diagram::titleChanged(const QString &title) { - emit(diagramTitleChanged(this, title)); + emit(diagramTitleChanged(this, title)); } /** - @brief Diagram::titleBlockTemplateChanged - This slot may be used to inform the diagram object that the given title - block template has changed. The diagram will thus flush its title - block-dedicated rendering cache. - @param template_name Name of the title block template that has changed + @brief Diagram::titleBlockTemplateChanged + This slot may be used to inform the diagram object that the given title + block template has changed. The diagram will thus flush its title + block-dedicated rendering cache. + @param template_name Name of the title block template that has changed */ void Diagram::titleBlockTemplateChanged(const QString &template_name) { - if (border_and_titleblock.titleBlockTemplateName() != template_name) - return; + if (border_and_titleblock.titleBlockTemplateName() != template_name) + return; - border_and_titleblock.titleBlockTemplateChanged(template_name); - update(); + border_and_titleblock.titleBlockTemplateChanged(template_name); + update(); } /** - @brief Diagram::titleBlockTemplateRemoved - This slot has to be be used to inform this class that the given title block - template is about to be removed and is no longer accessible. This class - will either use the provided optional TitleBlockTemplate or the default - title block provided by QETApp::defaultTitleBlockTemplate() - @param template_name Name of the title block template that has changed - @param new_template (Optional) Name of the title block template to use instead + @brief Diagram::titleBlockTemplateRemoved + This slot has to be be used to inform this class that the given title block + template is about to be removed and is no longer accessible. This class + will either use the provided optional TitleBlockTemplate or the default + title block provided by QETApp::defaultTitleBlockTemplate() + @param template_name Name of the title block template that has changed + @param new_template (Optional) Name of the title block template to use instead */ void Diagram::titleBlockTemplateRemoved(const QString &template_name, - const QString &new_template) + const QString &new_template) { - if (border_and_titleblock.titleBlockTemplateName() != template_name) return; - const TitleBlockTemplate *final_template = - m_project->embeddedTitleBlockTemplatesCollection() - ->getTemplate(new_template); - border_and_titleblock.titleBlockTemplateRemoved(template_name, - final_template); - update(); + if (border_and_titleblock.titleBlockTemplateName() != template_name) return; + const TitleBlockTemplate *final_template = + m_project->embeddedTitleBlockTemplatesCollection() + ->getTemplate(new_template); + border_and_titleblock.titleBlockTemplateRemoved(template_name, + final_template); + update(); } /** - @brief Diagram::setTitleBlockTemplate - Set the template to use to render the title block of this diagram. - @param template_name Name of the title block template. + @brief Diagram::setTitleBlockTemplate + Set the template to use to render the title block of this diagram. + @param template_name Name of the title block template. */ void Diagram::setTitleBlockTemplate(const QString &template_name) { - if (!m_project) return; + if (!m_project) return; - QString current_name = border_and_titleblock.titleBlockTemplateName(); - const TitleBlockTemplate *titleblock_template = - m_project->embeddedTitleBlockTemplatesCollection() - ->getTemplate(template_name); - border_and_titleblock.titleBlockTemplateRemoved(current_name, - titleblock_template); + QString current_name = border_and_titleblock.titleBlockTemplateName(); + const TitleBlockTemplate *titleblock_template = + m_project->embeddedTitleBlockTemplatesCollection() + ->getTemplate(template_name); + border_and_titleblock.titleBlockTemplateRemoved(current_name, + titleblock_template); - if (template_name != current_name) - emit(usedTitleBlockTemplateChanged(template_name)); + if (template_name != current_name) + emit(usedTitleBlockTemplateChanged(template_name)); } /** - @brief Diagram::selectAll - Select all schema objects - \~French Selectionne tous les objets du schema + @brief Diagram::selectAll + Select all schema objects + \~French Selectionne tous les objets du schema */ void Diagram::selectAll() { - if (items().isEmpty()) return; + if (items().isEmpty()) return; - blockSignals(true); - foreach(QGraphicsItem *qgi, items()) qgi -> setSelected(true); - blockSignals(false); - emit(selectionChanged()); + blockSignals(true); + foreach(QGraphicsItem *qgi, items()) qgi -> setSelected(true); + blockSignals(false); + emit(selectionChanged()); } /** - @brief Diagram::deselectAll - Deselects all selected objects - \~French Deslectionne tous les objets selectionnes + @brief Diagram::deselectAll + Deselects all selected objects + \~French Deslectionne tous les objets selectionnes */ void Diagram::deselectAll() { - if (items().isEmpty()) return; + if (items().isEmpty()) return; - clearSelection(); + clearSelection(); } /** - @brief Diagram::invertSelection - Reverses the selection state of all schema objects - Inverse l'etat de selection de tous les objets du schema + @brief Diagram::invertSelection + Reverses the selection state of all schema objects + Inverse l'etat de selection de tous les objets du schema */ void Diagram::invertSelection() { - if (items().isEmpty()) return; + if (items().isEmpty()) return; - blockSignals(true); - foreach (QGraphicsItem *item, - items()) item -> setSelected(!item -> isSelected()); - blockSignals(false); - emit(selectionChanged()); + blockSignals(true); + foreach (QGraphicsItem *item, + items()) item -> setSelected(!item -> isSelected()); + blockSignals(false); + emit(selectionChanged()); } /** - @brief Diagram::updateLabels - Update elements and conductors that reference folio field - in their labels. + @brief Diagram::updateLabels + Update elements and conductors that reference folio field + in their labels. */ void Diagram::updateLabels() { - for (Conductor *cnd : content().conductors()) - { - cnd->refreshText(); - } + for (Conductor *cnd : content().conductors()) + { + cnd->refreshText(); + } } /** - @brief Diagram::insertFolioSeqHash - This class inserts a stringlist containing all - sequential variables related to an autonum in a QHash - @param hash : to be accessed - @param title : autonum title - @param type : to be treated - @param nc : Context to be manipulated + @brief Diagram::insertFolioSeqHash + This class inserts a stringlist containing all + sequential variables related to an autonum in a QHash + @param hash : to be accessed + @param title : autonum title + @param type : to be treated + @param nc : Context to be manipulated */ void Diagram::insertFolioSeqHash(QHash *hash, - const QString& title, - const QString& type, - NumerotationContext *nc) { - QStringList max; - for (int i = 0; i < nc->size(); i++) { - if (nc->itemAt(i).at(0) == type) { - nc->replaceValue(i, - QString::number( - nc->itemAt(i).at(3).toInt())); - max.append(QString::number(nc->itemAt(i).at(3).toInt() - - nc->itemAt(i).at(2).toInt())); - } - } - hash->insert(title,max); + QStringList> *hash, + const QString& title, + const QString& type, + NumerotationContext *nc) { + QStringList max; + for (int i = 0; i < nc->size(); i++) { + if (nc->itemAt(i).at(0) == type) { + nc->replaceValue(i, + QString::number( + nc->itemAt(i).at(3).toInt())); + max.append(QString::number(nc->itemAt(i).at(3).toInt() + - nc->itemAt(i).at(2).toInt())); + } + } + hash->insert(title,max); } /** - @brief Diagram::loadFolioSeqHash - This class loads all folio sequential variables - related to the current autonum - @param hash : to be accessed - @param title : autonum title - @param type : to be treated - @param nc : Context to be manipulated + @brief Diagram::loadFolioSeqHash + This class loads all folio sequential variables + related to the current autonum + @param hash : to be accessed + @param title : autonum title + @param type : to be treated + @param nc : Context to be manipulated */ void Diagram::loadFolioSeqHash(QHash *hash, - const QString& title, - const QString& type, - NumerotationContext *nc) { - int j = 0; - for (int i = 0; i < nc->size(); i++) { - if (nc->itemAt(i).at(0) == type) { - QString new_value; - new_value = - QString::number( - hash->value(title).at(j).toInt() - + nc->itemAt(i).at(2).toInt()); - nc->replaceValue(i,new_value); - j++; - } - } + QStringList> *hash, + const QString& title, + const QString& type, + NumerotationContext *nc) { + int j = 0; + for (int i = 0; i < nc->size(); i++) { + if (nc->itemAt(i).at(0) == type) { + QString new_value; + new_value = + QString::number( + hash->value(title).at(j).toInt() + + nc->itemAt(i).at(2).toInt()); + nc->replaceValue(i,new_value); + j++; + } + } } /** - @brief Diagram::changeZValue - Change the Z value of the current selected item, according to option - @param option + @brief Diagram::changeZValue + Change the Z value of the current selected item, according to option + @param option */ void Diagram::changeZValue(QET::DepthOption option) { - DiagramContent dc(this); - QUndoCommand *undo = new QUndoCommand(tr("Modifier la profondeur")); - QList l = dc.items(DiagramContent::SelectedOnly | \ - DiagramContent::Elements | \ - DiagramContent::Shapes | \ - DiagramContent::Images); - QList list; - for(QGraphicsItem *item : l) - list << item->toGraphicsObject(); + DiagramContent dc(this); + QUndoCommand *undo = new QUndoCommand(tr("Modifier la profondeur")); + QList l = dc.items(DiagramContent::SelectedOnly | \ + DiagramContent::Elements | \ + DiagramContent::Shapes | \ + DiagramContent::Images); + QList list; + for(QGraphicsItem *item : l) + list << item->toGraphicsObject(); - qreal maxz=0, - minz=0; - for(QGraphicsItem *item : this->items()) - { - qreal z = item->zValue(); - if(z >= Terminal::Z-2) - continue; - maxz = std::max(maxz,z); - minz = std::min(minz,z); - } + qreal maxz=0, + minz=0; + for(QGraphicsItem *item : this->items()) + { + qreal z = item->zValue(); + if(z >= Terminal::Z-2) + continue; + maxz = std::max(maxz,z); + minz = std::min(minz,z); + } - if(option == QET::Raise) - { - for(QGraphicsObject *qgo : list) - if(qgo->zValue() < (Terminal::Z-2)) //Ensure item is always below terminal - new QPropertyUndoCommand(qgo, - "z", - qgo->zValue(), - qgo->zValue()+1, - undo); - } - else if(option == QET::Lower) - { - for(QGraphicsObject *qgo : list) - if(qgo->zValue() < (Terminal::Z-2)) //Ensure item is always below terminal - new QPropertyUndoCommand(qgo, - "z", - qgo->zValue(), - qgo->zValue()-1, - undo); - } - else if (option == QET::BringForward) - { - for(QGraphicsObject *qgo : list) - new QPropertyUndoCommand(qgo, - "z", - qgo->zValue(), - maxz+1, - undo); - } - else if(option == QET::SendBackward) - { - for(QGraphicsObject *qgo : list) - new QPropertyUndoCommand(qgo, - "z", - qgo->zValue(), - minz-1, - undo); - } + if(option == QET::Raise) + { + for(QGraphicsObject *qgo : list) + if(qgo->zValue() < (Terminal::Z-2)) //Ensure item is always below terminal + new QPropertyUndoCommand(qgo, + "z", + qgo->zValue(), + qgo->zValue()+1, + undo); + } + else if(option == QET::Lower) + { + for(QGraphicsObject *qgo : list) + if(qgo->zValue() < (Terminal::Z-2)) //Ensure item is always below terminal + new QPropertyUndoCommand(qgo, + "z", + qgo->zValue(), + qgo->zValue()-1, + undo); + } + else if (option == QET::BringForward) + { + for(QGraphicsObject *qgo : list) + new QPropertyUndoCommand(qgo, + "z", + qgo->zValue(), + maxz+1, + undo); + } + else if(option == QET::SendBackward) + { + for(QGraphicsObject *qgo : list) + new QPropertyUndoCommand(qgo, + "z", + qgo->zValue(), + minz-1, + undo); + } - if(undo->childCount()) - this->undoStack().push(undo); - else - delete undo; + if(undo->childCount()) + this->undoStack().push(undo); + else + delete undo; } /** - @brief Diagram::loadElmtFolioSeq - This class loads all folio sequential variables related - to the current autonum + @brief Diagram::loadElmtFolioSeq + This class loads all folio sequential variables related + to the current autonum */ void Diagram::loadElmtFolioSeq() { - QString title = project()->elementCurrentAutoNum(); - NumerotationContext nc = project()->elementAutoNum(title); + QString title = project()->elementCurrentAutoNum(); + NumerotationContext nc = project()->elementAutoNum(title); - //Unit Folio - if (m_elmt_unitfolio_max.isEmpty() - || !m_elmt_unitfolio_max.contains(title)) { - //Insert Initial Value - if (project()->elementAutoNumCurrentFormula().contains( - "%sequf_")) { - insertFolioSeqHash(&m_elmt_unitfolio_max, - title, - "unitfolio", - &nc); - project()->addElementAutoNum(title,nc); - } - } - else if (m_elmt_unitfolio_max.contains(title)) { - //Load Folio Current Value - if (project()->elementAutoNumCurrentFormula().contains( - "%sequf_")) { - loadFolioSeqHash(&m_elmt_unitfolio_max, - title, - "unitfolio", - &nc); - project()->addElementAutoNum(title,nc); - } - } + //Unit Folio + if (m_elmt_unitfolio_max.isEmpty() + || !m_elmt_unitfolio_max.contains(title)) { + //Insert Initial Value + if (project()->elementAutoNumCurrentFormula().contains( + "%sequf_")) { + insertFolioSeqHash(&m_elmt_unitfolio_max, + title, + "unitfolio", + &nc); + project()->addElementAutoNum(title,nc); + } + } + else if (m_elmt_unitfolio_max.contains(title)) { + //Load Folio Current Value + if (project()->elementAutoNumCurrentFormula().contains( + "%sequf_")) { + loadFolioSeqHash(&m_elmt_unitfolio_max, + title, + "unitfolio", + &nc); + project()->addElementAutoNum(title,nc); + } + } - //Ten Folio - if (m_elmt_tenfolio_max.isEmpty() - || !m_elmt_tenfolio_max.contains(title)) { - //Insert Initial Value - if (project()->elementAutoNumCurrentFormula().contains( - "%seqtf_")) { - insertFolioSeqHash(&m_elmt_tenfolio_max, - title, - "tenfolio", - &nc); - project()->addElementAutoNum(title,nc); - } - } - else if (m_elmt_tenfolio_max.contains(title)) { - //Load Folio Current Value - if (project()->elementAutoNumCurrentFormula().contains( - "%seqtf_")) { - loadFolioSeqHash(&m_elmt_tenfolio_max, - title, - "tenfolio", - &nc); - project()->addElementAutoNum(title,nc); - } - } + //Ten Folio + if (m_elmt_tenfolio_max.isEmpty() + || !m_elmt_tenfolio_max.contains(title)) { + //Insert Initial Value + if (project()->elementAutoNumCurrentFormula().contains( + "%seqtf_")) { + insertFolioSeqHash(&m_elmt_tenfolio_max, + title, + "tenfolio", + &nc); + project()->addElementAutoNum(title,nc); + } + } + else if (m_elmt_tenfolio_max.contains(title)) { + //Load Folio Current Value + if (project()->elementAutoNumCurrentFormula().contains( + "%seqtf_")) { + loadFolioSeqHash(&m_elmt_tenfolio_max, + title, + "tenfolio", + &nc); + project()->addElementAutoNum(title,nc); + } + } - //Hundred Folio - if (m_elmt_hundredfolio_max.isEmpty() - || !m_elmt_hundredfolio_max.contains(title)) { - //Insert Initial Value - if (project()->elementAutoNumCurrentFormula().contains( - "%seqhf_")) { - insertFolioSeqHash(&m_elmt_hundredfolio_max, - title, - "hundredfolio", - &nc); - project()->addElementAutoNum(title,nc); - } - } - else if (m_elmt_hundredfolio_max.contains(title)) { - //Load Folio Current Value - if (project()->elementAutoNumCurrentFormula().contains( - "%seqhf_")) { - loadFolioSeqHash(&m_elmt_hundredfolio_max, - title, - "hundredfolio", - &nc); - project()->addElementAutoNum(title,nc); - } - } + //Hundred Folio + if (m_elmt_hundredfolio_max.isEmpty() + || !m_elmt_hundredfolio_max.contains(title)) { + //Insert Initial Value + if (project()->elementAutoNumCurrentFormula().contains( + "%seqhf_")) { + insertFolioSeqHash(&m_elmt_hundredfolio_max, + title, + "hundredfolio", + &nc); + project()->addElementAutoNum(title,nc); + } + } + else if (m_elmt_hundredfolio_max.contains(title)) { + //Load Folio Current Value + if (project()->elementAutoNumCurrentFormula().contains( + "%seqhf_")) { + loadFolioSeqHash(&m_elmt_hundredfolio_max, + title, + "hundredfolio", + &nc); + project()->addElementAutoNum(title,nc); + } + } } /** - @brief Diagram::loadCndFolioSeq - This class loads all conductor folio sequential variables related - to the current autonum + @brief Diagram::loadCndFolioSeq + This class loads all conductor folio sequential variables related + to the current autonum */ void Diagram::loadCndFolioSeq() { - //Conductor - QString title = project()->conductorCurrentAutoNum(); - NumerotationContext nc = project()->conductorAutoNum(title); - QString formula = autonum::numerotationContextToFormula(nc); + //Conductor + QString title = project()->conductorCurrentAutoNum(); + NumerotationContext nc = project()->conductorAutoNum(title); + QString formula = autonum::numerotationContextToFormula(nc); - //Unit Folio - if (m_cnd_unitfolio_max.isEmpty() - || !m_cnd_unitfolio_max.contains(title)) { - //Insert Initial Value - if (formula.contains("%sequf_")) { - insertFolioSeqHash(&m_cnd_unitfolio_max, - title, - "unitfolio", - &nc); - project()->addConductorAutoNum(title,nc); - } - } - else if (m_cnd_unitfolio_max.contains(title)) { - //Load Folio Current Value - if (formula.contains("%sequf_")) { - loadFolioSeqHash(&m_cnd_unitfolio_max, - title, - "unitfolio", - &nc); - project()->addConductorAutoNum(title,nc); - } - } + //Unit Folio + if (m_cnd_unitfolio_max.isEmpty() + || !m_cnd_unitfolio_max.contains(title)) { + //Insert Initial Value + if (formula.contains("%sequf_")) { + insertFolioSeqHash(&m_cnd_unitfolio_max, + title, + "unitfolio", + &nc); + project()->addConductorAutoNum(title,nc); + } + } + else if (m_cnd_unitfolio_max.contains(title)) { + //Load Folio Current Value + if (formula.contains("%sequf_")) { + loadFolioSeqHash(&m_cnd_unitfolio_max, + title, + "unitfolio", + &nc); + project()->addConductorAutoNum(title,nc); + } + } - //Ten Folio - if (m_cnd_tenfolio_max.isEmpty() - || !m_cnd_tenfolio_max.contains(title)) { - //Insert Initial Value - if (formula.contains("%seqtf_")) { - insertFolioSeqHash(&m_cnd_tenfolio_max, - title, - "tenfolio", - &nc); - project()->addConductorAutoNum(title,nc); - } - } - else if (m_cnd_tenfolio_max.contains(title)) { - //Load Folio Current Value - if (formula.contains("%seqtf_")) { - loadFolioSeqHash(&m_cnd_tenfolio_max, - title, - "tenfolio", - &nc); - project()->addConductorAutoNum(title,nc); - } - } + //Ten Folio + if (m_cnd_tenfolio_max.isEmpty() + || !m_cnd_tenfolio_max.contains(title)) { + //Insert Initial Value + if (formula.contains("%seqtf_")) { + insertFolioSeqHash(&m_cnd_tenfolio_max, + title, + "tenfolio", + &nc); + project()->addConductorAutoNum(title,nc); + } + } + else if (m_cnd_tenfolio_max.contains(title)) { + //Load Folio Current Value + if (formula.contains("%seqtf_")) { + loadFolioSeqHash(&m_cnd_tenfolio_max, + title, + "tenfolio", + &nc); + project()->addConductorAutoNum(title,nc); + } + } - //Hundred Folio - if (m_cnd_hundredfolio_max.isEmpty() - || !m_cnd_hundredfolio_max.contains(title)) { - //Insert Initial Value - if (formula.contains("%seqhf_")) { - insertFolioSeqHash(&m_cnd_hundredfolio_max, - title, - "hundredfolio", - &nc); - project()->addConductorAutoNum(title,nc); - } - } - else if (m_cnd_hundredfolio_max.contains(title)) { - //Load Folio Current Value - if (formula.contains("%seqhf_")) { - loadFolioSeqHash(&m_cnd_hundredfolio_max, - title, - "hundredfolio", - &nc); - project()->addConductorAutoNum(title,nc); - } - } + //Hundred Folio + if (m_cnd_hundredfolio_max.isEmpty() + || !m_cnd_hundredfolio_max.contains(title)) { + //Insert Initial Value + if (formula.contains("%seqhf_")) { + insertFolioSeqHash(&m_cnd_hundredfolio_max, + title, + "hundredfolio", + &nc); + project()->addConductorAutoNum(title,nc); + } + } + else if (m_cnd_hundredfolio_max.contains(title)) { + //Load Folio Current Value + if (formula.contains("%seqhf_")) { + loadFolioSeqHash(&m_cnd_hundredfolio_max, + title, + "hundredfolio", + &nc); + project()->addConductorAutoNum(title,nc); + } + } } /** - @brief Diagram::title - @return title of the titleblock - \~Frenchle titre du cartouche + @brief Diagram::title + @return title of the titleblock + \~Frenchle titre du cartouche */ QString Diagram::title() const { - return(border_and_titleblock.title()); + return(border_and_titleblock.title()); } /** - @brief Diagram::elements - @return the list containing all elements + @brief Diagram::elements + @return the list containing all elements */ QList Diagram::elements() const { - QList element_list; - foreach (QGraphicsItem *qgi, items()) { - if (Element *elmt = qgraphicsitem_cast(qgi)) - element_list < element_list; + foreach (QGraphicsItem *qgi, items()) { + if (Element *elmt = qgraphicsitem_cast(qgi)) + element_list < Diagram::conductors() const { - QList cnd_list; - foreach (QGraphicsItem *qgi, items()) { - if (Conductor *cnd = qgraphicsitem_cast(qgi)) - cnd_list < cnd_list; + foreach (QGraphicsItem *qgi, items()) { + if (Conductor *cnd = qgraphicsitem_cast(qgi)) + cnd_list < location() == location) { - return(true); - } - } - return(false); + for(Element *element : elements()) { + if (element -> location() == location) { + return(true); + } + } + return(false); } /** - @brief Diagram::usesTitleBlockTemplate - @param name : a title block template name - @return true if the provided template is used by this diagram, false - otherwise. + @brief Diagram::usesTitleBlockTemplate + @param name : a title block template name + @return true if the provided template is used by this diagram, false + otherwise. */ bool Diagram::usesTitleBlockTemplate(const QString &name) { - return(name == border_and_titleblock.titleBlockTemplateName()); + return(name == border_and_titleblock.titleBlockTemplateName()); } /** - @brief Diagram::freezeElements - Freeze every existent element label. + @brief Diagram::freezeElements + Freeze every existent element label. */ void Diagram::freezeElements(bool freeze) { - foreach (Element *elmt, elements()) { - elmt->freezeLabel(freeze); - } + foreach (Element *elmt, elements()) { + elmt->freezeLabel(freeze); + } } /** - @brief Diagram::unfreezeElements - Unfreeze every existent element label. + @brief Diagram::unfreezeElements + Unfreeze every existent element label. */ void Diagram::unfreezeElements() { - foreach (Element *elmt, elements()) { - elmt->freezeLabel(false); - } + foreach (Element *elmt, elements()) { + elmt->freezeLabel(false); + } } /** - @brief Diagram::freezeNewElements - Set new element label to be frozen. + @brief Diagram::freezeNewElements + Set new element label to be frozen. */ void Diagram::setFreezeNewElements(bool b) { - m_freeze_new_elements = b; + m_freeze_new_elements = b; } /** - @brief Diagram::freezeNewElements - @return current freeze new element status . + @brief Diagram::freezeNewElements + @return current freeze new element status . */ bool Diagram::freezeNewElements() { - return m_freeze_new_elements; + return m_freeze_new_elements; } /** - @brief Diagram::freezeConductors - Freeze every existent conductor label. + @brief Diagram::freezeConductors + Freeze every existent conductor label. */ void Diagram::freezeConductors(bool freeze) { - foreach (Conductor *cnd, conductors()) { - cnd->setFreezeLabel(freeze); - } + foreach (Conductor *cnd, conductors()) { + cnd->setFreezeLabel(freeze); + } } /** - @brief Diagram::setfreezeNewConductors - Set new conductor label to be frozen. + @brief Diagram::setfreezeNewConductors + Set new conductor label to be frozen. */ void Diagram::setFreezeNewConductors(bool b) { - m_freeze_new_conductors_ = b; + m_freeze_new_conductors_ = b; } /** - @brief Diagram::freezeNewConductors - @return current freeze new conductor status . + @brief Diagram::freezeNewConductors + @return current freeze new conductor status . */ bool Diagram::freezeNewConductors() { - return m_freeze_new_conductors_; + return m_freeze_new_conductors_; } /** - @brief Diagram::adjustSceneRect - Recalcul and adjust the size of the scene + @brief Diagram::adjustSceneRect + Recalcul and adjust the size of the scene */ void Diagram::adjustSceneRect() { - QRectF old_rect = sceneRect(); - setSceneRect(border_and_titleblock.borderAndTitleBlockRect().united( - itemsBoundingRect())); - update(old_rect.united(sceneRect())); + QRectF old_rect = sceneRect(); + setSceneRect(border_and_titleblock.borderAndTitleBlockRect().united( + itemsBoundingRect())); + update(old_rect.united(sceneRect())); } /** - @brief Diagram::applyProperties - This method allows you to apply new rendering options while - accessing the current rendering properties. - \~French Cette methode permet d'appliquer de nouvelles options de rendu - tout en accedant aux proprietes de rendu en cours. - \~ @param new_properties : - New rendering options to apply - \~French Nouvelles options de rendu a appliquer - \~ @return rendering options before applying new_properties - \~French les options de rendu avant l'application de new_properties + @brief Diagram::applyProperties + This method allows you to apply new rendering options while + accessing the current rendering properties. + \~French Cette methode permet d'appliquer de nouvelles options de rendu + tout en accedant aux proprietes de rendu en cours. + \~ @param new_properties : + New rendering options to apply + \~French Nouvelles options de rendu a appliquer + \~ @return rendering options before applying new_properties + \~French les options de rendu avant l'application de new_properties */ ExportProperties Diagram::applyProperties( - const ExportProperties &new_properties) { - // exports current rendering options - // exporte les options de rendu en cours - ExportProperties old_properties; - old_properties.draw_grid = displayGrid(); - old_properties.draw_border = border_and_titleblock.borderIsDisplayed(); - old_properties.draw_titleblock = border_and_titleblock.titleBlockIsDisplayed(); - old_properties.draw_terminals = drawTerminals(); - old_properties.draw_colored_conductors = drawColoredConductors(); - old_properties.exported_area = useBorder() ? QET::BorderArea - : QET::ElementsArea; + const ExportProperties &new_properties) { + // exports current rendering options + // exporte les options de rendu en cours + ExportProperties old_properties; + old_properties.draw_grid = displayGrid(); + old_properties.draw_border = border_and_titleblock.borderIsDisplayed(); + old_properties.draw_titleblock = border_and_titleblock.titleBlockIsDisplayed(); + old_properties.draw_terminals = drawTerminals(); + old_properties.draw_colored_conductors = drawColoredConductors(); + old_properties.exported_area = useBorder() ? QET::BorderArea + : QET::ElementsArea; - // apply the new rendering options - // applique les nouvelles options de rendu - setUseBorder (new_properties.exported_area == QET::BorderArea); - setDrawTerminals (new_properties.draw_terminals); - setDrawColoredConductors (new_properties.draw_colored_conductors); - setDisplayGrid (new_properties.draw_grid); - border_and_titleblock.displayBorder(new_properties.draw_border); - border_and_titleblock.displayTitleBlock (new_properties.draw_titleblock); + // apply the new rendering options + // applique les nouvelles options de rendu + setUseBorder (new_properties.exported_area == QET::BorderArea); + setDrawTerminals (new_properties.draw_terminals); + setDrawColoredConductors (new_properties.draw_colored_conductors); + setDisplayGrid (new_properties.draw_grid); + border_and_titleblock.displayBorder(new_properties.draw_border); + border_and_titleblock.displayTitleBlock (new_properties.draw_titleblock); - // return old rendering options - // retourne les anciennes options de rendu - return(old_properties); + // return old rendering options + // retourne les anciennes options de rendu + return(old_properties); } /** - @brief Diagram::convertPosition - @param pos : - Cartesian position (ex: 10.3, 45.2) to transform into position - in the grid (ex: B2) - \~French Position cartesienne (ex : 10.3, 45.2) a transformer en position - dans la grille (ex : B2) - \~ @return a position in the grid corresponding to pos - \~French la position dans la grille correspondant a pos + @brief Diagram::convertPosition + @param pos : + Cartesian position (ex: 10.3, 45.2) to transform into position + in the grid (ex: B2) + \~French Position cartesienne (ex : 10.3, 45.2) a transformer en position + dans la grille (ex : B2) + \~ @return a position in the grid corresponding to pos + \~French la position dans la grille correspondant a pos */ DiagramPosition Diagram::convertPosition(const QPointF &pos) { - // delegue le calcul au BorderTitleBlock - DiagramPosition diagram_position = - border_and_titleblock.convertPosition(pos); + // delegue le calcul au BorderTitleBlock + DiagramPosition diagram_position = + border_and_titleblock.convertPosition(pos); - // embarque la position cartesienne - diagram_position.setPosition(pos); + // embarque la position cartesienne + diagram_position.setPosition(pos); - return(diagram_position); + return(diagram_position); } /** - @brief Diagram::snapToGrid - Return a nearest snap point of p - @param p point to find the nearest snaped point - @return + @brief Diagram::snapToGrid + Return a nearest snap point of p + @param p point to find the nearest snaped point + @return */ QPointF Diagram::snapToGrid(const QPointF &p) { - QSettings settings; - int xGrid = settings.value("diagrameditor/Xgrid", - Diagram::xGrid).toInt(); - int yGrid = settings.value("diagrameditor/Ygrid", - Diagram::yGrid).toInt(); + QSettings settings; + int xGrid = settings.value("diagrameditor/Xgrid", + Diagram::xGrid).toInt(); + int yGrid = settings.value("diagrameditor/Ygrid", + Diagram::yGrid).toInt(); - //Return a point rounded to the nearest pixel - if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - { - int p_x = qRound(p.x()); - int p_y = qRound(p.y()); - return (QPointF(p_x, p_y)); - } + //Return a point rounded to the nearest pixel + if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + { + int p_x = qRound(p.x()); + int p_y = qRound(p.y()); + return (QPointF(p_x, p_y)); + } - //Return a point snapped to the grid - int p_x = qRound(p.x() / xGrid) * xGrid; - int p_y = qRound(p.y() / yGrid) * yGrid; - return (QPointF(p_x, p_y)); + //Return a point snapped to the grid + int p_x = qRound(p.x() / xGrid) * xGrid; + int p_y = qRound(p.y() / yGrid) * yGrid; + return (QPointF(p_x, p_y)); } /** - @brief Diagram::setDrawTerminals - Defines whether or not to display the terminals - \~French Definit s'il faut afficher ou non les bornes - \~ @param dt : true to display the bounds, false otherwise - \~French true pour afficher les bornes, false sinon + @brief Diagram::setDrawTerminals + Defines whether or not to display the terminals + \~French Definit s'il faut afficher ou non les bornes + \~ @param dt : true to display the bounds, false otherwise + \~French true pour afficher les bornes, false sinon */ void Diagram::setDrawTerminals(bool dt) { - foreach(QGraphicsItem *qgi, items()) { - if (Terminal *t = qgraphicsitem_cast(qgi)) { - t -> setVisible(dt); - } - } + foreach(QGraphicsItem *qgi, items()) { + if (Terminal *t = qgraphicsitem_cast(qgi)) { + t -> setVisible(dt); + } + } } /** - @brief Diagram::setDrawColoredConductors - Defines whether or not to respect the colors of the conductors. - If not, the conductors are all drawn in black. - \~French Definit s'il faut respecter ou non les couleurs des conducteurs. - Si non, les conducteurs sont tous dessines en noir. - \~ @param dcc true to respect the colors, false otherwise - \~French dcc true pour respecter les couleurs, false sinon + @brief Diagram::setDrawColoredConductors + Defines whether or not to respect the colors of the conductors. + If not, the conductors are all drawn in black. + \~French Definit s'il faut respecter ou non les couleurs des conducteurs. + Si non, les conducteurs sont tous dessines en noir. + \~ @param dcc true to respect the colors, false otherwise + \~French dcc true pour respecter les couleurs, false sinon */ void Diagram::setDrawColoredConductors(bool dcc) { - draw_colored_conductors_ = dcc; + draw_colored_conductors_ = dcc; } /** - @brief Diagram::selectedConductors - @return the list of conductors selected on the diagram - \~French la liste des conducteurs selectionnes sur le schema + @brief Diagram::selectedConductors + @return the list of conductors selected on the diagram + \~French la liste des conducteurs selectionnes sur le schema */ QSet Diagram::selectedConductors() const { - QSet conductors_set; - foreach(QGraphicsItem *qgi, selectedItems()) { - if (Conductor *c = qgraphicsitem_cast(qgi)) { - conductors_set << c; - } - } - return(conductors_set); + QSet conductors_set; + foreach(QGraphicsItem *qgi, selectedItems()) { + if (Conductor *c = qgraphicsitem_cast(qgi)) { + conductors_set << c; + } + } + return(conductors_set); } /** - @brief Diagram::clipboardMayContainDiagram - @return true if the clipboard appears to contain a schema - \~French true si le presse-papier semble contenir un schema + @brief Diagram::clipboardMayContainDiagram + @return true if the clipboard appears to contain a schema + \~French true si le presse-papier semble contenir un schema */ bool Diagram::clipboardMayContainDiagram() { - QString clipboard_text = QApplication::clipboard() -> text().trimmed(); - bool may_be_diagram = clipboard_text.startsWith(""); - return(may_be_diagram); + QString clipboard_text = QApplication::clipboard() -> text().trimmed(); + bool may_be_diagram = clipboard_text.startsWith(""); + return(may_be_diagram); } /** - @brief Diagram::project - @return the project to which this schema belongs - or 0 if it is an independent schema. - \~French le projet auquel ce schema appartient - ou 0 s'il s'agit d'un schema independant. + @brief Diagram::project + @return the project to which this schema belongs + or 0 if it is an independent schema. + \~French le projet auquel ce schema appartient + ou 0 s'il s'agit d'un schema independant. */ QETProject *Diagram::project() const { - return(m_project); + return(m_project); } /** - @brief Diagram::folioIndex - @return the folio number of this diagram within its parent project, - or -1 if it is has no parent project + @brief Diagram::folioIndex + @return the folio number of this diagram within its parent project, + or -1 if it is has no parent project */ int Diagram::folioIndex() const { - if (!m_project) return(-1); - return(m_project -> folioIndex(this)); + if (!m_project) return(-1); + return(m_project -> folioIndex(this)); } /** - @brief Diagram::isReadOnly - @return true if this diagram is read only. - This method is same has call Diagram::project() -> isReadOnly() + @brief Diagram::isReadOnly + @return true if this diagram is read only. + This method is same has call Diagram::project() -> isReadOnly() */ bool Diagram::isReadOnly() const { - return m_project -> isReadOnly(); + return m_project -> isReadOnly(); } /** - @brief Diagram::content - @return The content of the diagram. - The conductors are all seated in conductorsToMove. - \~French Le contenu du schema. Les conducteurs sont tous places dans - conductorsToMove. + @brief Diagram::content + @return The content of the diagram. + The conductors are all seated in conductorsToMove. + \~French Le contenu du schema. Les conducteurs sont tous places dans + conductorsToMove. */ DiagramContent Diagram::content() const { - DiagramContent dc; - foreach(QGraphicsItem *qgi, items()) { - if (Element *e = qgraphicsitem_cast(qgi)) { - dc.m_elements << e; - } else if (IndependentTextItem *iti = - qgraphicsitem_cast(qgi)) { - dc.m_text_fields << iti; - } else if (Conductor *c = - qgraphicsitem_cast(qgi)) { - dc.m_conductors_to_move << c; - } - } - return(dc); + DiagramContent dc; + foreach(QGraphicsItem *qgi, items()) { + if (Element *e = qgraphicsitem_cast(qgi)) { + dc.m_elements << e; + } else if (IndependentTextItem *iti = + qgraphicsitem_cast(qgi)) { + dc.m_text_fields << iti; + } else if (Conductor *c = + qgraphicsitem_cast(qgi)) { + dc.m_conductors_to_move << c; + } + } + return(dc); } /** - @brief Diagram::canRotateSelection - @return True if a least one of selected items can be rotated + @brief Diagram::canRotateSelection + @return True if a least one of selected items can be rotated */ bool Diagram::canRotateSelection() const { - for (QGraphicsItem *qgi : selectedItems()) - { - if (qgi->type() == IndependentTextItem::Type || - qgi->type() == ConductorTextItem::Type || - qgi->type() == DiagramImageItem::Type || - qgi->type() == Element::Type || - qgi->type() == DynamicElementTextItem::Type) - return true; + for (QGraphicsItem *qgi : selectedItems()) + { + if (qgi->type() == IndependentTextItem::Type || + qgi->type() == ConductorTextItem::Type || + qgi->type() == DiagramImageItem::Type || + qgi->type() == Element::Type || + qgi->type() == DynamicElementTextItem::Type) + return true; - if(qgi->type() == QGraphicsItemGroup::Type) - if(dynamic_cast(qgi)) - return true; - } + if(qgi->type() == QGraphicsItemGroup::Type) + if(dynamic_cast(qgi)) + return true; + } - return false; + return false; } diff --git a/sources/diagram.h b/sources/diagram.h index f0df1ff60..553335b8b 100644 --- a/sources/diagram.h +++ b/sources/diagram.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef DIAGRAM_H #define DIAGRAM_H @@ -47,377 +47,377 @@ class DiagramFolioList; class QETProject; /** - @brief The Diagram class - This class represents an electric diagram. - It manages its various child elements, - conductors and texts and handles their graphic rendering. + @brief The Diagram class + This class represents an electric diagram. + It manages its various child elements, + conductors and texts and handles their graphic rendering. */ class Diagram : public QGraphicsScene { - friend DiagramFolioList; - friend QETProject; + friend DiagramFolioList; + friend QETProject; - Q_OBJECT - - // constructors, destructor - private: - Diagram(QETProject *project); - ~Diagram() override; - Diagram(const Diagram &diagram); - - // ATTRIBUTES - public: - /** - @brief The BorderOptions enum - Represents available options when rendering a particular diagram: - EmptyBorder: display border only - TitleBlock: display title block - Columns: display columns - */ - enum BorderOptions { EmptyBorder, TitleBlock, Columns }; - /// Represents available option of Numerotation type. - enum NumerotationType { Conductors }; - /// Default properties for new conductors - ConductorProperties defaultConductorProperties; - /// Diagram dimensions and title block - BorderTitleBlock border_and_titleblock; - /// abscissa grid step size - static int xGrid; - /// ordinate grid step size - static int yGrid; - /// Key grid x step size - static int xKeyGrid; - /// Key grid y step size - static int yKeyGrid; - /// Key grid fine x step size - static int xKeyGridFine; - /// Key grid fine y step size - static int yKeyGridFine; - /// margin around the diagram - static const qreal margin; - /// background color of diagram - static QColor background_color; - /// Hash containing max values for folio sequential autonums in this diagram - QHash m_elmt_unitfolio_max; - QHash m_elmt_tenfolio_max; - QHash m_elmt_hundredfolio_max; - /// Hash containing max values for folio sequential autonums in this diagram - QHash m_cnd_unitfolio_max; - QHash m_cnd_tenfolio_max; - QHash m_cnd_hundredfolio_max; + Q_OBJECT + + // constructors, destructor + private: + Diagram(QETProject *project); + ~Diagram() override; + Diagram(const Diagram &diagram); + + // ATTRIBUTES + public: + /** + @brief The BorderOptions enum + Represents available options when rendering a particular diagram: + EmptyBorder: display border only + TitleBlock: display title block + Columns: display columns + */ + enum BorderOptions { EmptyBorder, TitleBlock, Columns }; + /// Represents available option of Numerotation type. + enum NumerotationType { Conductors }; + /// Default properties for new conductors + ConductorProperties defaultConductorProperties; + /// Diagram dimensions and title block + BorderTitleBlock border_and_titleblock; + /// abscissa grid step size + static int xGrid; + /// ordinate grid step size + static int yGrid; + /// Key grid x step size + static int xKeyGrid; + /// Key grid y step size + static int yKeyGrid; + /// Key grid fine x step size + static int xKeyGridFine; + /// Key grid fine y step size + static int yKeyGridFine; + /// margin around the diagram + static const qreal margin; + /// background color of diagram + static QColor background_color; + /// Hash containing max values for folio sequential autonums in this diagram + QHash m_elmt_unitfolio_max; + QHash m_elmt_tenfolio_max; + QHash m_elmt_hundredfolio_max; + /// Hash containing max values for folio sequential autonums in this diagram + QHash m_cnd_unitfolio_max; + QHash m_cnd_tenfolio_max; + QHash m_cnd_hundredfolio_max; - private: - QGraphicsLineItem *conductor_setter_; - ElementsMover m_elements_mover; - ElementTextsMover m_element_texts_mover; - QGIManager *qgi_manager_; - QETProject *m_project; + private: + QGraphicsLineItem *conductor_setter_; + ElementsMover m_elements_mover; + ElementTextsMover m_element_texts_mover; + QGIManager *qgi_manager_; + QETProject *m_project; - QDomDocument xml_document_; + QDomDocument xml_document_; - qreal diagram_qet_version_; + qreal diagram_qet_version_; - bool draw_grid_; - bool use_border_; - bool draw_terminals_; - bool draw_colored_conductors_; + bool draw_grid_; + bool use_border_; + bool draw_terminals_; + bool draw_colored_conductors_; - QString m_conductors_autonum_name; - DiagramEventInterface *m_event_interface; + QString m_conductors_autonum_name; + DiagramEventInterface *m_event_interface; - bool m_freeze_new_elements; - bool m_freeze_new_conductors_; - QUuid m_uuid = QUuid::createUuid(); - - // METHODS - protected: - void drawBackground(QPainter *, const QRectF &) override; + bool m_freeze_new_elements; + bool m_freeze_new_conductors_; + QUuid m_uuid = QUuid::createUuid(); + + // METHODS + protected: + void drawBackground(QPainter *, const QRectF &) override; - void mouseDoubleClickEvent ( - QGraphicsSceneMouseEvent *event) override; - void mousePressEvent (QGraphicsSceneMouseEvent *event) override; - void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent ( - QGraphicsSceneMouseEvent *event) override; - void wheelEvent (QGraphicsSceneWheelEvent *event) override; - void keyPressEvent (QKeyEvent *event) override; - void keyReleaseEvent (QKeyEvent *) override; - - public: - QUuid uuid(); - void setEventInterface (DiagramEventInterface *event_interface); - void clearEventInterface(); + void mouseDoubleClickEvent ( + QGraphicsSceneMouseEvent *event) override; + void mousePressEvent (QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent ( + QGraphicsSceneMouseEvent *event) override; + void wheelEvent (QGraphicsSceneWheelEvent *event) override; + void keyPressEvent (QKeyEvent *event) override; + void keyReleaseEvent (QKeyEvent *) override; + + public: + QUuid uuid(); + void setEventInterface (DiagramEventInterface *event_interface); + void clearEventInterface(); - //methods related to autonum - QString conductorsAutonumName() const; - void setConductorsAutonumName(const QString &name); + //methods related to autonum + QString conductorsAutonumName() const; + void setConductorsAutonumName(const QString &name); - static bool clipboardMayContainDiagram(); - - // methods related to parent project - QETProject *project() const; - int folioIndex() const; - void showMe() {emit showDiagram(this);} - bool isReadOnly() const; - - // methods related to conductor creation - void setConductor(bool); - void setConductorStart (QPointF); - void setConductorStop(QPointF); - QList < QSet > potentials(); - - // methods related to XML import/export - QDomDocument toXml(bool = true); - bool initFromXml(QDomElement &, - QPointF = QPointF(), - bool = true, - DiagramContent * = nullptr); - bool fromXml(QDomDocument &, - QPointF = QPointF(), - bool = true, - DiagramContent * = nullptr); - bool fromXml(QDomElement &, - QPointF = QPointF(), - bool = true, - DiagramContent * = nullptr); - void folioSequentialsToXml(QHash*, - QDomElement *, - const QString&, - const QString&, - QDomDocument *); - void folioSequentialsFromXml(const QDomElement&, - QHash*, - const QString&, - const QString&, - const QString&, - const QString&); - - void refreshContents(); - - // methods related to graphics items addition/removal on the diagram - virtual void addItem (QGraphicsItem *item); - virtual void removeItem (QGraphicsItem *item); - - // methods related to graphics options - ExportProperties applyProperties(const ExportProperties &); - void setDisplayGrid(bool); - bool displayGrid(); - void setUseBorder(bool); - bool useBorder(); - void setBorderOptions(BorderOptions); - BorderOptions borderOptions(); - DiagramPosition convertPosition(const QPointF &); - static QPointF snapToGrid(const QPointF &p); - - bool drawTerminals() const; - void setDrawTerminals(bool); - bool drawColoredConductors() const; - void setDrawColoredConductors(bool); - - QString title() const; - bool toPaintDevice(QPaintDevice &, int = -1, int = -1, - Qt::AspectRatioMode = Qt::KeepAspectRatio); - QSize imageSize() const; - - bool isEmpty() const; - - QList elements() const; - QList conductors() const; - QSet selectedConductors() const; - DiagramContent content() const; - bool canRotateSelection() const; - ElementsMover &elementsMover(); - ElementTextsMover &elementTextsMover(); - bool usesElement(const ElementsLocation &); - bool usesTitleBlockTemplate(const QString &); - - QUndoStack &undoStack(); - QGIManager &qgiManager(); - - //methods related to element label Update Policy - void freezeElements(bool freeze); - void unfreezeElements(); - void setFreezeNewElements(bool); - bool freezeNewElements(); - - //methods related to conductor label Update Policy - void freezeConductors(bool freeze); - void setFreezeNewConductors(bool); - bool freezeNewConductors(); - - //methods related to insertion and loading of folio sequential - void insertFolioSeqHash (QHash *hash, - const QString& title, - const QString& seq, - NumerotationContext *nc); - void loadFolioSeqHash (QHash *hash, - const QString& title, const QString& seq, - NumerotationContext *nc); - void changeZValue(QET::DepthOption option); + static bool clipboardMayContainDiagram(); + + // methods related to parent project + QETProject *project() const; + int folioIndex() const; + void showMe() {emit showDiagram(this);} + bool isReadOnly() const; + + // methods related to conductor creation + void setConductor(bool); + void setConductorStart (QPointF); + void setConductorStop(QPointF); + QList < QSet > potentials(); + + // methods related to XML import/export + QDomDocument toXml(bool = true); + bool initFromXml(QDomElement &, + QPointF = QPointF(), + bool = true, + DiagramContent * = nullptr); + bool fromXml(QDomDocument &, + QPointF = QPointF(), + bool = true, + DiagramContent * = nullptr); + bool fromXml(QDomElement &, + QPointF = QPointF(), + bool = true, + DiagramContent * = nullptr); + void folioSequentialsToXml(QHash*, + QDomElement *, + const QString&, + const QString&, + QDomDocument *); + void folioSequentialsFromXml(const QDomElement&, + QHash*, + const QString&, + const QString&, + const QString&, + const QString&); + + void refreshContents(); + + // methods related to graphics items addition/removal on the diagram + virtual void addItem (QGraphicsItem *item); + virtual void removeItem (QGraphicsItem *item); + + // methods related to graphics options + ExportProperties applyProperties(const ExportProperties &); + void setDisplayGrid(bool); + bool displayGrid(); + void setUseBorder(bool); + bool useBorder(); + void setBorderOptions(BorderOptions); + BorderOptions borderOptions(); + DiagramPosition convertPosition(const QPointF &); + static QPointF snapToGrid(const QPointF &p); + + bool drawTerminals() const; + void setDrawTerminals(bool); + bool drawColoredConductors() const; + void setDrawColoredConductors(bool); + + QString title() const; + bool toPaintDevice(QPaintDevice &, int = -1, int = -1, + Qt::AspectRatioMode = Qt::KeepAspectRatio); + QSize imageSize() const; + + bool isEmpty() const; + + QList elements() const; + QList conductors() const; + QSet selectedConductors() const; + DiagramContent content() const; + bool canRotateSelection() const; + ElementsMover &elementsMover(); + ElementTextsMover &elementTextsMover(); + bool usesElement(const ElementsLocation &); + bool usesTitleBlockTemplate(const QString &); + + QUndoStack &undoStack(); + QGIManager &qgiManager(); + + //methods related to element label Update Policy + void freezeElements(bool freeze); + void unfreezeElements(); + void setFreezeNewElements(bool); + bool freezeNewElements(); + + //methods related to conductor label Update Policy + void freezeConductors(bool freeze); + void setFreezeNewConductors(bool); + bool freezeNewConductors(); + + //methods related to insertion and loading of folio sequential + void insertFolioSeqHash (QHash *hash, + const QString& title, + const QString& seq, + NumerotationContext *nc); + void loadFolioSeqHash (QHash *hash, + const QString& title, const QString& seq, + NumerotationContext *nc); + void changeZValue(QET::DepthOption option); - public slots: - void adjustSceneRect (); - void titleChanged(const QString &); - void titleBlockTemplateChanged(const QString &); - void titleBlockTemplateRemoved(const QString &, - const QString & = QString()); - void setTitleBlockTemplate(const QString &); - void updateLabels(); - void loadElmtFolioSeq(); - void loadCndFolioSeq(); - - // methods related to graphics items selection - void selectAll(); - void deselectAll(); - void invertSelection(); + public slots: + void adjustSceneRect (); + void titleChanged(const QString &); + void titleBlockTemplateChanged(const QString &); + void titleBlockTemplateRemoved(const QString &, + const QString & = QString()); + void setTitleBlockTemplate(const QString &); + void updateLabels(); + void loadElmtFolioSeq(); + void loadCndFolioSeq(); + + // methods related to graphics items selection + void selectAll(); + void deselectAll(); + void invertSelection(); - signals: - void showDiagram (Diagram *); - void usedTitleBlockTemplateChanged(const QString &); - void diagramTitleChanged(Diagram *, const QString &); + signals: + void showDiagram (Diagram *); + void usedTitleBlockTemplateChanged(const QString &); + void diagramTitleChanged(Diagram *, const QString &); - /// Signal emitted when users wish to locate an element - /// from the diagram within elements collection - void findElementRequired(const ElementsLocation &); + /// Signal emitted when users wish to locate an element + /// from the diagram within elements collection + void findElementRequired(const ElementsLocation &); - void diagramActivated(); + void diagramActivated(); }; Q_DECLARE_METATYPE(Diagram *) /** - @brief Diagram::setConductor - Display or hide the conductor setter, - i.e. a dashed conductor stub which appears - when creating a conductor between two terminals. - @param adding true add conductor ,false remove conductor + @brief Diagram::setConductor + Display or hide the conductor setter, + i.e. a dashed conductor stub which appears + when creating a conductor between two terminals. + @param adding true add conductor ,false remove conductor */ inline void Diagram::setConductor(bool adding) { - if (adding) { - if (!conductor_setter_ -> scene()) addItem(conductor_setter_); - } else { - if (conductor_setter_ -> scene()) removeItem(conductor_setter_); - } + if (adding) { + if (!conductor_setter_ -> scene()) addItem(conductor_setter_); + } else { + if (conductor_setter_ -> scene()) removeItem(conductor_setter_); + } } /** - @brief Diagram::setConductorStart - Set the start point of the conductor setter. - @param start the point (in scene coordinates) which the newly created - conductor should start from. + @brief Diagram::setConductorStart + Set the start point of the conductor setter. + @param start the point (in scene coordinates) which the newly created + conductor should start from. */ inline void Diagram::setConductorStart(QPointF start) { - conductor_setter_ -> setLine(QLineF(start, conductor_setter_ -> line().p2())); + conductor_setter_ -> setLine(QLineF(start, conductor_setter_ -> line().p2())); } /** - @brief Diagram::setConductorStop - Set the end point of the conductor setter. - @param end the point (in scene coordinates) upon to which the newly created - conductor should be drawn. + @brief Diagram::setConductorStop + Set the end point of the conductor setter. + @param end the point (in scene coordinates) upon to which the newly created + conductor should be drawn. */ inline void Diagram::setConductorStop(QPointF end) { - conductor_setter_ -> setLine(QLineF(conductor_setter_ -> line().p1(), end)); + conductor_setter_ -> setLine(QLineF(conductor_setter_ -> line().p1(), end)); } /** - @brief Diagram::setDisplayGrid - Set whether the diagram grid should be drawn. - @param dg true to render the grid, false otherwise. + @brief Diagram::setDisplayGrid + Set whether the diagram grid should be drawn. + @param dg true to render the grid, false otherwise. */ inline void Diagram::setDisplayGrid(bool dg) { - draw_grid_ = dg; + draw_grid_ = dg; } /** - @brief Diagram::displayGrid - @return draw_grid_ true if the grid is drawn, false otherwise. + @brief Diagram::displayGrid + @return draw_grid_ true if the grid is drawn, false otherwise. */ inline bool Diagram::displayGrid() { - return(draw_grid_); + return(draw_grid_); } /** - @brief Diagram::setUseBorder - Set whether the diagram border (including rows/colums headers and the title - block) should be rendered along with the diagram. When set to false, the size - of the smallest rectangle containing all items is considered as the diagram - size. - @param ub true to take the border into account, false otherwise + @brief Diagram::setUseBorder + Set whether the diagram border (including rows/colums headers and the title + block) should be rendered along with the diagram. When set to false, the size + of the smallest rectangle containing all items is considered as the diagram + size. + @param ub true to take the border into account, false otherwise */ inline void Diagram::setUseBorder(bool ub) { - use_border_ = ub; + use_border_ = ub; } /** - @brief Diagram::useBorder - @return use_border_ true if the border is rendered and take into account, - false otherwise. + @brief Diagram::useBorder + @return use_border_ true if the border is rendered and take into account, + false otherwise. */ inline bool Diagram::useBorder() { - return(use_border_); + return(use_border_); } /** - @brief Diagram::setBorderOptions - Set the rendering options for the diagram border (including rows/colums - headers and the title block) - @param bo Enabled options ORed together - @see BorderOptions + @brief Diagram::setBorderOptions + Set the rendering options for the diagram border (including rows/colums + headers and the title block) + @param bo Enabled options ORed together + @see BorderOptions */ inline void Diagram::setBorderOptions(Diagram::BorderOptions bo) { - border_and_titleblock.displayBorder(!(bo & EmptyBorder)); - border_and_titleblock.displayColumns(bo & Columns); - border_and_titleblock.displayTitleBlock(bo & TitleBlock); + border_and_titleblock.displayBorder(!(bo & EmptyBorder)); + border_and_titleblock.displayColumns(bo & Columns); + border_and_titleblock.displayTitleBlock(bo & TitleBlock); } /** - @brief Diagram::borderOptions - @return The rendering optios for the diagram border - @see setBorderOptions + @brief Diagram::borderOptions + @return The rendering optios for the diagram border + @see setBorderOptions */ inline Diagram::BorderOptions Diagram::borderOptions() { - BorderOptions options = EmptyBorder; - if (border_and_titleblock.titleBlockIsDisplayed()) - options = (BorderOptions)(options|TitleBlock); - if (border_and_titleblock.columnsAreDisplayed()) - options = (BorderOptions)(options|Columns); - return(options); + BorderOptions options = EmptyBorder; + if (border_and_titleblock.titleBlockIsDisplayed()) + options = (BorderOptions)(options|TitleBlock); + if (border_and_titleblock.columnsAreDisplayed()) + options = (BorderOptions)(options|Columns); + return(options); } /** - @brief Diagram::undoStack - @return the diagram undo stack + @brief Diagram::undoStack + @return the diagram undo stack */ inline QUndoStack &Diagram::undoStack() { - return *(project()->undoStack()); + return *(project()->undoStack()); } /** - @brief Diagram::qgiManager - @return the diagram graphics item manager + @brief Diagram::qgiManager + @return the diagram graphics item manager */ inline QGIManager &Diagram::qgiManager() { - return(*qgi_manager_); + return(*qgi_manager_); } /** - @brief Diagram::drawTerminals - @return true if terminals are rendered, false otherwise + @brief Diagram::drawTerminals + @return true if terminals are rendered, false otherwise */ inline bool Diagram::drawTerminals() const { - return(draw_terminals_); + return(draw_terminals_); } /** - @brief Diagram::drawColoredConductors - @return true if conductors colors are rendered, false otherwise. + @brief Diagram::drawColoredConductors + @return true if conductors colors are rendered, false otherwise. */ inline bool Diagram::drawColoredConductors() const { - return(draw_colored_conductors_); + return(draw_colored_conductors_); } #endif diff --git a/sources/diagramcontext.cpp b/sources/diagramcontext.cpp index b7e711099..9df38993c 100644 --- a/sources/diagramcontext.cpp +++ b/sources/diagramcontext.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "diagramcontext.h" #include "qet.h" @@ -22,238 +22,238 @@ #include /** - @brief DiagramContext::add - Add all value of other to this. - If a key already exist, the value is replaced. - If a key doesn't exist, she will be added. - All other keys of this context, which are not present in other, stay unchanged. - @param other + @brief DiagramContext::add + Add all value of other to this. + If a key already exist, the value is replaced. + If a key doesn't exist, she will be added. + All other keys of this context, which are not present in other, stay unchanged. + @param other */ void DiagramContext::add(DiagramContext other) { - for (QString key : other.keys()) { - addValue(key, other.value(key)); - } + for (QString key : other.keys()) { + addValue(key, other.value(key)); + } } /** - @brief DiagramContext::remove - @param key + @brief DiagramContext::remove + @param key */ void DiagramContext::remove(const QString &key) { - m_content.remove(key); + m_content.remove(key); } /** - @return a list containing all the keys in the context object. + @return a list containing all the keys in the context object. */ QList DiagramContext::keys(DiagramContext::KeyOrder order) const { - if (order == None) { - return m_content.keys(); - } - else - { - QList keys_list = m_content.keys(); - if (order == Alphabetical) { - std::sort(keys_list.begin(), keys_list.end()); - } else { - std::sort(keys_list.begin(), keys_list.end(), DiagramContext::stringLongerThan); - } - return(keys_list); - } + if (order == None) { + return m_content.keys(); + } + else + { + QList keys_list = m_content.keys(); + if (order == Alphabetical) { + std::sort(keys_list.begin(), keys_list.end()); + } else { + std::sort(keys_list.begin(), keys_list.end(), DiagramContext::stringLongerThan); + } + return(keys_list); + } } /** - @param key string key - @return true if that key is known to the diagram context, false otherwise + @param key string key + @return true if that key is known to the diagram context, false otherwise */ bool DiagramContext::contains(const QString &key) const { - return(m_content.contains(key)); + return(m_content.contains(key)); } /** - @param key + @param key */ const QVariant DiagramContext::operator[](const QString &key) const { - return(m_content[key]); + return(m_content[key]); } /** - @param key key to insert in the context - the key may only contain lowercase - letters and dashes. - If embedded key is set, key must be find it else value is not added. - @see DiagramContext::keyIsAcceptable() - @param value value to insert in the context - @param show if value is used to be show on the diagram or somewhere else, - we can specify if he is show(true) or not(false) - @return true if the insertion succeeds, false otherwise + @param key key to insert in the context - the key may only contain lowercase + letters and dashes. + If embedded key is set, key must be find it else value is not added. + @see DiagramContext::keyIsAcceptable() + @param value value to insert in the context + @param show if value is used to be show on the diagram or somewhere else, + we can specify if he is show(true) or not(false) + @return true if the insertion succeeds, false otherwise */ bool DiagramContext::addValue(const QString &key, const QVariant &value, bool show) { - if (keyIsAcceptable(key)) { - m_content.insert(key, value); - m_content_show.insert(key, show); - return(true); - } - return(false); + if (keyIsAcceptable(key)) { + m_content.insert(key, value); + m_content_show.insert(key, show); + return(true); + } + return(false); } QVariant DiagramContext::value(const QString &key) const { - return m_content.value(key); + return m_content.value(key); } /** - Clear the content of this diagram context. + Clear the content of this diagram context. */ void DiagramContext::clear() { - m_content.clear(); - m_content_show.clear(); + m_content.clear(); + m_content_show.clear(); } /** - @return the number of key/value pairs stored in this object. + @return the number of key/value pairs stored in this object. */ int DiagramContext::count() { - return(m_content.count()); + return(m_content.count()); } /** - @brief DiagramContext::keyMustShow - @return the value pairs with key, if key no found, return false + @brief DiagramContext::keyMustShow + @return the value pairs with key, if key no found, return false */ bool DiagramContext::keyMustShow(const QString &key) const { - if (m_content_show.contains(key)) - return m_content_show[key]; - return false; + if (m_content_show.contains(key)) + return m_content_show[key]; + return false; } bool DiagramContext::operator==(const DiagramContext &dc) const { - return(m_content == dc.m_content && - m_content_show == dc.m_content_show); + return(m_content == dc.m_content && + m_content_show == dc.m_content_show); } bool DiagramContext::operator!=(const DiagramContext &dc) const { - return(!(*this == dc)); + return(!(*this == dc)); } /** - Export this context properties under the \a e XML element, using tags - named \a tag_name (defaults to "property"). + Export this context properties under the \a e XML element, using tags + named \a tag_name (defaults to "property"). */ void DiagramContext::toXml(QDomElement &e, const QString &tag_name) const { - foreach (QString key, keys()) { - QDomElement property = e.ownerDocument().createElement(tag_name); - property.setAttribute("name", key); - property.setAttribute("show",m_content_show[key]); - QDomText value = e.ownerDocument().createTextNode(m_content[key].toString()); - property.appendChild(value); - e.appendChild(property); - } + foreach (QString key, keys()) { + QDomElement property = e.ownerDocument().createElement(tag_name); + property.setAttribute("name", key); + property.setAttribute("show",m_content_show[key]); + QDomText value = e.ownerDocument().createTextNode(m_content[key].toString()); + property.appendChild(value); + e.appendChild(property); + } } /** - Read this context properties from the \a e XML element, looking for tags named - \a tag_name (defaults to "property"). + Read this context properties from the \a e XML element, looking for tags named + \a tag_name (defaults to "property"). */ void DiagramContext::fromXml(const QDomElement &e, const QString &tag_name) { - foreach (QDomElement property, QET::findInDomElement(e, tag_name)) { - if (!property.hasAttribute("name")) continue; - addValue(property.attribute("name"), QVariant(property.text())); - m_content_show.insert(property.attribute("name"), property.attribute("show", "1").toInt()); - } + foreach (QDomElement property, QET::findInDomElement(e, tag_name)) { + if (!property.hasAttribute("name")) continue; + addValue(property.attribute("name"), QVariant(property.text())); + m_content_show.insert(property.attribute("name"), property.attribute("show", "1").toInt()); + } } /** - @brief DiagramContext::fromXml - Read this context properties from the dom_element, - looking for tags named tag_name - @param dom_element : dom element to parse - @param tag_name : tag name to find, by default "property" + @brief DiagramContext::fromXml + Read this context properties from the dom_element, + looking for tags named tag_name + @param dom_element : dom element to parse + @param tag_name : tag name to find, by default "property" */ void DiagramContext::fromXml(const pugi::xml_node &dom_element, const QString &tag_name) { - for(auto node = dom_element.child(tag_name.toStdString().c_str()) ; node ; node = node.next_sibling(tag_name.toStdString().c_str())) - { - addValue(node.attribute("name").as_string(), QVariant(node.text().as_string())); - m_content_show.insert(node.attribute("name").as_string(), node.attribute("show").empty()? 1 : node.attribute("show").as_int()); - } + for(auto node = dom_element.child(tag_name.toStdString().c_str()) ; node ; node = node.next_sibling(tag_name.toStdString().c_str())) + { + addValue(node.attribute("name").as_string(), QVariant(node.text().as_string())); + m_content_show.insert(node.attribute("name").as_string(), node.attribute("show").empty()? 1 : node.attribute("show").as_int()); + } } /** - Export this context properties to \a settings by creating an array named \a - array_name. + Export this context properties to \a settings by creating an array named \a + array_name. */ void DiagramContext::toSettings(QSettings &settings, const QString &array_name) const { - settings.beginWriteArray(array_name); - int i = 0; - foreach (QString key, m_content.keys()) { - settings.setArrayIndex(i); - settings.setValue("name", key); - settings.setValue("value", m_content[key].toString()); - ++ i; - } - settings.endArray(); + settings.beginWriteArray(array_name); + int i = 0; + foreach (QString key, m_content.keys()) { + settings.setArrayIndex(i); + settings.setValue("name", key); + settings.setValue("value", m_content[key].toString()); + ++ i; + } + settings.endArray(); } /** - Read this context properties from \a settings by running through the array - named \a array_name. + Read this context properties from \a settings by running through the array + named \a array_name. */ void DiagramContext::fromSettings(QSettings &settings, const QString &array_name) { - int size = settings.beginReadArray(array_name); - for (int i = 0 ; i < size; ++ i) { - settings.setArrayIndex(i); - QString key = settings.value("name").toString(); - if (key.isEmpty()) continue; - addValue(key, settings.value("value").toString()); - } - settings.endArray(); + int size = settings.beginReadArray(array_name); + for (int i = 0 ; i < size; ++ i) { + settings.setArrayIndex(i); + QString key = settings.value("name").toString(); + if (key.isEmpty()) continue; + addValue(key, settings.value("value").toString()); + } + settings.endArray(); } /** - @return the regular expression used to check whether a given key is acceptable. - @see keyIsAcceptable() + @return the regular expression used to check whether a given key is acceptable. + @see keyIsAcceptable() */ QString DiagramContext::validKeyRegExp() { - return("^[a-z0-9-_]+$"); + return("^[a-z0-9-_]+$"); } /** - @return True if \a a is longer than \a b, false otherwise. + @return True if \a a is longer than \a b, false otherwise. */ bool DiagramContext::stringLongerThan(const QString &a, const QString &b) { - return (a.length() > b.length()); + return (a.length() > b.length()); } /** - @param key a key string - @return true if that key is acceptable, false otherwise + @param key a key string + @return true if that key is acceptable, false otherwise */ bool DiagramContext::keyIsAcceptable(const QString &key) const { - QRegularExpression re(DiagramContext::validKeyRegExp()); - QRegularExpressionMatch match =re.match(key); - return match.hasMatch(); + QRegularExpression re(DiagramContext::validKeyRegExp()); + QRegularExpressionMatch match =re.match(key); + return match.hasMatch(); } QDebug operator <<(QDebug debug, const DiagramContext &context) { - debug << "DiagramContext"; - for (auto key : context.keys()) { - debug.nospace() << key << " : " << context.value(key) << "\n"; - } - debug << " end DiagramContext"; + debug << "DiagramContext"; + for (auto key : context.keys()) { + debug.nospace() << key << " : " << context.value(key) << "\n"; + } + debug << " end DiagramContext"; - return debug; + return debug; } diff --git a/sources/diagramcontext.h b/sources/diagramcontext.h index f887b0ff6..7dfc5b6f4 100644 --- a/sources/diagramcontext.h +++ b/sources/diagramcontext.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef DIAGRAM_CONTEXT_H #define DIAGRAM_CONTEXT_H @@ -26,9 +26,9 @@ #include "pugixml.hpp" /** - This class represents a diagram context, i.e. the data (a list of key/value - pairs) of a diagram at a given time. It is notably used by titleblock templates - to fetch the informations they need to do their rendering, or element for retrieve information about itself + This class represents a diagram context, i.e. the data (a list of key/value + pairs) of a diagram at a given time. It is notably used by titleblock templates + to fetch the informations they need to do their rendering, or element for retrieve information about itself */ /** @@ -54,41 +54,41 @@ */ class DiagramContext { - public: - enum KeyOrder { - None, - Alphabetical, - DecreasingLength - }; - - void add(DiagramContext other); - void remove(const QString &key); - QList keys(KeyOrder = None) const; - bool contains(const QString &) const; - const QVariant operator[](const QString &) const; - bool addValue(const QString &, const QVariant &, bool show = true); - QVariant value(const QString &key) const; - void clear(); - int count(); - bool keyMustShow (const QString &) const; - - bool operator==(const DiagramContext &) const; - bool operator!=(const DiagramContext &) const; - - void toXml(QDomElement &, const QString & = "property") const; - void fromXml(const QDomElement &, const QString & = "property"); - void fromXml(const pugi::xml_node &dom_element, const QString &tag_name = "property"); - void toSettings(QSettings &, const QString &) const; - void fromSettings(QSettings &, const QString &); - - static QString validKeyRegExp(); - - private: - static bool stringLongerThan(const QString &, const QString &); - bool keyIsAcceptable(const QString &) const; - /// Diagram context data (key/value pairs) - QHash m_content; - QHash m_content_show; + public: + enum KeyOrder { + None, + Alphabetical, + DecreasingLength + }; + + void add(DiagramContext other); + void remove(const QString &key); + QList keys(KeyOrder = None) const; + bool contains(const QString &) const; + const QVariant operator[](const QString &) const; + bool addValue(const QString &, const QVariant &, bool show = true); + QVariant value(const QString &key) const; + void clear(); + int count(); + bool keyMustShow (const QString &) const; + + bool operator==(const DiagramContext &) const; + bool operator!=(const DiagramContext &) const; + + void toXml(QDomElement &, const QString & = "property") const; + void fromXml(const QDomElement &, const QString & = "property"); + void fromXml(const pugi::xml_node &dom_element, const QString &tag_name = "property"); + void toSettings(QSettings &, const QString &) const; + void fromSettings(QSettings &, const QString &); + + static QString validKeyRegExp(); + + private: + static bool stringLongerThan(const QString &, const QString &); + bool keyIsAcceptable(const QString &) const; + /// Diagram context data (key/value pairs) + QHash m_content; + QHash m_content_show; }; QDebug operator <<(QDebug debug, const DiagramContext &context); diff --git a/sources/editor/graphicspart/customelementgraphicpart.cpp b/sources/editor/graphicspart/customelementgraphicpart.cpp index b804fdee6..53d0990c3 100644 --- a/sources/editor/graphicspart/customelementgraphicpart.cpp +++ b/sources/editor/graphicspart/customelementgraphicpart.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "customelementgraphicpart.h" #include "elementscene.h" @@ -22,503 +22,503 @@ #include /** - @brief CustomElementGraphicPart::CustomElementGraphicPart - Default constructor. - By default, item is selectable, send geometry change (Qt > 4.6), - accept mouse left button and accept hover event - @param editor QETElement editor that belong this. - @param parent + @brief CustomElementGraphicPart::CustomElementGraphicPart + Default constructor. + By default, item is selectable, send geometry change (Qt > 4.6), + accept mouse left button and accept hover event + @param editor QETElement editor that belong this. + @param parent */ CustomElementGraphicPart::CustomElementGraphicPart(QETElementEditor *editor, - QGraphicsItem *parent) : - QGraphicsObject (parent), - CustomElementPart(editor), - m_hovered (false), - _linestyle(NormalStyle), - _lineweight(NormalWeight), - _filling(NoneFilling), - _color(BlackColor), - _antialiased(false) + QGraphicsItem *parent) : + QGraphicsObject (parent), + CustomElementPart(editor), + m_hovered (false), + _linestyle(NormalStyle), + _lineweight(NormalWeight), + _filling(NoneFilling), + _color(BlackColor), + _antialiased(false) { - setFlags(QGraphicsItem::ItemIsSelectable - | QGraphicsItem::ItemIsMovable - | QGraphicsItem::ItemSendsGeometryChanges); - setAcceptHoverEvents(true); + setFlags(QGraphicsItem::ItemIsSelectable + | QGraphicsItem::ItemIsMovable + | QGraphicsItem::ItemSendsGeometryChanges); + setAcceptHoverEvents(true); } /** - @brief CustomElementGraphicPart::~CustomElementGraphicPart - Destructor + @brief CustomElementGraphicPart::~CustomElementGraphicPart + Destructor */ CustomElementGraphicPart::~CustomElementGraphicPart() {} /** - @brief CustomElementGraphicPart::drawCross - Draw a cross at pos center - @param center : center of cross - @param painter : painter to use for draw cross, - the painter state is restored at end of this method. + @brief CustomElementGraphicPart::drawCross + Draw a cross at pos center + @param center : center of cross + @param painter : painter to use for draw cross, + the painter state is restored at end of this method. */ void CustomElementGraphicPart::drawCross(const QPointF ¢er, - QPainter *painter) + QPainter *painter) { - painter -> save(); - painter -> setRenderHint(QPainter::Antialiasing, false); - painter -> setPen((painter -> brush().color() - == QColor(Qt::black) - && painter -> brush().isOpaque()) - ? Qt::yellow - : Qt::blue); - painter -> drawLine(QLineF(center.x() - 2.0, - center.y(), - center.x() + 2.0, - center.y())); - painter -> drawLine(QLineF(center.x(), - center.y() - 2.0, - center.x(), - center.y() + 2.0)); - painter -> restore(); + painter -> save(); + painter -> setRenderHint(QPainter::Antialiasing, false); + painter -> setPen((painter -> brush().color() + == QColor(Qt::black) + && painter -> brush().isOpaque()) + ? Qt::yellow + : Qt::blue); + painter -> drawLine(QLineF(center.x() - 2.0, + center.y(), + center.x() + 2.0, + center.y())); + painter -> drawLine(QLineF(center.x(), + center.y() - 2.0, + center.x(), + center.y() + 2.0)); + painter -> restore(); } /** - @brief CustomElementGraphicPart::setLineStyle - Set line style to ls - @param ls + @brief CustomElementGraphicPart::setLineStyle + Set line style to ls + @param ls */ void CustomElementGraphicPart::setLineStyle(const LineStyle ls) { - if (_linestyle == ls) return; - _linestyle = ls; - update(); + if (_linestyle == ls) return; + _linestyle = ls; + update(); } /** - @brief CustomElementGraphicPart::setLineWeight - Set line weight to lw - @param lw + @brief CustomElementGraphicPart::setLineWeight + Set line weight to lw + @param lw */ void CustomElementGraphicPart::setLineWeight(const LineWeight lw) { - if (_lineweight == lw) return; - _lineweight = lw; - update(); + if (_lineweight == lw) return; + _lineweight = lw; + update(); } /** - @brief CustomElementGraphicPart::penWeight - @return the weight of pen + @brief CustomElementGraphicPart::penWeight + @return the weight of pen */ qreal CustomElementGraphicPart::penWeight() const { - if (_lineweight == NoneWeight || _lineweight == ThinWeight) return 0; - else if (_lineweight == NormalWeight) return 1; - else if (_lineweight == UltraWeight) return 2; - else if (_lineweight == BigWeight) return 5; - return 1; + if (_lineweight == NoneWeight || _lineweight == ThinWeight) return 0; + else if (_lineweight == NormalWeight) return 1; + else if (_lineweight == UltraWeight) return 2; + else if (_lineweight == BigWeight) return 5; + return 1; } /** - @brief CustomElementGraphicPart::setFilling - Set filling to f - @param f + @brief CustomElementGraphicPart::setFilling + Set filling to f + @param f */ void CustomElementGraphicPart::setFilling(const Filling f) { - if (_filling == f) return; - _filling = f; - update(); + if (_filling == f) return; + _filling = f; + update(); } /** - @brief CustomElementGraphicPart::setColor - Set color to c - @param c + @brief CustomElementGraphicPart::setColor + Set color to c + @param c */ void CustomElementGraphicPart::setColor(const Color c) { - if (_color == c) return; - _color = c; - update(); + if (_color == c) return; + _color = c; + update(); } /** - @brief CustomElementGraphicPart::setAntialiased - Set antialias to b - @param b + @brief CustomElementGraphicPart::setAntialiased + Set antialias to b + @param b */ void CustomElementGraphicPart::setAntialiased(const bool b) { - if (_antialiased == b) return; - _antialiased = b; - update(); + if (_antialiased == b) return; + _antialiased = b; + update(); } /** - @brief CustomElementGraphicPart::stylesToXml - Write the curent style to xml element. - The style are stored like this: - name-of-style:value;name-of-style:value - Each style separate by ; and name-style/value are separate by : - @param qde : QDOmElement used to write the style. + @brief CustomElementGraphicPart::stylesToXml + Write the curent style to xml element. + The style are stored like this: + name-of-style:value;name-of-style:value + Each style separate by ; and name-style/value are separate by : + @param qde : QDOmElement used to write the style. */ void CustomElementGraphicPart::stylesToXml(QDomElement &qde) const { - QString css_like_styles; + QString css_like_styles; - css_like_styles += "line-style:"; - if (_linestyle == DashedStyle) css_like_styles += "dashed"; - else if (_linestyle == DottedStyle) css_like_styles += "dotted"; - else if (_linestyle == DashdottedStyle) css_like_styles += "dashdotted"; - else if (_linestyle == NormalStyle) css_like_styles += "normal"; + css_like_styles += "line-style:"; + if (_linestyle == DashedStyle) css_like_styles += "dashed"; + else if (_linestyle == DottedStyle) css_like_styles += "dotted"; + else if (_linestyle == DashdottedStyle) css_like_styles += "dashdotted"; + else if (_linestyle == NormalStyle) css_like_styles += "normal"; - css_like_styles += ";line-weight:"; - if (_lineweight == NoneWeight) css_like_styles += "none"; - else if (_lineweight == ThinWeight) css_like_styles += "thin"; - else if (_lineweight == NormalWeight) css_like_styles += "normal"; - else if (_lineweight == UltraWeight) css_like_styles += "hight"; - else if (_lineweight == BigWeight) css_like_styles += "eleve"; + css_like_styles += ";line-weight:"; + if (_lineweight == NoneWeight) css_like_styles += "none"; + else if (_lineweight == ThinWeight) css_like_styles += "thin"; + else if (_lineweight == NormalWeight) css_like_styles += "normal"; + else if (_lineweight == UltraWeight) css_like_styles += "hight"; + else if (_lineweight == BigWeight) css_like_styles += "eleve"; - css_like_styles += ";filling:"; - if (_filling == NoneFilling) css_like_styles += "none"; - else if (_filling == BlackFilling) css_like_styles += "black"; - else if (_filling == WhiteFilling) css_like_styles += "white"; - else if (_filling == GreenFilling) css_like_styles += "green"; - else if (_filling == BlueFilling) css_like_styles += "blue"; - else if (_filling == RedFilling) css_like_styles += "red"; - else if (_filling == GrayFilling) css_like_styles += "gray"; - else if (_filling == BrunFilling) css_like_styles += "brun"; - else if (_filling == YellowFilling) css_like_styles += "yellow"; - else if (_filling == CyanFilling) css_like_styles += "cyan"; - else if (_filling == MagentaFilling) css_like_styles += "magenta"; - else if (_filling == LightgrayFilling) css_like_styles += "lightgray"; - else if (_filling == OrangeFilling) css_like_styles += "orange"; - else if (_filling == PurpleFilling) css_like_styles += "purple"; - else if (_filling == HTMLPinkPinkFilling) css_like_styles += "HTMLPinkPink"; - else if (_filling == HTMLPinkLightPinkFilling) css_like_styles += "HTMLPinkLightPink"; - else if (_filling == HTMLPinkHotPinkFilling) css_like_styles += "HTMLPinkHotPink"; - else if (_filling == HTMLPinkDeepPinkFilling) css_like_styles += "HTMLPinkDeepPink"; - else if (_filling == HTMLPinkPaleVioletRedFilling) css_like_styles += "HTMLPinkPaleVioletRed"; - else if (_filling == HTMLPinkMediumVioletRedFilling) css_like_styles += "HTMLPinkMediumVioletRed"; - else if (_filling == HTMLRedLightSalmonFilling) css_like_styles += "HTMLRedLightSalmon"; - else if (_filling == HTMLRedSalmonFilling) css_like_styles += "HTMLRedSalmon"; - else if (_filling == HTMLRedDarkSalmonFilling) css_like_styles += "HTMLRedDarkSalmon"; - else if (_filling == HTMLRedLightCoralFilling) css_like_styles += "HTMLRedLightCoral"; - else if (_filling == HTMLRedIndianRedFilling) css_like_styles += "HTMLRedIndianRed"; - else if (_filling == HTMLRedCrimsonFilling) css_like_styles += "HTMLRedCrimson"; - else if (_filling == HTMLRedFirebrickFilling) css_like_styles += "HTMLRedFirebrick"; - else if (_filling == HTMLRedDarkRedFilling) css_like_styles += "HTMLRedDarkRed"; - else if (_filling == HTMLRedRedFilling) css_like_styles += "HTMLRedRed"; - else if (_filling == HTMLOrangeOrangeRedFilling) css_like_styles += "HTMLOrangeOrangeRed"; - else if (_filling == HTMLOrangeTomatoFilling) css_like_styles += "HTMLOrangeTomato"; - else if (_filling == HTMLOrangeCoralFilling) css_like_styles += "HTMLOrangeCoral"; - else if (_filling == HTMLOrangeDarkOrangeFilling) css_like_styles += "HTMLOrangeDarkOrange"; - else if (_filling == HTMLOrangeOrangeFilling) css_like_styles += "HTMLOrangeOrange"; - else if (_filling == HTMLYellowYellowFilling) css_like_styles += "HTMLYellowYellow"; - else if (_filling == HTMLYellowLightYellowFilling) css_like_styles += "HTMLYellowLightYellow"; - else if (_filling == HTMLYellowLemonChiffonFilling) css_like_styles += "HTMLYellowLemonChiffon"; - else if (_filling == HTMLYellowLightGoldenrodYellowFilling) css_like_styles += "HTMLYellowLightGoldenrodYellow"; - else if (_filling == HTMLYellowPapayaWhipFilling) css_like_styles += "HTMLYellowPapayaWhip"; - else if (_filling == HTMLYellowMoccasinFilling) css_like_styles += "HTMLYellowMoccasin"; - else if (_filling == HTMLYellowPeachPuffFilling) css_like_styles += "HTMLYellowPeachPuff"; - else if (_filling == HTMLYellowPaleGoldenrodFilling) css_like_styles += "HTMLYellowPaleGoldenrod"; - else if (_filling == HTMLYellowKhakiFilling) css_like_styles += "HTMLYellowKhaki"; - else if (_filling == HTMLYellowDarkKhakiFilling) css_like_styles += "HTMLYellowDarkKhaki"; - else if (_filling == HTMLYellowGoldFilling) css_like_styles += "HTMLYellowGold"; - else if (_filling == HTMLBrownCornsilkFilling) css_like_styles += "HTMLBrownCornsilk"; - else if (_filling == HTMLBrownBlanchedAlmondFilling) css_like_styles += "HTMLBrownBlanchedAlmond"; - else if (_filling == HTMLBrownBisqueFilling) css_like_styles += "HTMLBrownBisque"; - else if (_filling == HTMLBrownNavajoWhiteFilling) css_like_styles += "HTMLBrownNavajoWhite"; - else if (_filling == HTMLBrownWheatFilling) css_like_styles += "HTMLBrownWheat"; - else if (_filling == HTMLBrownBurlywoodFilling) css_like_styles += "HTMLBrownBurlywood"; - else if (_filling == HTMLBrownTanFilling) css_like_styles += "HTMLBrownTan"; - else if (_filling == HTMLBrownRosyBrownFilling) css_like_styles += "HTMLBrownRosyBrown"; - else if (_filling == HTMLBrownSandyBrownFilling) css_like_styles += "HTMLBrownSandyBrown"; - else if (_filling == HTMLBrownGoldenrodFilling) css_like_styles += "HTMLBrownGoldenrod"; - else if (_filling == HTMLBrownDarkGoldenrodFilling) css_like_styles += "HTMLBrownDarkGoldenrod"; - else if (_filling == HTMLBrownPeruFilling) css_like_styles += "HTMLBrownPeru"; - else if (_filling == HTMLBrownChocolateFilling) css_like_styles += "HTMLBrownChocolate"; - else if (_filling == HTMLBrownSaddleBrownFilling) css_like_styles += "HTMLBrownSaddleBrown"; - else if (_filling == HTMLBrownSiennaFilling) css_like_styles += "HTMLBrownSienna"; - else if (_filling == HTMLBrownBrownFilling) css_like_styles += "HTMLBrownBrown"; - else if (_filling == HTMLBrownMaroonFilling) css_like_styles += "HTMLBrownMaroon"; - else if (_filling == HTMLGreenDarkOliveGreenFilling) css_like_styles += "HTMLGreenDarkOliveGreen"; - else if (_filling == HTMLGreenOliveFilling) css_like_styles += "HTMLGreenOlive"; - else if (_filling == HTMLGreenOliveDrabFilling) css_like_styles += "HTMLGreenOliveDrab"; - else if (_filling == HTMLGreenYellowGreenFilling) css_like_styles += "HTMLGreenYellowGreen"; - else if (_filling == HTMLGreenLimeGreenFilling) css_like_styles += "HTMLGreenLimeGreen"; - else if (_filling == HTMLGreenLimeFilling) css_like_styles += "HTMLGreenLime"; - else if (_filling == HTMLGreenLawnGreenFilling) css_like_styles += "HTMLGreenLawnGreen"; - else if (_filling == HTMLGreenChartreuseFilling) css_like_styles += "HTMLGreenChartreuse"; - else if (_filling == HTMLGreenGreenYellowFilling) css_like_styles += "HTMLGreenGreenYellow"; - else if (_filling == HTMLGreenSpringGreenFilling) css_like_styles += "HTMLGreenSpringGreen"; - else if (_filling == HTMLGreenMediumSpringGreenFilling) css_like_styles += "HTMLGreenMediumSpringGreen"; - else if (_filling == HTMLGreenLightGreenFilling) css_like_styles += "HTMLGreenLightGreen"; - else if (_filling == HTMLGreenPaleGreenFilling) css_like_styles += "HTMLGreenPaleGreen"; - else if (_filling == HTMLGreenDarkSeaGreenFilling) css_like_styles += "HTMLGreenDarkSeaGreen"; - else if (_filling == HTMLGreenMediumAquamarineFilling) css_like_styles += "HTMLGreenMediumAquamarine"; - else if (_filling == HTMLGreenMediumSeaGreenFilling) css_like_styles += "HTMLGreenMediumSeaGreen"; - else if (_filling == HTMLGreenSeaGreenFilling) css_like_styles += "HTMLGreenSeaGreen"; - else if (_filling == HTMLGreenForestGreenFilling) css_like_styles += "HTMLGreenForestGreen"; - else if (_filling == HTMLGreenGreenFilling) css_like_styles += "HTMLGreenGreen"; - else if (_filling == HTMLGreenDarkGreenFilling) css_like_styles += "HTMLGreenDarkGreen"; - else if (_filling == HTMLCyanAquaFilling) css_like_styles += "HTMLCyanAqua"; - else if (_filling == HTMLCyanCyanFilling) css_like_styles += "HTMLCyanCyan"; - else if (_filling == HTMLCyanLightCyanFilling) css_like_styles += "HTMLCyanLightCyan"; - else if (_filling == HTMLCyanPaleTurquoiseFilling) css_like_styles += "HTMLCyanPaleTurquoise"; - else if (_filling == HTMLCyanAquamarineFilling) css_like_styles += "HTMLCyanAquamarine"; - else if (_filling == HTMLCyanTurquoiseFilling) css_like_styles += "HTMLCyanTurquoise"; - else if (_filling == HTMLCyanMediumTurquoiseFilling) css_like_styles += "HTMLCyanMediumTurquoise"; - else if (_filling == HTMLCyanDarkTurquoiseFilling) css_like_styles += "HTMLCyanDarkTurquoise"; - else if (_filling == HTMLCyanLightSeaGreenFilling) css_like_styles += "HTMLCyanLightSeaGreen"; - else if (_filling == HTMLCyanCadetBlueFilling) css_like_styles += "HTMLCyanCadetBlue"; - else if (_filling == HTMLCyanDarkCyanFilling) css_like_styles += "HTMLCyanDarkCyan"; - else if (_filling == HTMLCyanTealFilling) css_like_styles += "HTMLCyanTeal"; - else if (_filling == HTMLBlueLightSteelBlueFilling) css_like_styles += "HTMLBlueLightSteelBlue"; - else if (_filling == HTMLBluePowderBlueFilling) css_like_styles += "HTMLBluePowderBlue"; - else if (_filling == HTMLBlueLightBlueFilling) css_like_styles += "HTMLBlueLightBlue"; - else if (_filling == HTMLBlueSkyBlueFilling) css_like_styles += "HTMLBlueSkyBlue"; - else if (_filling == HTMLBlueLightSkyBlueFilling) css_like_styles += "HTMLBlueLightSkyBlue"; - else if (_filling == HTMLBlueDeepSkyBlueFilling) css_like_styles += "HTMLBlueDeepSkyBlue"; - else if (_filling == HTMLBlueDodgerBlueFilling) css_like_styles += "HTMLBlueDodgerBlue"; - else if (_filling == HTMLBlueCornflowerBlueFilling) css_like_styles += "HTMLBlueCornflowerBlue"; - else if (_filling == HTMLBlueSteelBlueFilling) css_like_styles += "HTMLBlueSteelBlue"; - else if (_filling == HTMLBlueRoyalBlueFilling) css_like_styles += "HTMLBlueRoyalBlue"; - else if (_filling == HTMLBlueBlueFilling) css_like_styles += "HTMLBlueBlue"; - else if (_filling == HTMLBlueMediumBlueFilling) css_like_styles += "HTMLBlueMediumBlue"; - else if (_filling == HTMLBlueDarkBlueFilling) css_like_styles += "HTMLBlueDarkBlue"; - else if (_filling == HTMLBlueNavyFilling) css_like_styles += "HTMLBlueNavy"; - else if (_filling == HTMLBlueMidnightBlueFilling) css_like_styles += "HTMLBlueMidnightBlue"; - else if (_filling == HTMLPurpleLavenderFilling) css_like_styles += "HTMLPurpleLavender"; - else if (_filling == HTMLPurpleThistleFilling) css_like_styles += "HTMLPurpleThistle"; - else if (_filling == HTMLPurplePlumFilling) css_like_styles += "HTMLPurplePlum"; - else if (_filling == HTMLPurpleVioletFilling) css_like_styles += "HTMLPurpleViolet"; - else if (_filling == HTMLPurpleOrchidFilling) css_like_styles += "HTMLPurpleOrchid"; - else if (_filling == HTMLPurpleFuchsiaFilling) css_like_styles += "HTMLPurpleFuchsia"; - else if (_filling == HTMLPurpleMagentaFilling) css_like_styles += "HTMLPurpleMagenta"; - else if (_filling == HTMLPurpleMediumOrchidFilling) css_like_styles += "HTMLPurpleMediumOrchid"; - else if (_filling == HTMLPurpleMediumPurpleFilling) css_like_styles += "HTMLPurpleMediumPurple"; - else if (_filling == HTMLPurpleBlueVioletFilling) css_like_styles += "HTMLPurpleBlueViolet"; - else if (_filling == HTMLPurpleDarkVioletFilling) css_like_styles += "HTMLPurpleDarkViolet"; - else if (_filling == HTMLPurpleDarkOrchidFilling) css_like_styles += "HTMLPurpleDarkOrchid"; - else if (_filling == HTMLPurpleDarkMagentaFilling) css_like_styles += "HTMLPurpleDarkMagenta"; - else if (_filling == HTMLPurplePurpleFilling) css_like_styles += "HTMLPurplePurple"; - else if (_filling == HTMLPurpleIndigoFilling) css_like_styles += "HTMLPurpleIndigo"; - else if (_filling == HTMLPurpleDarkSlateBlueFilling) css_like_styles += "HTMLPurpleDarkSlateBlue"; - else if (_filling == HTMLPurpleSlateBlueFilling) css_like_styles += "HTMLPurpleSlateBlue"; - else if (_filling == HTMLPurpleMediumSlateBlueFilling) css_like_styles += "HTMLPurpleMediumSlateBlue"; - else if (_filling == HTMLWhiteWhiteFilling) css_like_styles += "HTMLWhiteWhite"; - else if (_filling == HTMLWhiteSnowFilling) css_like_styles += "HTMLWhiteSnow"; - else if (_filling == HTMLWhiteHoneydewFilling) css_like_styles += "HTMLWhiteHoneydew"; - else if (_filling == HTMLWhiteMintCreamFilling) css_like_styles += "HTMLWhiteMintCream"; - else if (_filling == HTMLWhiteAzureFilling) css_like_styles += "HTMLWhiteAzure"; - else if (_filling == HTMLWhiteAliceBlueFilling) css_like_styles += "HTMLWhiteAliceBlue"; - else if (_filling == HTMLWhiteGhostWhiteFilling) css_like_styles += "HTMLWhiteGhostWhite"; - else if (_filling == HTMLWhiteWhiteSmokeFilling) css_like_styles += "HTMLWhiteWhiteSmoke"; - else if (_filling == HTMLWhiteSeashellFilling) css_like_styles += "HTMLWhiteSeashell"; - else if (_filling == HTMLWhiteBeigeFilling) css_like_styles += "HTMLWhiteBeige"; - else if (_filling == HTMLWhiteOldLaceFilling) css_like_styles += "HTMLWhiteOldLace"; - else if (_filling == HTMLWhiteFloralWhiteFilling) css_like_styles += "HTMLWhiteFloralWhite"; - else if (_filling == HTMLWhiteIvoryFilling) css_like_styles += "HTMLWhiteIvory"; - else if (_filling == HTMLWhiteAntiqueWhiteFilling) css_like_styles += "HTMLWhiteAntiqueWhite"; - else if (_filling == HTMLWhiteLinenFilling) css_like_styles += "HTMLWhiteLinen"; - else if (_filling == HTMLWhiteLavenderBlushFilling) css_like_styles += "HTMLWhiteLavenderBlush"; - else if (_filling == HTMLWhiteMistyRoseFilling) css_like_styles += "HTMLWhiteMistyRose"; - else if (_filling == HTMLGrayGainsboroFilling) css_like_styles += "HTMLGrayGainsboro"; - else if (_filling == HTMLGrayLightGrayFilling) css_like_styles += "HTMLGrayLightGray"; - else if (_filling == HTMLGraySilverFilling) css_like_styles += "HTMLGraySilver"; - else if (_filling == HTMLGrayDarkGrayFilling) css_like_styles += "HTMLGrayDarkGray"; - else if (_filling == HTMLGrayGrayFilling) css_like_styles += "HTMLGrayGray"; - else if (_filling == HTMLGrayDimGrayFilling) css_like_styles += "HTMLGrayDimGray"; - else if (_filling == HTMLGrayLightSlateGrayFilling) css_like_styles += "HTMLGrayLightSlateGray"; - else if (_filling == HTMLGraySlateGrayFilling) css_like_styles += "HTMLGraySlateGray"; - else if (_filling == HTMLGrayDarkSlateGrayFilling) css_like_styles += "HTMLGrayDarkSlateGray"; - else if (_filling == HTMLGrayBlackFilling) css_like_styles += "HTMLGrayBlack"; - else if (_filling == HorFilling) css_like_styles += "hor"; - else if (_filling == VerFilling) css_like_styles += "ver"; - else if (_filling == BdiagFilling) css_like_styles += "bdiag"; - else if (_filling == FdiagFilling) css_like_styles += "fdiag"; + css_like_styles += ";filling:"; + if (_filling == NoneFilling) css_like_styles += "none"; + else if (_filling == BlackFilling) css_like_styles += "black"; + else if (_filling == WhiteFilling) css_like_styles += "white"; + else if (_filling == GreenFilling) css_like_styles += "green"; + else if (_filling == BlueFilling) css_like_styles += "blue"; + else if (_filling == RedFilling) css_like_styles += "red"; + else if (_filling == GrayFilling) css_like_styles += "gray"; + else if (_filling == BrunFilling) css_like_styles += "brun"; + else if (_filling == YellowFilling) css_like_styles += "yellow"; + else if (_filling == CyanFilling) css_like_styles += "cyan"; + else if (_filling == MagentaFilling) css_like_styles += "magenta"; + else if (_filling == LightgrayFilling) css_like_styles += "lightgray"; + else if (_filling == OrangeFilling) css_like_styles += "orange"; + else if (_filling == PurpleFilling) css_like_styles += "purple"; + else if (_filling == HTMLPinkPinkFilling) css_like_styles += "HTMLPinkPink"; + else if (_filling == HTMLPinkLightPinkFilling) css_like_styles += "HTMLPinkLightPink"; + else if (_filling == HTMLPinkHotPinkFilling) css_like_styles += "HTMLPinkHotPink"; + else if (_filling == HTMLPinkDeepPinkFilling) css_like_styles += "HTMLPinkDeepPink"; + else if (_filling == HTMLPinkPaleVioletRedFilling) css_like_styles += "HTMLPinkPaleVioletRed"; + else if (_filling == HTMLPinkMediumVioletRedFilling) css_like_styles += "HTMLPinkMediumVioletRed"; + else if (_filling == HTMLRedLightSalmonFilling) css_like_styles += "HTMLRedLightSalmon"; + else if (_filling == HTMLRedSalmonFilling) css_like_styles += "HTMLRedSalmon"; + else if (_filling == HTMLRedDarkSalmonFilling) css_like_styles += "HTMLRedDarkSalmon"; + else if (_filling == HTMLRedLightCoralFilling) css_like_styles += "HTMLRedLightCoral"; + else if (_filling == HTMLRedIndianRedFilling) css_like_styles += "HTMLRedIndianRed"; + else if (_filling == HTMLRedCrimsonFilling) css_like_styles += "HTMLRedCrimson"; + else if (_filling == HTMLRedFirebrickFilling) css_like_styles += "HTMLRedFirebrick"; + else if (_filling == HTMLRedDarkRedFilling) css_like_styles += "HTMLRedDarkRed"; + else if (_filling == HTMLRedRedFilling) css_like_styles += "HTMLRedRed"; + else if (_filling == HTMLOrangeOrangeRedFilling) css_like_styles += "HTMLOrangeOrangeRed"; + else if (_filling == HTMLOrangeTomatoFilling) css_like_styles += "HTMLOrangeTomato"; + else if (_filling == HTMLOrangeCoralFilling) css_like_styles += "HTMLOrangeCoral"; + else if (_filling == HTMLOrangeDarkOrangeFilling) css_like_styles += "HTMLOrangeDarkOrange"; + else if (_filling == HTMLOrangeOrangeFilling) css_like_styles += "HTMLOrangeOrange"; + else if (_filling == HTMLYellowYellowFilling) css_like_styles += "HTMLYellowYellow"; + else if (_filling == HTMLYellowLightYellowFilling) css_like_styles += "HTMLYellowLightYellow"; + else if (_filling == HTMLYellowLemonChiffonFilling) css_like_styles += "HTMLYellowLemonChiffon"; + else if (_filling == HTMLYellowLightGoldenrodYellowFilling) css_like_styles += "HTMLYellowLightGoldenrodYellow"; + else if (_filling == HTMLYellowPapayaWhipFilling) css_like_styles += "HTMLYellowPapayaWhip"; + else if (_filling == HTMLYellowMoccasinFilling) css_like_styles += "HTMLYellowMoccasin"; + else if (_filling == HTMLYellowPeachPuffFilling) css_like_styles += "HTMLYellowPeachPuff"; + else if (_filling == HTMLYellowPaleGoldenrodFilling) css_like_styles += "HTMLYellowPaleGoldenrod"; + else if (_filling == HTMLYellowKhakiFilling) css_like_styles += "HTMLYellowKhaki"; + else if (_filling == HTMLYellowDarkKhakiFilling) css_like_styles += "HTMLYellowDarkKhaki"; + else if (_filling == HTMLYellowGoldFilling) css_like_styles += "HTMLYellowGold"; + else if (_filling == HTMLBrownCornsilkFilling) css_like_styles += "HTMLBrownCornsilk"; + else if (_filling == HTMLBrownBlanchedAlmondFilling) css_like_styles += "HTMLBrownBlanchedAlmond"; + else if (_filling == HTMLBrownBisqueFilling) css_like_styles += "HTMLBrownBisque"; + else if (_filling == HTMLBrownNavajoWhiteFilling) css_like_styles += "HTMLBrownNavajoWhite"; + else if (_filling == HTMLBrownWheatFilling) css_like_styles += "HTMLBrownWheat"; + else if (_filling == HTMLBrownBurlywoodFilling) css_like_styles += "HTMLBrownBurlywood"; + else if (_filling == HTMLBrownTanFilling) css_like_styles += "HTMLBrownTan"; + else if (_filling == HTMLBrownRosyBrownFilling) css_like_styles += "HTMLBrownRosyBrown"; + else if (_filling == HTMLBrownSandyBrownFilling) css_like_styles += "HTMLBrownSandyBrown"; + else if (_filling == HTMLBrownGoldenrodFilling) css_like_styles += "HTMLBrownGoldenrod"; + else if (_filling == HTMLBrownDarkGoldenrodFilling) css_like_styles += "HTMLBrownDarkGoldenrod"; + else if (_filling == HTMLBrownPeruFilling) css_like_styles += "HTMLBrownPeru"; + else if (_filling == HTMLBrownChocolateFilling) css_like_styles += "HTMLBrownChocolate"; + else if (_filling == HTMLBrownSaddleBrownFilling) css_like_styles += "HTMLBrownSaddleBrown"; + else if (_filling == HTMLBrownSiennaFilling) css_like_styles += "HTMLBrownSienna"; + else if (_filling == HTMLBrownBrownFilling) css_like_styles += "HTMLBrownBrown"; + else if (_filling == HTMLBrownMaroonFilling) css_like_styles += "HTMLBrownMaroon"; + else if (_filling == HTMLGreenDarkOliveGreenFilling) css_like_styles += "HTMLGreenDarkOliveGreen"; + else if (_filling == HTMLGreenOliveFilling) css_like_styles += "HTMLGreenOlive"; + else if (_filling == HTMLGreenOliveDrabFilling) css_like_styles += "HTMLGreenOliveDrab"; + else if (_filling == HTMLGreenYellowGreenFilling) css_like_styles += "HTMLGreenYellowGreen"; + else if (_filling == HTMLGreenLimeGreenFilling) css_like_styles += "HTMLGreenLimeGreen"; + else if (_filling == HTMLGreenLimeFilling) css_like_styles += "HTMLGreenLime"; + else if (_filling == HTMLGreenLawnGreenFilling) css_like_styles += "HTMLGreenLawnGreen"; + else if (_filling == HTMLGreenChartreuseFilling) css_like_styles += "HTMLGreenChartreuse"; + else if (_filling == HTMLGreenGreenYellowFilling) css_like_styles += "HTMLGreenGreenYellow"; + else if (_filling == HTMLGreenSpringGreenFilling) css_like_styles += "HTMLGreenSpringGreen"; + else if (_filling == HTMLGreenMediumSpringGreenFilling) css_like_styles += "HTMLGreenMediumSpringGreen"; + else if (_filling == HTMLGreenLightGreenFilling) css_like_styles += "HTMLGreenLightGreen"; + else if (_filling == HTMLGreenPaleGreenFilling) css_like_styles += "HTMLGreenPaleGreen"; + else if (_filling == HTMLGreenDarkSeaGreenFilling) css_like_styles += "HTMLGreenDarkSeaGreen"; + else if (_filling == HTMLGreenMediumAquamarineFilling) css_like_styles += "HTMLGreenMediumAquamarine"; + else if (_filling == HTMLGreenMediumSeaGreenFilling) css_like_styles += "HTMLGreenMediumSeaGreen"; + else if (_filling == HTMLGreenSeaGreenFilling) css_like_styles += "HTMLGreenSeaGreen"; + else if (_filling == HTMLGreenForestGreenFilling) css_like_styles += "HTMLGreenForestGreen"; + else if (_filling == HTMLGreenGreenFilling) css_like_styles += "HTMLGreenGreen"; + else if (_filling == HTMLGreenDarkGreenFilling) css_like_styles += "HTMLGreenDarkGreen"; + else if (_filling == HTMLCyanAquaFilling) css_like_styles += "HTMLCyanAqua"; + else if (_filling == HTMLCyanCyanFilling) css_like_styles += "HTMLCyanCyan"; + else if (_filling == HTMLCyanLightCyanFilling) css_like_styles += "HTMLCyanLightCyan"; + else if (_filling == HTMLCyanPaleTurquoiseFilling) css_like_styles += "HTMLCyanPaleTurquoise"; + else if (_filling == HTMLCyanAquamarineFilling) css_like_styles += "HTMLCyanAquamarine"; + else if (_filling == HTMLCyanTurquoiseFilling) css_like_styles += "HTMLCyanTurquoise"; + else if (_filling == HTMLCyanMediumTurquoiseFilling) css_like_styles += "HTMLCyanMediumTurquoise"; + else if (_filling == HTMLCyanDarkTurquoiseFilling) css_like_styles += "HTMLCyanDarkTurquoise"; + else if (_filling == HTMLCyanLightSeaGreenFilling) css_like_styles += "HTMLCyanLightSeaGreen"; + else if (_filling == HTMLCyanCadetBlueFilling) css_like_styles += "HTMLCyanCadetBlue"; + else if (_filling == HTMLCyanDarkCyanFilling) css_like_styles += "HTMLCyanDarkCyan"; + else if (_filling == HTMLCyanTealFilling) css_like_styles += "HTMLCyanTeal"; + else if (_filling == HTMLBlueLightSteelBlueFilling) css_like_styles += "HTMLBlueLightSteelBlue"; + else if (_filling == HTMLBluePowderBlueFilling) css_like_styles += "HTMLBluePowderBlue"; + else if (_filling == HTMLBlueLightBlueFilling) css_like_styles += "HTMLBlueLightBlue"; + else if (_filling == HTMLBlueSkyBlueFilling) css_like_styles += "HTMLBlueSkyBlue"; + else if (_filling == HTMLBlueLightSkyBlueFilling) css_like_styles += "HTMLBlueLightSkyBlue"; + else if (_filling == HTMLBlueDeepSkyBlueFilling) css_like_styles += "HTMLBlueDeepSkyBlue"; + else if (_filling == HTMLBlueDodgerBlueFilling) css_like_styles += "HTMLBlueDodgerBlue"; + else if (_filling == HTMLBlueCornflowerBlueFilling) css_like_styles += "HTMLBlueCornflowerBlue"; + else if (_filling == HTMLBlueSteelBlueFilling) css_like_styles += "HTMLBlueSteelBlue"; + else if (_filling == HTMLBlueRoyalBlueFilling) css_like_styles += "HTMLBlueRoyalBlue"; + else if (_filling == HTMLBlueBlueFilling) css_like_styles += "HTMLBlueBlue"; + else if (_filling == HTMLBlueMediumBlueFilling) css_like_styles += "HTMLBlueMediumBlue"; + else if (_filling == HTMLBlueDarkBlueFilling) css_like_styles += "HTMLBlueDarkBlue"; + else if (_filling == HTMLBlueNavyFilling) css_like_styles += "HTMLBlueNavy"; + else if (_filling == HTMLBlueMidnightBlueFilling) css_like_styles += "HTMLBlueMidnightBlue"; + else if (_filling == HTMLPurpleLavenderFilling) css_like_styles += "HTMLPurpleLavender"; + else if (_filling == HTMLPurpleThistleFilling) css_like_styles += "HTMLPurpleThistle"; + else if (_filling == HTMLPurplePlumFilling) css_like_styles += "HTMLPurplePlum"; + else if (_filling == HTMLPurpleVioletFilling) css_like_styles += "HTMLPurpleViolet"; + else if (_filling == HTMLPurpleOrchidFilling) css_like_styles += "HTMLPurpleOrchid"; + else if (_filling == HTMLPurpleFuchsiaFilling) css_like_styles += "HTMLPurpleFuchsia"; + else if (_filling == HTMLPurpleMagentaFilling) css_like_styles += "HTMLPurpleMagenta"; + else if (_filling == HTMLPurpleMediumOrchidFilling) css_like_styles += "HTMLPurpleMediumOrchid"; + else if (_filling == HTMLPurpleMediumPurpleFilling) css_like_styles += "HTMLPurpleMediumPurple"; + else if (_filling == HTMLPurpleBlueVioletFilling) css_like_styles += "HTMLPurpleBlueViolet"; + else if (_filling == HTMLPurpleDarkVioletFilling) css_like_styles += "HTMLPurpleDarkViolet"; + else if (_filling == HTMLPurpleDarkOrchidFilling) css_like_styles += "HTMLPurpleDarkOrchid"; + else if (_filling == HTMLPurpleDarkMagentaFilling) css_like_styles += "HTMLPurpleDarkMagenta"; + else if (_filling == HTMLPurplePurpleFilling) css_like_styles += "HTMLPurplePurple"; + else if (_filling == HTMLPurpleIndigoFilling) css_like_styles += "HTMLPurpleIndigo"; + else if (_filling == HTMLPurpleDarkSlateBlueFilling) css_like_styles += "HTMLPurpleDarkSlateBlue"; + else if (_filling == HTMLPurpleSlateBlueFilling) css_like_styles += "HTMLPurpleSlateBlue"; + else if (_filling == HTMLPurpleMediumSlateBlueFilling) css_like_styles += "HTMLPurpleMediumSlateBlue"; + else if (_filling == HTMLWhiteWhiteFilling) css_like_styles += "HTMLWhiteWhite"; + else if (_filling == HTMLWhiteSnowFilling) css_like_styles += "HTMLWhiteSnow"; + else if (_filling == HTMLWhiteHoneydewFilling) css_like_styles += "HTMLWhiteHoneydew"; + else if (_filling == HTMLWhiteMintCreamFilling) css_like_styles += "HTMLWhiteMintCream"; + else if (_filling == HTMLWhiteAzureFilling) css_like_styles += "HTMLWhiteAzure"; + else if (_filling == HTMLWhiteAliceBlueFilling) css_like_styles += "HTMLWhiteAliceBlue"; + else if (_filling == HTMLWhiteGhostWhiteFilling) css_like_styles += "HTMLWhiteGhostWhite"; + else if (_filling == HTMLWhiteWhiteSmokeFilling) css_like_styles += "HTMLWhiteWhiteSmoke"; + else if (_filling == HTMLWhiteSeashellFilling) css_like_styles += "HTMLWhiteSeashell"; + else if (_filling == HTMLWhiteBeigeFilling) css_like_styles += "HTMLWhiteBeige"; + else if (_filling == HTMLWhiteOldLaceFilling) css_like_styles += "HTMLWhiteOldLace"; + else if (_filling == HTMLWhiteFloralWhiteFilling) css_like_styles += "HTMLWhiteFloralWhite"; + else if (_filling == HTMLWhiteIvoryFilling) css_like_styles += "HTMLWhiteIvory"; + else if (_filling == HTMLWhiteAntiqueWhiteFilling) css_like_styles += "HTMLWhiteAntiqueWhite"; + else if (_filling == HTMLWhiteLinenFilling) css_like_styles += "HTMLWhiteLinen"; + else if (_filling == HTMLWhiteLavenderBlushFilling) css_like_styles += "HTMLWhiteLavenderBlush"; + else if (_filling == HTMLWhiteMistyRoseFilling) css_like_styles += "HTMLWhiteMistyRose"; + else if (_filling == HTMLGrayGainsboroFilling) css_like_styles += "HTMLGrayGainsboro"; + else if (_filling == HTMLGrayLightGrayFilling) css_like_styles += "HTMLGrayLightGray"; + else if (_filling == HTMLGraySilverFilling) css_like_styles += "HTMLGraySilver"; + else if (_filling == HTMLGrayDarkGrayFilling) css_like_styles += "HTMLGrayDarkGray"; + else if (_filling == HTMLGrayGrayFilling) css_like_styles += "HTMLGrayGray"; + else if (_filling == HTMLGrayDimGrayFilling) css_like_styles += "HTMLGrayDimGray"; + else if (_filling == HTMLGrayLightSlateGrayFilling) css_like_styles += "HTMLGrayLightSlateGray"; + else if (_filling == HTMLGraySlateGrayFilling) css_like_styles += "HTMLGraySlateGray"; + else if (_filling == HTMLGrayDarkSlateGrayFilling) css_like_styles += "HTMLGrayDarkSlateGray"; + else if (_filling == HTMLGrayBlackFilling) css_like_styles += "HTMLGrayBlack"; + else if (_filling == HorFilling) css_like_styles += "hor"; + else if (_filling == VerFilling) css_like_styles += "ver"; + else if (_filling == BdiagFilling) css_like_styles += "bdiag"; + else if (_filling == FdiagFilling) css_like_styles += "fdiag"; - css_like_styles += ";color:"; - if (_color == WhiteColor) css_like_styles += "white"; - else if (_color == BlackColor) css_like_styles += "black"; - else if (_color == GreenColor) css_like_styles += "green"; - else if (_color == RedColor) css_like_styles += "red"; - else if (_color == BlueColor) css_like_styles += "blue"; - else if (_color == GrayColor) css_like_styles += "gray"; - else if (_color == BrunColor) css_like_styles += "brun"; - else if (_color == YellowColor) css_like_styles += "yellow"; - else if (_color == CyanColor) css_like_styles += "cyan"; - else if (_color == MagentaColor) css_like_styles += "magenta"; - else if (_color == LightgrayColor) css_like_styles += "lightgray"; - else if (_color == OrangeColor) css_like_styles += "orange"; - else if (_color == PurpleColor) css_like_styles += "purple"; - else if (_color == HTMLPinkPinkColor) css_like_styles += "HTMLPinkPink"; - else if (_color == HTMLPinkLightPinkColor) css_like_styles += "HTMLPinkLightPink"; - else if (_color == HTMLPinkHotPinkColor) css_like_styles += "HTMLPinkHotPink"; - else if (_color == HTMLPinkDeepPinkColor) css_like_styles += "HTMLPinkDeepPink"; - else if (_color == HTMLPinkPaleVioletRedColor) css_like_styles += "HTMLPinkPaleVioletRed"; - else if (_color == HTMLPinkMediumVioletRedColor) css_like_styles += "HTMLPinkMediumVioletRed"; - else if (_color == HTMLRedLightSalmonColor) css_like_styles += "HTMLRedLightSalmon"; - else if (_color == HTMLRedSalmonColor) css_like_styles += "HTMLRedSalmon"; - else if (_color == HTMLRedDarkSalmonColor) css_like_styles += "HTMLRedDarkSalmon"; - else if (_color == HTMLRedLightCoralColor) css_like_styles += "HTMLRedLightCoral"; - else if (_color == HTMLRedIndianRedColor) css_like_styles += "HTMLRedIndianRed"; - else if (_color == HTMLRedCrimsonColor) css_like_styles += "HTMLRedCrimson"; - else if (_color == HTMLRedFirebrickColor) css_like_styles += "HTMLRedFirebrick"; - else if (_color == HTMLRedDarkRedColor) css_like_styles += "HTMLRedDarkRed"; - else if (_color == HTMLRedRedColor) css_like_styles += "HTMLRedRed"; - else if (_color == HTMLOrangeOrangeRedColor) css_like_styles += "HTMLOrangeOrangeRed"; - else if (_color == HTMLOrangeTomatoColor) css_like_styles += "HTMLOrangeTomato"; - else if (_color == HTMLOrangeCoralColor) css_like_styles += "HTMLOrangeCoral"; - else if (_color == HTMLOrangeDarkOrangeColor) css_like_styles += "HTMLOrangeDarkOrange"; - else if (_color == HTMLOrangeOrangeColor) css_like_styles += "HTMLOrangeOrange"; - else if (_color == HTMLYellowYellowColor) css_like_styles += "HTMLYellowYellow"; - else if (_color == HTMLYellowLightYellowColor) css_like_styles += "HTMLYellowLightYellow"; - else if (_color == HTMLYellowLemonChiffonColor) css_like_styles += "HTMLYellowLemonChiffon"; - else if (_color == HTMLYellowLightGoldenrodYellowColor) css_like_styles += "HTMLYellowLightGoldenrodYellow"; - else if (_color == HTMLYellowPapayaWhipColor) css_like_styles += "HTMLYellowPapayaWhip"; - else if (_color == HTMLYellowMoccasinColor) css_like_styles += "HTMLYellowMoccasin"; - else if (_color == HTMLYellowPeachPuffColor) css_like_styles += "HTMLYellowPeachPuff"; - else if (_color == HTMLYellowPaleGoldenrodColor) css_like_styles += "HTMLYellowPaleGoldenrod"; - else if (_color == HTMLYellowKhakiColor) css_like_styles += "HTMLYellowKhaki"; - else if (_color == HTMLYellowDarkKhakiColor) css_like_styles += "HTMLYellowDarkKhaki"; - else if (_color == HTMLYellowGoldColor) css_like_styles += "HTMLYellowGold"; - else if (_color == HTMLBrownCornsilkColor) css_like_styles += "HTMLBrownCornsilk"; - else if (_color == HTMLBrownBlanchedAlmondColor) css_like_styles += "HTMLBrownBlanchedAlmond"; - else if (_color == HTMLBrownBisqueColor) css_like_styles += "HTMLBrownBisque"; - else if (_color == HTMLBrownNavajoWhiteColor) css_like_styles += "HTMLBrownNavajoWhite"; - else if (_color == HTMLBrownWheatColor) css_like_styles += "HTMLBrownWheat"; - else if (_color == HTMLBrownBurlywoodColor) css_like_styles += "HTMLBrownBurlywood"; - else if (_color == HTMLBrownTanColor) css_like_styles += "HTMLBrownTan"; - else if (_color == HTMLBrownRosyBrownColor) css_like_styles += "HTMLBrownRosyBrown"; - else if (_color == HTMLBrownSandyBrownColor) css_like_styles += "HTMLBrownSandyBrown"; - else if (_color == HTMLBrownGoldenrodColor) css_like_styles += "HTMLBrownGoldenrod"; - else if (_color == HTMLBrownDarkGoldenrodColor) css_like_styles += "HTMLBrownDarkGoldenrod"; - else if (_color == HTMLBrownPeruColor) css_like_styles += "HTMLBrownPeru"; - else if (_color == HTMLBrownChocolateColor) css_like_styles += "HTMLBrownChocolate"; - else if (_color == HTMLBrownSaddleBrownColor) css_like_styles += "HTMLBrownSaddleBrown"; - else if (_color == HTMLBrownSiennaColor) css_like_styles += "HTMLBrownSienna"; - else if (_color == HTMLBrownBrownColor) css_like_styles += "HTMLBrownBrown"; - else if (_color == HTMLBrownMaroonColor) css_like_styles += "HTMLBrownMaroon"; - else if (_color == HTMLGreenDarkOliveGreenColor) css_like_styles += "HTMLGreenDarkOliveGreen"; - else if (_color == HTMLGreenOliveColor) css_like_styles += "HTMLGreenOlive"; - else if (_color == HTMLGreenOliveDrabColor) css_like_styles += "HTMLGreenOliveDrab"; - else if (_color == HTMLGreenYellowGreenColor) css_like_styles += "HTMLGreenYellowGreen"; - else if (_color == HTMLGreenLimeGreenColor) css_like_styles += "HTMLGreenLimeGreen"; - else if (_color == HTMLGreenLimeColor) css_like_styles += "HTMLGreenLime"; - else if (_color == HTMLGreenLawnGreenColor) css_like_styles += "HTMLGreenLawnGreen"; - else if (_color == HTMLGreenChartreuseColor) css_like_styles += "HTMLGreenChartreuse"; - else if (_color == HTMLGreenGreenYellowColor) css_like_styles += "HTMLGreenGreenYellow"; - else if (_color == HTMLGreenSpringGreenColor) css_like_styles += "HTMLGreenSpringGreen"; - else if (_color == HTMLGreenMediumSpringGreenColor) css_like_styles += "HTMLGreenMediumSpringGreen"; - else if (_color == HTMLGreenLightGreenColor) css_like_styles += "HTMLGreenLightGreen"; - else if (_color == HTMLGreenPaleGreenColor) css_like_styles += "HTMLGreenPaleGreen"; - else if (_color == HTMLGreenDarkSeaGreenColor) css_like_styles += "HTMLGreenDarkSeaGreen"; - else if (_color == HTMLGreenMediumAquamarineColor) css_like_styles += "HTMLGreenMediumAquamarine"; - else if (_color == HTMLGreenMediumSeaGreenColor) css_like_styles += "HTMLGreenMediumSeaGreen"; - else if (_color == HTMLGreenSeaGreenColor) css_like_styles += "HTMLGreenSeaGreen"; - else if (_color == HTMLGreenForestGreenColor) css_like_styles += "HTMLGreenForestGreen"; - else if (_color == HTMLGreenGreenColor) css_like_styles += "HTMLGreenGreen"; - else if (_color == HTMLGreenDarkGreenColor) css_like_styles += "HTMLGreenDarkGreen"; - else if (_color == HTMLCyanAquaColor) css_like_styles += "HTMLCyanAqua"; - else if (_color == HTMLCyanCyanColor) css_like_styles += "HTMLCyanCyan"; - else if (_color == HTMLCyanLightCyanColor) css_like_styles += "HTMLCyanLightCyan"; - else if (_color == HTMLCyanPaleTurquoiseColor) css_like_styles += "HTMLCyanPaleTurquoise"; - else if (_color == HTMLCyanAquamarineColor) css_like_styles += "HTMLCyanAquamarine"; - else if (_color == HTMLCyanTurquoiseColor) css_like_styles += "HTMLCyanTurquoise"; - else if (_color == HTMLCyanMediumTurquoiseColor) css_like_styles += "HTMLCyanMediumTurquoise"; - else if (_color == HTMLCyanDarkTurquoiseColor) css_like_styles += "HTMLCyanDarkTurquoise"; - else if (_color == HTMLCyanLightSeaGreenColor) css_like_styles += "HTMLCyanLightSeaGreen"; - else if (_color == HTMLCyanCadetBlueColor) css_like_styles += "HTMLCyanCadetBlue"; - else if (_color == HTMLCyanDarkCyanColor) css_like_styles += "HTMLCyanDarkCyan"; - else if (_color == HTMLCyanTealColor) css_like_styles += "HTMLCyanTeal"; - else if (_color == HTMLBlueLightSteelBlueColor) css_like_styles += "HTMLBlueLightSteelBlue"; - else if (_color == HTMLBluePowderBlueColor) css_like_styles += "HTMLBluePowderBlue"; - else if (_color == HTMLBlueLightBlueColor) css_like_styles += "HTMLBlueLightBlue"; - else if (_color == HTMLBlueSkyBlueColor) css_like_styles += "HTMLBlueSkyBlue"; - else if (_color == HTMLBlueLightSkyBlueColor) css_like_styles += "HTMLBlueLightSkyBlue"; - else if (_color == HTMLBlueDeepSkyBlueColor) css_like_styles += "HTMLBlueDeepSkyBlue"; - else if (_color == HTMLBlueDodgerBlueColor) css_like_styles += "HTMLBlueDodgerBlue"; - else if (_color == HTMLBlueCornflowerBlueColor) css_like_styles += "HTMLBlueCornflowerBlue"; - else if (_color == HTMLBlueSteelBlueColor) css_like_styles += "HTMLBlueSteelBlue"; - else if (_color == HTMLBlueRoyalBlueColor) css_like_styles += "HTMLBlueRoyalBlue"; - else if (_color == HTMLBlueBlueColor) css_like_styles += "HTMLBlueBlue"; - else if (_color == HTMLBlueMediumBlueColor) css_like_styles += "HTMLBlueMediumBlue"; - else if (_color == HTMLBlueDarkBlueColor) css_like_styles += "HTMLBlueDarkBlue"; - else if (_color == HTMLBlueNavyColor) css_like_styles += "HTMLBlueNavy"; - else if (_color == HTMLBlueMidnightBlueColor) css_like_styles += "HTMLBlueMidnightBlue"; - else if (_color == HTMLPurpleLavenderColor) css_like_styles += "HTMLPurpleLavender"; - else if (_color == HTMLPurpleThistleColor) css_like_styles += "HTMLPurpleThistle"; - else if (_color == HTMLPurplePlumColor) css_like_styles += "HTMLPurplePlum"; - else if (_color == HTMLPurpleVioletColor) css_like_styles += "HTMLPurpleViolet"; - else if (_color == HTMLPurpleOrchidColor) css_like_styles += "HTMLPurpleOrchid"; - else if (_color == HTMLPurpleFuchsiaColor) css_like_styles += "HTMLPurpleFuchsia"; - else if (_color == HTMLPurpleMagentaColor) css_like_styles += "HTMLPurpleMagenta"; - else if (_color == HTMLPurpleMediumOrchidColor) css_like_styles += "HTMLPurpleMediumOrchid"; - else if (_color == HTMLPurpleMediumPurpleColor) css_like_styles += "HTMLPurpleMediumPurple"; - else if (_color == HTMLPurpleBlueVioletColor) css_like_styles += "HTMLPurpleBlueViolet"; - else if (_color == HTMLPurpleDarkVioletColor) css_like_styles += "HTMLPurpleDarkViolet"; - else if (_color == HTMLPurpleDarkOrchidColor) css_like_styles += "HTMLPurpleDarkOrchid"; - else if (_color == HTMLPurpleDarkMagentaColor) css_like_styles += "HTMLPurpleDarkMagenta"; - else if (_color == HTMLPurplePurpleColor) css_like_styles += "HTMLPurplePurple"; - else if (_color == HTMLPurpleIndigoColor) css_like_styles += "HTMLPurpleIndigo"; - else if (_color == HTMLPurpleDarkSlateBlueColor) css_like_styles += "HTMLPurpleDarkSlateBlue"; - else if (_color == HTMLPurpleSlateBlueColor) css_like_styles += "HTMLPurpleSlateBlue"; - else if (_color == HTMLPurpleMediumSlateBlueColor) css_like_styles += "HTMLPurpleMediumSlateBlue"; - else if (_color == HTMLWhiteWhiteColor) css_like_styles += "HTMLWhiteWhite"; - else if (_color == HTMLWhiteSnowColor) css_like_styles += "HTMLWhiteSnow"; - else if (_color == HTMLWhiteHoneydewColor) css_like_styles += "HTMLWhiteHoneydew"; - else if (_color == HTMLWhiteMintCreamColor) css_like_styles += "HTMLWhiteMintCream"; - else if (_color == HTMLWhiteAzureColor) css_like_styles += "HTMLWhiteAzure"; - else if (_color == HTMLWhiteAliceBlueColor) css_like_styles += "HTMLWhiteAliceBlue"; - else if (_color == HTMLWhiteGhostWhiteColor) css_like_styles += "HTMLWhiteGhostWhite"; - else if (_color == HTMLWhiteWhiteSmokeColor) css_like_styles += "HTMLWhiteWhiteSmoke"; - else if (_color == HTMLWhiteSeashellColor) css_like_styles += "HTMLWhiteSeashell"; - else if (_color == HTMLWhiteBeigeColor) css_like_styles += "HTMLWhiteBeige"; - else if (_color == HTMLWhiteOldLaceColor) css_like_styles += "HTMLWhiteOldLace"; - else if (_color == HTMLWhiteFloralWhiteColor) css_like_styles += "HTMLWhiteFloralWhite"; - else if (_color == HTMLWhiteIvoryColor) css_like_styles += "HTMLWhiteIvory"; - else if (_color == HTMLWhiteAntiqueWhiteColor) css_like_styles += "HTMLWhiteAntiqueWhite"; - else if (_color == HTMLWhiteLinenColor) css_like_styles += "HTMLWhiteLinen"; - else if (_color == HTMLWhiteLavenderBlushColor) css_like_styles += "HTMLWhiteLavenderBlush"; - else if (_color == HTMLWhiteMistyRoseColor) css_like_styles += "HTMLWhiteMistyRose"; - else if (_color == HTMLGrayGainsboroColor) css_like_styles += "HTMLGrayGainsboro"; - else if (_color == HTMLGrayLightGrayColor) css_like_styles += "HTMLGrayLightGray"; - else if (_color == HTMLGraySilverColor) css_like_styles += "HTMLGraySilver"; - else if (_color == HTMLGrayDarkGrayColor) css_like_styles += "HTMLGrayDarkGray"; - else if (_color == HTMLGrayGrayColor) css_like_styles += "HTMLGrayGray"; - else if (_color == HTMLGrayDimGrayColor) css_like_styles += "HTMLGrayDimGray"; - else if (_color == HTMLGrayLightSlateGrayColor) css_like_styles += "HTMLGrayLightSlateGray"; - else if (_color == HTMLGraySlateGrayColor) css_like_styles += "HTMLGraySlateGray"; - else if (_color == HTMLGrayDarkSlateGrayColor) css_like_styles += "HTMLGrayDarkSlateGray"; - else if (_color == HTMLGrayBlackColor) css_like_styles += "HTMLGrayBlack"; - else if (_color == NoneColor) css_like_styles += "none"; + css_like_styles += ";color:"; + if (_color == WhiteColor) css_like_styles += "white"; + else if (_color == BlackColor) css_like_styles += "black"; + else if (_color == GreenColor) css_like_styles += "green"; + else if (_color == RedColor) css_like_styles += "red"; + else if (_color == BlueColor) css_like_styles += "blue"; + else if (_color == GrayColor) css_like_styles += "gray"; + else if (_color == BrunColor) css_like_styles += "brun"; + else if (_color == YellowColor) css_like_styles += "yellow"; + else if (_color == CyanColor) css_like_styles += "cyan"; + else if (_color == MagentaColor) css_like_styles += "magenta"; + else if (_color == LightgrayColor) css_like_styles += "lightgray"; + else if (_color == OrangeColor) css_like_styles += "orange"; + else if (_color == PurpleColor) css_like_styles += "purple"; + else if (_color == HTMLPinkPinkColor) css_like_styles += "HTMLPinkPink"; + else if (_color == HTMLPinkLightPinkColor) css_like_styles += "HTMLPinkLightPink"; + else if (_color == HTMLPinkHotPinkColor) css_like_styles += "HTMLPinkHotPink"; + else if (_color == HTMLPinkDeepPinkColor) css_like_styles += "HTMLPinkDeepPink"; + else if (_color == HTMLPinkPaleVioletRedColor) css_like_styles += "HTMLPinkPaleVioletRed"; + else if (_color == HTMLPinkMediumVioletRedColor) css_like_styles += "HTMLPinkMediumVioletRed"; + else if (_color == HTMLRedLightSalmonColor) css_like_styles += "HTMLRedLightSalmon"; + else if (_color == HTMLRedSalmonColor) css_like_styles += "HTMLRedSalmon"; + else if (_color == HTMLRedDarkSalmonColor) css_like_styles += "HTMLRedDarkSalmon"; + else if (_color == HTMLRedLightCoralColor) css_like_styles += "HTMLRedLightCoral"; + else if (_color == HTMLRedIndianRedColor) css_like_styles += "HTMLRedIndianRed"; + else if (_color == HTMLRedCrimsonColor) css_like_styles += "HTMLRedCrimson"; + else if (_color == HTMLRedFirebrickColor) css_like_styles += "HTMLRedFirebrick"; + else if (_color == HTMLRedDarkRedColor) css_like_styles += "HTMLRedDarkRed"; + else if (_color == HTMLRedRedColor) css_like_styles += "HTMLRedRed"; + else if (_color == HTMLOrangeOrangeRedColor) css_like_styles += "HTMLOrangeOrangeRed"; + else if (_color == HTMLOrangeTomatoColor) css_like_styles += "HTMLOrangeTomato"; + else if (_color == HTMLOrangeCoralColor) css_like_styles += "HTMLOrangeCoral"; + else if (_color == HTMLOrangeDarkOrangeColor) css_like_styles += "HTMLOrangeDarkOrange"; + else if (_color == HTMLOrangeOrangeColor) css_like_styles += "HTMLOrangeOrange"; + else if (_color == HTMLYellowYellowColor) css_like_styles += "HTMLYellowYellow"; + else if (_color == HTMLYellowLightYellowColor) css_like_styles += "HTMLYellowLightYellow"; + else if (_color == HTMLYellowLemonChiffonColor) css_like_styles += "HTMLYellowLemonChiffon"; + else if (_color == HTMLYellowLightGoldenrodYellowColor) css_like_styles += "HTMLYellowLightGoldenrodYellow"; + else if (_color == HTMLYellowPapayaWhipColor) css_like_styles += "HTMLYellowPapayaWhip"; + else if (_color == HTMLYellowMoccasinColor) css_like_styles += "HTMLYellowMoccasin"; + else if (_color == HTMLYellowPeachPuffColor) css_like_styles += "HTMLYellowPeachPuff"; + else if (_color == HTMLYellowPaleGoldenrodColor) css_like_styles += "HTMLYellowPaleGoldenrod"; + else if (_color == HTMLYellowKhakiColor) css_like_styles += "HTMLYellowKhaki"; + else if (_color == HTMLYellowDarkKhakiColor) css_like_styles += "HTMLYellowDarkKhaki"; + else if (_color == HTMLYellowGoldColor) css_like_styles += "HTMLYellowGold"; + else if (_color == HTMLBrownCornsilkColor) css_like_styles += "HTMLBrownCornsilk"; + else if (_color == HTMLBrownBlanchedAlmondColor) css_like_styles += "HTMLBrownBlanchedAlmond"; + else if (_color == HTMLBrownBisqueColor) css_like_styles += "HTMLBrownBisque"; + else if (_color == HTMLBrownNavajoWhiteColor) css_like_styles += "HTMLBrownNavajoWhite"; + else if (_color == HTMLBrownWheatColor) css_like_styles += "HTMLBrownWheat"; + else if (_color == HTMLBrownBurlywoodColor) css_like_styles += "HTMLBrownBurlywood"; + else if (_color == HTMLBrownTanColor) css_like_styles += "HTMLBrownTan"; + else if (_color == HTMLBrownRosyBrownColor) css_like_styles += "HTMLBrownRosyBrown"; + else if (_color == HTMLBrownSandyBrownColor) css_like_styles += "HTMLBrownSandyBrown"; + else if (_color == HTMLBrownGoldenrodColor) css_like_styles += "HTMLBrownGoldenrod"; + else if (_color == HTMLBrownDarkGoldenrodColor) css_like_styles += "HTMLBrownDarkGoldenrod"; + else if (_color == HTMLBrownPeruColor) css_like_styles += "HTMLBrownPeru"; + else if (_color == HTMLBrownChocolateColor) css_like_styles += "HTMLBrownChocolate"; + else if (_color == HTMLBrownSaddleBrownColor) css_like_styles += "HTMLBrownSaddleBrown"; + else if (_color == HTMLBrownSiennaColor) css_like_styles += "HTMLBrownSienna"; + else if (_color == HTMLBrownBrownColor) css_like_styles += "HTMLBrownBrown"; + else if (_color == HTMLBrownMaroonColor) css_like_styles += "HTMLBrownMaroon"; + else if (_color == HTMLGreenDarkOliveGreenColor) css_like_styles += "HTMLGreenDarkOliveGreen"; + else if (_color == HTMLGreenOliveColor) css_like_styles += "HTMLGreenOlive"; + else if (_color == HTMLGreenOliveDrabColor) css_like_styles += "HTMLGreenOliveDrab"; + else if (_color == HTMLGreenYellowGreenColor) css_like_styles += "HTMLGreenYellowGreen"; + else if (_color == HTMLGreenLimeGreenColor) css_like_styles += "HTMLGreenLimeGreen"; + else if (_color == HTMLGreenLimeColor) css_like_styles += "HTMLGreenLime"; + else if (_color == HTMLGreenLawnGreenColor) css_like_styles += "HTMLGreenLawnGreen"; + else if (_color == HTMLGreenChartreuseColor) css_like_styles += "HTMLGreenChartreuse"; + else if (_color == HTMLGreenGreenYellowColor) css_like_styles += "HTMLGreenGreenYellow"; + else if (_color == HTMLGreenSpringGreenColor) css_like_styles += "HTMLGreenSpringGreen"; + else if (_color == HTMLGreenMediumSpringGreenColor) css_like_styles += "HTMLGreenMediumSpringGreen"; + else if (_color == HTMLGreenLightGreenColor) css_like_styles += "HTMLGreenLightGreen"; + else if (_color == HTMLGreenPaleGreenColor) css_like_styles += "HTMLGreenPaleGreen"; + else if (_color == HTMLGreenDarkSeaGreenColor) css_like_styles += "HTMLGreenDarkSeaGreen"; + else if (_color == HTMLGreenMediumAquamarineColor) css_like_styles += "HTMLGreenMediumAquamarine"; + else if (_color == HTMLGreenMediumSeaGreenColor) css_like_styles += "HTMLGreenMediumSeaGreen"; + else if (_color == HTMLGreenSeaGreenColor) css_like_styles += "HTMLGreenSeaGreen"; + else if (_color == HTMLGreenForestGreenColor) css_like_styles += "HTMLGreenForestGreen"; + else if (_color == HTMLGreenGreenColor) css_like_styles += "HTMLGreenGreen"; + else if (_color == HTMLGreenDarkGreenColor) css_like_styles += "HTMLGreenDarkGreen"; + else if (_color == HTMLCyanAquaColor) css_like_styles += "HTMLCyanAqua"; + else if (_color == HTMLCyanCyanColor) css_like_styles += "HTMLCyanCyan"; + else if (_color == HTMLCyanLightCyanColor) css_like_styles += "HTMLCyanLightCyan"; + else if (_color == HTMLCyanPaleTurquoiseColor) css_like_styles += "HTMLCyanPaleTurquoise"; + else if (_color == HTMLCyanAquamarineColor) css_like_styles += "HTMLCyanAquamarine"; + else if (_color == HTMLCyanTurquoiseColor) css_like_styles += "HTMLCyanTurquoise"; + else if (_color == HTMLCyanMediumTurquoiseColor) css_like_styles += "HTMLCyanMediumTurquoise"; + else if (_color == HTMLCyanDarkTurquoiseColor) css_like_styles += "HTMLCyanDarkTurquoise"; + else if (_color == HTMLCyanLightSeaGreenColor) css_like_styles += "HTMLCyanLightSeaGreen"; + else if (_color == HTMLCyanCadetBlueColor) css_like_styles += "HTMLCyanCadetBlue"; + else if (_color == HTMLCyanDarkCyanColor) css_like_styles += "HTMLCyanDarkCyan"; + else if (_color == HTMLCyanTealColor) css_like_styles += "HTMLCyanTeal"; + else if (_color == HTMLBlueLightSteelBlueColor) css_like_styles += "HTMLBlueLightSteelBlue"; + else if (_color == HTMLBluePowderBlueColor) css_like_styles += "HTMLBluePowderBlue"; + else if (_color == HTMLBlueLightBlueColor) css_like_styles += "HTMLBlueLightBlue"; + else if (_color == HTMLBlueSkyBlueColor) css_like_styles += "HTMLBlueSkyBlue"; + else if (_color == HTMLBlueLightSkyBlueColor) css_like_styles += "HTMLBlueLightSkyBlue"; + else if (_color == HTMLBlueDeepSkyBlueColor) css_like_styles += "HTMLBlueDeepSkyBlue"; + else if (_color == HTMLBlueDodgerBlueColor) css_like_styles += "HTMLBlueDodgerBlue"; + else if (_color == HTMLBlueCornflowerBlueColor) css_like_styles += "HTMLBlueCornflowerBlue"; + else if (_color == HTMLBlueSteelBlueColor) css_like_styles += "HTMLBlueSteelBlue"; + else if (_color == HTMLBlueRoyalBlueColor) css_like_styles += "HTMLBlueRoyalBlue"; + else if (_color == HTMLBlueBlueColor) css_like_styles += "HTMLBlueBlue"; + else if (_color == HTMLBlueMediumBlueColor) css_like_styles += "HTMLBlueMediumBlue"; + else if (_color == HTMLBlueDarkBlueColor) css_like_styles += "HTMLBlueDarkBlue"; + else if (_color == HTMLBlueNavyColor) css_like_styles += "HTMLBlueNavy"; + else if (_color == HTMLBlueMidnightBlueColor) css_like_styles += "HTMLBlueMidnightBlue"; + else if (_color == HTMLPurpleLavenderColor) css_like_styles += "HTMLPurpleLavender"; + else if (_color == HTMLPurpleThistleColor) css_like_styles += "HTMLPurpleThistle"; + else if (_color == HTMLPurplePlumColor) css_like_styles += "HTMLPurplePlum"; + else if (_color == HTMLPurpleVioletColor) css_like_styles += "HTMLPurpleViolet"; + else if (_color == HTMLPurpleOrchidColor) css_like_styles += "HTMLPurpleOrchid"; + else if (_color == HTMLPurpleFuchsiaColor) css_like_styles += "HTMLPurpleFuchsia"; + else if (_color == HTMLPurpleMagentaColor) css_like_styles += "HTMLPurpleMagenta"; + else if (_color == HTMLPurpleMediumOrchidColor) css_like_styles += "HTMLPurpleMediumOrchid"; + else if (_color == HTMLPurpleMediumPurpleColor) css_like_styles += "HTMLPurpleMediumPurple"; + else if (_color == HTMLPurpleBlueVioletColor) css_like_styles += "HTMLPurpleBlueViolet"; + else if (_color == HTMLPurpleDarkVioletColor) css_like_styles += "HTMLPurpleDarkViolet"; + else if (_color == HTMLPurpleDarkOrchidColor) css_like_styles += "HTMLPurpleDarkOrchid"; + else if (_color == HTMLPurpleDarkMagentaColor) css_like_styles += "HTMLPurpleDarkMagenta"; + else if (_color == HTMLPurplePurpleColor) css_like_styles += "HTMLPurplePurple"; + else if (_color == HTMLPurpleIndigoColor) css_like_styles += "HTMLPurpleIndigo"; + else if (_color == HTMLPurpleDarkSlateBlueColor) css_like_styles += "HTMLPurpleDarkSlateBlue"; + else if (_color == HTMLPurpleSlateBlueColor) css_like_styles += "HTMLPurpleSlateBlue"; + else if (_color == HTMLPurpleMediumSlateBlueColor) css_like_styles += "HTMLPurpleMediumSlateBlue"; + else if (_color == HTMLWhiteWhiteColor) css_like_styles += "HTMLWhiteWhite"; + else if (_color == HTMLWhiteSnowColor) css_like_styles += "HTMLWhiteSnow"; + else if (_color == HTMLWhiteHoneydewColor) css_like_styles += "HTMLWhiteHoneydew"; + else if (_color == HTMLWhiteMintCreamColor) css_like_styles += "HTMLWhiteMintCream"; + else if (_color == HTMLWhiteAzureColor) css_like_styles += "HTMLWhiteAzure"; + else if (_color == HTMLWhiteAliceBlueColor) css_like_styles += "HTMLWhiteAliceBlue"; + else if (_color == HTMLWhiteGhostWhiteColor) css_like_styles += "HTMLWhiteGhostWhite"; + else if (_color == HTMLWhiteWhiteSmokeColor) css_like_styles += "HTMLWhiteWhiteSmoke"; + else if (_color == HTMLWhiteSeashellColor) css_like_styles += "HTMLWhiteSeashell"; + else if (_color == HTMLWhiteBeigeColor) css_like_styles += "HTMLWhiteBeige"; + else if (_color == HTMLWhiteOldLaceColor) css_like_styles += "HTMLWhiteOldLace"; + else if (_color == HTMLWhiteFloralWhiteColor) css_like_styles += "HTMLWhiteFloralWhite"; + else if (_color == HTMLWhiteIvoryColor) css_like_styles += "HTMLWhiteIvory"; + else if (_color == HTMLWhiteAntiqueWhiteColor) css_like_styles += "HTMLWhiteAntiqueWhite"; + else if (_color == HTMLWhiteLinenColor) css_like_styles += "HTMLWhiteLinen"; + else if (_color == HTMLWhiteLavenderBlushColor) css_like_styles += "HTMLWhiteLavenderBlush"; + else if (_color == HTMLWhiteMistyRoseColor) css_like_styles += "HTMLWhiteMistyRose"; + else if (_color == HTMLGrayGainsboroColor) css_like_styles += "HTMLGrayGainsboro"; + else if (_color == HTMLGrayLightGrayColor) css_like_styles += "HTMLGrayLightGray"; + else if (_color == HTMLGraySilverColor) css_like_styles += "HTMLGraySilver"; + else if (_color == HTMLGrayDarkGrayColor) css_like_styles += "HTMLGrayDarkGray"; + else if (_color == HTMLGrayGrayColor) css_like_styles += "HTMLGrayGray"; + else if (_color == HTMLGrayDimGrayColor) css_like_styles += "HTMLGrayDimGray"; + else if (_color == HTMLGrayLightSlateGrayColor) css_like_styles += "HTMLGrayLightSlateGray"; + else if (_color == HTMLGraySlateGrayColor) css_like_styles += "HTMLGraySlateGray"; + else if (_color == HTMLGrayDarkSlateGrayColor) css_like_styles += "HTMLGrayDarkSlateGray"; + else if (_color == HTMLGrayBlackColor) css_like_styles += "HTMLGrayBlack"; + else if (_color == NoneColor) css_like_styles += "none"; - qde.setAttribute("style", css_like_styles); - qde.setAttribute("antialias", _antialiased ? "true" : "false"); + qde.setAttribute("style", css_like_styles); + qde.setAttribute("antialias", _antialiased ? "true" : "false"); } /** - @brief CustomElementGraphicPart::stylesFromXml - Read the style used by this, from a xml element. - @param qde : QDomElement used to read the style + @brief CustomElementGraphicPart::stylesFromXml + Read the style used by this, from a xml element. + @param qde : QDomElement used to read the style */ void CustomElementGraphicPart::stylesFromXml(const QDomElement &qde) { - resetStyles(); + resetStyles(); - //Get the list of pair style/value -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove - QStringList styles = qde.attribute("style").split(";", QString::SkipEmptyParts); + //Get the list of pair style/value +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove + QStringList styles = qde.attribute("style").split(";", QString::SkipEmptyParts); #else #if TODO_LIST #pragma message("@TODO remove code for QT 5.14 or later") #endif - QStringList styles = qde.attribute("style").split(";", Qt::SkipEmptyParts); + QStringList styles = qde.attribute("style").split(";", Qt::SkipEmptyParts); #endif //Check each pair of style @@ -873,466 +873,466 @@ void CustomElementGraphicPart::stylesFromXml(const QDomElement &qde) /** - @brief CustomElementGraphicPart::resetStyles - Reset the curent style to default, - same style of default constructor + @brief CustomElementGraphicPart::resetStyles + Reset the curent style to default, + same style of default constructor */ void CustomElementGraphicPart::resetStyles() { - _linestyle = NormalStyle; - _lineweight = NormalWeight; - _filling = NoneFilling; - _color = BlackColor; - _antialiased = false; + _linestyle = NormalStyle; + _lineweight = NormalWeight; + _filling = NoneFilling; + _color = BlackColor; + _antialiased = false; } /** - @brief CustomElementGraphicPart::applyStylesToQPainter - Apply the current style to the QPainter - @param painter + @brief CustomElementGraphicPart::applyStylesToQPainter + Apply the current style to the QPainter + @param painter */ void CustomElementGraphicPart::applyStylesToQPainter(QPainter &painter) const { - //Get the pen and brush - QPen pen = painter.pen(); - QBrush brush = painter.brush(); + //Get the pen and brush + QPen pen = painter.pen(); + QBrush brush = painter.brush(); - //Apply pen style - if (_linestyle == DashedStyle) pen.setStyle(Qt::DashLine); - else if (_linestyle == DashdottedStyle) pen.setStyle(Qt::DashDotLine); - else if (_linestyle == DottedStyle) pen.setStyle(Qt::DotLine); - else if (_linestyle == NormalStyle) pen.setStyle(Qt::SolidLine); + //Apply pen style + if (_linestyle == DashedStyle) pen.setStyle(Qt::DashLine); + else if (_linestyle == DashdottedStyle) pen.setStyle(Qt::DashDotLine); + else if (_linestyle == DottedStyle) pen.setStyle(Qt::DotLine); + else if (_linestyle == NormalStyle) pen.setStyle(Qt::SolidLine); - //Apply pen width - if (_lineweight == NoneWeight) pen.setColor(QColor(0, 0, 0, 0)); - else if (_lineweight == ThinWeight) pen.setWidth(0); - else if (_lineweight == NormalWeight) pen.setWidthF(1.0); - else if (_lineweight == UltraWeight) pen.setWidthF(2.0); - else if (_lineweight == BigWeight) pen.setWidthF(5.0); + //Apply pen width + if (_lineweight == NoneWeight) pen.setColor(QColor(0, 0, 0, 0)); + else if (_lineweight == ThinWeight) pen.setWidth(0); + else if (_lineweight == NormalWeight) pen.setWidthF(1.0); + else if (_lineweight == UltraWeight) pen.setWidthF(2.0); + else if (_lineweight == BigWeight) pen.setWidthF(5.0); - //Apply brush color - if (_filling == NoneFilling) brush.setStyle(Qt::NoBrush); - else if (_filling == HorFilling) brush.setStyle(Qt::HorPattern); - else if (_filling == VerFilling) brush.setStyle(Qt::VerPattern); - else if (_filling == BdiagFilling) brush.setStyle(Qt::BDiagPattern); - else if (_filling == FdiagFilling) brush.setStyle(Qt::FDiagPattern); - else - { - brush.setStyle(Qt::SolidPattern); - if (_filling == BlackFilling) brush.setColor(Qt::black); - else if (_filling == WhiteFilling) brush.setColor(Qt::white); - else if (_filling == GreenFilling) brush.setColor(Qt::green); - else if (_filling == RedFilling) brush.setColor(Qt::red); - else if (_filling == BlueFilling) brush.setColor(Qt::blue); - else if (_filling == GrayFilling) brush.setColor(Qt::gray); - else if (_filling == BrunFilling) brush.setColor(QColor(97, 44, 0)); - else if (_filling == YellowFilling) brush.setColor(Qt::yellow); - else if (_filling == CyanFilling) brush.setColor(Qt::cyan); - else if (_filling == MagentaFilling) brush.setColor(Qt::magenta); - else if (_filling == LightgrayFilling) brush.setColor(Qt::lightGray); - else if (_filling == OrangeFilling) brush.setColor(QColor(255, 128, 0)); - else if (_filling == PurpleFilling) brush.setColor(QColor(136, 28, 168)); - else if (_filling == HTMLPinkPinkFilling) brush.setColor(QColor(255, 192, 203)); - else if (_filling == HTMLPinkLightPinkFilling) brush.setColor(QColor(255, 182, 193)); - else if (_filling == HTMLPinkHotPinkFilling) brush.setColor(QColor(255, 105, 180)); - else if (_filling == HTMLPinkDeepPinkFilling) brush.setColor(QColor(255, 20, 147)); - else if (_filling == HTMLPinkPaleVioletRedFilling) brush.setColor(QColor(219, 112, 147)); - else if (_filling == HTMLPinkMediumVioletRedFilling) brush.setColor(QColor(199, 21, 133)); - else if (_filling == HTMLRedLightSalmonFilling) brush.setColor(QColor(255, 160, 122)); - else if (_filling == HTMLRedSalmonFilling) brush.setColor(QColor(250, 128, 114)); - else if (_filling == HTMLRedDarkSalmonFilling) brush.setColor(QColor(233, 150, 122)); - else if (_filling == HTMLRedLightCoralFilling) brush.setColor(QColor(240, 128, 128)); - else if (_filling == HTMLRedIndianRedFilling) brush.setColor(QColor(205, 92, 92)); - else if (_filling == HTMLRedCrimsonFilling) brush.setColor(QColor(220, 20, 60)); - else if (_filling == HTMLRedFirebrickFilling) brush.setColor(QColor(178, 34, 34)); - else if (_filling == HTMLRedDarkRedFilling) brush.setColor(QColor(139, 0, 0)); - else if (_filling == HTMLRedRedFilling) brush.setColor(QColor(255, 0, 0)); - else if (_filling == HTMLOrangeOrangeRedFilling) brush.setColor(QColor(255, 69, 0)); - else if (_filling == HTMLOrangeTomatoFilling) brush.setColor(QColor(255, 99, 71)); - else if (_filling == HTMLOrangeCoralFilling) brush.setColor(QColor(255, 127, 80)); - else if (_filling == HTMLOrangeDarkOrangeFilling) brush.setColor(QColor(255, 140, 0)); - else if (_filling == HTMLOrangeOrangeFilling) brush.setColor(QColor(255, 165, 0)); - else if (_filling == HTMLYellowYellowFilling) brush.setColor(QColor(255, 255, 0)); - else if (_filling == HTMLYellowLightYellowFilling) brush.setColor(QColor(255, 255, 224)); - else if (_filling == HTMLYellowLemonChiffonFilling) brush.setColor(QColor(255, 250, 205)); - else if (_filling == HTMLYellowLightGoldenrodYellowFilling) brush.setColor(QColor(250, 250, 210)); - else if (_filling == HTMLYellowPapayaWhipFilling) brush.setColor(QColor(255, 239, 213)); - else if (_filling == HTMLYellowMoccasinFilling) brush.setColor(QColor(255, 228, 181)); - else if (_filling == HTMLYellowPeachPuffFilling) brush.setColor(QColor(255, 218, 185)); - else if (_filling == HTMLYellowPaleGoldenrodFilling) brush.setColor(QColor(238, 232, 170)); - else if (_filling == HTMLYellowKhakiFilling) brush.setColor(QColor(240, 230, 140)); - else if (_filling == HTMLYellowDarkKhakiFilling) brush.setColor(QColor(189, 183, 107)); - else if (_filling == HTMLYellowGoldFilling) brush.setColor(QColor(255, 215, 0)); - else if (_filling == HTMLBrownCornsilkFilling) brush.setColor(QColor(255, 248, 220)); - else if (_filling == HTMLBrownBlanchedAlmondFilling) brush.setColor(QColor(255, 235, 205)); - else if (_filling == HTMLBrownBisqueFilling) brush.setColor(QColor(255, 228, 196)); - else if (_filling == HTMLBrownNavajoWhiteFilling) brush.setColor(QColor(255, 222, 173)); - else if (_filling == HTMLBrownWheatFilling) brush.setColor(QColor(245, 222, 179)); - else if (_filling == HTMLBrownBurlywoodFilling) brush.setColor(QColor(222, 184, 135)); - else if (_filling == HTMLBrownTanFilling) brush.setColor(QColor(210, 180, 140)); - else if (_filling == HTMLBrownRosyBrownFilling) brush.setColor(QColor(188, 143, 143)); - else if (_filling == HTMLBrownSandyBrownFilling) brush.setColor(QColor(244, 164, 96)); - else if (_filling == HTMLBrownGoldenrodFilling) brush.setColor(QColor(218, 165, 32)); - else if (_filling == HTMLBrownDarkGoldenrodFilling) brush.setColor(QColor(184, 134, 11)); - else if (_filling == HTMLBrownPeruFilling) brush.setColor(QColor(205, 133, 63)); - else if (_filling == HTMLBrownChocolateFilling) brush.setColor(QColor(210, 105, 30)); - else if (_filling == HTMLBrownSaddleBrownFilling) brush.setColor(QColor(139, 69, 19)); - else if (_filling == HTMLBrownSiennaFilling) brush.setColor(QColor(160, 82, 45)); - else if (_filling == HTMLBrownBrownFilling) brush.setColor(QColor(165, 42, 42)); - else if (_filling == HTMLBrownMaroonFilling) brush.setColor(QColor(128, 0, 0)); - else if (_filling == HTMLGreenDarkOliveGreenFilling) brush.setColor(QColor(85, 107, 47)); - else if (_filling == HTMLGreenOliveFilling) brush.setColor(QColor(128, 128, 0)); - else if (_filling == HTMLGreenOliveDrabFilling) brush.setColor(QColor(107, 142, 35)); - else if (_filling == HTMLGreenYellowGreenFilling) brush.setColor(QColor(154, 205, 50)); - else if (_filling == HTMLGreenLimeGreenFilling) brush.setColor(QColor(50, 205, 50)); - else if (_filling == HTMLGreenLimeFilling) brush.setColor(QColor(0, 255, 0)); - else if (_filling == HTMLGreenLawnGreenFilling) brush.setColor(QColor(124, 252, 0)); - else if (_filling == HTMLGreenChartreuseFilling) brush.setColor(QColor(127, 255, 0)); - else if (_filling == HTMLGreenGreenYellowFilling) brush.setColor(QColor(173, 255, 47)); - else if (_filling == HTMLGreenSpringGreenFilling) brush.setColor(QColor(0, 255, 127)); - else if (_filling == HTMLGreenMediumSpringGreenFilling) brush.setColor(QColor(0, 250, 154)); - else if (_filling == HTMLGreenLightGreenFilling) brush.setColor(QColor(144, 238, 144)); - else if (_filling == HTMLGreenPaleGreenFilling) brush.setColor(QColor(152, 251, 152)); - else if (_filling == HTMLGreenDarkSeaGreenFilling) brush.setColor(QColor(143, 188, 143)); - else if (_filling == HTMLGreenMediumAquamarineFilling) brush.setColor(QColor(102, 205, 170)); - else if (_filling == HTMLGreenMediumSeaGreenFilling) brush.setColor(QColor(60, 179, 113)); - else if (_filling == HTMLGreenSeaGreenFilling) brush.setColor(QColor(46, 139, 87)); - else if (_filling == HTMLGreenForestGreenFilling) brush.setColor(QColor(34, 139, 34)); - else if (_filling == HTMLGreenGreenFilling) brush.setColor(QColor(0, 128, 0)); - else if (_filling == HTMLGreenDarkGreenFilling) brush.setColor(QColor(0, 100, 0)); - else if (_filling == HTMLCyanAquaFilling) brush.setColor(QColor(0, 255, 255)); - else if (_filling == HTMLCyanCyanFilling) brush.setColor(QColor(0, 255, 255)); - else if (_filling == HTMLCyanLightCyanFilling) brush.setColor(QColor(224, 255, 255)); - else if (_filling == HTMLCyanPaleTurquoiseFilling) brush.setColor(QColor(175, 238, 238)); - else if (_filling == HTMLCyanAquamarineFilling) brush.setColor(QColor(127, 255, 212)); - else if (_filling == HTMLCyanTurquoiseFilling) brush.setColor(QColor(64, 224, 208)); - else if (_filling == HTMLCyanMediumTurquoiseFilling) brush.setColor(QColor(72, 209, 204)); - else if (_filling == HTMLCyanDarkTurquoiseFilling) brush.setColor(QColor(0, 206, 209)); - else if (_filling == HTMLCyanLightSeaGreenFilling) brush.setColor(QColor(32, 178, 170)); - else if (_filling == HTMLCyanCadetBlueFilling) brush.setColor(QColor(95, 158, 160)); - else if (_filling == HTMLCyanDarkCyanFilling) brush.setColor(QColor(0, 139, 139)); - else if (_filling == HTMLCyanTealFilling) brush.setColor(QColor(0, 128, 128)); - else if (_filling == HTMLBlueLightSteelBlueFilling) brush.setColor(QColor(176, 196, 222)); - else if (_filling == HTMLBluePowderBlueFilling) brush.setColor(QColor(176, 224, 230)); - else if (_filling == HTMLBlueLightBlueFilling) brush.setColor(QColor(173, 216, 230)); - else if (_filling == HTMLBlueSkyBlueFilling) brush.setColor(QColor(135, 206, 235)); - else if (_filling == HTMLBlueLightSkyBlueFilling) brush.setColor(QColor(135, 206, 250)); - else if (_filling == HTMLBlueDeepSkyBlueFilling) brush.setColor(QColor(0, 191, 255)); - else if (_filling == HTMLBlueDodgerBlueFilling) brush.setColor(QColor(30, 144, 255)); - else if (_filling == HTMLBlueCornflowerBlueFilling) brush.setColor(QColor(100, 149, 237)); - else if (_filling == HTMLBlueSteelBlueFilling) brush.setColor(QColor(70, 130, 180)); - else if (_filling == HTMLBlueRoyalBlueFilling) brush.setColor(QColor(65, 105, 225)); - else if (_filling == HTMLBlueBlueFilling) brush.setColor(QColor(0, 0, 255)); - else if (_filling == HTMLBlueMediumBlueFilling) brush.setColor(QColor(0, 0, 205)); - else if (_filling == HTMLBlueDarkBlueFilling) brush.setColor(QColor(0, 0, 139)); - else if (_filling == HTMLBlueNavyFilling) brush.setColor(QColor(0, 0, 128)); - else if (_filling == HTMLBlueMidnightBlueFilling) brush.setColor(QColor(25, 25, 112)); - else if (_filling == HTMLPurpleLavenderFilling) brush.setColor(QColor(230, 230, 250)); - else if (_filling == HTMLPurpleThistleFilling) brush.setColor(QColor(216, 191, 216)); - else if (_filling == HTMLPurplePlumFilling) brush.setColor(QColor(221, 160, 221)); - else if (_filling == HTMLPurpleVioletFilling) brush.setColor(QColor(238, 130, 238)); - else if (_filling == HTMLPurpleOrchidFilling) brush.setColor(QColor(218, 112, 214)); - else if (_filling == HTMLPurpleFuchsiaFilling) brush.setColor(QColor(255, 0, 255)); - else if (_filling == HTMLPurpleMagentaFilling) brush.setColor(QColor(255, 0, 255)); - else if (_filling == HTMLPurpleMediumOrchidFilling) brush.setColor(QColor(186, 85, 211)); - else if (_filling == HTMLPurpleMediumPurpleFilling) brush.setColor(QColor(147, 112, 219)); - else if (_filling == HTMLPurpleBlueVioletFilling) brush.setColor(QColor(138, 43, 226)); - else if (_filling == HTMLPurpleDarkVioletFilling) brush.setColor(QColor(148, 0, 211)); - else if (_filling == HTMLPurpleDarkOrchidFilling) brush.setColor(QColor(153, 50, 204)); - else if (_filling == HTMLPurpleDarkMagentaFilling) brush.setColor(QColor(139, 0, 139)); - else if (_filling == HTMLPurplePurpleFilling) brush.setColor(QColor(128, 0, 128)); - else if (_filling == HTMLPurpleIndigoFilling) brush.setColor(QColor(75, 0, 130)); - else if (_filling == HTMLPurpleDarkSlateBlueFilling) brush.setColor(QColor(72, 61, 139)); - else if (_filling == HTMLPurpleSlateBlueFilling) brush.setColor(QColor(106, 90, 205)); - else if (_filling == HTMLPurpleMediumSlateBlueFilling) brush.setColor(QColor(123, 104, 238)); - else if (_filling == HTMLWhiteWhiteFilling) brush.setColor(QColor(255, 255, 255)); - else if (_filling == HTMLWhiteSnowFilling) brush.setColor(QColor(255, 250, 250)); - else if (_filling == HTMLWhiteHoneydewFilling) brush.setColor(QColor(240, 255, 240)); - else if (_filling == HTMLWhiteMintCreamFilling) brush.setColor(QColor(245, 255, 250)); - else if (_filling == HTMLWhiteAzureFilling) brush.setColor(QColor(240, 255, 255)); - else if (_filling == HTMLWhiteAliceBlueFilling) brush.setColor(QColor(240, 248, 255)); - else if (_filling == HTMLWhiteGhostWhiteFilling) brush.setColor(QColor(248, 248, 255)); - else if (_filling == HTMLWhiteWhiteSmokeFilling) brush.setColor(QColor(245, 245, 245)); - else if (_filling == HTMLWhiteSeashellFilling) brush.setColor(QColor(255, 245, 238)); - else if (_filling == HTMLWhiteBeigeFilling) brush.setColor(QColor(245, 245, 220)); - else if (_filling == HTMLWhiteOldLaceFilling) brush.setColor(QColor(253, 245, 230)); - else if (_filling == HTMLWhiteFloralWhiteFilling) brush.setColor(QColor(255, 250, 240)); - else if (_filling == HTMLWhiteIvoryFilling) brush.setColor(QColor(255, 255, 240)); - else if (_filling == HTMLWhiteAntiqueWhiteFilling) brush.setColor(QColor(250, 235, 215)); - else if (_filling == HTMLWhiteLinenFilling) brush.setColor(QColor(250, 240, 230)); - else if (_filling == HTMLWhiteLavenderBlushFilling) brush.setColor(QColor(255, 240, 245)); - else if (_filling == HTMLWhiteMistyRoseFilling) brush.setColor(QColor(255, 228, 225)); - else if (_filling == HTMLGrayGainsboroFilling) brush.setColor(QColor(220, 220, 220)); - else if (_filling == HTMLGrayLightGrayFilling) brush.setColor(QColor(211, 211, 211)); - else if (_filling == HTMLGraySilverFilling) brush.setColor(QColor(192, 192, 192)); - else if (_filling == HTMLGrayDarkGrayFilling) brush.setColor(QColor(169, 169, 169)); - else if (_filling == HTMLGrayGrayFilling) brush.setColor(QColor(128, 128, 128)); - else if (_filling == HTMLGrayDimGrayFilling) brush.setColor(QColor(105, 105, 105)); - else if (_filling == HTMLGrayLightSlateGrayFilling) brush.setColor(QColor(119, 136, 153)); - else if (_filling == HTMLGraySlateGrayFilling) brush.setColor(QColor(112, 128, 144)); - else if (_filling == HTMLGrayDarkSlateGrayFilling) brush.setColor(QColor(47, 79, 79)); - else if (_filling == HTMLGrayBlackFilling) brush.setColor(QColor(0, 0, 0)); - } + //Apply brush color + if (_filling == NoneFilling) brush.setStyle(Qt::NoBrush); + else if (_filling == HorFilling) brush.setStyle(Qt::HorPattern); + else if (_filling == VerFilling) brush.setStyle(Qt::VerPattern); + else if (_filling == BdiagFilling) brush.setStyle(Qt::BDiagPattern); + else if (_filling == FdiagFilling) brush.setStyle(Qt::FDiagPattern); + else + { + brush.setStyle(Qt::SolidPattern); + if (_filling == BlackFilling) brush.setColor(Qt::black); + else if (_filling == WhiteFilling) brush.setColor(Qt::white); + else if (_filling == GreenFilling) brush.setColor(Qt::green); + else if (_filling == RedFilling) brush.setColor(Qt::red); + else if (_filling == BlueFilling) brush.setColor(Qt::blue); + else if (_filling == GrayFilling) brush.setColor(Qt::gray); + else if (_filling == BrunFilling) brush.setColor(QColor(97, 44, 0)); + else if (_filling == YellowFilling) brush.setColor(Qt::yellow); + else if (_filling == CyanFilling) brush.setColor(Qt::cyan); + else if (_filling == MagentaFilling) brush.setColor(Qt::magenta); + else if (_filling == LightgrayFilling) brush.setColor(Qt::lightGray); + else if (_filling == OrangeFilling) brush.setColor(QColor(255, 128, 0)); + else if (_filling == PurpleFilling) brush.setColor(QColor(136, 28, 168)); + else if (_filling == HTMLPinkPinkFilling) brush.setColor(QColor(255, 192, 203)); + else if (_filling == HTMLPinkLightPinkFilling) brush.setColor(QColor(255, 182, 193)); + else if (_filling == HTMLPinkHotPinkFilling) brush.setColor(QColor(255, 105, 180)); + else if (_filling == HTMLPinkDeepPinkFilling) brush.setColor(QColor(255, 20, 147)); + else if (_filling == HTMLPinkPaleVioletRedFilling) brush.setColor(QColor(219, 112, 147)); + else if (_filling == HTMLPinkMediumVioletRedFilling) brush.setColor(QColor(199, 21, 133)); + else if (_filling == HTMLRedLightSalmonFilling) brush.setColor(QColor(255, 160, 122)); + else if (_filling == HTMLRedSalmonFilling) brush.setColor(QColor(250, 128, 114)); + else if (_filling == HTMLRedDarkSalmonFilling) brush.setColor(QColor(233, 150, 122)); + else if (_filling == HTMLRedLightCoralFilling) brush.setColor(QColor(240, 128, 128)); + else if (_filling == HTMLRedIndianRedFilling) brush.setColor(QColor(205, 92, 92)); + else if (_filling == HTMLRedCrimsonFilling) brush.setColor(QColor(220, 20, 60)); + else if (_filling == HTMLRedFirebrickFilling) brush.setColor(QColor(178, 34, 34)); + else if (_filling == HTMLRedDarkRedFilling) brush.setColor(QColor(139, 0, 0)); + else if (_filling == HTMLRedRedFilling) brush.setColor(QColor(255, 0, 0)); + else if (_filling == HTMLOrangeOrangeRedFilling) brush.setColor(QColor(255, 69, 0)); + else if (_filling == HTMLOrangeTomatoFilling) brush.setColor(QColor(255, 99, 71)); + else if (_filling == HTMLOrangeCoralFilling) brush.setColor(QColor(255, 127, 80)); + else if (_filling == HTMLOrangeDarkOrangeFilling) brush.setColor(QColor(255, 140, 0)); + else if (_filling == HTMLOrangeOrangeFilling) brush.setColor(QColor(255, 165, 0)); + else if (_filling == HTMLYellowYellowFilling) brush.setColor(QColor(255, 255, 0)); + else if (_filling == HTMLYellowLightYellowFilling) brush.setColor(QColor(255, 255, 224)); + else if (_filling == HTMLYellowLemonChiffonFilling) brush.setColor(QColor(255, 250, 205)); + else if (_filling == HTMLYellowLightGoldenrodYellowFilling) brush.setColor(QColor(250, 250, 210)); + else if (_filling == HTMLYellowPapayaWhipFilling) brush.setColor(QColor(255, 239, 213)); + else if (_filling == HTMLYellowMoccasinFilling) brush.setColor(QColor(255, 228, 181)); + else if (_filling == HTMLYellowPeachPuffFilling) brush.setColor(QColor(255, 218, 185)); + else if (_filling == HTMLYellowPaleGoldenrodFilling) brush.setColor(QColor(238, 232, 170)); + else if (_filling == HTMLYellowKhakiFilling) brush.setColor(QColor(240, 230, 140)); + else if (_filling == HTMLYellowDarkKhakiFilling) brush.setColor(QColor(189, 183, 107)); + else if (_filling == HTMLYellowGoldFilling) brush.setColor(QColor(255, 215, 0)); + else if (_filling == HTMLBrownCornsilkFilling) brush.setColor(QColor(255, 248, 220)); + else if (_filling == HTMLBrownBlanchedAlmondFilling) brush.setColor(QColor(255, 235, 205)); + else if (_filling == HTMLBrownBisqueFilling) brush.setColor(QColor(255, 228, 196)); + else if (_filling == HTMLBrownNavajoWhiteFilling) brush.setColor(QColor(255, 222, 173)); + else if (_filling == HTMLBrownWheatFilling) brush.setColor(QColor(245, 222, 179)); + else if (_filling == HTMLBrownBurlywoodFilling) brush.setColor(QColor(222, 184, 135)); + else if (_filling == HTMLBrownTanFilling) brush.setColor(QColor(210, 180, 140)); + else if (_filling == HTMLBrownRosyBrownFilling) brush.setColor(QColor(188, 143, 143)); + else if (_filling == HTMLBrownSandyBrownFilling) brush.setColor(QColor(244, 164, 96)); + else if (_filling == HTMLBrownGoldenrodFilling) brush.setColor(QColor(218, 165, 32)); + else if (_filling == HTMLBrownDarkGoldenrodFilling) brush.setColor(QColor(184, 134, 11)); + else if (_filling == HTMLBrownPeruFilling) brush.setColor(QColor(205, 133, 63)); + else if (_filling == HTMLBrownChocolateFilling) brush.setColor(QColor(210, 105, 30)); + else if (_filling == HTMLBrownSaddleBrownFilling) brush.setColor(QColor(139, 69, 19)); + else if (_filling == HTMLBrownSiennaFilling) brush.setColor(QColor(160, 82, 45)); + else if (_filling == HTMLBrownBrownFilling) brush.setColor(QColor(165, 42, 42)); + else if (_filling == HTMLBrownMaroonFilling) brush.setColor(QColor(128, 0, 0)); + else if (_filling == HTMLGreenDarkOliveGreenFilling) brush.setColor(QColor(85, 107, 47)); + else if (_filling == HTMLGreenOliveFilling) brush.setColor(QColor(128, 128, 0)); + else if (_filling == HTMLGreenOliveDrabFilling) brush.setColor(QColor(107, 142, 35)); + else if (_filling == HTMLGreenYellowGreenFilling) brush.setColor(QColor(154, 205, 50)); + else if (_filling == HTMLGreenLimeGreenFilling) brush.setColor(QColor(50, 205, 50)); + else if (_filling == HTMLGreenLimeFilling) brush.setColor(QColor(0, 255, 0)); + else if (_filling == HTMLGreenLawnGreenFilling) brush.setColor(QColor(124, 252, 0)); + else if (_filling == HTMLGreenChartreuseFilling) brush.setColor(QColor(127, 255, 0)); + else if (_filling == HTMLGreenGreenYellowFilling) brush.setColor(QColor(173, 255, 47)); + else if (_filling == HTMLGreenSpringGreenFilling) brush.setColor(QColor(0, 255, 127)); + else if (_filling == HTMLGreenMediumSpringGreenFilling) brush.setColor(QColor(0, 250, 154)); + else if (_filling == HTMLGreenLightGreenFilling) brush.setColor(QColor(144, 238, 144)); + else if (_filling == HTMLGreenPaleGreenFilling) brush.setColor(QColor(152, 251, 152)); + else if (_filling == HTMLGreenDarkSeaGreenFilling) brush.setColor(QColor(143, 188, 143)); + else if (_filling == HTMLGreenMediumAquamarineFilling) brush.setColor(QColor(102, 205, 170)); + else if (_filling == HTMLGreenMediumSeaGreenFilling) brush.setColor(QColor(60, 179, 113)); + else if (_filling == HTMLGreenSeaGreenFilling) brush.setColor(QColor(46, 139, 87)); + else if (_filling == HTMLGreenForestGreenFilling) brush.setColor(QColor(34, 139, 34)); + else if (_filling == HTMLGreenGreenFilling) brush.setColor(QColor(0, 128, 0)); + else if (_filling == HTMLGreenDarkGreenFilling) brush.setColor(QColor(0, 100, 0)); + else if (_filling == HTMLCyanAquaFilling) brush.setColor(QColor(0, 255, 255)); + else if (_filling == HTMLCyanCyanFilling) brush.setColor(QColor(0, 255, 255)); + else if (_filling == HTMLCyanLightCyanFilling) brush.setColor(QColor(224, 255, 255)); + else if (_filling == HTMLCyanPaleTurquoiseFilling) brush.setColor(QColor(175, 238, 238)); + else if (_filling == HTMLCyanAquamarineFilling) brush.setColor(QColor(127, 255, 212)); + else if (_filling == HTMLCyanTurquoiseFilling) brush.setColor(QColor(64, 224, 208)); + else if (_filling == HTMLCyanMediumTurquoiseFilling) brush.setColor(QColor(72, 209, 204)); + else if (_filling == HTMLCyanDarkTurquoiseFilling) brush.setColor(QColor(0, 206, 209)); + else if (_filling == HTMLCyanLightSeaGreenFilling) brush.setColor(QColor(32, 178, 170)); + else if (_filling == HTMLCyanCadetBlueFilling) brush.setColor(QColor(95, 158, 160)); + else if (_filling == HTMLCyanDarkCyanFilling) brush.setColor(QColor(0, 139, 139)); + else if (_filling == HTMLCyanTealFilling) brush.setColor(QColor(0, 128, 128)); + else if (_filling == HTMLBlueLightSteelBlueFilling) brush.setColor(QColor(176, 196, 222)); + else if (_filling == HTMLBluePowderBlueFilling) brush.setColor(QColor(176, 224, 230)); + else if (_filling == HTMLBlueLightBlueFilling) brush.setColor(QColor(173, 216, 230)); + else if (_filling == HTMLBlueSkyBlueFilling) brush.setColor(QColor(135, 206, 235)); + else if (_filling == HTMLBlueLightSkyBlueFilling) brush.setColor(QColor(135, 206, 250)); + else if (_filling == HTMLBlueDeepSkyBlueFilling) brush.setColor(QColor(0, 191, 255)); + else if (_filling == HTMLBlueDodgerBlueFilling) brush.setColor(QColor(30, 144, 255)); + else if (_filling == HTMLBlueCornflowerBlueFilling) brush.setColor(QColor(100, 149, 237)); + else if (_filling == HTMLBlueSteelBlueFilling) brush.setColor(QColor(70, 130, 180)); + else if (_filling == HTMLBlueRoyalBlueFilling) brush.setColor(QColor(65, 105, 225)); + else if (_filling == HTMLBlueBlueFilling) brush.setColor(QColor(0, 0, 255)); + else if (_filling == HTMLBlueMediumBlueFilling) brush.setColor(QColor(0, 0, 205)); + else if (_filling == HTMLBlueDarkBlueFilling) brush.setColor(QColor(0, 0, 139)); + else if (_filling == HTMLBlueNavyFilling) brush.setColor(QColor(0, 0, 128)); + else if (_filling == HTMLBlueMidnightBlueFilling) brush.setColor(QColor(25, 25, 112)); + else if (_filling == HTMLPurpleLavenderFilling) brush.setColor(QColor(230, 230, 250)); + else if (_filling == HTMLPurpleThistleFilling) brush.setColor(QColor(216, 191, 216)); + else if (_filling == HTMLPurplePlumFilling) brush.setColor(QColor(221, 160, 221)); + else if (_filling == HTMLPurpleVioletFilling) brush.setColor(QColor(238, 130, 238)); + else if (_filling == HTMLPurpleOrchidFilling) brush.setColor(QColor(218, 112, 214)); + else if (_filling == HTMLPurpleFuchsiaFilling) brush.setColor(QColor(255, 0, 255)); + else if (_filling == HTMLPurpleMagentaFilling) brush.setColor(QColor(255, 0, 255)); + else if (_filling == HTMLPurpleMediumOrchidFilling) brush.setColor(QColor(186, 85, 211)); + else if (_filling == HTMLPurpleMediumPurpleFilling) brush.setColor(QColor(147, 112, 219)); + else if (_filling == HTMLPurpleBlueVioletFilling) brush.setColor(QColor(138, 43, 226)); + else if (_filling == HTMLPurpleDarkVioletFilling) brush.setColor(QColor(148, 0, 211)); + else if (_filling == HTMLPurpleDarkOrchidFilling) brush.setColor(QColor(153, 50, 204)); + else if (_filling == HTMLPurpleDarkMagentaFilling) brush.setColor(QColor(139, 0, 139)); + else if (_filling == HTMLPurplePurpleFilling) brush.setColor(QColor(128, 0, 128)); + else if (_filling == HTMLPurpleIndigoFilling) brush.setColor(QColor(75, 0, 130)); + else if (_filling == HTMLPurpleDarkSlateBlueFilling) brush.setColor(QColor(72, 61, 139)); + else if (_filling == HTMLPurpleSlateBlueFilling) brush.setColor(QColor(106, 90, 205)); + else if (_filling == HTMLPurpleMediumSlateBlueFilling) brush.setColor(QColor(123, 104, 238)); + else if (_filling == HTMLWhiteWhiteFilling) brush.setColor(QColor(255, 255, 255)); + else if (_filling == HTMLWhiteSnowFilling) brush.setColor(QColor(255, 250, 250)); + else if (_filling == HTMLWhiteHoneydewFilling) brush.setColor(QColor(240, 255, 240)); + else if (_filling == HTMLWhiteMintCreamFilling) brush.setColor(QColor(245, 255, 250)); + else if (_filling == HTMLWhiteAzureFilling) brush.setColor(QColor(240, 255, 255)); + else if (_filling == HTMLWhiteAliceBlueFilling) brush.setColor(QColor(240, 248, 255)); + else if (_filling == HTMLWhiteGhostWhiteFilling) brush.setColor(QColor(248, 248, 255)); + else if (_filling == HTMLWhiteWhiteSmokeFilling) brush.setColor(QColor(245, 245, 245)); + else if (_filling == HTMLWhiteSeashellFilling) brush.setColor(QColor(255, 245, 238)); + else if (_filling == HTMLWhiteBeigeFilling) brush.setColor(QColor(245, 245, 220)); + else if (_filling == HTMLWhiteOldLaceFilling) brush.setColor(QColor(253, 245, 230)); + else if (_filling == HTMLWhiteFloralWhiteFilling) brush.setColor(QColor(255, 250, 240)); + else if (_filling == HTMLWhiteIvoryFilling) brush.setColor(QColor(255, 255, 240)); + else if (_filling == HTMLWhiteAntiqueWhiteFilling) brush.setColor(QColor(250, 235, 215)); + else if (_filling == HTMLWhiteLinenFilling) brush.setColor(QColor(250, 240, 230)); + else if (_filling == HTMLWhiteLavenderBlushFilling) brush.setColor(QColor(255, 240, 245)); + else if (_filling == HTMLWhiteMistyRoseFilling) brush.setColor(QColor(255, 228, 225)); + else if (_filling == HTMLGrayGainsboroFilling) brush.setColor(QColor(220, 220, 220)); + else if (_filling == HTMLGrayLightGrayFilling) brush.setColor(QColor(211, 211, 211)); + else if (_filling == HTMLGraySilverFilling) brush.setColor(QColor(192, 192, 192)); + else if (_filling == HTMLGrayDarkGrayFilling) brush.setColor(QColor(169, 169, 169)); + else if (_filling == HTMLGrayGrayFilling) brush.setColor(QColor(128, 128, 128)); + else if (_filling == HTMLGrayDimGrayFilling) brush.setColor(QColor(105, 105, 105)); + else if (_filling == HTMLGrayLightSlateGrayFilling) brush.setColor(QColor(119, 136, 153)); + else if (_filling == HTMLGraySlateGrayFilling) brush.setColor(QColor(112, 128, 144)); + else if (_filling == HTMLGrayDarkSlateGrayFilling) brush.setColor(QColor(47, 79, 79)); + else if (_filling == HTMLGrayBlackFilling) brush.setColor(QColor(0, 0, 0)); + } - //Apply pen color - if (_color == WhiteColor) pen.setColor(QColor(255, 255, 255, pen.color().alpha())); - else if (_color == BlackColor) pen.setColor(QColor( 0, 0, 0, pen.color().alpha())); - else if (_color == GreenColor) pen.setColor(QColor(Qt::green)); - else if (_color == RedColor) pen.setColor(QColor(Qt::red)); - else if (_color == BlueColor) pen.setColor(QColor(Qt::blue)); - else if (_color == GrayColor) pen.setColor(QColor(Qt::gray)); - else if (_color == BrunColor) pen.setColor(QColor(97, 44, 0)); - else if (_color == YellowColor) pen.setColor(QColor(Qt::yellow)); - else if (_color == CyanColor) pen.setColor(Qt::cyan); - else if (_color == MagentaColor) pen.setColor(Qt::magenta); - else if (_color == LightgrayColor) pen.setColor(Qt::lightGray); - else if (_color == OrangeColor) pen.setColor(QColor(255, 128, 0)); - else if (_color == PurpleColor) pen.setColor(QColor(136, 28, 168)); - else if (_color == HTMLPinkPinkColor) pen.setColor(QColor(255, 192, 203)); - else if (_color == HTMLPinkLightPinkColor) pen.setColor(QColor(255, 182, 193)); - else if (_color == HTMLPinkHotPinkColor) pen.setColor(QColor(255, 105, 180)); - else if (_color == HTMLPinkDeepPinkColor) pen.setColor(QColor(255, 20, 147)); - else if (_color == HTMLPinkPaleVioletRedColor) pen.setColor(QColor(219, 112, 147)); - else if (_color == HTMLPinkMediumVioletRedColor) pen.setColor(QColor(199, 21, 133)); - else if (_color == HTMLRedLightSalmonColor) pen.setColor(QColor(255, 160, 122)); - else if (_color == HTMLRedSalmonColor) pen.setColor(QColor(250, 128, 114)); - else if (_color == HTMLRedDarkSalmonColor) pen.setColor(QColor(233, 150, 122)); - else if (_color == HTMLRedLightCoralColor) pen.setColor(QColor(240, 128, 128)); - else if (_color == HTMLRedIndianRedColor) pen.setColor(QColor(205, 92, 92)); - else if (_color == HTMLRedCrimsonColor) pen.setColor(QColor(220, 20, 60)); - else if (_color == HTMLRedFirebrickColor) pen.setColor(QColor(178, 34, 34)); - else if (_color == HTMLRedDarkRedColor) pen.setColor(QColor(139, 0, 0)); - else if (_color == HTMLRedRedColor) pen.setColor(QColor(255, 0, 0)); - else if (_color == HTMLOrangeOrangeRedColor) pen.setColor(QColor(255, 69, 0)); - else if (_color == HTMLOrangeTomatoColor) pen.setColor(QColor(255, 99, 71)); - else if (_color == HTMLOrangeCoralColor) pen.setColor(QColor(255, 127, 80)); - else if (_color == HTMLOrangeDarkOrangeColor) pen.setColor(QColor(255, 140, 0)); - else if (_color == HTMLOrangeOrangeColor) pen.setColor(QColor(255, 165, 0)); - else if (_color == HTMLYellowYellowColor) pen.setColor(QColor(255, 255, 0)); - else if (_color == HTMLYellowLightYellowColor) pen.setColor(QColor(255, 255, 224)); - else if (_color == HTMLYellowLemonChiffonColor) pen.setColor(QColor(255, 250, 205)); - else if (_color == HTMLYellowLightGoldenrodYellowColor) pen.setColor(QColor(250, 250, 210)); - else if (_color == HTMLYellowPapayaWhipColor) pen.setColor(QColor(255, 239, 213)); - else if (_color == HTMLYellowMoccasinColor) pen.setColor(QColor(255, 228, 181)); - else if (_color == HTMLYellowPeachPuffColor) pen.setColor(QColor(255, 218, 185)); - else if (_color == HTMLYellowPaleGoldenrodColor) pen.setColor(QColor(238, 232, 170)); - else if (_color == HTMLYellowKhakiColor) pen.setColor(QColor(240, 230, 140)); - else if (_color == HTMLYellowDarkKhakiColor) pen.setColor(QColor(189, 183, 107)); - else if (_color == HTMLYellowGoldColor) pen.setColor(QColor(255, 215, 0)); - else if (_color == HTMLBrownCornsilkColor) pen.setColor(QColor(255, 248, 220)); - else if (_color == HTMLBrownBlanchedAlmondColor) pen.setColor(QColor(255, 235, 205)); - else if (_color == HTMLBrownBisqueColor) pen.setColor(QColor(255, 228, 196)); - else if (_color == HTMLBrownNavajoWhiteColor) pen.setColor(QColor(255, 222, 173)); - else if (_color == HTMLBrownWheatColor) pen.setColor(QColor(245, 222, 179)); - else if (_color == HTMLBrownBurlywoodColor) pen.setColor(QColor(222, 184, 135)); - else if (_color == HTMLBrownTanColor) pen.setColor(QColor(210, 180, 140)); - else if (_color == HTMLBrownRosyBrownColor) pen.setColor(QColor(188, 143, 143)); - else if (_color == HTMLBrownSandyBrownColor) pen.setColor(QColor(244, 164, 96)); - else if (_color == HTMLBrownGoldenrodColor) pen.setColor(QColor(218, 165, 32)); - else if (_color == HTMLBrownDarkGoldenrodColor) pen.setColor(QColor(184, 134, 11)); - else if (_color == HTMLBrownPeruColor) pen.setColor(QColor(205, 133, 63)); - else if (_color == HTMLBrownChocolateColor) pen.setColor(QColor(210, 105, 30)); - else if (_color == HTMLBrownSaddleBrownColor) pen.setColor(QColor(139, 69, 19)); - else if (_color == HTMLBrownSiennaColor) pen.setColor(QColor(160, 82, 45)); - else if (_color == HTMLBrownBrownColor) pen.setColor(QColor(165, 42, 42)); - else if (_color == HTMLBrownMaroonColor) pen.setColor(QColor(128, 0, 0)); - else if (_color == HTMLGreenDarkOliveGreenColor) pen.setColor(QColor(85, 107, 47)); - else if (_color == HTMLGreenOliveColor) pen.setColor(QColor(128, 128, 0)); - else if (_color == HTMLGreenOliveDrabColor) pen.setColor(QColor(107, 142, 35)); - else if (_color == HTMLGreenYellowGreenColor) pen.setColor(QColor(154, 205, 50)); - else if (_color == HTMLGreenLimeGreenColor) pen.setColor(QColor(50, 205, 50)); - else if (_color == HTMLGreenLimeColor) pen.setColor(QColor(0, 255, 0)); - else if (_color == HTMLGreenLawnGreenColor) pen.setColor(QColor(124, 252, 0)); - else if (_color == HTMLGreenChartreuseColor) pen.setColor(QColor(127, 255, 0)); - else if (_color == HTMLGreenGreenYellowColor) pen.setColor(QColor(173, 255, 47)); - else if (_color == HTMLGreenSpringGreenColor) pen.setColor(QColor(0, 255, 127)); - else if (_color == HTMLGreenMediumSpringGreenColor) pen.setColor(QColor(0, 250, 154)); - else if (_color == HTMLGreenLightGreenColor) pen.setColor(QColor(144, 238, 144)); - else if (_color == HTMLGreenPaleGreenColor) pen.setColor(QColor(152, 251, 152)); - else if (_color == HTMLGreenDarkSeaGreenColor) pen.setColor(QColor(143, 188, 143)); - else if (_color == HTMLGreenMediumAquamarineColor) pen.setColor(QColor(102, 205, 170)); - else if (_color == HTMLGreenMediumSeaGreenColor) pen.setColor(QColor(60, 179, 113)); - else if (_color == HTMLGreenSeaGreenColor) pen.setColor(QColor(46, 139, 87)); - else if (_color == HTMLGreenForestGreenColor) pen.setColor(QColor(34, 139, 34)); - else if (_color == HTMLGreenGreenColor) pen.setColor(QColor(0, 128, 0)); - else if (_color == HTMLGreenDarkGreenColor) pen.setColor(QColor(0, 100, 0)); - else if (_color == HTMLCyanAquaColor) pen.setColor(QColor(0, 255, 255)); - else if (_color == HTMLCyanCyanColor) pen.setColor(QColor(0, 255, 255)); - else if (_color == HTMLCyanLightCyanColor) pen.setColor(QColor(224, 255, 255)); - else if (_color == HTMLCyanPaleTurquoiseColor) pen.setColor(QColor(175, 238, 238)); - else if (_color == HTMLCyanAquamarineColor) pen.setColor(QColor(127, 255, 212)); - else if (_color == HTMLCyanTurquoiseColor) pen.setColor(QColor(64, 224, 208)); - else if (_color == HTMLCyanMediumTurquoiseColor) pen.setColor(QColor(72, 209, 204)); - else if (_color == HTMLCyanDarkTurquoiseColor) pen.setColor(QColor(0, 206, 209)); - else if (_color == HTMLCyanLightSeaGreenColor) pen.setColor(QColor(32, 178, 170)); - else if (_color == HTMLCyanCadetBlueColor) pen.setColor(QColor(95, 158, 160)); - else if (_color == HTMLCyanDarkCyanColor) pen.setColor(QColor(0, 139, 139)); - else if (_color == HTMLCyanTealColor) pen.setColor(QColor(0, 128, 128)); - else if (_color == HTMLBlueLightSteelBlueColor) pen.setColor(QColor(176, 196, 222)); - else if (_color == HTMLBluePowderBlueColor) pen.setColor(QColor(176, 224, 230)); - else if (_color == HTMLBlueLightBlueColor) pen.setColor(QColor(173, 216, 230)); - else if (_color == HTMLBlueSkyBlueColor) pen.setColor(QColor(135, 206, 235)); - else if (_color == HTMLBlueLightSkyBlueColor) pen.setColor(QColor(135, 206, 250)); - else if (_color == HTMLBlueDeepSkyBlueColor) pen.setColor(QColor(0, 191, 255)); - else if (_color == HTMLBlueDodgerBlueColor) pen.setColor(QColor(30, 144, 255)); - else if (_color == HTMLBlueCornflowerBlueColor) pen.setColor(QColor(100, 149, 237)); - else if (_color == HTMLBlueSteelBlueColor) pen.setColor(QColor(70, 130, 180)); - else if (_color == HTMLBlueRoyalBlueColor) pen.setColor(QColor(65, 105, 225)); - else if (_color == HTMLBlueBlueColor) pen.setColor(QColor(0, 0, 255)); - else if (_color == HTMLBlueMediumBlueColor) pen.setColor(QColor(0, 0, 205)); - else if (_color == HTMLBlueDarkBlueColor) pen.setColor(QColor(0, 0, 139)); - else if (_color == HTMLBlueNavyColor) pen.setColor(QColor(0, 0, 128)); - else if (_color == HTMLBlueMidnightBlueColor) pen.setColor(QColor(25, 25, 112)); - else if (_color == HTMLPurpleLavenderColor) pen.setColor(QColor(230, 230, 250)); - else if (_color == HTMLPurpleThistleColor) pen.setColor(QColor(216, 191, 216)); - else if (_color == HTMLPurplePlumColor) pen.setColor(QColor(221, 160, 221)); - else if (_color == HTMLPurpleVioletColor) pen.setColor(QColor(238, 130, 238)); - else if (_color == HTMLPurpleOrchidColor) pen.setColor(QColor(218, 112, 214)); - else if (_color == HTMLPurpleFuchsiaColor) pen.setColor(QColor(255, 0, 255)); - else if (_color == HTMLPurpleMagentaColor) pen.setColor(QColor(255, 0, 255)); - else if (_color == HTMLPurpleMediumOrchidColor) pen.setColor(QColor(186, 85, 211)); - else if (_color == HTMLPurpleMediumPurpleColor) pen.setColor(QColor(147, 112, 219)); - else if (_color == HTMLPurpleBlueVioletColor) pen.setColor(QColor(138, 43, 226)); - else if (_color == HTMLPurpleDarkVioletColor) pen.setColor(QColor(148, 0, 211)); - else if (_color == HTMLPurpleDarkOrchidColor) pen.setColor(QColor(153, 50, 204)); - else if (_color == HTMLPurpleDarkMagentaColor) pen.setColor(QColor(139, 0, 139)); - else if (_color == HTMLPurplePurpleColor) pen.setColor(QColor(128, 0, 128)); - else if (_color == HTMLPurpleIndigoColor) pen.setColor(QColor(75, 0, 130)); - else if (_color == HTMLPurpleDarkSlateBlueColor) pen.setColor(QColor(72, 61, 139)); - else if (_color == HTMLPurpleSlateBlueColor) pen.setColor(QColor(106, 90, 205)); - else if (_color == HTMLPurpleMediumSlateBlueColor) pen.setColor(QColor(123, 104, 238)); - else if (_color == HTMLWhiteWhiteColor) pen.setColor(QColor(255, 255, 255)); - else if (_color == HTMLWhiteSnowColor) pen.setColor(QColor(255, 250, 250)); - else if (_color == HTMLWhiteHoneydewColor) pen.setColor(QColor(240, 255, 240)); - else if (_color == HTMLWhiteMintCreamColor) pen.setColor(QColor(245, 255, 250)); - else if (_color == HTMLWhiteAzureColor) pen.setColor(QColor(240, 255, 255)); - else if (_color == HTMLWhiteAliceBlueColor) pen.setColor(QColor(240, 248, 255)); - else if (_color == HTMLWhiteGhostWhiteColor) pen.setColor(QColor(248, 248, 255)); - else if (_color == HTMLWhiteWhiteSmokeColor) pen.setColor(QColor(245, 245, 245)); - else if (_color == HTMLWhiteSeashellColor) pen.setColor(QColor(255, 245, 238)); - else if (_color == HTMLWhiteBeigeColor) pen.setColor(QColor(245, 245, 220)); - else if (_color == HTMLWhiteOldLaceColor) pen.setColor(QColor(253, 245, 230)); - else if (_color == HTMLWhiteFloralWhiteColor) pen.setColor(QColor(255, 250, 240)); - else if (_color == HTMLWhiteIvoryColor) pen.setColor(QColor(255, 255, 240)); - else if (_color == HTMLWhiteAntiqueWhiteColor) pen.setColor(QColor(250, 235, 215)); - else if (_color == HTMLWhiteLinenColor) pen.setColor(QColor(250, 240, 230)); - else if (_color == HTMLWhiteLavenderBlushColor) pen.setColor(QColor(255, 240, 245)); - else if (_color == HTMLWhiteMistyRoseColor) pen.setColor(QColor(255, 228, 225)); - else if (_color == HTMLGrayGainsboroColor) pen.setColor(QColor(220, 220, 220)); - else if (_color == HTMLGrayLightGrayColor) pen.setColor(QColor(211, 211, 211)); - else if (_color == HTMLGraySilverColor) pen.setColor(QColor(192, 192, 192)); - else if (_color == HTMLGrayDarkGrayColor) pen.setColor(QColor(169, 169, 169)); - else if (_color == HTMLGrayGrayColor) pen.setColor(QColor(128, 128, 128)); - else if (_color == HTMLGrayDimGrayColor) pen.setColor(QColor(105, 105, 105)); - else if (_color == HTMLGrayLightSlateGrayColor) pen.setColor(QColor(119, 136, 153)); - else if (_color == HTMLGraySlateGrayColor) pen.setColor(QColor(112, 128, 144)); - else if (_color == HTMLGrayDarkSlateGrayColor) pen.setColor(QColor(47, 79, 79)); - else if (_color == HTMLGrayBlackColor) pen.setColor(QColor(0, 0, 0)); - else if (_color == NoneColor) pen.setBrush(Qt::transparent); + //Apply pen color + if (_color == WhiteColor) pen.setColor(QColor(255, 255, 255, pen.color().alpha())); + else if (_color == BlackColor) pen.setColor(QColor( 0, 0, 0, pen.color().alpha())); + else if (_color == GreenColor) pen.setColor(QColor(Qt::green)); + else if (_color == RedColor) pen.setColor(QColor(Qt::red)); + else if (_color == BlueColor) pen.setColor(QColor(Qt::blue)); + else if (_color == GrayColor) pen.setColor(QColor(Qt::gray)); + else if (_color == BrunColor) pen.setColor(QColor(97, 44, 0)); + else if (_color == YellowColor) pen.setColor(QColor(Qt::yellow)); + else if (_color == CyanColor) pen.setColor(Qt::cyan); + else if (_color == MagentaColor) pen.setColor(Qt::magenta); + else if (_color == LightgrayColor) pen.setColor(Qt::lightGray); + else if (_color == OrangeColor) pen.setColor(QColor(255, 128, 0)); + else if (_color == PurpleColor) pen.setColor(QColor(136, 28, 168)); + else if (_color == HTMLPinkPinkColor) pen.setColor(QColor(255, 192, 203)); + else if (_color == HTMLPinkLightPinkColor) pen.setColor(QColor(255, 182, 193)); + else if (_color == HTMLPinkHotPinkColor) pen.setColor(QColor(255, 105, 180)); + else if (_color == HTMLPinkDeepPinkColor) pen.setColor(QColor(255, 20, 147)); + else if (_color == HTMLPinkPaleVioletRedColor) pen.setColor(QColor(219, 112, 147)); + else if (_color == HTMLPinkMediumVioletRedColor) pen.setColor(QColor(199, 21, 133)); + else if (_color == HTMLRedLightSalmonColor) pen.setColor(QColor(255, 160, 122)); + else if (_color == HTMLRedSalmonColor) pen.setColor(QColor(250, 128, 114)); + else if (_color == HTMLRedDarkSalmonColor) pen.setColor(QColor(233, 150, 122)); + else if (_color == HTMLRedLightCoralColor) pen.setColor(QColor(240, 128, 128)); + else if (_color == HTMLRedIndianRedColor) pen.setColor(QColor(205, 92, 92)); + else if (_color == HTMLRedCrimsonColor) pen.setColor(QColor(220, 20, 60)); + else if (_color == HTMLRedFirebrickColor) pen.setColor(QColor(178, 34, 34)); + else if (_color == HTMLRedDarkRedColor) pen.setColor(QColor(139, 0, 0)); + else if (_color == HTMLRedRedColor) pen.setColor(QColor(255, 0, 0)); + else if (_color == HTMLOrangeOrangeRedColor) pen.setColor(QColor(255, 69, 0)); + else if (_color == HTMLOrangeTomatoColor) pen.setColor(QColor(255, 99, 71)); + else if (_color == HTMLOrangeCoralColor) pen.setColor(QColor(255, 127, 80)); + else if (_color == HTMLOrangeDarkOrangeColor) pen.setColor(QColor(255, 140, 0)); + else if (_color == HTMLOrangeOrangeColor) pen.setColor(QColor(255, 165, 0)); + else if (_color == HTMLYellowYellowColor) pen.setColor(QColor(255, 255, 0)); + else if (_color == HTMLYellowLightYellowColor) pen.setColor(QColor(255, 255, 224)); + else if (_color == HTMLYellowLemonChiffonColor) pen.setColor(QColor(255, 250, 205)); + else if (_color == HTMLYellowLightGoldenrodYellowColor) pen.setColor(QColor(250, 250, 210)); + else if (_color == HTMLYellowPapayaWhipColor) pen.setColor(QColor(255, 239, 213)); + else if (_color == HTMLYellowMoccasinColor) pen.setColor(QColor(255, 228, 181)); + else if (_color == HTMLYellowPeachPuffColor) pen.setColor(QColor(255, 218, 185)); + else if (_color == HTMLYellowPaleGoldenrodColor) pen.setColor(QColor(238, 232, 170)); + else if (_color == HTMLYellowKhakiColor) pen.setColor(QColor(240, 230, 140)); + else if (_color == HTMLYellowDarkKhakiColor) pen.setColor(QColor(189, 183, 107)); + else if (_color == HTMLYellowGoldColor) pen.setColor(QColor(255, 215, 0)); + else if (_color == HTMLBrownCornsilkColor) pen.setColor(QColor(255, 248, 220)); + else if (_color == HTMLBrownBlanchedAlmondColor) pen.setColor(QColor(255, 235, 205)); + else if (_color == HTMLBrownBisqueColor) pen.setColor(QColor(255, 228, 196)); + else if (_color == HTMLBrownNavajoWhiteColor) pen.setColor(QColor(255, 222, 173)); + else if (_color == HTMLBrownWheatColor) pen.setColor(QColor(245, 222, 179)); + else if (_color == HTMLBrownBurlywoodColor) pen.setColor(QColor(222, 184, 135)); + else if (_color == HTMLBrownTanColor) pen.setColor(QColor(210, 180, 140)); + else if (_color == HTMLBrownRosyBrownColor) pen.setColor(QColor(188, 143, 143)); + else if (_color == HTMLBrownSandyBrownColor) pen.setColor(QColor(244, 164, 96)); + else if (_color == HTMLBrownGoldenrodColor) pen.setColor(QColor(218, 165, 32)); + else if (_color == HTMLBrownDarkGoldenrodColor) pen.setColor(QColor(184, 134, 11)); + else if (_color == HTMLBrownPeruColor) pen.setColor(QColor(205, 133, 63)); + else if (_color == HTMLBrownChocolateColor) pen.setColor(QColor(210, 105, 30)); + else if (_color == HTMLBrownSaddleBrownColor) pen.setColor(QColor(139, 69, 19)); + else if (_color == HTMLBrownSiennaColor) pen.setColor(QColor(160, 82, 45)); + else if (_color == HTMLBrownBrownColor) pen.setColor(QColor(165, 42, 42)); + else if (_color == HTMLBrownMaroonColor) pen.setColor(QColor(128, 0, 0)); + else if (_color == HTMLGreenDarkOliveGreenColor) pen.setColor(QColor(85, 107, 47)); + else if (_color == HTMLGreenOliveColor) pen.setColor(QColor(128, 128, 0)); + else if (_color == HTMLGreenOliveDrabColor) pen.setColor(QColor(107, 142, 35)); + else if (_color == HTMLGreenYellowGreenColor) pen.setColor(QColor(154, 205, 50)); + else if (_color == HTMLGreenLimeGreenColor) pen.setColor(QColor(50, 205, 50)); + else if (_color == HTMLGreenLimeColor) pen.setColor(QColor(0, 255, 0)); + else if (_color == HTMLGreenLawnGreenColor) pen.setColor(QColor(124, 252, 0)); + else if (_color == HTMLGreenChartreuseColor) pen.setColor(QColor(127, 255, 0)); + else if (_color == HTMLGreenGreenYellowColor) pen.setColor(QColor(173, 255, 47)); + else if (_color == HTMLGreenSpringGreenColor) pen.setColor(QColor(0, 255, 127)); + else if (_color == HTMLGreenMediumSpringGreenColor) pen.setColor(QColor(0, 250, 154)); + else if (_color == HTMLGreenLightGreenColor) pen.setColor(QColor(144, 238, 144)); + else if (_color == HTMLGreenPaleGreenColor) pen.setColor(QColor(152, 251, 152)); + else if (_color == HTMLGreenDarkSeaGreenColor) pen.setColor(QColor(143, 188, 143)); + else if (_color == HTMLGreenMediumAquamarineColor) pen.setColor(QColor(102, 205, 170)); + else if (_color == HTMLGreenMediumSeaGreenColor) pen.setColor(QColor(60, 179, 113)); + else if (_color == HTMLGreenSeaGreenColor) pen.setColor(QColor(46, 139, 87)); + else if (_color == HTMLGreenForestGreenColor) pen.setColor(QColor(34, 139, 34)); + else if (_color == HTMLGreenGreenColor) pen.setColor(QColor(0, 128, 0)); + else if (_color == HTMLGreenDarkGreenColor) pen.setColor(QColor(0, 100, 0)); + else if (_color == HTMLCyanAquaColor) pen.setColor(QColor(0, 255, 255)); + else if (_color == HTMLCyanCyanColor) pen.setColor(QColor(0, 255, 255)); + else if (_color == HTMLCyanLightCyanColor) pen.setColor(QColor(224, 255, 255)); + else if (_color == HTMLCyanPaleTurquoiseColor) pen.setColor(QColor(175, 238, 238)); + else if (_color == HTMLCyanAquamarineColor) pen.setColor(QColor(127, 255, 212)); + else if (_color == HTMLCyanTurquoiseColor) pen.setColor(QColor(64, 224, 208)); + else if (_color == HTMLCyanMediumTurquoiseColor) pen.setColor(QColor(72, 209, 204)); + else if (_color == HTMLCyanDarkTurquoiseColor) pen.setColor(QColor(0, 206, 209)); + else if (_color == HTMLCyanLightSeaGreenColor) pen.setColor(QColor(32, 178, 170)); + else if (_color == HTMLCyanCadetBlueColor) pen.setColor(QColor(95, 158, 160)); + else if (_color == HTMLCyanDarkCyanColor) pen.setColor(QColor(0, 139, 139)); + else if (_color == HTMLCyanTealColor) pen.setColor(QColor(0, 128, 128)); + else if (_color == HTMLBlueLightSteelBlueColor) pen.setColor(QColor(176, 196, 222)); + else if (_color == HTMLBluePowderBlueColor) pen.setColor(QColor(176, 224, 230)); + else if (_color == HTMLBlueLightBlueColor) pen.setColor(QColor(173, 216, 230)); + else if (_color == HTMLBlueSkyBlueColor) pen.setColor(QColor(135, 206, 235)); + else if (_color == HTMLBlueLightSkyBlueColor) pen.setColor(QColor(135, 206, 250)); + else if (_color == HTMLBlueDeepSkyBlueColor) pen.setColor(QColor(0, 191, 255)); + else if (_color == HTMLBlueDodgerBlueColor) pen.setColor(QColor(30, 144, 255)); + else if (_color == HTMLBlueCornflowerBlueColor) pen.setColor(QColor(100, 149, 237)); + else if (_color == HTMLBlueSteelBlueColor) pen.setColor(QColor(70, 130, 180)); + else if (_color == HTMLBlueRoyalBlueColor) pen.setColor(QColor(65, 105, 225)); + else if (_color == HTMLBlueBlueColor) pen.setColor(QColor(0, 0, 255)); + else if (_color == HTMLBlueMediumBlueColor) pen.setColor(QColor(0, 0, 205)); + else if (_color == HTMLBlueDarkBlueColor) pen.setColor(QColor(0, 0, 139)); + else if (_color == HTMLBlueNavyColor) pen.setColor(QColor(0, 0, 128)); + else if (_color == HTMLBlueMidnightBlueColor) pen.setColor(QColor(25, 25, 112)); + else if (_color == HTMLPurpleLavenderColor) pen.setColor(QColor(230, 230, 250)); + else if (_color == HTMLPurpleThistleColor) pen.setColor(QColor(216, 191, 216)); + else if (_color == HTMLPurplePlumColor) pen.setColor(QColor(221, 160, 221)); + else if (_color == HTMLPurpleVioletColor) pen.setColor(QColor(238, 130, 238)); + else if (_color == HTMLPurpleOrchidColor) pen.setColor(QColor(218, 112, 214)); + else if (_color == HTMLPurpleFuchsiaColor) pen.setColor(QColor(255, 0, 255)); + else if (_color == HTMLPurpleMagentaColor) pen.setColor(QColor(255, 0, 255)); + else if (_color == HTMLPurpleMediumOrchidColor) pen.setColor(QColor(186, 85, 211)); + else if (_color == HTMLPurpleMediumPurpleColor) pen.setColor(QColor(147, 112, 219)); + else if (_color == HTMLPurpleBlueVioletColor) pen.setColor(QColor(138, 43, 226)); + else if (_color == HTMLPurpleDarkVioletColor) pen.setColor(QColor(148, 0, 211)); + else if (_color == HTMLPurpleDarkOrchidColor) pen.setColor(QColor(153, 50, 204)); + else if (_color == HTMLPurpleDarkMagentaColor) pen.setColor(QColor(139, 0, 139)); + else if (_color == HTMLPurplePurpleColor) pen.setColor(QColor(128, 0, 128)); + else if (_color == HTMLPurpleIndigoColor) pen.setColor(QColor(75, 0, 130)); + else if (_color == HTMLPurpleDarkSlateBlueColor) pen.setColor(QColor(72, 61, 139)); + else if (_color == HTMLPurpleSlateBlueColor) pen.setColor(QColor(106, 90, 205)); + else if (_color == HTMLPurpleMediumSlateBlueColor) pen.setColor(QColor(123, 104, 238)); + else if (_color == HTMLWhiteWhiteColor) pen.setColor(QColor(255, 255, 255)); + else if (_color == HTMLWhiteSnowColor) pen.setColor(QColor(255, 250, 250)); + else if (_color == HTMLWhiteHoneydewColor) pen.setColor(QColor(240, 255, 240)); + else if (_color == HTMLWhiteMintCreamColor) pen.setColor(QColor(245, 255, 250)); + else if (_color == HTMLWhiteAzureColor) pen.setColor(QColor(240, 255, 255)); + else if (_color == HTMLWhiteAliceBlueColor) pen.setColor(QColor(240, 248, 255)); + else if (_color == HTMLWhiteGhostWhiteColor) pen.setColor(QColor(248, 248, 255)); + else if (_color == HTMLWhiteWhiteSmokeColor) pen.setColor(QColor(245, 245, 245)); + else if (_color == HTMLWhiteSeashellColor) pen.setColor(QColor(255, 245, 238)); + else if (_color == HTMLWhiteBeigeColor) pen.setColor(QColor(245, 245, 220)); + else if (_color == HTMLWhiteOldLaceColor) pen.setColor(QColor(253, 245, 230)); + else if (_color == HTMLWhiteFloralWhiteColor) pen.setColor(QColor(255, 250, 240)); + else if (_color == HTMLWhiteIvoryColor) pen.setColor(QColor(255, 255, 240)); + else if (_color == HTMLWhiteAntiqueWhiteColor) pen.setColor(QColor(250, 235, 215)); + else if (_color == HTMLWhiteLinenColor) pen.setColor(QColor(250, 240, 230)); + else if (_color == HTMLWhiteLavenderBlushColor) pen.setColor(QColor(255, 240, 245)); + else if (_color == HTMLWhiteMistyRoseColor) pen.setColor(QColor(255, 228, 225)); + else if (_color == HTMLGrayGainsboroColor) pen.setColor(QColor(220, 220, 220)); + else if (_color == HTMLGrayLightGrayColor) pen.setColor(QColor(211, 211, 211)); + else if (_color == HTMLGraySilverColor) pen.setColor(QColor(192, 192, 192)); + else if (_color == HTMLGrayDarkGrayColor) pen.setColor(QColor(169, 169, 169)); + else if (_color == HTMLGrayGrayColor) pen.setColor(QColor(128, 128, 128)); + else if (_color == HTMLGrayDimGrayColor) pen.setColor(QColor(105, 105, 105)); + else if (_color == HTMLGrayLightSlateGrayColor) pen.setColor(QColor(119, 136, 153)); + else if (_color == HTMLGraySlateGrayColor) pen.setColor(QColor(112, 128, 144)); + else if (_color == HTMLGrayDarkSlateGrayColor) pen.setColor(QColor(47, 79, 79)); + else if (_color == HTMLGrayBlackColor) pen.setColor(QColor(0, 0, 0)); + else if (_color == NoneColor) pen.setBrush(Qt::transparent); - //Apply antialiasing - painter.setRenderHint(QPainter::Antialiasing, _antialiased); - painter.setRenderHint(QPainter::TextAntialiasing, _antialiased); - painter.setRenderHint(QPainter::SmoothPixmapTransform, _antialiased); + //Apply antialiasing + painter.setRenderHint(QPainter::Antialiasing, _antialiased); + painter.setRenderHint(QPainter::TextAntialiasing, _antialiased); + painter.setRenderHint(QPainter::SmoothPixmapTransform, _antialiased); - painter.setPen(pen); - painter.setBrush(brush); + painter.setPen(pen); + painter.setBrush(brush); } /** - @brief CustomElementGraphicPart::drawShadowShape - Draw a transparent blue shadow arround the shape of this item. - The QPainterPathStroker used to draw shadows have a width of SHADOWS_HEIGHT - Be carefull if penWeight of this item is to 0 the outline of strock is bigger of 0.5 - @param painter : painter to use for draw this shadows + @brief CustomElementGraphicPart::drawShadowShape + Draw a transparent blue shadow arround the shape of this item. + The QPainterPathStroker used to draw shadows have a width of SHADOWS_HEIGHT + Be carefull if penWeight of this item is to 0 the outline of strock is bigger of 0.5 + @param painter : painter to use for draw this shadows */ void CustomElementGraphicPart::drawShadowShape(QPainter *painter) { - //@FIXME if pen weight is 0, the strock outline is SHADOWS_HEIGHT/2 + 0.5 - //may be because shape have no line weight - QPainterPathStroker strock; - strock.setWidth(SHADOWS_HEIGHT); - strock.setJoinStyle(Qt::RoundJoin); + //@FIXME if pen weight is 0, the strock outline is SHADOWS_HEIGHT/2 + 0.5 + //may be because shape have no line weight + QPainterPathStroker strock; + strock.setWidth(SHADOWS_HEIGHT); + strock.setJoinStyle(Qt::RoundJoin); - painter->save(); - QColor color(Qt::darkBlue); - color.setAlpha(50); - painter -> setBrush (QBrush (color)); - painter -> setPen (Qt::NoPen); - painter -> drawPath (strock.createStroke(shadowShape())); - painter -> restore (); + painter->save(); + QColor color(Qt::darkBlue); + color.setAlpha(50); + painter -> setBrush (QBrush (color)); + painter -> setPen (Qt::NoPen); + painter -> drawPath (strock.createStroke(shadowShape())); + painter -> restore (); } /** - @brief CustomElementGraphicPart::itemChange - Reimplemented from QGraphicsObject. - If the item position change call updateCurrentPartEditor() - the change is always send to QGraphicsObject - @param change - @param value - @return the returned value of QGraphicsObject::itemChange + @brief CustomElementGraphicPart::itemChange + Reimplemented from QGraphicsObject. + If the item position change call updateCurrentPartEditor() + the change is always send to QGraphicsObject + @param change + @param value + @return the returned value of QGraphicsObject::itemChange */ QVariant CustomElementGraphicPart::itemChange(GraphicsItemChange change, const QVariant &value) { - if (scene()) - if (change == QGraphicsItem::ItemPositionChange || change == QGraphicsItem::ItemPositionHasChanged) - updateCurrentPartEditor(); + if (scene()) + if (change == QGraphicsItem::ItemPositionChange || change == QGraphicsItem::ItemPositionHasChanged) + updateCurrentPartEditor(); - return(QGraphicsObject::itemChange(change, value)); + return(QGraphicsObject::itemChange(change, value)); } /** - @brief CustomElementGraphicPart::hoverEnterEvent - Reimplemented from QGraphicsObject. - Set m_hovered to true - @param event + @brief CustomElementGraphicPart::hoverEnterEvent + Reimplemented from QGraphicsObject. + Set m_hovered to true + @param event */ void CustomElementGraphicPart::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - m_hovered = true; - QGraphicsObject::hoverEnterEvent(event); + m_hovered = true; + QGraphicsObject::hoverEnterEvent(event); } /** - @brief CustomElementGraphicPart::hoverLeaveEvent - Reimplemented from QGraphicsObject. - Set m_hovered to false - @param event + @brief CustomElementGraphicPart::hoverLeaveEvent + Reimplemented from QGraphicsObject. + Set m_hovered to false + @param event */ void CustomElementGraphicPart::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - m_hovered = false; - QGraphicsObject::hoverLeaveEvent(event); + m_hovered = false; + QGraphicsObject::hoverLeaveEvent(event); } void CustomElementGraphicPart::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if(event->button() == Qt::LeftButton) - m_origin_pos = this->pos(); + if(event->button() == Qt::LeftButton) + m_origin_pos = this->pos(); - QGraphicsObject::mousePressEvent(event); + QGraphicsObject::mousePressEvent(event); } void CustomElementGraphicPart::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if((event->buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) - { - QPointF pos = event->scenePos() + (m_origin_pos - event->buttonDownScenePos(Qt::LeftButton)); - event->modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene()->snapToGrid(pos)); - } - else - QGraphicsObject::mouseMoveEvent(event); + if((event->buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) + { + QPointF pos = event->scenePos() + (m_origin_pos - event->buttonDownScenePos(Qt::LeftButton)); + event->modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene()->snapToGrid(pos)); + } + else + QGraphicsObject::mouseMoveEvent(event); } void CustomElementGraphicPart::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if((event->button() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable) && m_origin_pos != pos()) - { - QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "pos", QVariant(m_origin_pos), QVariant(pos())); - undo->setText(tr("Déplacer une primitive")); - undo->enableAnimation(); - elementScene()->undoStack().push(undo); - } + if((event->button() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable) && m_origin_pos != pos()) + { + QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "pos", QVariant(m_origin_pos), QVariant(pos())); + undo->setText(tr("D??placer une primitive")); + undo->enableAnimation(); + elementScene()->undoStack().push(undo); + } - QGraphicsObject::mouseReleaseEvent(event); + QGraphicsObject::mouseReleaseEvent(event); } diff --git a/sources/editor/graphicspart/customelementgraphicpart.h b/sources/editor/graphicspart/customelementgraphicpart.h index 4131c86a1..4138d21e0 100644 --- a/sources/editor/graphicspart/customelementgraphicpart.h +++ b/sources/editor/graphicspart/customelementgraphicpart.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef CUSTOM_ELEMENT_GRAPHIC_PART_H #define CUSTOM_ELEMENT_GRAPHIC_PART_H @@ -26,308 +26,308 @@ class QPainter; /** - @brief The CustomElementGraphicPart class - This class is the base for all home-made primitive like line, - rectangle, ellipse etc.... - It provides methods and enums to manage style attributes available - for primitive (color, pen style, etc...) + @brief The CustomElementGraphicPart class + This class is the base for all home-made primitive like line, + rectangle, ellipse etc.... + It provides methods and enums to manage style attributes available + for primitive (color, pen style, etc...) */ class CustomElementGraphicPart : public QGraphicsObject, public CustomElementPart { - #define SHADOWS_HEIGHT 4.0 + #define SHADOWS_HEIGHT 4.0 - Q_OBJECT + Q_OBJECT - Q_PROPERTY(LineStyle line_style READ lineStyle WRITE setLineStyle) - Q_PROPERTY(LineWeight line_weight READ lineWeight WRITE setLineWeight) - Q_PROPERTY(Filling filling READ filling WRITE setFilling) - Q_PROPERTY(Color color READ color WRITE setColor) - Q_PROPERTY(bool antialias READ antialiased WRITE setAntialiased) + Q_PROPERTY(LineStyle line_style READ lineStyle WRITE setLineStyle) + Q_PROPERTY(LineWeight line_weight READ lineWeight WRITE setLineWeight) + Q_PROPERTY(Filling filling READ filling WRITE setFilling) + Q_PROPERTY(Color color READ color WRITE setColor) + Q_PROPERTY(bool antialias READ antialiased WRITE setAntialiased) - public: - //Line style - enum LineStyle {NormalStyle, - DashedStyle, - DottedStyle, - DashdottedStyle}; - Q_ENUM (LineStyle) + public: + //Line style + enum LineStyle {NormalStyle, + DashedStyle, + DottedStyle, + DashdottedStyle}; + Q_ENUM (LineStyle) - //Line weight : invisible, 0px, 1px, 2px, 5px - enum LineWeight {NoneWeight, - ThinWeight, - NormalWeight, - UltraWeight, - BigWeight}; - Q_ENUM (LineWeight) + //Line weight : invisible, 0px, 1px, 2px, 5px + enum LineWeight {NoneWeight, + ThinWeight, + NormalWeight, + UltraWeight, + BigWeight}; + Q_ENUM (LineWeight) - //Filling color of the part : NoneFilling -> No filling (i.e. transparent) - enum Filling { NoneFilling, BlackFilling, WhiteFilling, - GreenFilling, RedFilling, BlueFilling, - GrayFilling, BrunFilling, YellowFilling, - CyanFilling, MagentaFilling, LightgrayFilling, - OrangeFilling, PurpleFilling, - HTMLPinkPinkFilling, HTMLPinkLightPinkFilling, - HTMLPinkHotPinkFilling, HTMLPinkDeepPinkFilling, - HTMLPinkPaleVioletRedFilling, - HTMLPinkMediumVioletRedFilling, - HTMLRedLightSalmonFilling, HTMLRedSalmonFilling, - HTMLRedDarkSalmonFilling, - HTMLRedLightCoralFilling, - HTMLRedIndianRedFilling, HTMLRedCrimsonFilling, - HTMLRedFirebrickFilling, HTMLRedDarkRedFilling, - HTMLRedRedFilling, HTMLOrangeOrangeRedFilling, - HTMLOrangeTomatoFilling, HTMLOrangeCoralFilling, - HTMLOrangeDarkOrangeFilling, - HTMLOrangeOrangeFilling, HTMLYellowYellowFilling, - HTMLYellowLightYellowFilling, - HTMLYellowLemonChiffonFilling, - HTMLYellowLightGoldenrodYellowFilling, - HTMLYellowPapayaWhipFilling, - HTMLYellowMoccasinFilling, - HTMLYellowPeachPuffFilling, - HTMLYellowPaleGoldenrodFilling, - HTMLYellowKhakiFilling, - HTMLYellowDarkKhakiFilling, - HTMLYellowGoldFilling, HTMLBrownCornsilkFilling, - HTMLBrownBlanchedAlmondFilling, - HTMLBrownBisqueFilling, - HTMLBrownNavajoWhiteFilling, - HTMLBrownWheatFilling, HTMLBrownBurlywoodFilling, - HTMLBrownTanFilling, HTMLBrownRosyBrownFilling, - HTMLBrownSandyBrownFilling, - HTMLBrownGoldenrodFilling, - HTMLBrownDarkGoldenrodFilling, - HTMLBrownPeruFilling, HTMLBrownChocolateFilling, - HTMLBrownSaddleBrownFilling, - HTMLBrownSiennaFilling, HTMLBrownBrownFilling, - HTMLBrownMaroonFilling, - HTMLGreenDarkOliveGreenFilling, - HTMLGreenOliveFilling, HTMLGreenOliveDrabFilling, - HTMLGreenYellowGreenFilling, - HTMLGreenLimeGreenFilling, HTMLGreenLimeFilling, - HTMLGreenLawnGreenFilling, - HTMLGreenChartreuseFilling, - HTMLGreenGreenYellowFilling, - HTMLGreenSpringGreenFilling, - HTMLGreenMediumSpringGreenFilling, - HTMLGreenLightGreenFilling, - HTMLGreenPaleGreenFilling, - HTMLGreenDarkSeaGreenFilling, - HTMLGreenMediumAquamarineFilling, - HTMLGreenMediumSeaGreenFilling, - HTMLGreenSeaGreenFilling, - HTMLGreenForestGreenFilling, - HTMLGreenGreenFilling, HTMLGreenDarkGreenFilling, - HTMLCyanAquaFilling, HTMLCyanCyanFilling, - HTMLCyanLightCyanFilling, - HTMLCyanPaleTurquoiseFilling, - HTMLCyanAquamarineFilling, - HTMLCyanTurquoiseFilling, - HTMLCyanMediumTurquoiseFilling, - HTMLCyanDarkTurquoiseFilling, - HTMLCyanLightSeaGreenFilling, - HTMLCyanCadetBlueFilling, - HTMLCyanDarkCyanFilling, HTMLCyanTealFilling, - HTMLBlueLightSteelBlueFilling, - HTMLBluePowderBlueFilling, - HTMLBlueLightBlueFilling, HTMLBlueSkyBlueFilling, - HTMLBlueLightSkyBlueFilling, - HTMLBlueDeepSkyBlueFilling, - HTMLBlueDodgerBlueFilling, - HTMLBlueCornflowerBlueFilling, - HTMLBlueSteelBlueFilling, - HTMLBlueRoyalBlueFilling, HTMLBlueBlueFilling, - HTMLBlueMediumBlueFilling, - HTMLBlueDarkBlueFilling, HTMLBlueNavyFilling, - HTMLBlueMidnightBlueFilling, - HTMLPurpleLavenderFilling, - HTMLPurpleThistleFilling, HTMLPurplePlumFilling, - HTMLPurpleVioletFilling, HTMLPurpleOrchidFilling, - HTMLPurpleFuchsiaFilling, - HTMLPurpleMagentaFilling, - HTMLPurpleMediumOrchidFilling, - HTMLPurpleMediumPurpleFilling, - HTMLPurpleBlueVioletFilling, - HTMLPurpleDarkVioletFilling, - HTMLPurpleDarkOrchidFilling, - HTMLPurpleDarkMagentaFilling, - HTMLPurplePurpleFilling, HTMLPurpleIndigoFilling, - HTMLPurpleDarkSlateBlueFilling, - HTMLPurpleSlateBlueFilling, - HTMLPurpleMediumSlateBlueFilling, - HTMLWhiteWhiteFilling, HTMLWhiteSnowFilling, - HTMLWhiteHoneydewFilling, - HTMLWhiteMintCreamFilling, HTMLWhiteAzureFilling, - HTMLWhiteAliceBlueFilling, - HTMLWhiteGhostWhiteFilling, - HTMLWhiteWhiteSmokeFilling, - HTMLWhiteSeashellFilling, HTMLWhiteBeigeFilling, - HTMLWhiteOldLaceFilling, - HTMLWhiteFloralWhiteFilling, - HTMLWhiteIvoryFilling, - HTMLWhiteAntiqueWhiteFilling, - HTMLWhiteLinenFilling, - HTMLWhiteLavenderBlushFilling, - HTMLWhiteMistyRoseFilling, - HTMLGrayGainsboroFilling, - HTMLGrayLightGrayFilling, HTMLGraySilverFilling, - HTMLGrayDarkGrayFilling, HTMLGrayGrayFilling, - HTMLGrayDimGrayFilling, - HTMLGrayLightSlateGrayFilling, - HTMLGraySlateGrayFilling, - HTMLGrayDarkSlateGrayFilling, - HTMLGrayBlackFilling, HorFilling, VerFilling, - BdiagFilling, FdiagFilling}; - Q_ENUM (Filling) + //Filling color of the part : NoneFilling -> No filling (i.e. transparent) + enum Filling { NoneFilling, BlackFilling, WhiteFilling, + GreenFilling, RedFilling, BlueFilling, + GrayFilling, BrunFilling, YellowFilling, + CyanFilling, MagentaFilling, LightgrayFilling, + OrangeFilling, PurpleFilling, + HTMLPinkPinkFilling, HTMLPinkLightPinkFilling, + HTMLPinkHotPinkFilling, HTMLPinkDeepPinkFilling, + HTMLPinkPaleVioletRedFilling, + HTMLPinkMediumVioletRedFilling, + HTMLRedLightSalmonFilling, HTMLRedSalmonFilling, + HTMLRedDarkSalmonFilling, + HTMLRedLightCoralFilling, + HTMLRedIndianRedFilling, HTMLRedCrimsonFilling, + HTMLRedFirebrickFilling, HTMLRedDarkRedFilling, + HTMLRedRedFilling, HTMLOrangeOrangeRedFilling, + HTMLOrangeTomatoFilling, HTMLOrangeCoralFilling, + HTMLOrangeDarkOrangeFilling, + HTMLOrangeOrangeFilling, HTMLYellowYellowFilling, + HTMLYellowLightYellowFilling, + HTMLYellowLemonChiffonFilling, + HTMLYellowLightGoldenrodYellowFilling, + HTMLYellowPapayaWhipFilling, + HTMLYellowMoccasinFilling, + HTMLYellowPeachPuffFilling, + HTMLYellowPaleGoldenrodFilling, + HTMLYellowKhakiFilling, + HTMLYellowDarkKhakiFilling, + HTMLYellowGoldFilling, HTMLBrownCornsilkFilling, + HTMLBrownBlanchedAlmondFilling, + HTMLBrownBisqueFilling, + HTMLBrownNavajoWhiteFilling, + HTMLBrownWheatFilling, HTMLBrownBurlywoodFilling, + HTMLBrownTanFilling, HTMLBrownRosyBrownFilling, + HTMLBrownSandyBrownFilling, + HTMLBrownGoldenrodFilling, + HTMLBrownDarkGoldenrodFilling, + HTMLBrownPeruFilling, HTMLBrownChocolateFilling, + HTMLBrownSaddleBrownFilling, + HTMLBrownSiennaFilling, HTMLBrownBrownFilling, + HTMLBrownMaroonFilling, + HTMLGreenDarkOliveGreenFilling, + HTMLGreenOliveFilling, HTMLGreenOliveDrabFilling, + HTMLGreenYellowGreenFilling, + HTMLGreenLimeGreenFilling, HTMLGreenLimeFilling, + HTMLGreenLawnGreenFilling, + HTMLGreenChartreuseFilling, + HTMLGreenGreenYellowFilling, + HTMLGreenSpringGreenFilling, + HTMLGreenMediumSpringGreenFilling, + HTMLGreenLightGreenFilling, + HTMLGreenPaleGreenFilling, + HTMLGreenDarkSeaGreenFilling, + HTMLGreenMediumAquamarineFilling, + HTMLGreenMediumSeaGreenFilling, + HTMLGreenSeaGreenFilling, + HTMLGreenForestGreenFilling, + HTMLGreenGreenFilling, HTMLGreenDarkGreenFilling, + HTMLCyanAquaFilling, HTMLCyanCyanFilling, + HTMLCyanLightCyanFilling, + HTMLCyanPaleTurquoiseFilling, + HTMLCyanAquamarineFilling, + HTMLCyanTurquoiseFilling, + HTMLCyanMediumTurquoiseFilling, + HTMLCyanDarkTurquoiseFilling, + HTMLCyanLightSeaGreenFilling, + HTMLCyanCadetBlueFilling, + HTMLCyanDarkCyanFilling, HTMLCyanTealFilling, + HTMLBlueLightSteelBlueFilling, + HTMLBluePowderBlueFilling, + HTMLBlueLightBlueFilling, HTMLBlueSkyBlueFilling, + HTMLBlueLightSkyBlueFilling, + HTMLBlueDeepSkyBlueFilling, + HTMLBlueDodgerBlueFilling, + HTMLBlueCornflowerBlueFilling, + HTMLBlueSteelBlueFilling, + HTMLBlueRoyalBlueFilling, HTMLBlueBlueFilling, + HTMLBlueMediumBlueFilling, + HTMLBlueDarkBlueFilling, HTMLBlueNavyFilling, + HTMLBlueMidnightBlueFilling, + HTMLPurpleLavenderFilling, + HTMLPurpleThistleFilling, HTMLPurplePlumFilling, + HTMLPurpleVioletFilling, HTMLPurpleOrchidFilling, + HTMLPurpleFuchsiaFilling, + HTMLPurpleMagentaFilling, + HTMLPurpleMediumOrchidFilling, + HTMLPurpleMediumPurpleFilling, + HTMLPurpleBlueVioletFilling, + HTMLPurpleDarkVioletFilling, + HTMLPurpleDarkOrchidFilling, + HTMLPurpleDarkMagentaFilling, + HTMLPurplePurpleFilling, HTMLPurpleIndigoFilling, + HTMLPurpleDarkSlateBlueFilling, + HTMLPurpleSlateBlueFilling, + HTMLPurpleMediumSlateBlueFilling, + HTMLWhiteWhiteFilling, HTMLWhiteSnowFilling, + HTMLWhiteHoneydewFilling, + HTMLWhiteMintCreamFilling, HTMLWhiteAzureFilling, + HTMLWhiteAliceBlueFilling, + HTMLWhiteGhostWhiteFilling, + HTMLWhiteWhiteSmokeFilling, + HTMLWhiteSeashellFilling, HTMLWhiteBeigeFilling, + HTMLWhiteOldLaceFilling, + HTMLWhiteFloralWhiteFilling, + HTMLWhiteIvoryFilling, + HTMLWhiteAntiqueWhiteFilling, + HTMLWhiteLinenFilling, + HTMLWhiteLavenderBlushFilling, + HTMLWhiteMistyRoseFilling, + HTMLGrayGainsboroFilling, + HTMLGrayLightGrayFilling, HTMLGraySilverFilling, + HTMLGrayDarkGrayFilling, HTMLGrayGrayFilling, + HTMLGrayDimGrayFilling, + HTMLGrayLightSlateGrayFilling, + HTMLGraySlateGrayFilling, + HTMLGrayDarkSlateGrayFilling, + HTMLGrayBlackFilling, HorFilling, VerFilling, + BdiagFilling, FdiagFilling}; + Q_ENUM (Filling) - //Line color - enum Color { - BlackColor, WhiteColor, GreenColor, RedColor, BlueColor, - GrayColor, BrunColor, YellowColor, CyanColor, - MagentaColor, LightgrayColor, OrangeColor, PurpleColor, - HTMLPinkPinkColor, HTMLPinkLightPinkColor, - HTMLPinkHotPinkColor, HTMLPinkDeepPinkColor, - HTMLPinkPaleVioletRedColor, - HTMLPinkMediumVioletRedColor, HTMLRedLightSalmonColor, - HTMLRedSalmonColor, HTMLRedDarkSalmonColor, - HTMLRedLightCoralColor, HTMLRedIndianRedColor, - HTMLRedCrimsonColor, HTMLRedFirebrickColor, - HTMLRedDarkRedColor, HTMLRedRedColor, - HTMLOrangeOrangeRedColor, HTMLOrangeTomatoColor, - HTMLOrangeCoralColor, HTMLOrangeDarkOrangeColor, - HTMLOrangeOrangeColor, HTMLYellowYellowColor, - HTMLYellowLightYellowColor, HTMLYellowLemonChiffonColor, - HTMLYellowLightGoldenrodYellowColor, - HTMLYellowPapayaWhipColor, HTMLYellowMoccasinColor, - HTMLYellowPeachPuffColor, HTMLYellowPaleGoldenrodColor, - HTMLYellowKhakiColor, HTMLYellowDarkKhakiColor, - HTMLYellowGoldColor, HTMLBrownCornsilkColor, - HTMLBrownBlanchedAlmondColor, HTMLBrownBisqueColor, - HTMLBrownNavajoWhiteColor, HTMLBrownWheatColor, - HTMLBrownBurlywoodColor, HTMLBrownTanColor, - HTMLBrownRosyBrownColor, HTMLBrownSandyBrownColor, - HTMLBrownGoldenrodColor, HTMLBrownDarkGoldenrodColor, - HTMLBrownPeruColor, HTMLBrownChocolateColor, - HTMLBrownSaddleBrownColor, HTMLBrownSiennaColor, - HTMLBrownBrownColor, HTMLBrownMaroonColor, - HTMLGreenDarkOliveGreenColor, HTMLGreenOliveColor, - HTMLGreenOliveDrabColor, HTMLGreenYellowGreenColor, - HTMLGreenLimeGreenColor, HTMLGreenLimeColor, - HTMLGreenLawnGreenColor, HTMLGreenChartreuseColor, - HTMLGreenGreenYellowColor, HTMLGreenSpringGreenColor, - HTMLGreenMediumSpringGreenColor, - HTMLGreenLightGreenColor, HTMLGreenPaleGreenColor, - HTMLGreenDarkSeaGreenColor, - HTMLGreenMediumAquamarineColor, - HTMLGreenMediumSeaGreenColor, HTMLGreenSeaGreenColor, - HTMLGreenForestGreenColor, HTMLGreenGreenColor, - HTMLGreenDarkGreenColor, HTMLCyanAquaColor, - HTMLCyanCyanColor, HTMLCyanLightCyanColor, - HTMLCyanPaleTurquoiseColor, HTMLCyanAquamarineColor, - HTMLCyanTurquoiseColor, HTMLCyanMediumTurquoiseColor, - HTMLCyanDarkTurquoiseColor, HTMLCyanLightSeaGreenColor, - HTMLCyanCadetBlueColor, HTMLCyanDarkCyanColor, - HTMLCyanTealColor, HTMLBlueLightSteelBlueColor, - HTMLBluePowderBlueColor, HTMLBlueLightBlueColor, - HTMLBlueSkyBlueColor, HTMLBlueLightSkyBlueColor, - HTMLBlueDeepSkyBlueColor, HTMLBlueDodgerBlueColor, - HTMLBlueCornflowerBlueColor, HTMLBlueSteelBlueColor, - HTMLBlueRoyalBlueColor, HTMLBlueBlueColor, - HTMLBlueMediumBlueColor, HTMLBlueDarkBlueColor, - HTMLBlueNavyColor, HTMLBlueMidnightBlueColor, - HTMLPurpleLavenderColor, HTMLPurpleThistleColor, - HTMLPurplePlumColor, HTMLPurpleVioletColor, - HTMLPurpleOrchidColor, HTMLPurpleFuchsiaColor, - HTMLPurpleMagentaColor, HTMLPurpleMediumOrchidColor, - HTMLPurpleMediumPurpleColor, HTMLPurpleBlueVioletColor, - HTMLPurpleDarkVioletColor, HTMLPurpleDarkOrchidColor, - HTMLPurpleDarkMagentaColor, HTMLPurplePurpleColor, - HTMLPurpleIndigoColor, HTMLPurpleDarkSlateBlueColor, - HTMLPurpleSlateBlueColor, - HTMLPurpleMediumSlateBlueColor, - HTMLWhiteWhiteColor, HTMLWhiteSnowColor, - HTMLWhiteHoneydewColor, HTMLWhiteMintCreamColor, - HTMLWhiteAzureColor, HTMLWhiteAliceBlueColor, - HTMLWhiteGhostWhiteColor, HTMLWhiteWhiteSmokeColor, - HTMLWhiteSeashellColor, HTMLWhiteBeigeColor, - HTMLWhiteOldLaceColor, HTMLWhiteFloralWhiteColor, - HTMLWhiteIvoryColor, HTMLWhiteAntiqueWhiteColor, - HTMLWhiteLinenColor, HTMLWhiteLavenderBlushColor, - HTMLWhiteMistyRoseColor, HTMLGrayGainsboroColor, - HTMLGrayLightGrayColor, HTMLGraySilverColor, - HTMLGrayDarkGrayColor, HTMLGrayGrayColor, - HTMLGrayDimGrayColor, HTMLGrayLightSlateGrayColor, - HTMLGraySlateGrayColor, HTMLGrayDarkSlateGrayColor, - HTMLGrayBlackColor, NoneColor}; - Q_ENUM (Color) + //Line color + enum Color { + BlackColor, WhiteColor, GreenColor, RedColor, BlueColor, + GrayColor, BrunColor, YellowColor, CyanColor, + MagentaColor, LightgrayColor, OrangeColor, PurpleColor, + HTMLPinkPinkColor, HTMLPinkLightPinkColor, + HTMLPinkHotPinkColor, HTMLPinkDeepPinkColor, + HTMLPinkPaleVioletRedColor, + HTMLPinkMediumVioletRedColor, HTMLRedLightSalmonColor, + HTMLRedSalmonColor, HTMLRedDarkSalmonColor, + HTMLRedLightCoralColor, HTMLRedIndianRedColor, + HTMLRedCrimsonColor, HTMLRedFirebrickColor, + HTMLRedDarkRedColor, HTMLRedRedColor, + HTMLOrangeOrangeRedColor, HTMLOrangeTomatoColor, + HTMLOrangeCoralColor, HTMLOrangeDarkOrangeColor, + HTMLOrangeOrangeColor, HTMLYellowYellowColor, + HTMLYellowLightYellowColor, HTMLYellowLemonChiffonColor, + HTMLYellowLightGoldenrodYellowColor, + HTMLYellowPapayaWhipColor, HTMLYellowMoccasinColor, + HTMLYellowPeachPuffColor, HTMLYellowPaleGoldenrodColor, + HTMLYellowKhakiColor, HTMLYellowDarkKhakiColor, + HTMLYellowGoldColor, HTMLBrownCornsilkColor, + HTMLBrownBlanchedAlmondColor, HTMLBrownBisqueColor, + HTMLBrownNavajoWhiteColor, HTMLBrownWheatColor, + HTMLBrownBurlywoodColor, HTMLBrownTanColor, + HTMLBrownRosyBrownColor, HTMLBrownSandyBrownColor, + HTMLBrownGoldenrodColor, HTMLBrownDarkGoldenrodColor, + HTMLBrownPeruColor, HTMLBrownChocolateColor, + HTMLBrownSaddleBrownColor, HTMLBrownSiennaColor, + HTMLBrownBrownColor, HTMLBrownMaroonColor, + HTMLGreenDarkOliveGreenColor, HTMLGreenOliveColor, + HTMLGreenOliveDrabColor, HTMLGreenYellowGreenColor, + HTMLGreenLimeGreenColor, HTMLGreenLimeColor, + HTMLGreenLawnGreenColor, HTMLGreenChartreuseColor, + HTMLGreenGreenYellowColor, HTMLGreenSpringGreenColor, + HTMLGreenMediumSpringGreenColor, + HTMLGreenLightGreenColor, HTMLGreenPaleGreenColor, + HTMLGreenDarkSeaGreenColor, + HTMLGreenMediumAquamarineColor, + HTMLGreenMediumSeaGreenColor, HTMLGreenSeaGreenColor, + HTMLGreenForestGreenColor, HTMLGreenGreenColor, + HTMLGreenDarkGreenColor, HTMLCyanAquaColor, + HTMLCyanCyanColor, HTMLCyanLightCyanColor, + HTMLCyanPaleTurquoiseColor, HTMLCyanAquamarineColor, + HTMLCyanTurquoiseColor, HTMLCyanMediumTurquoiseColor, + HTMLCyanDarkTurquoiseColor, HTMLCyanLightSeaGreenColor, + HTMLCyanCadetBlueColor, HTMLCyanDarkCyanColor, + HTMLCyanTealColor, HTMLBlueLightSteelBlueColor, + HTMLBluePowderBlueColor, HTMLBlueLightBlueColor, + HTMLBlueSkyBlueColor, HTMLBlueLightSkyBlueColor, + HTMLBlueDeepSkyBlueColor, HTMLBlueDodgerBlueColor, + HTMLBlueCornflowerBlueColor, HTMLBlueSteelBlueColor, + HTMLBlueRoyalBlueColor, HTMLBlueBlueColor, + HTMLBlueMediumBlueColor, HTMLBlueDarkBlueColor, + HTMLBlueNavyColor, HTMLBlueMidnightBlueColor, + HTMLPurpleLavenderColor, HTMLPurpleThistleColor, + HTMLPurplePlumColor, HTMLPurpleVioletColor, + HTMLPurpleOrchidColor, HTMLPurpleFuchsiaColor, + HTMLPurpleMagentaColor, HTMLPurpleMediumOrchidColor, + HTMLPurpleMediumPurpleColor, HTMLPurpleBlueVioletColor, + HTMLPurpleDarkVioletColor, HTMLPurpleDarkOrchidColor, + HTMLPurpleDarkMagentaColor, HTMLPurplePurpleColor, + HTMLPurpleIndigoColor, HTMLPurpleDarkSlateBlueColor, + HTMLPurpleSlateBlueColor, + HTMLPurpleMediumSlateBlueColor, + HTMLWhiteWhiteColor, HTMLWhiteSnowColor, + HTMLWhiteHoneydewColor, HTMLWhiteMintCreamColor, + HTMLWhiteAzureColor, HTMLWhiteAliceBlueColor, + HTMLWhiteGhostWhiteColor, HTMLWhiteWhiteSmokeColor, + HTMLWhiteSeashellColor, HTMLWhiteBeigeColor, + HTMLWhiteOldLaceColor, HTMLWhiteFloralWhiteColor, + HTMLWhiteIvoryColor, HTMLWhiteAntiqueWhiteColor, + HTMLWhiteLinenColor, HTMLWhiteLavenderBlushColor, + HTMLWhiteMistyRoseColor, HTMLGrayGainsboroColor, + HTMLGrayLightGrayColor, HTMLGraySilverColor, + HTMLGrayDarkGrayColor, HTMLGrayGrayColor, + HTMLGrayDimGrayColor, HTMLGrayLightSlateGrayColor, + HTMLGraySlateGrayColor, HTMLGrayDarkSlateGrayColor, + HTMLGrayBlackColor, NoneColor}; + Q_ENUM (Color) - // constructors, destructor - public: + // constructors, destructor + public: - CustomElementGraphicPart(QETElementEditor *editor, - QGraphicsItem *parent = nullptr); - ~CustomElementGraphicPart() override; + CustomElementGraphicPart(QETElementEditor *editor, + QGraphicsItem *parent = nullptr); + ~CustomElementGraphicPart() override; - static void drawCross (const QPointF ¢er, - QPainter *painter); + static void drawCross (const QPointF ¢er, + QPainter *painter); - //Getter and setter - LineStyle lineStyle () const {return _linestyle;} - void setLineStyle (const LineStyle ls); + //Getter and setter + LineStyle lineStyle () const {return _linestyle;} + void setLineStyle (const LineStyle ls); - LineWeight lineWeight () const {return _lineweight;} - void setLineWeight (const LineWeight lw); - qreal penWeight () const; + LineWeight lineWeight () const {return _lineweight;} + void setLineWeight (const LineWeight lw); + qreal penWeight () const; - Filling filling () const {return _filling;} - void setFilling(const Filling f); + Filling filling () const {return _filling;} + void setFilling(const Filling f); - Color color () const {return _color;} - void setColor(const Color c); + Color color () const {return _color;} + void setColor(const Color c); - bool antialiased () const {return _antialiased;} - void setAntialiased(const bool b); - //End of getter and setter + bool antialiased () const {return _antialiased;} + void setAntialiased(const bool b); + //End of getter and setter - //Rediriged to QObject Q_PROPERTY system - void setProperty (const char *name, - const QVariant &value) override { - QObject::setProperty(name, value);} - QVariant property (const char *name) const override { - return QObject::property(name);} + //Rediriged to QObject Q_PROPERTY system + void setProperty (const char *name, + const QVariant &value) override { + QObject::setProperty(name, value);} + QVariant property (const char *name) const override { + return QObject::property(name);} - virtual QPainterPath shadowShape ()const = 0; - virtual void setHandlerColor(QPointF /*pos*/, - const QColor &/*color*/) {} - virtual void resetAllHandlerColor() {} + virtual QPainterPath shadowShape ()const = 0; + virtual void setHandlerColor(QPointF /*pos*/, + const QColor &/*color*/) {} + virtual void resetAllHandlerColor() {} - protected: - void stylesToXml (QDomElement &) const; - void stylesFromXml(const QDomElement &); - void resetStyles (); - void applyStylesToQPainter(QPainter &) const; - void drawShadowShape (QPainter *painter); + protected: + void stylesToXml (QDomElement &) const; + void stylesFromXml(const QDomElement &); + void resetStyles (); + void applyStylesToQPainter(QPainter &) const; + void drawShadowShape (QPainter *painter); - QVariant itemChange(GraphicsItemChange change, - const QVariant &value) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + QVariant itemChange(GraphicsItemChange change, + const QVariant &value) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent( - QGraphicsSceneMouseEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent( + QGraphicsSceneMouseEvent *event) override; - // attributes - bool m_hovered; - private: - LineStyle _linestyle; - LineWeight _lineweight; - Filling _filling ; - Color _color; - bool _antialiased; - QPointF m_origin_pos; + // attributes + bool m_hovered; + private: + LineStyle _linestyle; + LineWeight _lineweight; + Filling _filling ; + Color _color; + bool _antialiased; + QPointF m_origin_pos; }; typedef CustomElementGraphicPart CEGP; diff --git a/sources/editor/graphicspart/customelementpart.h b/sources/editor/graphicspart/customelementpart.h index 9f3eaddc7..a4e88ad96 100644 --- a/sources/editor/graphicspart/customelementpart.h +++ b/sources/editor/graphicspart/customelementpart.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef CUSTOM_ELEMENT_PART_H #define CUSTOM_ELEMENT_PART_H @@ -29,94 +29,94 @@ class QGraphicsItem; class QGraphicsSceneMouseEvent; /** - @brief The CustomElementPart class - This abstract class represents a primitive of - the visual representation of an electrical element. - The Element, FixedElement and CustomElement classes do not embed - its attributes and methods in order to remain lightweight; indeed, - there is no point for those classes to store their visual representation - with anything more complex than a QImage. + @brief The CustomElementPart class + This abstract class represents a primitive of + the visual representation of an electrical element. + The Element, FixedElement and CustomElement classes do not embed + its attributes and methods in order to remain lightweight; indeed, + there is no point for those classes to store their visual representation + with anything more complex than a QImage. */ class CustomElementPart { - // constructors, destructor - public: - /** - @brief CustomElementPart - Constructor - @param editor Element editor this primitive is attached to - */ - CustomElementPart(QETElementEditor *editor) : element_editor(editor) {} - /** - @brief ~CustomElementPart - Destructor - */ - virtual ~CustomElementPart() {} - - private: - CustomElementPart(const CustomElementPart &); - - // attributes - private: - QETElementEditor *element_editor; - - // methods - public: - /** - Load the primitive from an XML element that describes it - */ - virtual void fromXml(const QDomElement &) = 0; - /** - Export the primitive as an XML element - */ - virtual const QDomElement toXml(QDomDocument &) const = 0; - /** - Set a specific property of the primitive - */ - virtual void setProperty(const char *name, const QVariant &value) = 0; - /** - Get the current value of a specific primitive property - */ - virtual QVariant property(const char *name) const = 0; - /** - @return whether the primitive appears to be useless (e.g. 0-length line) - Typically, useless primitives are discarded when saving the element. - */ - virtual bool isUseless() const = 0; - virtual QRectF sceneGeometricRect() const = 0; - /** - Inform this part a user-induced transformation is about to begin. - This method can be used to save data required by handleUserTransformation(). - */ - virtual void startUserTransformation(const QRectF &) = 0; - /** - Make this part fit into the provided rectangle. - */ - virtual void handleUserTransformation(const QRectF &, - const QRectF &) = 0; - /// @return a pointer to the parent element editor - virtual QETElementEditor *elementEditor() const; - /** - Call the updateCurrentPartEditor() slot of the editor - @see QETElementEditor::updateCurrentPartEditor() - */ - virtual void updateCurrentPartEditor() const; - /// @return a pointer to the parent editing scene - virtual ElementScene *elementScene() const; - /// @return the element editor undo stack - virtual QUndoStack &undoStack() const; - /// @return the name of the primitive - virtual QString name() const = 0; - /// @return the name that will be used as XML tag when exporting the primitive - virtual QString xmlName() const = 0; - - virtual QGraphicsItem *toItem(); - - virtual QET::ScalingMethod preferredScalingMethod() const; - - protected: - QList mapPoints( - const QRectF &, - const QRectF &, - const QList &); + // constructors, destructor + public: + /** + @brief CustomElementPart + Constructor + @param editor Element editor this primitive is attached to + */ + CustomElementPart(QETElementEditor *editor) : element_editor(editor) {} + /** + @brief ~CustomElementPart + Destructor + */ + virtual ~CustomElementPart() {} + + private: + CustomElementPart(const CustomElementPart &); + + // attributes + private: + QETElementEditor *element_editor; + + // methods + public: + /** + Load the primitive from an XML element that describes it + */ + virtual void fromXml(const QDomElement &) = 0; + /** + Export the primitive as an XML element + */ + virtual const QDomElement toXml(QDomDocument &) const = 0; + /** + Set a specific property of the primitive + */ + virtual void setProperty(const char *name, const QVariant &value) = 0; + /** + Get the current value of a specific primitive property + */ + virtual QVariant property(const char *name) const = 0; + /** + @return whether the primitive appears to be useless (e.g. 0-length line) + Typically, useless primitives are discarded when saving the element. + */ + virtual bool isUseless() const = 0; + virtual QRectF sceneGeometricRect() const = 0; + /** + Inform this part a user-induced transformation is about to begin. + This method can be used to save data required by handleUserTransformation(). + */ + virtual void startUserTransformation(const QRectF &) = 0; + /** + Make this part fit into the provided rectangle. + */ + virtual void handleUserTransformation(const QRectF &, + const QRectF &) = 0; + /// @return a pointer to the parent element editor + virtual QETElementEditor *elementEditor() const; + /** + Call the updateCurrentPartEditor() slot of the editor + @see QETElementEditor::updateCurrentPartEditor() + */ + virtual void updateCurrentPartEditor() const; + /// @return a pointer to the parent editing scene + virtual ElementScene *elementScene() const; + /// @return the element editor undo stack + virtual QUndoStack &undoStack() const; + /// @return the name of the primitive + virtual QString name() const = 0; + /// @return the name that will be used as XML tag when exporting the primitive + virtual QString xmlName() const = 0; + + virtual QGraphicsItem *toItem(); + + virtual QET::ScalingMethod preferredScalingMethod() const; + + protected: + QList mapPoints( + const QRectF &, + const QRectF &, + const QList &); }; #endif diff --git a/sources/editor/graphicspart/partarc.cpp b/sources/editor/graphicspart/partarc.cpp index 1b3430d8c..6c33a5b98 100644 --- a/sources/editor/graphicspart/partarc.cpp +++ b/sources/editor/graphicspart/partarc.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partarc.h" #include "QPropertyUndoCommand/qpropertyundocommand.h" @@ -23,143 +23,143 @@ /** - @brief PartArc::PartArc - Constructor - @param editor : QETElementEditor of this part - @param parent : parent item + @brief PartArc::PartArc + Constructor + @param editor : QETElementEditor of this part + @param parent : parent item */ PartArc::PartArc(QETElementEditor *editor, QGraphicsItem *parent) : - AbstractPartEllipse(editor, parent) + AbstractPartEllipse(editor, parent) { - m_start_angle = 0; - m_span_angle = -1440; + m_start_angle = 0; + m_span_angle = -1440; } /** - @brief PartArc::~PartArc - Destructor + @brief PartArc::~PartArc + Destructor */ PartArc::~PartArc() { - if(m_undo_command) delete m_undo_command; - removeHandler(); + if(m_undo_command) delete m_undo_command; + removeHandler(); } /** - @brief PartArc::paint - Draw this arc - @param painter - @param options - @param widget + @brief PartArc::paint + Draw this arc + @param painter + @param options + @param widget */ void PartArc::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget) { - Q_UNUSED(widget) + Q_UNUSED(widget) - applyStylesToQPainter(*painter); + applyStylesToQPainter(*painter); - //Always remove the brush - painter -> setBrush(Qt::NoBrush); - QPen t = painter -> pen(); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - t.setCosmetic(options && options -> levelOfDetail < 1.0); + //Always remove the brush + painter -> setBrush(Qt::NoBrush); + QPen t = painter -> pen(); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + t.setCosmetic(options && options -> levelOfDetail < 1.0); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); + t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); #endif - painter -> setPen(t); + painter -> setPen(t); - if (isSelected()) - { - painter->save(); - QPen pen(Qt::DotLine); - pen.setWidth(1); - pen.setCosmetic(true); - painter->setPen(pen); - //Draw the ellipse in black - painter -> drawEllipse(rect()); - painter->restore(); + if (isSelected()) + { + painter->save(); + QPen pen(Qt::DotLine); + pen.setWidth(1); + pen.setCosmetic(true); + painter->setPen(pen); + //Draw the ellipse in black + painter -> drawEllipse(rect()); + painter->restore(); - //Draw the arc in red - t.setColor(Qt::red); - painter -> setPen(t); - } + //Draw the arc in red + t.setColor(Qt::red); + painter -> setPen(t); + } - painter->drawArc(m_rect, m_start_angle, m_span_angle); + painter->drawArc(m_rect, m_start_angle, m_span_angle); - if (m_hovered) - drawShadowShape(painter); + if (m_hovered) + drawShadowShape(painter); - if (isSelected()) - drawCross(m_rect.center(), painter); + if (isSelected()) + drawCross(m_rect.center(), painter); } /** - @brief PartArc::toXml - Export this arc in xml - @param xml_document : Xml document to use for create the xml element. - @return : an xml element that describe this arc + @brief PartArc::toXml + Export this arc in xml + @param xml_document : Xml document to use for create the xml element. + @return : an xml element that describe this arc */ const QDomElement PartArc::toXml(QDomDocument &xml_document) const { - QDomElement xml_element = xml_document.createElement("arc"); - QPointF top_left(sceneTopLeft()); - xml_element.setAttribute("x", QString("%1").arg(top_left.x())); - xml_element.setAttribute("y", QString("%1").arg(top_left.y())); - xml_element.setAttribute("width", QString("%1").arg(rect().width())); - xml_element.setAttribute("height", QString("%1").arg(rect().height())); - //to maintain compatibility with the previous version, we write the angle in degrees. - xml_element.setAttribute("start", QString("%1").arg(m_start_angle / 16)); - xml_element.setAttribute("angle", QString("%1").arg(m_span_angle / 16)); - stylesToXml(xml_element); - return(xml_element); + QDomElement xml_element = xml_document.createElement("arc"); + QPointF top_left(sceneTopLeft()); + xml_element.setAttribute("x", QString("%1").arg(top_left.x())); + xml_element.setAttribute("y", QString("%1").arg(top_left.y())); + xml_element.setAttribute("width", QString("%1").arg(rect().width())); + xml_element.setAttribute("height", QString("%1").arg(rect().height())); + //to maintain compatibility with the previous version, we write the angle in degrees. + xml_element.setAttribute("start", QString("%1").arg(m_start_angle / 16)); + xml_element.setAttribute("angle", QString("%1").arg(m_span_angle / 16)); + stylesToXml(xml_element); + return(xml_element); } /** - @brief PartArc::fromXml - Import the properties of this arc from a xml element. - @param qde : Xml document to use. + @brief PartArc::fromXml + Import the properties of this arc from a xml element. + @param qde : Xml document to use. */ void PartArc::fromXml(const QDomElement &qde) { - stylesFromXml(qde); - m_rect = QRectF(mapFromScene(qde.attribute("x", "0").toDouble(), - qde.attribute("y", "0").toDouble()), - QSizeF(qde.attribute("width", "0").toDouble(), - qde.attribute("height", "0").toDouble()) ); + stylesFromXml(qde); + m_rect = QRectF(mapFromScene(qde.attribute("x", "0").toDouble(), + qde.attribute("y", "0").toDouble()), + QSizeF(qde.attribute("width", "0").toDouble(), + qde.attribute("height", "0").toDouble()) ); - m_start_angle = qde.attribute("start", "0").toDouble() * 16; - m_span_angle = qde.attribute("angle", "-1440").toDouble() * 16; + m_start_angle = qde.attribute("start", "0").toDouble() * 16; + m_span_angle = qde.attribute("angle", "-1440").toDouble() * 16; } /** - @brief PartArc::shape - @return the shape of this item + @brief PartArc::shape + @return the shape of this item */ QPainterPath PartArc::shape() const { - QPainterPath shape; - shape.arcMoveTo(m_rect, m_start_angle/16); - shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16); + QPainterPath shape; + shape.arcMoveTo(m_rect, m_start_angle/16); + shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16); - QPainterPathStroker pps; - pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); - shape = pps.createStroke(shape); + QPainterPathStroker pps; + pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); + shape = pps.createStroke(shape); - return shape; + return shape; } QPainterPath PartArc::shadowShape() const { - QPainterPath shape; - shape.arcMoveTo(m_rect, m_start_angle/16); - shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16); + QPainterPath shape; + shape.arcMoveTo(m_rect, m_start_angle/16); + shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16); - QPainterPathStroker pps; - pps.setWidth(penWeight()); + QPainterPathStroker pps; + pps.setWidth(penWeight()); - return (pps.createStroke(shape)); + return (pps.createStroke(shape)); } /** @@ -173,327 +173,327 @@ QPainterPath PartArc::shadowShape() const */ QRectF PartArc::sceneGeometricRect() const { - return mapToScene(QetGraphicsHandlerUtility::rectForArc(m_rect, m_start_angle/16, m_span_angle/16)).boundingRect(); + return mapToScene(QetGraphicsHandlerUtility::rectForArc(m_rect, m_start_angle/16, m_span_angle/16)).boundingRect(); } /** - @brief PartArc::mouseReleaseEvent - Handle mouse release event - @param event + @brief PartArc::mouseReleaseEvent + Handle mouse release event + @param event */ void PartArc::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) - switchResizeMode(); + if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) + switchResizeMode(); - CustomElementGraphicPart::mouseReleaseEvent(event); + CustomElementGraphicPart::mouseReleaseEvent(event); } /** - @brief PartArc::itemChange - @param change - @param value - @return + @brief PartArc::itemChange + @param change + @param value + @return */ QVariant PartArc::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged && scene()) - { - if (value.toBool() == true) - { - //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, - //according to the number of selected items. - connect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); + if (change == ItemSelectedHasChanged && scene()) + { + if (value.toBool() == true) + { + //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, + //according to the number of selected items. + connect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); - if (scene()->selectedItems().size() == 1) - addHandler(); - } - else - { - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); - removeHandler(); - } - } - else if (change == ItemPositionHasChanged) - { - adjusteHandlerPos(); - } - else if (change == ItemSceneChange) - { - if(scene()) - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); + if (scene()->selectedItems().size() == 1) + addHandler(); + } + else + { + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); + removeHandler(); + } + } + else if (change == ItemPositionHasChanged) + { + adjusteHandlerPos(); + } + else if (change == ItemSceneChange) + { + if(scene()) + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); - setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed. - } + setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed. + } - return QGraphicsItem::itemChange(change, value); + return QGraphicsItem::itemChange(change, value); } /** - @brief PartArc::sceneEventFilter - @param watched - @param event - @return + @brief PartArc::sceneEventFilter + @param watched + @param event + @return */ bool PartArc::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(qghi, static_cast(event)); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(qghi, static_cast(event)); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(qghi, static_cast(event)); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(qghi, static_cast(event)); + return true; + } + } + } + } - return false; + return false; } /** - @brief PartArc::switchResizeMode + @brief PartArc::switchResizeMode */ void PartArc::switchResizeMode() { - if (m_resize_mode == 1) - { - m_resize_mode = 2; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::darkGreen); - } - else if (m_resize_mode == 2) - { - m_resize_mode = 3; + if (m_resize_mode == 1) + { + m_resize_mode = 2; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::darkGreen); + } + else if (m_resize_mode == 2) + { + m_resize_mode = 3; - //From rect mode to angle mode, then numbers of handlers change - removeHandler(); - addHandler(); + //From rect mode to angle mode, then numbers of handlers change + removeHandler(); + addHandler(); - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::magenta); - } - else - { - m_resize_mode = 1; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::magenta); + } + else + { + m_resize_mode = 1; - //From angle mode to rect mode, then numbers of handlers change - removeHandler(); - addHandler(); + //From angle mode to rect mode, then numbers of handlers change + removeHandler(); + addHandler(); - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::blue); - } + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::blue); + } } /** - @brief PartArc::adjusteHandlerPos + @brief PartArc::adjusteHandlerPos */ void PartArc::adjusteHandlerPos() { - if (m_handler_vector.isEmpty()) - return; + if (m_handler_vector.isEmpty()) + return; - QVector points_vector; + QVector points_vector; - if(m_resize_mode == 3) - points_vector = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16); - else - points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); + if(m_resize_mode == 3) + points_vector = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16); + else + points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); - if (m_handler_vector.size() == points_vector.size()) - { - points_vector = mapToScene(points_vector); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } + if (m_handler_vector.size() == points_vector.size()) + { + points_vector = mapToScene(points_vector); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } } /** - @brief PartArc::handlerMousePressEvent - @param qghi - @param event + @brief PartArc::handlerMousePressEvent + @param qghi + @param event */ void PartArc::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) - Q_UNUSED(event) + Q_UNUSED(qghi) + Q_UNUSED(event) - if (m_resize_mode == 3) //Resize angle - { - if (m_vector_index == 0) - { - m_span_point = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(1); + if (m_resize_mode == 3) //Resize angle + { + if (m_vector_index == 0) + { + m_span_point = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(1); - m_undo_command = new QPropertyUndoCommand(this, "startAngle", QVariant(m_start_angle)); - m_undo_command->setText(tr("Modifier un arc")); - m_undo_command->enableAnimation(); + m_undo_command = new QPropertyUndoCommand(this, "startAngle", QVariant(m_start_angle)); + m_undo_command->setText(tr("Modifier un arc")); + m_undo_command->enableAnimation(); - m_undo_command2 = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle), m_undo_command); - m_undo_command2->setText(tr("Modifier un arc")); - m_undo_command2->enableAnimation(); - } - else if (m_vector_index == 1) - { - m_undo_command = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle)); - m_undo_command->setText(tr("Modifier un arc")); - m_undo_command->enableAnimation(); - } - } - else //resize rect - { - m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect)); - m_undo_command->setText(tr("Modifier un arc")); - m_undo_command->enableAnimation(); - } + m_undo_command2 = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle), m_undo_command); + m_undo_command2->setText(tr("Modifier un arc")); + m_undo_command2->enableAnimation(); + } + else if (m_vector_index == 1) + { + m_undo_command = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle)); + m_undo_command->setText(tr("Modifier un arc")); + m_undo_command->enableAnimation(); + } + } + else //resize rect + { + m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect)); + m_undo_command->setText(tr("Modifier un arc")); + m_undo_command->enableAnimation(); + } } /** - @brief PartArc::handlerMouseMoveEvent - @param qghi - @param event + @brief PartArc::handlerMouseMoveEvent + @param qghi + @param event */ void PartArc::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) + Q_UNUSED(qghi) - QPointF new_pos = event->scenePos(); - if (event->modifiers() != Qt::ControlModifier) - new_pos = elementScene()->snapToGrid(event->scenePos()); - new_pos = mapFromScene(new_pos); + QPointF new_pos = event->scenePos(); + if (event->modifiers() != Qt::ControlModifier) + new_pos = elementScene()->snapToGrid(event->scenePos()); + new_pos = mapFromScene(new_pos); - if (m_resize_mode == 1) - setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); - else if (m_resize_mode == 2) - setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); - else - { - QLineF line(m_rect.center(), mapFromScene(event->scenePos())); - prepareGeometryChange(); + if (m_resize_mode == 1) + setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); + else if (m_resize_mode == 2) + setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); + else + { + QLineF line(m_rect.center(), mapFromScene(event->scenePos())); + prepareGeometryChange(); - if (m_vector_index == 0) { - setStartAngle(line.angle()*16); - setSpanAngle(line.angleTo(QLineF(m_rect.center(), m_span_point))*16); - } - else if (m_vector_index == 1) { - QLineF line2(m_rect.center(), QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(0)); - setSpanAngle (line2.angleTo(line)*16); - } - } + if (m_vector_index == 0) { + setStartAngle(line.angle()*16); + setSpanAngle(line.angleTo(QLineF(m_rect.center(), m_span_point))*16); + } + else if (m_vector_index == 1) { + QLineF line2(m_rect.center(), QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(0)); + setSpanAngle (line2.angleTo(line)*16); + } + } } /** - @brief PartArc::handlerMouseReleaseEvent - @param qghi - @param event + @brief PartArc::handlerMouseReleaseEvent + @param qghi + @param event */ void PartArc::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) - Q_UNUSED(event) + Q_UNUSED(qghi) + Q_UNUSED(event) - if (m_resize_mode == 3) - { - if (m_vector_index == 0) - { - m_undo_command->setNewValue(QVariant(m_start_angle)); - m_undo_command2->setNewValue(QVariant(m_span_angle)); - elementScene()->undoStack().push(m_undo_command); - m_undo_command = nullptr; - m_undo_command2 = nullptr; - m_vector_index = -1; - } - else if (m_vector_index == 1) - { - m_undo_command->setNewValue(QVariant(m_span_angle)); - elementScene()->undoStack().push(m_undo_command); - m_undo_command = nullptr; - m_vector_index = -1; - } - } - else - { - if (!m_rect.isValid()) - m_rect = m_rect.normalized(); + if (m_resize_mode == 3) + { + if (m_vector_index == 0) + { + m_undo_command->setNewValue(QVariant(m_start_angle)); + m_undo_command2->setNewValue(QVariant(m_span_angle)); + elementScene()->undoStack().push(m_undo_command); + m_undo_command = nullptr; + m_undo_command2 = nullptr; + m_vector_index = -1; + } + else if (m_vector_index == 1) + { + m_undo_command->setNewValue(QVariant(m_span_angle)); + elementScene()->undoStack().push(m_undo_command); + m_undo_command = nullptr; + m_vector_index = -1; + } + } + else + { + if (!m_rect.isValid()) + m_rect = m_rect.normalized(); - m_undo_command->setNewValue(QVariant(m_rect)); - elementScene()->undoStack().push(m_undo_command); - m_undo_command = nullptr; - m_vector_index = -1; - } + m_undo_command->setNewValue(QVariant(m_rect)); + elementScene()->undoStack().push(m_undo_command); + m_undo_command = nullptr; + m_vector_index = -1; + } } /** - @brief PartArc::sceneSelectionChanged - When the scene selection change, if there are several primitive selected, we remove the handler of this item + @brief PartArc::sceneSelectionChanged + When the scene selection change, if there are several primitive selected, we remove the handler of this item */ void PartArc::sceneSelectionChanged() { - if (this->isSelected() && scene()->selectedItems().size() == 1) - addHandler(); - else - removeHandler(); + if (this->isSelected() && scene()->selectedItems().size() == 1) + addHandler(); + else + removeHandler(); } /** - @brief PartArc::addHandler - Add handlers for this item + @brief PartArc::addHandler + Add handlers for this item */ void PartArc::addHandler() { - if (m_handler_vector.isEmpty() && scene()) - { - if(m_resize_mode == 3) - { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16))); - } - else - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); + if (m_handler_vector.isEmpty() && scene()) + { + if(m_resize_mode == 3) + { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16))); + } + else + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - { - QColor color = Qt::blue; - if (m_resize_mode == 2) - color = Qt::darkGreen; - else if (m_resize_mode == 3) - color = Qt::magenta; + for(QetGraphicsHandlerItem *handler : m_handler_vector) + { + QColor color = Qt::blue; + if (m_resize_mode == 2) + color = Qt::darkGreen; + else if (m_resize_mode == 3) + color = Qt::magenta; - handler->setColor(color); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - handler->setZValue(this->zValue()+1); - } - } + handler->setColor(color); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + handler->setZValue(this->zValue()+1); + } + } } /** - @brief PartArc::removeHandler - Remove the handlers of this item + @brief PartArc::removeHandler + Remove the handlers of this item */ void PartArc::removeHandler() { - if (!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } + if (!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } } diff --git a/sources/editor/graphicspart/partarc.h b/sources/editor/graphicspart/partarc.h index 9026f833f..2cb00a545 100644 --- a/sources/editor/graphicspart/partarc.h +++ b/sources/editor/graphicspart/partarc.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_ARC_H #define PART_ARC_H @@ -24,65 +24,65 @@ class QPropertyUndoCommand; class QetGraphicsHandlerItem; /** - @brief The PartArc class - This class represents an elliptical arc primitive which may be used to - compose the drawing of an electrical element within the element editor. + @brief The PartArc class + This class represents an elliptical arc primitive which may be used to + compose the drawing of an electrical element within the element editor. */ class PartArc : public AbstractPartEllipse { - Q_OBJECT + Q_OBJECT - public: - PartArc(QETElementEditor *editor, QGraphicsItem *parent = nullptr); - ~PartArc() override; - - private: - PartArc(const PartArc &); - // methods - public: - enum { Type = UserType + 1101 }; - /** - Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartArc. - @return the QGraphicsItem type - */ - int type() const override { return Type; } - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; + public: + PartArc(QETElementEditor *editor, QGraphicsItem *parent = nullptr); + ~PartArc() override; + + private: + PartArc(const PartArc &); + // methods + public: + enum { Type = UserType + 1101 }; + /** + Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartArc. + @return the QGraphicsItem type + */ + int type() const override { return Type; } + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; - //Name and XML - QString name() const override { return(QObject::tr("arc", "element part name")); } - QString xmlName() const override { return(QString("arc")); } - const QDomElement toXml (QDomDocument &) const override; - void fromXml (const QDomElement &) override; + //Name and XML + QString name() const override { return(QObject::tr("arc", "element part name")); } + QString xmlName() const override { return(QString("arc")); } + const QDomElement toXml (QDomDocument &) const override; + void fromXml (const QDomElement &) override; - QPainterPath shape() const override; - QPainterPath shadowShape() const override; - void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();} - void setStartAngle(const int &start_angle) override {AbstractPartEllipse::setStartAngle(start_angle); adjusteHandlerPos();} - void setSpanAngle(const int &span_angle) override {AbstractPartEllipse::setSpanAngle(span_angle); adjusteHandlerPos();} - QRectF sceneGeometricRect() const override; + QPainterPath shape() const override; + QPainterPath shadowShape() const override; + void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();} + void setStartAngle(const int &start_angle) override {AbstractPartEllipse::setStartAngle(start_angle); adjusteHandlerPos();} + void setSpanAngle(const int &span_angle) override {AbstractPartEllipse::setSpanAngle(span_angle); adjusteHandlerPos();} + QRectF sceneGeometricRect() const override; - protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; + protected: + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; - private: - void switchResizeMode(); - void adjusteHandlerPos(); - void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void sceneSelectionChanged (); - - void addHandler(); - void removeHandler(); + private: + void switchResizeMode(); + void adjusteHandlerPos(); + void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void sceneSelectionChanged (); + + void addHandler(); + void removeHandler(); - private: - QPropertyUndoCommand *m_undo_command = nullptr; - QPropertyUndoCommand *m_undo_command2 = nullptr; - int m_resize_mode = 1, - m_vector_index = -1; - QPointF m_span_point; - QVector m_handler_vector; + private: + QPropertyUndoCommand *m_undo_command = nullptr; + QPropertyUndoCommand *m_undo_command2 = nullptr; + int m_resize_mode = 1, + m_vector_index = -1; + QPointF m_span_point; + QVector m_handler_vector; }; #endif diff --git a/sources/editor/graphicspart/partdynamictextfield.cpp b/sources/editor/graphicspart/partdynamictextfield.cpp index a425628d3..e40a80f70 100644 --- a/sources/editor/graphicspart/partdynamictextfield.cpp +++ b/sources/editor/graphicspart/partdynamictextfield.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partdynamictextfield.h" #include "QPropertyUndoCommand/qpropertyundocommand.h" @@ -25,574 +25,574 @@ #include PartDynamicTextField::PartDynamicTextField(QETElementEditor *editor, QGraphicsItem *parent) : - QGraphicsTextItem(parent), - CustomElementPart(editor), - m_uuid(QUuid::createUuid()) + QGraphicsTextItem(parent), + CustomElementPart(editor), + m_uuid(QUuid::createUuid()) { - setDefaultTextColor(Qt::black); - setFont(QETApp::dynamicTextsItemFont()); - QSettings settings; - setRotation(settings.value("diagrameditor/dynamic_text_rotation", 0).toInt()); - setTextWidth(settings.value("diagrameditor/dynamic_text_width", -1).toInt()); - setText("_"); - setTextFrom(DynamicElementTextItem::UserText); - setFlags( - QGraphicsItem::ItemIsSelectable | - QGraphicsItem::ItemSendsGeometryChanges | - QGraphicsItem::ItemIsMovable - ); + setDefaultTextColor(Qt::black); + setFont(QETApp::dynamicTextsItemFont()); + QSettings settings; + setRotation(settings.value("diagrameditor/dynamic_text_rotation", 0).toInt()); + setTextWidth(settings.value("diagrameditor/dynamic_text_width", -1).toInt()); + setText("_"); + setTextFrom(DynamicElementTextItem::UserText); + setFlags( + QGraphicsItem::ItemIsSelectable | + QGraphicsItem::ItemSendsGeometryChanges | + QGraphicsItem::ItemIsMovable + ); - //Option when text is displayed in multiple line - QTextOption option = document() -> defaultTextOption(); - option.setAlignment(Qt::AlignHCenter); - option.setWrapMode(QTextOption::WordWrap); - document() -> setDefaultTextOption(option); + //Option when text is displayed in multiple line + QTextOption option = document() -> defaultTextOption(); + option.setAlignment(Qt::AlignHCenter); + option.setWrapMode(QTextOption::WordWrap); + document() -> setDefaultTextOption(option); } QString PartDynamicTextField::name() const { - return tr("Champ de texte dynamique", "element part name"); + return tr("Champ de texte dynamique", "element part name"); } QString PartDynamicTextField::xmlName() const { - return QString("dynamic_text"); + return QString("dynamic_text"); } /** - @brief PartDynamicTextField::startUserTransformation - @param initial_selection_rect - Start the user-induced transformation, - provided this primitive is contained - within the initial_selection_rect bounding rectangle. + @brief PartDynamicTextField::startUserTransformation + @param initial_selection_rect + Start the user-induced transformation, + provided this primitive is contained + within the initial_selection_rect bounding rectangle. */ void PartDynamicTextField::startUserTransformation(const QRectF &initial_selection_rect) { - Q_UNUSED(initial_selection_rect) - m_saved_point = pos(); // scene coordinates, no need to mapFromScene() + Q_UNUSED(initial_selection_rect) + m_saved_point = pos(); // scene coordinates, no need to mapFromScene() } /** - @brief PartDynamicTextField::handleUserTransformation - @param initial_selection_rect - @param new_selection_rect - Handle the user-induced transformation - from initial_selection_rect to new_selection_rect + @brief PartDynamicTextField::handleUserTransformation + @param initial_selection_rect + @param new_selection_rect + Handle the user-induced transformation + from initial_selection_rect to new_selection_rect */ void PartDynamicTextField::handleUserTransformation( - const QRectF &initial_selection_rect, - const QRectF &new_selection_rect) + const QRectF &initial_selection_rect, + const QRectF &new_selection_rect) { - QPointF new_pos = mapPoints( - initial_selection_rect, new_selection_rect, QList() << m_saved_point).first(); - setPos(new_pos); + QPointF new_pos = mapPoints( + initial_selection_rect, new_selection_rect, QList() << m_saved_point).first(); + setPos(new_pos); } /** - @brief PartDynamicTextField::toXml - @param dom_doc - @return + @brief PartDynamicTextField::toXml + @param dom_doc + @return */ const QDomElement PartDynamicTextField::toXml(QDomDocument &dom_doc) const { - QDomElement root_element = dom_doc.createElement(xmlName()); + QDomElement root_element = dom_doc.createElement(xmlName()); - root_element.setAttribute("x", QString::number(pos().x())); - root_element.setAttribute("y", QString::number(pos().y())); - root_element.setAttribute("z", QString::number(zValue())); - root_element.setAttribute("rotation", QString::number(QET::correctAngle(rotation()))); - root_element.setAttribute("font", font().toString()); - root_element.setAttribute("uuid", m_uuid.toString()); - root_element.setAttribute("frame", m_frame? "true" : "false"); - root_element.setAttribute("text_width", QString::number(m_text_width)); + root_element.setAttribute("x", QString::number(pos().x())); + root_element.setAttribute("y", QString::number(pos().y())); + root_element.setAttribute("z", QString::number(zValue())); + root_element.setAttribute("rotation", QString::number(QET::correctAngle(rotation()))); + root_element.setAttribute("font", font().toString()); + root_element.setAttribute("uuid", m_uuid.toString()); + root_element.setAttribute("frame", m_frame? "true" : "false"); + root_element.setAttribute("text_width", QString::number(m_text_width)); - QMetaEnum me = DynamicElementTextItem::textFromMetaEnum(); - root_element.setAttribute("text_from", me.valueToKey(m_text_from)); + QMetaEnum me = DynamicElementTextItem::textFromMetaEnum(); + root_element.setAttribute("text_from", me.valueToKey(m_text_from)); - me = QMetaEnum::fromType(); - if(this -> alignment() &Qt::AlignRight) - root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignRight)); - else if(this -> alignment() &Qt::AlignLeft) - root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignLeft)); - else if(this -> alignment() &Qt::AlignHCenter) - root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignHCenter)); + me = QMetaEnum::fromType(); + if(this -> alignment() &Qt::AlignRight) + root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignRight)); + else if(this -> alignment() &Qt::AlignLeft) + root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignLeft)); + else if(this -> alignment() &Qt::AlignHCenter) + root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignHCenter)); - if(this -> alignment() &Qt::AlignBottom) - root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignBottom)); - else if(this -> alignment() & Qt::AlignTop) - root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignTop)); - else if(this -> alignment() &Qt::AlignVCenter) - root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignVCenter)); + if(this -> alignment() &Qt::AlignBottom) + root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignBottom)); + else if(this -> alignment() & Qt::AlignTop) + root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignTop)); + else if(this -> alignment() &Qt::AlignVCenter) + root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignVCenter)); - QDomElement dom_text = dom_doc.createElement("text"); - dom_text.appendChild(dom_doc.createTextNode(toPlainText())); - root_element.appendChild(dom_text); + QDomElement dom_text = dom_doc.createElement("text"); + dom_text.appendChild(dom_doc.createTextNode(toPlainText())); + root_element.appendChild(dom_text); - //Info name - if(!m_info_name.isEmpty()) { - QDomElement dom_info_name = dom_doc.createElement("info_name"); - dom_info_name.appendChild(dom_doc.createTextNode(m_info_name)); - root_element.appendChild(dom_info_name); - } + //Info name + if(!m_info_name.isEmpty()) { + QDomElement dom_info_name = dom_doc.createElement("info_name"); + dom_info_name.appendChild(dom_doc.createTextNode(m_info_name)); + root_element.appendChild(dom_info_name); + } - //Composite text - if(!m_composite_text.isEmpty()) { - QDomElement dom_comp_text = dom_doc.createElement("composite_text"); - dom_comp_text.appendChild(dom_doc.createTextNode(m_composite_text)); - root_element.appendChild(dom_comp_text); - } + //Composite text + if(!m_composite_text.isEmpty()) { + QDomElement dom_comp_text = dom_doc.createElement("composite_text"); + dom_comp_text.appendChild(dom_doc.createTextNode(m_composite_text)); + root_element.appendChild(dom_comp_text); + } - //Color - if(color() != QColor(Qt::black)) { - QDomElement dom_color = dom_doc.createElement("color"); - dom_color.appendChild(dom_doc.createTextNode(color().name())); - root_element.appendChild(dom_color); - } + //Color + if(color() != QColor(Qt::black)) { + QDomElement dom_color = dom_doc.createElement("color"); + dom_color.appendChild(dom_doc.createTextNode(color().name())); + root_element.appendChild(dom_color); + } - return root_element; + return root_element; } /** - @brief PartDynamicTextField::fromXml - @param dom_elmt + @brief PartDynamicTextField::fromXml + @param dom_elmt */ void PartDynamicTextField::fromXml(const QDomElement &dom_elmt) { - if (dom_elmt.tagName() != xmlName()) { - qDebug() << "PartDynamicTextField::fromXml : Wrong tagg name"; - return; - } + if (dom_elmt.tagName() != xmlName()) { + qDebug() << "PartDynamicTextField::fromXml : Wrong tagg name"; + return; + } - QGraphicsTextItem::setPos( - dom_elmt.attribute("x", QString::number(0)).toDouble(), - dom_elmt.attribute("y", QString::number(0)).toDouble() - ); - setZValue(dom_elmt.attribute("z", QString::number(zValue())).toDouble()); - QGraphicsTextItem::setRotation(dom_elmt.attribute("rotation", QString::number(0)).toDouble()); + QGraphicsTextItem::setPos( + dom_elmt.attribute("x", QString::number(0)).toDouble(), + dom_elmt.attribute("y", QString::number(0)).toDouble() + ); + setZValue(dom_elmt.attribute("z", QString::number(zValue())).toDouble()); + QGraphicsTextItem::setRotation(dom_elmt.attribute("rotation", QString::number(0)).toDouble()); - if (dom_elmt.hasAttribute("font")) { - QFont font_; - font_.fromString(dom_elmt.attribute("font")); - setFont(font_); - } - else { + if (dom_elmt.hasAttribute("font")) { + QFont font_; + font_.fromString(dom_elmt.attribute("font")); + setFont(font_); + } + else { #if TODO_LIST #pragma message("@TODO remove in futur") #endif - //Keep compatibility TODO remove in futur - setFont(QETApp::dynamicTextsItemFont(9)); - } + //Keep compatibility TODO remove in futur + setFont(QETApp::dynamicTextsItemFont(9)); + } - m_uuid = QUuid(dom_elmt.attribute("uuid", QUuid::createUuid().toString())); - setFrame(dom_elmt.attribute("frame", "false") == "true"? true : false); - setTextWidth(dom_elmt.attribute("text_width", QString::number(-1)).toDouble()); + m_uuid = QUuid(dom_elmt.attribute("uuid", QUuid::createUuid().toString())); + setFrame(dom_elmt.attribute("frame", "false") == "true"? true : false); + setTextWidth(dom_elmt.attribute("text_width", QString::number(-1)).toDouble()); - QMetaEnum me = DynamicElementTextItem::textFromMetaEnum(); - m_text_from = DynamicElementTextItem::TextFrom( - me.keyToValue(dom_elmt.attribute("text_from").toStdString().data())); + QMetaEnum me = DynamicElementTextItem::textFromMetaEnum(); + m_text_from = DynamicElementTextItem::TextFrom( + me.keyToValue(dom_elmt.attribute("text_from").toStdString().data())); - me = QMetaEnum::fromType(); - if(dom_elmt.hasAttribute("Halignment")) - setAlignment(Qt::Alignment( - me.keyToValue(dom_elmt.attribute("Halignment").toStdString().data()))); - if(dom_elmt.hasAttribute(("Valignment"))) - setAlignment(Qt::Alignment( - me.keyToValue(dom_elmt.attribute("Valignment").toStdString().data())) | this -> alignment()); + me = QMetaEnum::fromType(); + if(dom_elmt.hasAttribute("Halignment")) + setAlignment(Qt::Alignment( + me.keyToValue(dom_elmt.attribute("Halignment").toStdString().data()))); + if(dom_elmt.hasAttribute(("Valignment"))) + setAlignment(Qt::Alignment( + me.keyToValue(dom_elmt.attribute("Valignment").toStdString().data())) | this -> alignment()); - //Text - QDomElement dom_text = dom_elmt.firstChildElement("text"); - if (!dom_text.isNull()) { - m_text = dom_text.text(); - m_block_alignment = true; - setPlainText(m_text); - m_block_alignment = false; - } + //Text + QDomElement dom_text = dom_elmt.firstChildElement("text"); + if (!dom_text.isNull()) { + m_text = dom_text.text(); + m_block_alignment = true; + setPlainText(m_text); + m_block_alignment = false; + } - //Info name - QDomElement dom_info_name = dom_elmt.firstChildElement("info_name"); - if(!dom_info_name.isNull()) - m_info_name = dom_info_name.text(); + //Info name + QDomElement dom_info_name = dom_elmt.firstChildElement("info_name"); + if(!dom_info_name.isNull()) + m_info_name = dom_info_name.text(); - //Composite text - QDomElement dom_comp_text = dom_elmt.firstChildElement("composite_text"); - if(!dom_comp_text.isNull()) - m_composite_text = dom_comp_text.text(); + //Composite text + QDomElement dom_comp_text = dom_elmt.firstChildElement("composite_text"); + if(!dom_comp_text.isNull()) + m_composite_text = dom_comp_text.text(); - //Color - QDomElement dom_color = dom_elmt.firstChildElement("color"); - if(!dom_color.isNull()) - setColor(QColor(dom_color.text())); + //Color + QDomElement dom_color = dom_elmt.firstChildElement("color"); + if(!dom_color.isNull()) + setColor(QColor(dom_color.text())); } /** - @brief PartDynamicTextField::fromTextFieldXml - Setup this text from the xml definition - of a text field (The xml tagg of a text field is "input"); - @param dom_element + @brief PartDynamicTextField::fromTextFieldXml + Setup this text from the xml definition + of a text field (The xml tagg of a text field is "input"); + @param dom_element */ void PartDynamicTextField::fromTextFieldXml(const QDomElement &dom_element) { - if(dom_element.tagName() != "input") - return; + if(dom_element.tagName() != "input") + return; - setFont(QETApp::diagramTextsFont(dom_element.attribute("size", QString::number(9)).toInt())); + setFont(QETApp::diagramTextsFont(dom_element.attribute("size", QString::number(9)).toInt())); - if(dom_element.attribute("tagg", "none") == "none") { - setTextFrom(DynamicElementTextItem::UserText); - setText(dom_element.attribute("text", "_")); - } - else { - setTextFrom(DynamicElementTextItem::ElementInfo); - setInfoName(dom_element.attribute("tagg", "label")); - } + if(dom_element.attribute("tagg", "none") == "none") { + setTextFrom(DynamicElementTextItem::UserText); + setText(dom_element.attribute("text", "_")); + } + else { + setTextFrom(DynamicElementTextItem::ElementInfo); + setInfoName(dom_element.attribute("tagg", "label")); + } - QGraphicsTextItem::setRotation(dom_element.attribute("rotation", "0").toDouble()); + QGraphicsTextItem::setRotation(dom_element.attribute("rotation", "0").toDouble()); - //the origin transformation point of PartDynamicTextField is the top left corner, no matter the font size - //The origin transformation point of PartTextField is the middle of left edge, and so by definition, change with the size of the font - //We need to use a QTransform to find the pos of this text from the saved pos of text item - QTransform transform; - //First make the rotation - transform.rotate(dom_element.attribute("rotation", "0").toDouble()); - QPointF pos = transform.map(QPointF(0, -boundingRect().height()/2)); - transform.reset(); - //Second translate to the pos - transform.translate( - dom_element.attribute("x", QString::number(0)).toDouble(), - dom_element.attribute("y", QString::number(0)).toDouble() - ); - QGraphicsTextItem::setPos(transform.map(pos)); + //the origin transformation point of PartDynamicTextField is the top left corner, no matter the font size + //The origin transformation point of PartTextField is the middle of left edge, and so by definition, change with the size of the font + //We need to use a QTransform to find the pos of this text from the saved pos of text item + QTransform transform; + //First make the rotation + transform.rotate(dom_element.attribute("rotation", "0").toDouble()); + QPointF pos = transform.map(QPointF(0, -boundingRect().height()/2)); + transform.reset(); + //Second translate to the pos + transform.translate( + dom_element.attribute("x", QString::number(0)).toDouble(), + dom_element.attribute("y", QString::number(0)).toDouble() + ); + QGraphicsTextItem::setPos(transform.map(pos)); } /** - @brief PartDynamicTextField::textFrom - @return what the final text is created from. + @brief PartDynamicTextField::textFrom + @return what the final text is created from. */ DynamicElementTextItem::TextFrom PartDynamicTextField::textFrom() const { - return m_text_from; + return m_text_from; } /** - @brief PartDynamicTextField::setTextFrom - Set the final text is created from. - @param text_from + @brief PartDynamicTextField::setTextFrom + Set the final text is created from. + @param text_from */ void PartDynamicTextField::setTextFrom(DynamicElementTextItem::TextFrom text_from) { - m_text_from = text_from; - switch (m_text_from) { - case DynamicElementTextItem::UserText: - setPlainText(m_text); - break; - case DynamicElementTextItem::ElementInfo: - setInfoName(m_info_name); - break; - case DynamicElementTextItem::CompositeText: - setCompositeText(m_composite_text); - break; - default: - break; - } - emit textFromChanged(m_text_from); + m_text_from = text_from; + switch (m_text_from) { + case DynamicElementTextItem::UserText: + setPlainText(m_text); + break; + case DynamicElementTextItem::ElementInfo: + setInfoName(m_info_name); + break; + case DynamicElementTextItem::CompositeText: + setCompositeText(m_composite_text); + break; + default: + break; + } + emit textFromChanged(m_text_from); } /** - @brief PartDynamicTextField::text - @return the text of this text + @brief PartDynamicTextField::text + @return the text of this text */ QString PartDynamicTextField::text() const { - return m_text; + return m_text; } /** - @brief PartDynamicTextField::setText - Set the text of this text - @param text + @brief PartDynamicTextField::setText + Set the text of this text + @param text */ void PartDynamicTextField::setText(const QString &text) { - m_text = text; - setPlainText(m_text); - emit textChanged(m_text); + m_text = text; + setPlainText(m_text); + emit textChanged(m_text); } void PartDynamicTextField::setInfoName(const QString &info_name) { - m_info_name = info_name; - if(m_text_from == DynamicElementTextItem::ElementInfo && elementScene()) - setPlainText(elementScene() -> elementInformation().value(m_info_name).toString()); - emit infoNameChanged(m_info_name); + m_info_name = info_name; + if(m_text_from == DynamicElementTextItem::ElementInfo && elementScene()) + setPlainText(elementScene() -> elementInformation().value(m_info_name).toString()); + emit infoNameChanged(m_info_name); } /** - @brief PartDynamicTextField::infoName - @return the info name of this text + @brief PartDynamicTextField::infoName + @return the info name of this text */ QString PartDynamicTextField::infoName() const{ - return m_info_name; + return m_info_name; } /** - @brief PartDynamicTextField::setCompositeText - Set the composite text of this text item to text - @param text + @brief PartDynamicTextField::setCompositeText + Set the composite text of this text item to text + @param text */ void PartDynamicTextField::setCompositeText(const QString &text) { - m_composite_text = text; - if(m_text_from == DynamicElementTextItem::CompositeText && elementScene()) - setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, elementScene() -> elementInformation())); - emit compositeTextChanged(m_composite_text); + m_composite_text = text; + if(m_text_from == DynamicElementTextItem::CompositeText && elementScene()) + setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, elementScene() -> elementInformation())); + emit compositeTextChanged(m_composite_text); } /** - @brief PartDynamicTextField::compositeText - @return the composite text of this text + @brief PartDynamicTextField::compositeText + @return the composite text of this text */ QString PartDynamicTextField::compositeText() const { - return m_composite_text; + return m_composite_text; } /** - @brief PartDynamicTextField::setColor - @param color set text color to color + @brief PartDynamicTextField::setColor + @param color set text color to color */ void PartDynamicTextField::setColor(const QColor& color) { - setDefaultTextColor(color); - emit colorChanged(color); + setDefaultTextColor(color); + emit colorChanged(color); } /** - @brief PartDynamicTextField::color - @return The color of this text + @brief PartDynamicTextField::color + @return The color of this text */ QColor PartDynamicTextField::color() const { - return defaultTextColor(); + return defaultTextColor(); } void PartDynamicTextField::setFrame(bool frame) { - m_frame = frame; - update(); - emit frameChanged(m_frame); + m_frame = frame; + update(); + emit frameChanged(m_frame); } bool PartDynamicTextField::frame() const { - return m_frame; + return m_frame; } void PartDynamicTextField::setTextWidth(qreal width) { - this -> document() -> setTextWidth(width); + this -> document() -> setTextWidth(width); - //Adjust the width, to ideal width if needed - if(width > 0 && document() -> size().width() > width) - document() -> setTextWidth(document() -> idealWidth()); + //Adjust the width, to ideal width if needed + if(width > 0 && document() -> size().width() > width) + document() -> setTextWidth(document() -> idealWidth()); - m_text_width = document() -> textWidth(); - emit textWidthChanged(m_text_width); + m_text_width = document() -> textWidth(); + emit textWidthChanged(m_text_width); } void PartDynamicTextField::setPlainText(const QString &text) { - if(toPlainText() == text) - return; + if(toPlainText() == text) + return; - prepareAlignment(); - QGraphicsTextItem::setPlainText(text); + prepareAlignment(); + QGraphicsTextItem::setPlainText(text); - //User define a text width - if(m_text_width > 0) { - if(document() -> size().width() > m_text_width) { - document() -> setTextWidth(m_text_width); - if(document() -> size().width() > m_text_width) { - document() -> setTextWidth(document() -> idealWidth()); - } - } - } - finishAlignment(); + //User define a text width + if(m_text_width > 0) { + if(document() -> size().width() > m_text_width) { + document() -> setTextWidth(m_text_width); + if(document() -> size().width() > m_text_width) { + document() -> setTextWidth(document() -> idealWidth()); + } + } + } + finishAlignment(); } void PartDynamicTextField::setAlignment(Qt::Alignment alignment) { - m_alignment = alignment; - emit alignmentChanged(m_alignment); + m_alignment = alignment; + emit alignmentChanged(m_alignment); } Qt::Alignment PartDynamicTextField::alignment() const { - return m_alignment; + return m_alignment; } void PartDynamicTextField::setFont(const QFont &font) { - if (font == this -> font()) { - return; - } - prepareAlignment(); - QGraphicsTextItem::setFont(font); - finishAlignment(); - emit fontChanged(font); + if (font == this -> font()) { + return; + } + prepareAlignment(); + QGraphicsTextItem::setFont(font); + finishAlignment(); + emit fontChanged(font); } /** - @brief PartDynamicTextField::mouseMoveEvent - @param event + @brief PartDynamicTextField::mouseMoveEvent + @param event */ void PartDynamicTextField::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if((event -> buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) { - QPointF pos = event -> scenePos() + (m_origine_pos - event -> buttonDownScenePos(Qt::LeftButton)); - event -> modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene() -> snapToGrid(pos)); - } - else - QGraphicsObject::mouseMoveEvent(event); + if((event -> buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) { + QPointF pos = event -> scenePos() + (m_origine_pos - event -> buttonDownScenePos(Qt::LeftButton)); + event -> modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene() -> snapToGrid(pos)); + } + else + QGraphicsObject::mouseMoveEvent(event); } /** - @brief PartDynamicTextField::mousePressEvent - @param event + @brief PartDynamicTextField::mousePressEvent + @param event */ void PartDynamicTextField::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if(event -> button() == Qt::LeftButton) - m_origine_pos = this -> pos(); + if(event -> button() == Qt::LeftButton) + m_origine_pos = this -> pos(); - QGraphicsObject::mousePressEvent(event); + QGraphicsObject::mousePressEvent(event); } /** - @brief PartDynamicTextField::mouseReleaseEvent - @param event + @brief PartDynamicTextField::mouseReleaseEvent + @param event */ void PartDynamicTextField::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if((event -> button() & Qt::LeftButton) && - (flags() & QGraphicsItem::ItemIsMovable) && - m_origine_pos != pos()) { - QPropertyUndoCommand *undo =\ - new QPropertyUndoCommand(this, "pos", QVariant(m_origine_pos), QVariant(pos())); - undo -> setText(tr("Déplacer un champ texte")); - undo -> enableAnimation(); - elementScene() -> undoStack().push(undo); - } + if((event -> button() & Qt::LeftButton) && + (flags() & QGraphicsItem::ItemIsMovable) && + m_origine_pos != pos()) { + QPropertyUndoCommand *undo =\ + new QPropertyUndoCommand(this, "pos", QVariant(m_origine_pos), QVariant(pos())); + undo -> setText(tr("D??placer un champ texte")); + undo -> enableAnimation(); + elementScene() -> undoStack().push(undo); + } - QGraphicsObject::mouseReleaseEvent(event); + QGraphicsObject::mouseReleaseEvent(event); } /** - @brief PartDynamicTextField::itemChange - @param change - @param value - @return + @brief PartDynamicTextField::itemChange + @param change + @param value + @return */ QVariant PartDynamicTextField::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == QGraphicsItem::ItemPositionHasChanged || change == QGraphicsItem::ItemSceneHasChanged) { - updateCurrentPartEditor(); - if(change == QGraphicsItem::ItemSceneHasChanged && - m_first_add && - elementScene() != nullptr) - { - connect(elementScene(), &ElementScene::elementInfoChanged, - this, &PartDynamicTextField::elementInfoChanged); - m_first_add = false; - } - } - else if ((change == QGraphicsItem::ItemSelectedHasChanged) && (value.toBool() == true)) - updateCurrentPartEditor(); + if (change == QGraphicsItem::ItemPositionHasChanged || change == QGraphicsItem::ItemSceneHasChanged) { + updateCurrentPartEditor(); + if(change == QGraphicsItem::ItemSceneHasChanged && + m_first_add && + elementScene() != nullptr) + { + connect(elementScene(), &ElementScene::elementInfoChanged, + this, &PartDynamicTextField::elementInfoChanged); + m_first_add = false; + } + } + else if ((change == QGraphicsItem::ItemSelectedHasChanged) && (value.toBool() == true)) + updateCurrentPartEditor(); - return(QGraphicsTextItem::itemChange(change, value)); + return(QGraphicsTextItem::itemChange(change, value)); } void PartDynamicTextField::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - QGraphicsTextItem::paint(painter, option, widget); + QGraphicsTextItem::paint(painter, option, widget); - if (m_frame) { - painter -> save(); - painter -> setFont(this -> font()); + if (m_frame) { + painter -> save(); + painter -> setFont(this -> font()); - //Adjust the thickness according to the font size, - qreal w=0.3; - if(this -> font().pointSize() >= 5) { - w = this -> font().pointSizeF()*0.1; - if(w > 2.5) - w = 2.5; - } + //Adjust the thickness according to the font size, + qreal w=0.3; + if(this -> font().pointSize() >= 5) { + w = this -> font().pointSizeF()*0.1; + if(w > 2.5) + w = 2.5; + } - QPen pen; - pen.setColor(color()); - pen.setWidthF(w); - painter -> setPen(pen); - painter -> setRenderHint(QPainter::Antialiasing); + QPen pen; + pen.setColor(color()); + pen.setWidthF(w); + painter -> setPen(pen); + painter -> setRenderHint(QPainter::Antialiasing); - //Get the bounding rectangle of the text - QSizeF size = document() -> size(); - size.setWidth(document() -> idealWidth()); - //Remove the margin. Size is exactly the bounding rect of the text - size.rheight() -= document() -> documentMargin()*2; - size.rwidth() -= document() -> documentMargin()*2; - //Add a little margin only for a better visual; - size.rheight() += 2; - size.rwidth() += 2; + //Get the bounding rectangle of the text + QSizeF size = document() -> size(); + size.setWidth(document() -> idealWidth()); + //Remove the margin. Size is exactly the bounding rect of the text + size.rheight() -= document() -> documentMargin()*2; + size.rwidth() -= document() -> documentMargin()*2; + //Add a little margin only for a better visual; + size.rheight() += 2; + size.rwidth() += 2; - //The pos of the rect - QPointF pos = boundingRect().center(); - pos.rx() -= size.width()/2; - pos.ry() -= size.height()/2; + //The pos of the rect + QPointF pos = boundingRect().center(); + pos.rx() -= size.width()/2; + pos.ry() -= size.height()/2; - //Adjust the rounding of the rectangle according to the size of the font - qreal ro = this -> font().pointSizeF()/3; - painter -> drawRoundedRect(QRectF(pos, size), ro, ro); + //Adjust the rounding of the rectangle according to the size of the font + qreal ro = this -> font().pointSizeF()/3; + painter -> drawRoundedRect(QRectF(pos, size), ro, ro); - painter -> restore(); - } + painter -> restore(); + } } /** - @brief PartDynamicTextField::elementInfoChanged - Used to up to date this text field, - when the element information (see elementScene) changed + @brief PartDynamicTextField::elementInfoChanged + Used to up to date this text field, + when the element information (see elementScene) changed */ void PartDynamicTextField::elementInfoChanged() { - if(!elementScene()) - return; + if(!elementScene()) + return; - if(m_text_from == DynamicElementTextItem::ElementInfo) - setPlainText(elementScene() -> elementInformation().value(m_info_name).toString()); - else if (m_text_from == DynamicElementTextItem::CompositeText && elementScene()) - setPlainText(autonum::AssignVariables::replaceVariable( - m_composite_text, elementScene() -> elementInformation())); + if(m_text_from == DynamicElementTextItem::ElementInfo) + setPlainText(elementScene() -> elementInformation().value(m_info_name).toString()); + else if (m_text_from == DynamicElementTextItem::CompositeText && elementScene()) + setPlainText(autonum::AssignVariables::replaceVariable( + m_composite_text, elementScene() -> elementInformation())); } void PartDynamicTextField::prepareAlignment() { - m_alignment_rect = boundingRect(); + m_alignment_rect = boundingRect(); } void PartDynamicTextField::finishAlignment() { - if(m_block_alignment) - return; + if(m_block_alignment) + return; - QTransform transform; - transform.rotate(this -> rotation()); - qreal x,xa, y,ya; - x=xa=0; - y=ya=0; + QTransform transform; + transform.rotate(this -> rotation()); + qreal x,xa, y,ya; + x=xa=0; + y=ya=0; - if(m_alignment &Qt::AlignRight) { - x = m_alignment_rect.right(); - xa = boundingRect().right(); - } - else if(m_alignment &Qt::AlignHCenter) { - x = m_alignment_rect.center().x(); - xa = boundingRect().center().x(); - } + if(m_alignment &Qt::AlignRight) { + x = m_alignment_rect.right(); + xa = boundingRect().right(); + } + else if(m_alignment &Qt::AlignHCenter) { + x = m_alignment_rect.center().x(); + xa = boundingRect().center().x(); + } - if(m_alignment &Qt::AlignBottom) { - y = m_alignment_rect.bottom(); - ya = boundingRect().bottom(); - } - else if(m_alignment &Qt::AlignVCenter) { - y = m_alignment_rect.center().y(); - ya = boundingRect().center().y(); - } + if(m_alignment &Qt::AlignBottom) { + y = m_alignment_rect.bottom(); + ya = boundingRect().bottom(); + } + else if(m_alignment &Qt::AlignVCenter) { + y = m_alignment_rect.center().y(); + ya = boundingRect().center().y(); + } - QPointF p = transform.map(QPointF(x,y)); - QPointF pa = transform.map(QPointF(xa,ya)); - QPointF diff = pa-p; + QPointF p = transform.map(QPointF(x,y)); + QPointF pa = transform.map(QPointF(xa,ya)); + QPointF diff = pa-p; - setPos(this -> pos() - diff); + setPos(this -> pos() - diff); } diff --git a/sources/editor/graphicspart/partdynamictextfield.h b/sources/editor/graphicspart/partdynamictextfield.h index 2ed40a123..39eecdfd2 100644 --- a/sources/editor/graphicspart/partdynamictextfield.h +++ b/sources/editor/graphicspart/partdynamictextfield.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PARTDYNAMICTEXTFIELD_H #define PARTDYNAMICTEXTFIELD_H @@ -23,106 +23,106 @@ #include "dynamicelementtextitem.h" /** - @brief The PartDynamicTextField class - This class represents an editable dynamic text field - which may be used to compose the - drawing of an electrical element within the element editor. - The field will remain editable once the element is added onto - a diagram + @brief The PartDynamicTextField class + This class represents an editable dynamic text field + which may be used to compose the + drawing of an electrical element within the element editor. + The field will remain editable once the element is added onto + a diagram */ class PartDynamicTextField : public QGraphicsTextItem, public CustomElementPart { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) - Q_PROPERTY(DynamicElementTextItem::TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged) - Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged) - Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged) - Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) - Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged) - Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged) - Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) - Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged) + Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) + Q_PROPERTY(DynamicElementTextItem::TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged) + Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged) + Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged) + Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) + Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged) + Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged) + Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) + Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged) - public: - ///PROPERTY - void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);} - QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);} + public: + ///PROPERTY + void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);} + QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);} - signals: - void taggChanged(QString tagg); - void textChanged(QString text); - void textFromChanged(DynamicElementTextItem::TextFrom text_from); - void infoNameChanged(QString info); - void compositeTextChanged(QString text); - void colorChanged(QColor color); - void frameChanged(bool frame); - void textWidthChanged(qreal width); - void alignmentChanged(Qt::Alignment alignment); - void fontChanged(QFont font); + signals: + void taggChanged(QString tagg); + void textChanged(QString text); + void textFromChanged(DynamicElementTextItem::TextFrom text_from); + void infoNameChanged(QString info); + void compositeTextChanged(QString text); + void colorChanged(QColor color); + void frameChanged(bool frame); + void textWidthChanged(qreal width); + void alignmentChanged(Qt::Alignment alignment); + void fontChanged(QFont font); - public: - PartDynamicTextField(QETElementEditor *editor, QGraphicsItem *parent = nullptr); + public: + PartDynamicTextField(QETElementEditor *editor, QGraphicsItem *parent = nullptr); - enum {Type = UserType + 1110}; - int type() const override {return Type;} + enum {Type = UserType + 1110}; + int type() const override {return Type;} - QString name() const override; - QString xmlName() const override; - static QString xmlTaggName() {return QString("dynamic_text");} - bool isUseless() const override {return false;} - QRectF sceneGeometricRect() const override {return sceneBoundingRect();} - void startUserTransformation(const QRectF &initial_selection_rect) override; - void handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) override; + QString name() const override; + QString xmlName() const override; + static QString xmlTaggName() {return QString("dynamic_text");} + bool isUseless() const override {return false;} + QRectF sceneGeometricRect() const override {return sceneBoundingRect();} + void startUserTransformation(const QRectF &initial_selection_rect) override; + void handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) override; - const QDomElement toXml(QDomDocument &dom_doc) const override; - void fromXml(const QDomElement &dom_elmt) override; - void fromTextFieldXml(const QDomElement &dom_element); + const QDomElement toXml(QDomDocument &dom_doc) const override; + void fromXml(const QDomElement &dom_elmt) override; + void fromTextFieldXml(const QDomElement &dom_element); - DynamicElementTextItem::TextFrom textFrom() const; - void setTextFrom (DynamicElementTextItem::TextFrom text_from); - QString text() const; - void setText(const QString &text); - void setInfoName(const QString &info_name); - QString infoName() const; - void setCompositeText(const QString &text); - QString compositeText() const; - void setColor(const QColor& color); - QColor color() const; - void setFrame(bool frame); - bool frame() const; - void setTextWidth(qreal width); - void setPlainText(const QString &text); - void setAlignment(Qt::Alignment alignment); - Qt::Alignment alignment() const; - void setFont(const QFont &font); + DynamicElementTextItem::TextFrom textFrom() const; + void setTextFrom (DynamicElementTextItem::TextFrom text_from); + QString text() const; + void setText(const QString &text); + void setInfoName(const QString &info_name); + QString infoName() const; + void setCompositeText(const QString &text); + QString compositeText() const; + void setColor(const QColor& color); + QColor color() const; + void setFrame(bool frame); + bool frame() const; + void setTextWidth(qreal width); + void setPlainText(const QString &text); + void setAlignment(Qt::Alignment alignment); + Qt::Alignment alignment() const; + void setFont(const QFont &font); - protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; + protected: + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; - private: - void elementInfoChanged(); - void prepareAlignment(); - void finishAlignment(); + private: + void elementInfoChanged(); + void prepareAlignment(); + void finishAlignment(); - private: - QPointF m_origine_pos, - m_saved_point; - QString m_text, - m_info_name, - m_composite_text; - DynamicElementTextItem::TextFrom m_text_from = DynamicElementTextItem::UserText; - QUuid m_uuid; - bool m_frame = false, - m_first_add = true, - m_block_alignment = false; - qreal m_text_width = -1; - Qt::Alignment m_alignment = Qt::AlignTop|Qt::AlignLeft; - QRectF m_alignment_rect; + private: + QPointF m_origine_pos, + m_saved_point; + QString m_text, + m_info_name, + m_composite_text; + DynamicElementTextItem::TextFrom m_text_from = DynamicElementTextItem::UserText; + QUuid m_uuid; + bool m_frame = false, + m_first_add = true, + m_block_alignment = false; + qreal m_text_width = -1; + Qt::Alignment m_alignment = Qt::AlignTop|Qt::AlignLeft; + QRectF m_alignment_rect; }; #endif // PARTDYNAMICTEXTFIELD_H diff --git a/sources/editor/graphicspart/partellipse.cpp b/sources/editor/graphicspart/partellipse.cpp index c121e6135..b7f7a2c1a 100644 --- a/sources/editor/graphicspart/partellipse.cpp +++ b/sources/editor/graphicspart/partellipse.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partellipse.h" #include "QPropertyUndoCommand/qpropertyundocommand.h" @@ -22,367 +22,367 @@ #include "QetGraphicsItemModeler/qetgraphicshandlerutility.h" /** - @brief PartEllipse::PartEllipse - Constructor - @param editor : QETElementEditor of this part - @param parent : parent item + @brief PartEllipse::PartEllipse + Constructor + @param editor : QETElementEditor of this part + @param parent : parent item */ PartEllipse::PartEllipse(QETElementEditor *editor, QGraphicsItem *parent) : - AbstractPartEllipse(editor, parent), - m_undo_command(nullptr) + AbstractPartEllipse(editor, parent), + m_undo_command(nullptr) {} /** - @brief PartEllipse::~PartEllipse - Destructor + @brief PartEllipse::~PartEllipse + Destructor */ PartEllipse::~PartEllipse() { - if(m_undo_command) delete m_undo_command; - removeHandler(); + if(m_undo_command) delete m_undo_command; + removeHandler(); } /** - @brief PartEllipse::paint - Draw this ellpise - @param painter - @param options - @param widget + @brief PartEllipse::paint + Draw this ellpise + @param painter + @param options + @param widget */ void PartEllipse::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget) { - Q_UNUSED(widget); - applyStylesToQPainter(*painter); + Q_UNUSED(widget); + applyStylesToQPainter(*painter); - QPen t = painter -> pen(); + QPen t = painter -> pen(); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - t.setCosmetic(options && options -> levelOfDetail < 1.0); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + t.setCosmetic(options && options -> levelOfDetail < 1.0); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); + t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); #endif - if (isSelected()) - t.setColor(Qt::red); + if (isSelected()) + t.setColor(Qt::red); - painter -> setPen(t); - painter -> drawEllipse(rect()); + painter -> setPen(t); + painter -> drawEllipse(rect()); - if (m_hovered) - drawShadowShape(painter); + if (m_hovered) + drawShadowShape(painter); - if (isSelected()) - drawCross(m_rect.center(), painter); + if (isSelected()) + drawCross(m_rect.center(), painter); } /** - @brief PartEllipse::toXml - Export this ellipse in xml - @param xml_document : Xml document to use for create the xml element. - @return : an xml element that describe this ellipse + @brief PartEllipse::toXml + Export this ellipse in xml + @param xml_document : Xml document to use for create the xml element. + @return : an xml element that describe this ellipse */ const QDomElement PartEllipse::toXml(QDomDocument &xml_document) const { - QDomElement xml_element; - if (qFuzzyCompare(rect().width(), rect().height())) - { - xml_element = xml_document.createElement("circle"); - xml_element.setAttribute("diameter", QString("%1").arg(rect().width())); - } - else - { - xml_element = xml_document.createElement("ellipse"); - xml_element.setAttribute("width", QString("%1").arg(rect().width())); - xml_element.setAttribute("height", QString("%1").arg(rect().height())); - } + QDomElement xml_element; + if (qFuzzyCompare(rect().width(), rect().height())) + { + xml_element = xml_document.createElement("circle"); + xml_element.setAttribute("diameter", QString("%1").arg(rect().width())); + } + else + { + xml_element = xml_document.createElement("ellipse"); + xml_element.setAttribute("width", QString("%1").arg(rect().width())); + xml_element.setAttribute("height", QString("%1").arg(rect().height())); + } - QPointF top_left(sceneTopLeft()); - xml_element.setAttribute("x", QString("%1").arg(top_left.x())); - xml_element.setAttribute("y", QString("%1").arg(top_left.y())); + QPointF top_left(sceneTopLeft()); + xml_element.setAttribute("x", QString("%1").arg(top_left.x())); + xml_element.setAttribute("y", QString("%1").arg(top_left.y())); - stylesToXml(xml_element); + stylesToXml(xml_element); - return(xml_element); + return(xml_element); } /** - @brief PartEllipse::fromXml - Import the properties of this ellipse from a xml element. - @param qde : Xml document to use. + @brief PartEllipse::fromXml + Import the properties of this ellipse from a xml element. + @param qde : Xml document to use. */ void PartEllipse::fromXml(const QDomElement &qde) { - stylesFromXml(qde); - qreal width, height; + stylesFromXml(qde); + qreal width, height; - if (qde.tagName() == "ellipse") - { - width = qde.attribute("width", "0").toDouble(); - height = qde.attribute("height", "0").toDouble(); - } - else - width = height = qde.attribute("diameter", "0").toDouble(); + if (qde.tagName() == "ellipse") + { + width = qde.attribute("width", "0").toDouble(); + height = qde.attribute("height", "0").toDouble(); + } + else + width = height = qde.attribute("diameter", "0").toDouble(); - m_rect = QRectF(mapFromScene(qde.attribute("x", "0").toDouble(), - qde.attribute("y", "0").toDouble()), - QSizeF(width, height)); + m_rect = QRectF(mapFromScene(qde.attribute("x", "0").toDouble(), + qde.attribute("y", "0").toDouble()), + QSizeF(width, height)); } /** - @brief PartEllipse::shape - @return the shape of this item + @brief PartEllipse::shape + @return the shape of this item */ QPainterPath PartEllipse::shape() const { - QPainterPath shape; - shape.addEllipse(m_rect); + QPainterPath shape; + shape.addEllipse(m_rect); - QPainterPathStroker pps; - pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); - shape = pps.createStroke(shape); + QPainterPathStroker pps; + pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); + shape = pps.createStroke(shape); - return shape; + return shape; } QPainterPath PartEllipse::shadowShape() const { - QPainterPath shape; - shape.addEllipse(m_rect); + QPainterPath shape; + shape.addEllipse(m_rect); - QPainterPathStroker pps; - pps.setWidth(penWeight()); + QPainterPathStroker pps; + pps.setWidth(penWeight()); - return (pps.createStroke(shape)); + return (pps.createStroke(shape)); } /** - @brief PartEllipse::mouseReleaseEvent - Handle mouse release event - @param event + @brief PartEllipse::mouseReleaseEvent + Handle mouse release event + @param event */ void PartEllipse::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) - switchResizeMode(); + if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) + switchResizeMode(); - CustomElementGraphicPart::mouseReleaseEvent(event); + CustomElementGraphicPart::mouseReleaseEvent(event); } /** - @brief PartEllipse::itemChange - @param change - @param value - @return + @brief PartEllipse::itemChange + @param change + @param value + @return */ QVariant PartEllipse::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged && scene()) - { - if (value.toBool() == true) - { - //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, - //according to the number of selected items. - connect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); + if (change == ItemSelectedHasChanged && scene()) + { + if (value.toBool() == true) + { + //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, + //according to the number of selected items. + connect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); - if (scene()->selectedItems().size() == 1) - addHandler(); - } - else - { - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); - removeHandler(); - } - } - else if (change == ItemPositionHasChanged) - { - adjusteHandlerPos(); - } - else if (change == ItemSceneChange) - { - if(scene()) - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); + if (scene()->selectedItems().size() == 1) + addHandler(); + } + else + { + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); + removeHandler(); + } + } + else if (change == ItemPositionHasChanged) + { + adjusteHandlerPos(); + } + else if (change == ItemSceneChange) + { + if(scene()) + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); - setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed. - } + setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed. + } - return QGraphicsItem::itemChange(change, value); + return QGraphicsItem::itemChange(change, value); } /** - @brief PartEllipse::sceneEventFilter - @param watched - @param event - @return + @brief PartEllipse::sceneEventFilter + @param watched + @param event + @return */ bool PartEllipse::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(qghi, static_cast(event)); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(qghi, static_cast(event)); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(qghi, static_cast(event)); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(qghi, static_cast(event)); + return true; + } + } + } + } - return false; + return false; } void PartEllipse::switchResizeMode() { - if (m_resize_mode == 1) - { - m_resize_mode = 2; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::darkGreen); - } - else - { - m_resize_mode = 1; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::blue); - } + if (m_resize_mode == 1) + { + m_resize_mode = 2; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::darkGreen); + } + else + { + m_resize_mode = 1; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::blue); + } } /** - @brief PartEllipse::adjusteHandlerPos + @brief PartEllipse::adjusteHandlerPos */ void PartEllipse::adjusteHandlerPos() { - if (m_handler_vector.isEmpty()) - return; + if (m_handler_vector.isEmpty()) + return; - QVector points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); + QVector points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); - if (m_handler_vector.size() == points_vector.size()) - { - points_vector = mapToScene(points_vector); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } + if (m_handler_vector.size() == points_vector.size()) + { + points_vector = mapToScene(points_vector); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } } /** - @brief PartEllipse::handlerMousePressEvent - @param qghi - @param event + @brief PartEllipse::handlerMousePressEvent + @param qghi + @param event */ void PartEllipse::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi); - Q_UNUSED(event); + Q_UNUSED(qghi); + Q_UNUSED(event); - m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect)); - m_undo_command->setText(tr("Modifier un rectangle")); - m_undo_command->enableAnimation(); - return; + m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect)); + m_undo_command->setText(tr("Modifier un rectangle")); + m_undo_command->enableAnimation(); + return; } /** - @brief PartEllipse::handlerMouseMoveEvent - @param qghi - @param event + @brief PartEllipse::handlerMouseMoveEvent + @param qghi + @param event */ void PartEllipse::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi); + Q_UNUSED(qghi); - QPointF new_pos = event->scenePos(); - if (event->modifiers() != Qt::ControlModifier) - new_pos = elementScene()->snapToGrid(event->scenePos()); - new_pos = mapFromScene(new_pos); + QPointF new_pos = event->scenePos(); + if (event->modifiers() != Qt::ControlModifier) + new_pos = elementScene()->snapToGrid(event->scenePos()); + new_pos = mapFromScene(new_pos); - if (m_resize_mode == 1) - setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); - else - setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); + if (m_resize_mode == 1) + setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); + else + setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); - adjusteHandlerPos(); + adjusteHandlerPos(); } /** - @brief PartEllipse::handlerMouseReleaseEvent - @param qghi - @param event + @brief PartEllipse::handlerMouseReleaseEvent + @param qghi + @param event */ void PartEllipse::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi); - Q_UNUSED(event); + Q_UNUSED(qghi); + Q_UNUSED(event); - m_undo_command->setNewValue(QVariant(m_rect)); - elementScene()->undoStack().push(m_undo_command); - m_undo_command = nullptr; - m_vector_index = -1; + m_undo_command->setNewValue(QVariant(m_rect)); + elementScene()->undoStack().push(m_undo_command); + m_undo_command = nullptr; + m_vector_index = -1; } /** - @brief PartEllipse::sceneSelectionChanged - When the scene selection change, if there are several primitive selected, we remove the handler of this item + @brief PartEllipse::sceneSelectionChanged + When the scene selection change, if there are several primitive selected, we remove the handler of this item */ void PartEllipse::sceneSelectionChanged() { - if (this->isSelected() && scene()->selectedItems().size() == 1) - addHandler(); - else - removeHandler(); + if (this->isSelected() && scene()->selectedItems().size() == 1) + addHandler(); + else + removeHandler(); } /** - @brief PartEllipse::addHandler - Add handlers for this item + @brief PartEllipse::addHandler + Add handlers for this item */ void PartEllipse::addHandler() { - if (m_handler_vector.isEmpty() && scene()) - { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); + if (m_handler_vector.isEmpty() && scene()) + { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - { - QColor color = Qt::blue; - if (m_resize_mode == 2) - color = Qt::darkGreen; + for(QetGraphicsHandlerItem *handler : m_handler_vector) + { + QColor color = Qt::blue; + if (m_resize_mode == 2) + color = Qt::darkGreen; - handler->setColor(color); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - handler->setZValue(this->zValue()+1); - } - } + handler->setColor(color); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + handler->setZValue(this->zValue()+1); + } + } } /** - @brief PartEllipse::removeHandler - Remove the handlers of this item + @brief PartEllipse::removeHandler + Remove the handlers of this item */ void PartEllipse::removeHandler() { - if (!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } + if (!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } } diff --git a/sources/editor/graphicspart/partellipse.h b/sources/editor/graphicspart/partellipse.h index 477db5111..472b1abc3 100644 --- a/sources/editor/graphicspart/partellipse.h +++ b/sources/editor/graphicspart/partellipse.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_ELLIPSE_H #define PART_ELLIPSE_H @@ -23,60 +23,60 @@ class QPropertyUndoCommand; /** - @brief The PartEllipse class - This class represents an ellipse primitive which may be used to compose the - drawing of an electrical element within the element editor. + @brief The PartEllipse class + This class represents an ellipse primitive which may be used to compose the + drawing of an electrical element within the element editor. */ class PartEllipse : public AbstractPartEllipse { - Q_OBJECT + Q_OBJECT - // constructors, destructor - public: - PartEllipse(QETElementEditor *editor, QGraphicsItem * parent = nullptr); - ~PartEllipse() override; - - private: - PartEllipse(const PartEllipse &); - - // methods - public: - enum { Type = UserType + 1103 }; - /** - Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartEllipse. - @return the QGraphicsItem type - */ - int type() const override { return Type; } - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; + // constructors, destructor + public: + PartEllipse(QETElementEditor *editor, QGraphicsItem * parent = nullptr); + ~PartEllipse() override; + + private: + PartEllipse(const PartEllipse &); + + // methods + public: + enum { Type = UserType + 1103 }; + /** + Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartEllipse. + @return the QGraphicsItem type + */ + int type() const override { return Type; } + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; - //Name and XML - QString name() const override { return(QObject::tr("ellipse", "element part name")); } - QString xmlName() const override { return(QString("ellipse")); } - const QDomElement toXml (QDomDocument &) const override; - void fromXml (const QDomElement &) override; - QPainterPath shape() const override; - QPainterPath shadowShape() const override; - void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();} + //Name and XML + QString name() const override { return(QObject::tr("ellipse", "element part name")); } + QString xmlName() const override { return(QString("ellipse")); } + const QDomElement toXml (QDomDocument &) const override; + void fromXml (const QDomElement &) override; + QPainterPath shape() const override; + QPainterPath shadowShape() const override; + void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();} - protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; + protected: + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; - private: - void switchResizeMode(); - void adjusteHandlerPos(); - void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void sceneSelectionChanged (); - - void addHandler(); - void removeHandler(); + private: + void switchResizeMode(); + void adjusteHandlerPos(); + void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void sceneSelectionChanged (); + + void addHandler(); + void removeHandler(); - private: - QPropertyUndoCommand *m_undo_command; - int m_resize_mode = 1, - m_vector_index = -1; + private: + QPropertyUndoCommand *m_undo_command; + int m_resize_mode = 1, + m_vector_index = -1; }; #endif diff --git a/sources/editor/graphicspart/partline.cpp b/sources/editor/graphicspart/partline.cpp index 304406e2e..d65935a2d 100644 --- a/sources/editor/graphicspart/partline.cpp +++ b/sources/editor/graphicspart/partline.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partline.h" #include @@ -23,697 +23,697 @@ /** - @brief PartLine::PartLine - Constructor - @param editor : QETElementEditor of this part - @param parent : parent item + @brief PartLine::PartLine + Constructor + @param editor : QETElementEditor of this part + @param parent : parent item */ PartLine::PartLine(QETElementEditor *editor, QGraphicsItem *parent) : - CustomElementGraphicPart(editor, parent), - first_end(Qet::None), - first_length(1.5), - second_end(Qet::None), - second_length(1.5), - m_undo_command(nullptr) + CustomElementGraphicPart(editor, parent), + first_end(Qet::None), + first_length(1.5), + second_end(Qet::None), + second_length(1.5), + m_undo_command(nullptr) {} /// Destructeur PartLine::~PartLine() { - if(m_undo_command) - delete m_undo_command; + if(m_undo_command) + delete m_undo_command; - removeHandler(); + removeHandler(); } /** - @brief PartLine::requiredLengthForEndType - @param end_type - @return the number of "length" needed to draw a extremity of type Qet::EndType. + @brief PartLine::requiredLengthForEndType + @param end_type + @return the number of "length" needed to draw a extremity of type Qet::EndType. */ uint PartLine::requiredLengthForEndType(const Qet::EndType &end_type) { - uint length_count_required = 0; + uint length_count_required = 0; - if (end_type == Qet::Circle || end_type == Qet::Diamond) - length_count_required = 2; - else if (end_type == Qet::Simple || end_type == Qet::Triangle) - length_count_required = 1; + if (end_type == Qet::Circle || end_type == Qet::Diamond) + length_count_required = 2; + else if (end_type == Qet::Simple || end_type == Qet::Triangle) + length_count_required = 1; - return(length_count_required); + return(length_count_required); } /** - @brief PartLine::paint - Draw this line - @param painter - @param options - @param widget + @brief PartLine::paint + Draw this line + @param painter + @param options + @param widget */ void PartLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget) { - Q_UNUSED(widget) - if (isUseless()) return; + Q_UNUSED(widget) + if (isUseless()) return; - painter->save(); - applyStylesToQPainter(*painter); - QPen t = painter -> pen(); - t.setJoinStyle(Qt::MiterJoin); + painter->save(); + applyStylesToQPainter(*painter); + QPen t = painter -> pen(); + t.setJoinStyle(Qt::MiterJoin); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - t.setCosmetic(options && options -> levelOfDetail < 1.0); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + t.setCosmetic(options && options -> levelOfDetail < 1.0); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); + t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); #endif - if (isSelected()) t.setColor(Qt::red); + if (isSelected()) t.setColor(Qt::red); - painter -> setPen(t); + painter -> setPen(t); - if (first_end || second_end) - painter -> drawPath(path()); - else - painter -> drawLine(m_line); + if (first_end || second_end) + painter -> drawPath(path()); + else + painter -> drawLine(m_line); - if (m_hovered) - drawShadowShape(painter); + if (m_hovered) + drawShadowShape(painter); - painter->restore(); + painter->restore(); } /** - @brief PartLine::toXml - Export this line in xml - @param xml_document : Xml document to use for create the xml element. - @return an xml element that describe this line + @brief PartLine::toXml + Export this line in xml + @param xml_document : Xml document to use for create the xml element. + @return an xml element that describe this line */ const QDomElement PartLine::toXml(QDomDocument &xml_document) const { - QPointF p1(sceneP1()); - QPointF p2(sceneP2()); + QPointF p1(sceneP1()); + QPointF p2(sceneP2()); - QDomElement xml_element = xml_document.createElement("line"); - xml_element.setAttribute("x1", QString("%1").arg(p1.x())); - xml_element.setAttribute("y1", QString("%1").arg(p1.y())); - xml_element.setAttribute("x2", QString("%1").arg(p2.x())); - xml_element.setAttribute("y2", QString("%1").arg(p2.y())); - xml_element.setAttribute("end1", Qet::endTypeToString(first_end)); - xml_element.setAttribute("length1", QString("%1").arg(first_length)); - xml_element.setAttribute("end2", Qet::endTypeToString(second_end)); - xml_element.setAttribute("length2", QString("%1").arg(second_length)); + QDomElement xml_element = xml_document.createElement("line"); + xml_element.setAttribute("x1", QString("%1").arg(p1.x())); + xml_element.setAttribute("y1", QString("%1").arg(p1.y())); + xml_element.setAttribute("x2", QString("%1").arg(p2.x())); + xml_element.setAttribute("y2", QString("%1").arg(p2.y())); + xml_element.setAttribute("end1", Qet::endTypeToString(first_end)); + xml_element.setAttribute("length1", QString("%1").arg(first_length)); + xml_element.setAttribute("end2", Qet::endTypeToString(second_end)); + xml_element.setAttribute("length2", QString("%1").arg(second_length)); - stylesToXml(xml_element); - return(xml_element); + stylesToXml(xml_element); + return(xml_element); } /** - @brief PartLine::fromXml - Import the properties of this line from a xml element. - @param qde : Xml document to use + @brief PartLine::fromXml + Import the properties of this line from a xml element. + @param qde : Xml document to use */ void PartLine::fromXml(const QDomElement &qde) { - stylesFromXml(qde); - m_line = QLineF(mapFromScene(qde.attribute("x1", "0").toDouble(), - qde.attribute("y1", "0").toDouble()), - mapFromScene(qde.attribute("x2", "0").toDouble(), - qde.attribute("y2", "0").toDouble())); + stylesFromXml(qde); + m_line = QLineF(mapFromScene(qde.attribute("x1", "0").toDouble(), + qde.attribute("y1", "0").toDouble()), + mapFromScene(qde.attribute("x2", "0").toDouble(), + qde.attribute("y2", "0").toDouble())); - first_end = Qet::endTypeFromString(qde.attribute("end1")); - first_length = qde.attribute("length1", "1.5").toDouble(); - second_end = Qet::endTypeFromString(qde.attribute("end2")); - second_length = qde.attribute("length2", "1.5").toDouble(); + first_end = Qet::endTypeFromString(qde.attribute("end1")); + first_length = qde.attribute("length1", "1.5").toDouble(); + second_end = Qet::endTypeFromString(qde.attribute("end2")); + second_length = qde.attribute("length2", "1.5").toDouble(); } /** - @brief PartLine::itemChange - @param change - @param value - @return + @brief PartLine::itemChange + @param change + @param value + @return */ QVariant PartLine::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged && scene()) - { - if (value.toBool() == true) - { - //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, - //according to the number of selected items. - connect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); + if (change == ItemSelectedHasChanged && scene()) + { + if (value.toBool() == true) + { + //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, + //according to the number of selected items. + connect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); - if (scene()->selectedItems().size() == 1) - addHandler(); - } - else - { - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); - removeHandler(); - } - } - else if (change == ItemPositionHasChanged) - { - adjusteHandlerPos(); - } - else if (change == ItemSceneChange) - { - if(scene()) - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); + if (scene()->selectedItems().size() == 1) + addHandler(); + } + else + { + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); + removeHandler(); + } + } + else if (change == ItemPositionHasChanged) + { + adjusteHandlerPos(); + } + else if (change == ItemSceneChange) + { + if(scene()) + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); - setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed. - } + setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed. + } - return QGraphicsItem::itemChange(change, value); + return QGraphicsItem::itemChange(change, value); } /** - @brief PartLine::sceneEventFilter - @param watched - @param event - @return + @brief PartLine::sceneEventFilter + @param watched + @param event + @return */ bool PartLine::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(qghi, static_cast(event)); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(qghi, static_cast(event)); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(qghi, static_cast(event)); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(qghi, static_cast(event)); + return true; + } + } + } + } - return false; + return false; } /** - @brief PartLine::adjusteHandlerPos - Adjust the position of the handler item + @brief PartLine::adjusteHandlerPos + Adjust the position of the handler item */ void PartLine::adjusteHandlerPos() { - if(m_handler_vector.isEmpty()) - return; + if(m_handler_vector.isEmpty()) + return; - QVector points_vector; - points_vector << m_line.p1() << m_line.p2(); + QVector points_vector; + points_vector << m_line.p1() << m_line.p2(); - if (m_handler_vector.size() == points_vector.size()) - { - points_vector = mapToScene(points_vector); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } + if (m_handler_vector.size() == points_vector.size()) + { + points_vector = mapToScene(points_vector); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } } /** - @brief PartLine::handlerMousePressEvent - @param qghi - @param event + @brief PartLine::handlerMousePressEvent + @param qghi + @param event */ void PartLine::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) - Q_UNUSED(event) + Q_UNUSED(qghi) + Q_UNUSED(event) - m_undo_command = new QPropertyUndoCommand(this, "line", QVariant(m_line)); - m_undo_command->setText(tr("Modifier une ligne")); - m_undo_command->enableAnimation(); - return; + m_undo_command = new QPropertyUndoCommand(this, "line", QVariant(m_line)); + m_undo_command->setText(tr("Modifier une ligne")); + m_undo_command->enableAnimation(); + return; } /** - @brief PartLine::handlerMouseMoveEvent - @param qghi - @param event + @brief PartLine::handlerMouseMoveEvent + @param qghi + @param event */ void PartLine::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) + Q_UNUSED(qghi) - QPointF new_pos = event->scenePos(); - if (event->modifiers() != Qt::ControlModifier) - new_pos = elementScene()->snapToGrid(event->scenePos()); - new_pos = mapFromScene(new_pos); + QPointF new_pos = event->scenePos(); + if (event->modifiers() != Qt::ControlModifier) + new_pos = elementScene()->snapToGrid(event->scenePos()); + new_pos = mapFromScene(new_pos); - prepareGeometryChange(); - if (m_vector_index == 0) - m_line.setP1(new_pos); - else - m_line.setP2(new_pos); + prepareGeometryChange(); + if (m_vector_index == 0) + m_line.setP1(new_pos); + else + m_line.setP2(new_pos); - emit lineChanged(); + emit lineChanged(); - adjusteHandlerPos(); + adjusteHandlerPos(); } /** - @brief PartLine::handlerMouseReleaseEvent - @param qghi - @param event + @brief PartLine::handlerMouseReleaseEvent + @param qghi + @param event */ void PartLine::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) - Q_UNUSED(event) + Q_UNUSED(qghi) + Q_UNUSED(event) - m_undo_command->setNewValue(QVariant(m_line)); - elementScene()->undoStack().push(m_undo_command); - m_undo_command = nullptr; - m_vector_index = -1; + m_undo_command->setNewValue(QVariant(m_line)); + elementScene()->undoStack().push(m_undo_command); + m_undo_command = nullptr; + m_vector_index = -1; } /** - @brief PartLine::sceneSelectionChanged - When the scene selection change, if there are several primitive selected, we remove the handler of this item + @brief PartLine::sceneSelectionChanged + When the scene selection change, if there are several primitive selected, we remove the handler of this item */ void PartLine::sceneSelectionChanged() { - if (this->isSelected() && scene()->selectedItems().size() == 1) - addHandler(); - else - removeHandler(); + if (this->isSelected() && scene()->selectedItems().size() == 1) + addHandler(); + else + removeHandler(); } /** - @brief PartLine::addHandler - Add handlers for this item + @brief PartLine::addHandler + Add handlers for this item */ void PartLine::addHandler() { - if (m_handler_vector.isEmpty() && scene()) - { - QVector points_vector; - points_vector << m_line.p1() << m_line.p2(); + if (m_handler_vector.isEmpty() && scene()) + { + QVector points_vector; + points_vector << m_line.p1() << m_line.p2(); - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector)); + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector)); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - { - handler->setColor(Qt::blue); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - handler->setZValue(this->zValue()+1); - } - } + for(QetGraphicsHandlerItem *handler : m_handler_vector) + { + handler->setColor(Qt::blue); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + handler->setZValue(this->zValue()+1); + } + } } /** - @brief PartLine::removeHandler - Remove the handlers of this item + @brief PartLine::removeHandler + Remove the handlers of this item */ void PartLine::removeHandler() { - if (!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } + if (!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } } /** - @brief PartLine::sceneP1 - @return the point p1 in scene coordinate + @brief PartLine::sceneP1 + @return the point p1 in scene coordinate */ QPointF PartLine::sceneP1() const { - return(mapToScene(m_line.p1())); + return(mapToScene(m_line.p1())); } /** - @brief PartLine::sceneP2 - @return the point p2 in scen coordinate + @brief PartLine::sceneP2 + @return the point p2 in scen coordinate */ QPointF PartLine::sceneP2() const { - return(mapToScene(m_line.p2())); + return(mapToScene(m_line.p2())); } /** - @brief PartLine::shape - @return the shape of this item + @brief PartLine::shape + @return the shape of this item */ QPainterPath PartLine::shape() const { - QPainterPath shape; + QPainterPath shape; - //We calcul path only if there is an end type - //Else we just draw a line - if (first_end || second_end) - shape.addPath(path()); - else - { - shape.moveTo(m_line.p1()); - shape.lineTo(m_line.p2()); - } + //We calcul path only if there is an end type + //Else we just draw a line + if (first_end || second_end) + shape.addPath(path()); + else + { + shape.moveTo(m_line.p1()); + shape.lineTo(m_line.p2()); + } - QPainterPathStroker pps; - pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); - shape = pps.createStroke(shape); + QPainterPathStroker pps; + pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); + shape = pps.createStroke(shape); - return shape; + return shape; } QPainterPath PartLine::shadowShape() const { - QPainterPath shape; + QPainterPath shape; - //We calcul path only if there is an end type - //Else we just draw a line - if (first_end || second_end) - shape.addPath(path()); - else - { - shape.moveTo(m_line.p1()); - shape.lineTo(m_line.p2()); - } + //We calcul path only if there is an end type + //Else we just draw a line + if (first_end || second_end) + shape.addPath(path()); + else + { + shape.moveTo(m_line.p1()); + shape.lineTo(m_line.p2()); + } - QPainterPathStroker pps; - pps.setWidth(penWeight()); + QPainterPathStroker pps; + pps.setWidth(penWeight()); - return (pps.createStroke(shape)); + return (pps.createStroke(shape)); } /** - @brief PartLine::firstEndCircleRect - @return the rectangle bordering the entirety of the first extremity + @brief PartLine::firstEndCircleRect + @return the rectangle bordering the entirety of the first extremity */ QRectF PartLine::firstEndCircleRect() const { - QList interesting_points = fourEndPoints(m_line.p1(), - m_line.p2(), - first_length); + QList interesting_points = fourEndPoints(m_line.p1(), + m_line.p2(), + first_length); - QRectF end_rect( - interesting_points[0] - QPointF(first_length, first_length), - QSizeF(2.0 * first_length, 2.0 * first_length) - ); + QRectF end_rect( + interesting_points[0] - QPointF(first_length, first_length), + QSizeF(2.0 * first_length, 2.0 * first_length) + ); - return(end_rect); + return(end_rect); } /** - @brief PartLine::secondEndCircleRect - @return the rectangle bordering the entirety of the second extremity + @brief PartLine::secondEndCircleRect + @return the rectangle bordering the entirety of the second extremity */ QRectF PartLine::secondEndCircleRect() const { - QList interesting_points = fourEndPoints(m_line.p2(), - m_line.p1(), - second_length); + QList interesting_points = fourEndPoints(m_line.p2(), + m_line.p1(), + second_length); - QRectF end_rect( - interesting_points[0] - QPointF(second_length, second_length), - QSizeF(2.0 * second_length, 2.0 * second_length) - ); + QRectF end_rect( + interesting_points[0] - QPointF(second_length, second_length), + QSizeF(2.0 * second_length, 2.0 * second_length) + ); - return(end_rect); + return(end_rect); } /** - @brief PartLine::boundingRect - @return the bounding rect of this part + @brief PartLine::boundingRect + @return the bounding rect of this part */ QRectF PartLine::boundingRect() const { - QRectF bound; - if (first_end || second_end) - bound = path().boundingRect(); - else - bound = QRectF (m_line.p1(), m_line.p2()); + QRectF bound; + if (first_end || second_end) + bound = path().boundingRect(); + else + bound = QRectF (m_line.p1(), m_line.p2()); - qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2; - //We add 0.5 because CustomElementGraphicPart::drawShadowShape - //draw a shape bigger of 0.5 when pen weight is to 0. - if (penWeight() == 0) adjust += 0.5; + qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2; + //We add 0.5 because CustomElementGraphicPart::drawShadowShape + //draw a shape bigger of 0.5 when pen weight is to 0. + if (penWeight() == 0) adjust += 0.5; - bound = bound.normalized(); - bound.adjust(-adjust, -adjust, adjust, adjust); + bound = bound.normalized(); + bound.adjust(-adjust, -adjust, adjust, adjust); - return bound; + return bound; } /** - @brief PartLine::isUseless - @return true if this part is irrelevant and does not deserve to be Retained / registered. - A line is relevant when is two point is different + @brief PartLine::isUseless + @return true if this part is irrelevant and does not deserve to be Retained / registered. + A line is relevant when is two point is different */ bool PartLine::isUseless() const { - return(m_line.p1() == m_line.p2()); + return(m_line.p1() == m_line.p2()); } /** - @brief PartLine::sceneGeometricRect - @return the minimum, margin-less rectangle this part can fit into, in scene - coordinates. It is different from boundingRect() because it is not supposed - to imply any margin, and it is different from shape because it is a regular - rectangle, not a complex shape. + @brief PartLine::sceneGeometricRect + @return the minimum, margin-less rectangle this part can fit into, in scene + coordinates. It is different from boundingRect() because it is not supposed + to imply any margin, and it is different from shape because it is a regular + rectangle, not a complex shape. */ QRectF PartLine::sceneGeometricRect() const { - return(QRectF(sceneP1(), sceneP2())); + return(QRectF(sceneP1(), sceneP2())); } /** - @brief PartLine::startUserTransformation - Start the user-induced transformation, provided this primitive is contained - within the \a initial_selection_rect bounding rectangle. - @param initial_selection_rect + @brief PartLine::startUserTransformation + Start the user-induced transformation, provided this primitive is contained + within the \a initial_selection_rect bounding rectangle. + @param initial_selection_rect */ void PartLine::startUserTransformation(const QRectF &initial_selection_rect) { - Q_UNUSED(initial_selection_rect) - saved_points_.clear(); - saved_points_ << sceneP1() << sceneP2(); + Q_UNUSED(initial_selection_rect) + saved_points_.clear(); + saved_points_ << sceneP1() << sceneP2(); } /** - @brief PartLine::handleUserTransformation - Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect - @param initial_selection_rect - @param new_selection_rect + @brief PartLine::handleUserTransformation + Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect + @param initial_selection_rect + @param new_selection_rect */ void PartLine::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) { - QList mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); - prepareGeometryChange(); - m_line = QLineF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1))); + QList mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); + prepareGeometryChange(); + m_line = QLineF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1))); } /** - @brief PartLine::fourEndPoints - Return the four interesting point needed to draw the shape - at extremity of line (circle, diamond, arrow, triangle) - This points are in order : - * O : point on the line, at a distance 'length' of the extremity - * A : point on the line at a 'length' of 2x the extremity length - * B : point at a distance of length O - O is the projection of B on the line - * C : point at a distance of length O - O is the projection of C on the line - @param end_point : The concerned extremity - @param other_point : other needed point to define the line - @param length : length to use between the extremity and the point O - @return + @brief PartLine::fourEndPoints + Return the four interesting point needed to draw the shape + at extremity of line (circle, diamond, arrow, triangle) + This points are in order : + * O : point on the line, at a distance 'length' of the extremity + * A : point on the line at a 'length' of 2x the extremity length + * B : point at a distance of length O - O is the projection of B on the line + * C : point at a distance of length O - O is the projection of C on the line + @param end_point : The concerned extremity + @param other_point : other needed point to define the line + @param length : length to use between the extremity and the point O + @return */ QList PartLine::fourEndPoints(const QPointF &end_point, const QPointF &other_point, const qreal &length) { - //Vector and length of the line - QPointF line_vector = end_point - other_point; - qreal line_length = sqrt(pow(line_vector.x(), 2) + pow(line_vector.y(), 2)); + //Vector and length of the line + QPointF line_vector = end_point - other_point; + qreal line_length = sqrt(pow(line_vector.x(), 2) + pow(line_vector.y(), 2)); - //Unitary vector and perpendicular vector - QPointF u(line_vector / line_length * length); - QPointF v(-u.y(), u.x()); + //Unitary vector and perpendicular vector + QPointF u(line_vector / line_length * length); + QPointF v(-u.y(), u.x()); - // points O, A, B, C - QPointF o(end_point - u); - QPointF a(o - u); - QPointF b(o + v); - QPointF c(o - v); + // points O, A, B, C + QPointF o(end_point - u); + QPointF a(o - u); + QPointF b(o + v); + QPointF c(o - v); - return(QList() << o << a << b << c); + return(QList() << o << a << b << c); } QLineF PartLine::line() const { - return m_line; + return m_line; } void PartLine::setLine(const QLineF &line) { - if (m_line == line) return; - prepareGeometryChange(); - m_line = line; - adjusteHandlerPos(); - emit lineChanged(); + if (m_line == line) return; + prepareGeometryChange(); + m_line = line; + adjusteHandlerPos(); + emit lineChanged(); } void PartLine::setFirstEndType(const Qet::EndType &et) { - if (first_end == et) return; - prepareGeometryChange(); - first_end = et; - emit firstEndTypeChanged(); + if (first_end == et) return; + prepareGeometryChange(); + first_end = et; + emit firstEndTypeChanged(); } void PartLine::setSecondEndType(const Qet::EndType &et) { - if (second_end == et) return; - prepareGeometryChange(); - second_end = et; - emit secondEndTypeChanged(); + if (second_end == et) return; + prepareGeometryChange(); + second_end = et; + emit secondEndTypeChanged(); } void PartLine::setFirstEndLength(const qreal &l) { - qreal length = qMin(qAbs(l), m_line.length()); - if (first_length == length) return; - prepareGeometryChange(); - first_length = length; - emit firstEndLengthChanged(); + qreal length = qMin(qAbs(l), m_line.length()); + if (first_length == length) return; + prepareGeometryChange(); + first_length = length; + emit firstEndLengthChanged(); } void PartLine::setSecondEndLength(const qreal &l) { - qreal length = qMin(qAbs(l), m_line.length()); - if (second_length == length) return; - prepareGeometryChange(); - second_length = length; - emit secondEndLengthChanged(); + qreal length = qMin(qAbs(l), m_line.length()); + if (second_length == length) return; + prepareGeometryChange(); + second_length = length; + emit secondEndLengthChanged(); } /** - @brief PartLine::path - @return this line has a QPainterPath. - It's notably use when this line have an end type (circle, triangle etc....), - because return a QPainterPath with end already draw. - Else if there isn't an end type get P1 and P2 of line is better (faster). + @brief PartLine::path + @return this line has a QPainterPath. + It's notably use when this line have an end type (circle, triangle etc....), + because return a QPainterPath with end already draw. + Else if there isn't an end type get P1 and P2 of line is better (faster). */ QPainterPath PartLine::path() const { - QPainterPath path; + QPainterPath path; - QPointF point1(m_line.p1()); - QPointF point2(m_line.p2()); + QPointF point1(m_line.p1()); + QPointF point2(m_line.p2()); - qreal line_length(m_line.length()); - qreal pen_width = penWeight(); + qreal line_length(m_line.length()); + qreal pen_width = penWeight(); - qreal length1 = first_length; - qreal length2 = second_length; + qreal length1 = first_length; + qreal length2 = second_length; - //debugPaint(painter); + //debugPaint(painter); - //Determine if we must to draw extremity - qreal reduced_line_length = line_length - (length1 * requiredLengthForEndType(first_end)); - bool draw_1st_end = first_end && reduced_line_length >= 0; + //Determine if we must to draw extremity + qreal reduced_line_length = line_length - (length1 * requiredLengthForEndType(first_end)); + bool draw_1st_end = first_end && reduced_line_length >= 0; - if (draw_1st_end) - reduced_line_length -= (length2 * requiredLengthForEndType(second_end)); - else - reduced_line_length = line_length - (length2 * requiredLengthForEndType(second_end)); + if (draw_1st_end) + reduced_line_length -= (length2 * requiredLengthForEndType(second_end)); + else + reduced_line_length = line_length - (length2 * requiredLengthForEndType(second_end)); - //Draw the first extremity - QPointF start_point; - if (draw_1st_end) - { - QList four_points1(fourEndPoints(point1, point2, length1)); + //Draw the first extremity + QPointF start_point; + if (draw_1st_end) + { + QList four_points1(fourEndPoints(point1, point2, length1)); - if (first_end == Qet::Circle) - { - path.addEllipse(QRectF(four_points1[0] - QPointF(length1, length1), QSizeF(length1 * 2.0, length1 * 2.0))); - start_point = four_points1[1]; - } - else if (first_end == Qet::Diamond) - { - path.addPolygon(QPolygonF() << four_points1[1] << four_points1[2] << point1 << four_points1[3] << four_points1[1]); - start_point = four_points1[1]; - } - else if (first_end == Qet::Simple) - { - path.addPolygon(QPolygonF() << four_points1[3] << point1 << four_points1[2]); - start_point = point1; + if (first_end == Qet::Circle) + { + path.addEllipse(QRectF(four_points1[0] - QPointF(length1, length1), QSizeF(length1 * 2.0, length1 * 2.0))); + start_point = four_points1[1]; + } + else if (first_end == Qet::Diamond) + { + path.addPolygon(QPolygonF() << four_points1[1] << four_points1[2] << point1 << four_points1[3] << four_points1[1]); + start_point = four_points1[1]; + } + else if (first_end == Qet::Simple) + { + path.addPolygon(QPolygonF() << four_points1[3] << point1 << four_points1[2]); + start_point = point1; - } - else if (first_end == Qet::Triangle) - { - path.addPolygon(QPolygonF() << four_points1[0] << four_points1[2] << point1 << four_points1[3] << four_points1[0]); - start_point = four_points1[0]; - } + } + else if (first_end == Qet::Triangle) + { + path.addPolygon(QPolygonF() << four_points1[0] << four_points1[2] << point1 << four_points1[3] << four_points1[0]); + start_point = four_points1[0]; + } - //Adjust the start point according to the pen width - if (pen_width && (first_end == Qet::Simple || first_end == Qet::Circle)) - start_point = QLineF(start_point, point2).pointAt(pen_width / 2.0 / line_length); - } - else - { - start_point = point1; - } + //Adjust the start point according to the pen width + if (pen_width && (first_end == Qet::Simple || first_end == Qet::Circle)) + start_point = QLineF(start_point, point2).pointAt(pen_width / 2.0 / line_length); + } + else + { + start_point = point1; + } - //Draw the second extremity - QPointF stop_point; - bool draw_2nd_end = second_end && reduced_line_length >= 0; - if (draw_2nd_end) - { - QList four_points2(fourEndPoints(point2, point1, length2)); + //Draw the second extremity + QPointF stop_point; + bool draw_2nd_end = second_end && reduced_line_length >= 0; + if (draw_2nd_end) + { + QList four_points2(fourEndPoints(point2, point1, length2)); - if (second_end == Qet::Circle) - { - path.addEllipse(QRectF(four_points2[0] - QPointF(length2, length2), QSizeF(length2 * 2.0, length2 * 2.0))); - stop_point = four_points2[1]; - } - else if (second_end == Qet::Diamond) - { - path.addPolygon(QPolygonF() << four_points2[2] << point2 << four_points2[3] << four_points2[1] << four_points2[2]); - stop_point = four_points2[1]; - } - else if (second_end == Qet::Simple) - { - path.addPolygon(QPolygonF() << four_points2[3] << point2 << four_points2[2]); - stop_point = point2; - } - else if (second_end == Qet::Triangle) - {/** - @return true si cette partie n'est pas pertinente et ne merite pas d'etre - conservee / enregistree. - Une ligne est pertinente des lors que ses deux points sont differents + if (second_end == Qet::Circle) + { + path.addEllipse(QRectF(four_points2[0] - QPointF(length2, length2), QSizeF(length2 * 2.0, length2 * 2.0))); + stop_point = four_points2[1]; + } + else if (second_end == Qet::Diamond) + { + path.addPolygon(QPolygonF() << four_points2[2] << point2 << four_points2[3] << four_points2[1] << four_points2[2]); + stop_point = four_points2[1]; + } + else if (second_end == Qet::Simple) + { + path.addPolygon(QPolygonF() << four_points2[3] << point2 << four_points2[2]); + stop_point = point2; + } + else if (second_end == Qet::Triangle) + {/** + @return true si cette partie n'est pas pertinente et ne merite pas d'etre + conservee / enregistree. + Une ligne est pertinente des lors que ses deux points sont differents */ - path.addPolygon(QPolygonF() << four_points2[0] << four_points2[2] << point2 << four_points2[3] << four_points2[0]); - stop_point = four_points2[0]; - } + path.addPolygon(QPolygonF() << four_points2[0] << four_points2[2] << point2 << four_points2[3] << four_points2[0]); + stop_point = four_points2[0]; + } - //Adjust the end point accordint to the pen width - if (pen_width && (second_end == Qet::Simple || second_end == Qet::Circle)) - stop_point = QLineF(point1, stop_point).pointAt((line_length - (pen_width / 2.0)) / line_length); - } - else - { - stop_point = point2; - } + //Adjust the end point accordint to the pen width + if (pen_width && (second_end == Qet::Simple || second_end == Qet::Circle)) + stop_point = QLineF(point1, stop_point).pointAt((line_length - (pen_width / 2.0)) / line_length); + } + else + { + stop_point = point2; + } - path.moveTo(start_point); - path.lineTo(stop_point); + path.moveTo(start_point); + path.lineTo(stop_point); - return path; + return path; } diff --git a/sources/editor/graphicspart/partline.h b/sources/editor/graphicspart/partline.h index 589335ba2..22635d2d1 100644 --- a/sources/editor/graphicspart/partline.h +++ b/sources/editor/graphicspart/partline.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_LINE_H #define PART_LINE_H @@ -25,104 +25,104 @@ class QPropertyUndoCommand; class QetGraphicsHandlerItem; /** - This class represents a line primitive which may be used to compose the - drawing of an electrical element within the element editor. Lines may have - specific visual ends (e.g. arrows) through the setFirstEndType and - setSecondEndType methods. Their size can be defined using the - setFirstEndLength and setSecondEndLength methods. Please note ends are not - drawn if the required length for their drawing is longer than the line itself. - In case there is room for a single end only, the first one get priority. + This class represents a line primitive which may be used to compose the + drawing of an electrical element within the element editor. Lines may have + specific visual ends (e.g. arrows) through the setFirstEndType and + setSecondEndType methods. Their size can be defined using the + setFirstEndLength and setSecondEndLength methods. Please note ends are not + drawn if the required length for their drawing is longer than the line itself. + In case there is room for a single end only, the first one get priority. */ class PartLine : public CustomElementGraphicPart { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(Qet::EndType end1 READ firstEndType WRITE setFirstEndType) - Q_PROPERTY(Qet::EndType end2 READ secondEndType WRITE setSecondEndType) - Q_PROPERTY(qreal length1 READ firstEndLength WRITE setFirstEndLength) - Q_PROPERTY(qreal length2 READ secondEndLength WRITE setSecondEndLength) - Q_PROPERTY(QLineF line READ line WRITE setLine) + Q_PROPERTY(Qet::EndType end1 READ firstEndType WRITE setFirstEndType) + Q_PROPERTY(Qet::EndType end2 READ secondEndType WRITE setSecondEndType) + Q_PROPERTY(qreal length1 READ firstEndLength WRITE setFirstEndLength) + Q_PROPERTY(qreal length2 READ secondEndLength WRITE setSecondEndLength) + Q_PROPERTY(QLineF line READ line WRITE setLine) - // constructors, destructor - public: - PartLine(QETElementEditor *, QGraphicsItem * = nullptr); - ~PartLine() override; - private: - PartLine(const PartLine &); + // constructors, destructor + public: + PartLine(QETElementEditor *, QGraphicsItem * = nullptr); + ~PartLine() override; + private: + PartLine(const PartLine &); - signals: - void lineChanged(); - void firstEndTypeChanged(); - void secondEndTypeChanged(); - void firstEndLengthChanged(); - void secondEndLengthChanged(); + signals: + void lineChanged(); + void firstEndTypeChanged(); + void secondEndTypeChanged(); + void firstEndLengthChanged(); + void secondEndLengthChanged(); - - // methods - public: - enum { Type = UserType + 1104 }; - - /** - Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartLine. - @return the QGraphicsItem type - */ - int type() const override { return Type; } - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; - QString name() const override { return(QObject::tr("ligne", "element part name")); } - QString xmlName() const override { return(QString("line")); } - const QDomElement toXml(QDomDocument &) const override; - void fromXml(const QDomElement &) override; - virtual QPointF sceneP1() const; - virtual QPointF sceneP2() const; - QPainterPath shape() const override; - QPainterPath shadowShape() const override; - QRectF boundingRect() const override; - bool isUseless() const override; - QRectF sceneGeometricRect() const override; - void startUserTransformation(const QRectF &) override; - void handleUserTransformation(const QRectF &, const QRectF &) override; - static uint requiredLengthForEndType(const Qet::EndType &); - static QList fourEndPoints(const QPointF &, const QPointF &, const qreal &); + + // methods + public: + enum { Type = UserType + 1104 }; + + /** + Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartLine. + @return the QGraphicsItem type + */ + int type() const override { return Type; } + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; + QString name() const override { return(QObject::tr("ligne", "element part name")); } + QString xmlName() const override { return(QString("line")); } + const QDomElement toXml(QDomDocument &) const override; + void fromXml(const QDomElement &) override; + virtual QPointF sceneP1() const; + virtual QPointF sceneP2() const; + QPainterPath shape() const override; + QPainterPath shadowShape() const override; + QRectF boundingRect() const override; + bool isUseless() const override; + QRectF sceneGeometricRect() const override; + void startUserTransformation(const QRectF &) override; + void handleUserTransformation(const QRectF &, const QRectF &) override; + static uint requiredLengthForEndType(const Qet::EndType &); + static QList fourEndPoints(const QPointF &, const QPointF &, const qreal &); - QLineF line() const; - void setLine(const QLineF &line); - Qet::EndType firstEndType() const {return first_end;} - void setFirstEndType(const Qet::EndType &et); - Qet::EndType secondEndType() const {return second_end;} - void setSecondEndType(const Qet::EndType &et); - qreal firstEndLength() const {return first_length;} - void setFirstEndLength(const qreal &l); - qreal secondEndLength() const {return second_length;} - void setSecondEndLength(const qreal &l); + QLineF line() const; + void setLine(const QLineF &line); + Qet::EndType firstEndType() const {return first_end;} + void setFirstEndType(const Qet::EndType &et); + Qet::EndType secondEndType() const {return second_end;} + void setSecondEndType(const Qet::EndType &et); + qreal firstEndLength() const {return first_length;} + void setFirstEndLength(const qreal &l); + qreal secondEndLength() const {return second_length;} + void setSecondEndLength(const qreal &l); - protected: - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; - - private: - void adjusteHandlerPos(); - void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void sceneSelectionChanged (); - - void addHandler(); - void removeHandler(); - - QPainterPath path() const; - QRectF firstEndCircleRect() const; - QRectF secondEndCircleRect() const; + protected: + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; + + private: + void adjusteHandlerPos(); + void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void sceneSelectionChanged (); + + void addHandler(); + void removeHandler(); + + QPainterPath path() const; + QRectF firstEndCircleRect() const; + QRectF secondEndCircleRect() const; - /*****************/ - Qet::EndType first_end; - qreal first_length; + /*****************/ + Qet::EndType first_end; + qreal first_length; - Qet::EndType second_end; - qreal second_length; - QList saved_points_; - QLineF m_line; - int m_vector_index = -1; - QPropertyUndoCommand *m_undo_command; - QVector m_handler_vector; + Qet::EndType second_end; + qreal second_length; + QList saved_points_; + QLineF m_line; + int m_vector_index = -1; + QPropertyUndoCommand *m_undo_command; + QVector m_handler_vector; }; #endif diff --git a/sources/editor/graphicspart/partpolygon.cpp b/sources/editor/graphicspart/partpolygon.cpp index 89e21beb9..5b00d585f 100644 --- a/sources/editor/graphicspart/partpolygon.cpp +++ b/sources/editor/graphicspart/partpolygon.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partpolygon.h" #include "QPropertyUndoCommand/qpropertyundocommand.h" @@ -25,593 +25,593 @@ /** - @brief PartPolygon::PartPolygon - Constructor - @param editor : editor of this item - @param parent : parent item + @brief PartPolygon::PartPolygon + Constructor + @param editor : editor of this item + @param parent : parent item */ PartPolygon::PartPolygon(QETElementEditor *editor, QGraphicsItem *parent) : - CustomElementGraphicPart(editor, parent), - m_closed(false), - m_undo_command(nullptr) + CustomElementGraphicPart(editor, parent), + m_closed(false), + m_undo_command(nullptr) { - m_insert_point = new QAction(tr("Ajouter un point"), this); - m_insert_point->setIcon(QET::Icons::Add); - connect(m_insert_point, &QAction::triggered, this, &PartPolygon::insertPoint); - m_remove_point = new QAction(tr("Supprimer ce point"), this); - m_remove_point->setIcon(QET::Icons::Remove); - connect(m_remove_point, &QAction::triggered, this, &PartPolygon::removePoint); + m_insert_point = new QAction(tr("Ajouter un point"), this); + m_insert_point->setIcon(QET::Icons::Add); + connect(m_insert_point, &QAction::triggered, this, &PartPolygon::insertPoint); + m_remove_point = new QAction(tr("Supprimer ce point"), this); + m_remove_point->setIcon(QET::Icons::Remove); + connect(m_remove_point, &QAction::triggered, this, &PartPolygon::removePoint); } /** - @brief PartPolygon::~PartPolygon + @brief PartPolygon::~PartPolygon */ PartPolygon::~PartPolygon() { - if(m_undo_command) delete m_undo_command; - removeHandler(); + if(m_undo_command) delete m_undo_command; + removeHandler(); } /** - @brief PartPolygon::paint - Draw this polygon - @param painter - @param options - @param widget + @brief PartPolygon::paint + Draw this polygon + @param painter + @param options + @param widget */ void PartPolygon::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget) { Q_UNUSED(widget) - applyStylesToQPainter(*painter); + applyStylesToQPainter(*painter); - QPen t = painter -> pen(); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - t.setCosmetic(options && options -> levelOfDetail < 1.0); + QPen t = painter -> pen(); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + t.setCosmetic(options && options -> levelOfDetail < 1.0); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); + t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); #endif - if (isSelected()) t.setColor(Qt::red); - painter -> setPen(t); + if (isSelected()) t.setColor(Qt::red); + painter -> setPen(t); - m_closed ? painter -> drawPolygon (m_polygon) : - painter -> drawPolyline(m_polygon); + m_closed ? painter -> drawPolygon (m_polygon) : + painter -> drawPolyline(m_polygon); - if (m_hovered) - drawShadowShape(painter); + if (m_hovered) + drawShadowShape(painter); } /** - @brief PartPolygon::fromXml - Import the properties of this polygon from a xml element - @param qde : Xml document to use + @brief PartPolygon::fromXml + Import the properties of this polygon from a xml element + @param qde : Xml document to use */ void PartPolygon::fromXml(const QDomElement &qde) { - stylesFromXml(qde); + stylesFromXml(qde); - int i = 1; - while(true) - { - if (QET::attributeIsAReal(qde, QString("x%1").arg(i)) &&\ - QET::attributeIsAReal(qde, QString("y%1").arg(i))) - ++ i; + int i = 1; + while(true) + { + if (QET::attributeIsAReal(qde, QString("x%1").arg(i)) &&\ + QET::attributeIsAReal(qde, QString("y%1").arg(i))) + ++ i; - else break; - } + else break; + } - QPolygonF temp_polygon; - for (int j = 1 ; j < i ; ++ j) - { - temp_polygon << QPointF(qde.attribute(QString("x%1").arg(j)).toDouble(), - qde.attribute(QString("y%1").arg(j)).toDouble()); - } - m_polygon = temp_polygon; + QPolygonF temp_polygon; + for (int j = 1 ; j < i ; ++ j) + { + temp_polygon << QPointF(qde.attribute(QString("x%1").arg(j)).toDouble(), + qde.attribute(QString("y%1").arg(j)).toDouble()); + } + m_polygon = temp_polygon; - m_closed = qde.attribute("closed") != "false"; + m_closed = qde.attribute("closed") != "false"; } /** - @brief PartPolygon::toXml - Export this polygin in xml - @param xml_document : Xml document to use for create the xml element - @return an xml element that describe this polygon + @brief PartPolygon::toXml + Export this polygin in xml + @param xml_document : Xml document to use for create the xml element + @return an xml element that describe this polygon */ const QDomElement PartPolygon::toXml(QDomDocument &xml_document) const { - QDomElement xml_element = xml_document.createElement("polygon"); - int i = 1; - foreach(QPointF point, m_polygon) { - point = mapToScene(point); - xml_element.setAttribute(QString("x%1").arg(i), QString("%1").arg(point.x())); - xml_element.setAttribute(QString("y%1").arg(i), QString("%1").arg(point.y())); - ++ i; - } - if (!m_closed) xml_element.setAttribute("closed", "false"); - stylesToXml(xml_element); - return(xml_element); + QDomElement xml_element = xml_document.createElement("polygon"); + int i = 1; + foreach(QPointF point, m_polygon) { + point = mapToScene(point); + xml_element.setAttribute(QString("x%1").arg(i), QString("%1").arg(point.x())); + xml_element.setAttribute(QString("y%1").arg(i), QString("%1").arg(point.y())); + ++ i; + } + if (!m_closed) xml_element.setAttribute("closed", "false"); + stylesToXml(xml_element); + return(xml_element); } /** - @brief PartPolygon::isUseless - @return true if this part is irrelevant and does not deserve to be Retained / registered. - A polygon is relevant when he have 2 differents points + @brief PartPolygon::isUseless + @return true if this part is irrelevant and does not deserve to be Retained / registered. + A polygon is relevant when he have 2 differents points */ bool PartPolygon::isUseless() const { - if (m_polygon.count() < 2) return(true); + if (m_polygon.count() < 2) return(true); - for (int i = 1 ; i < m_polygon.count() ; ++ i) - if (m_polygon[i] != m_polygon[i-1]) return(false); + for (int i = 1 ; i < m_polygon.count() ; ++ i) + if (m_polygon[i] != m_polygon[i-1]) return(false); - return(true); + return(true); } /** - @brief PartPolygon::sceneGeometricRect - @return the minimum, margin-less rectangle this part can fit into, in scene - coordinates. It is different from boundingRect() because it is not supposed - to imply any margin, and it is different from shape because it is a regular - rectangle, not a complex shape. + @brief PartPolygon::sceneGeometricRect + @return the minimum, margin-less rectangle this part can fit into, in scene + coordinates. It is different from boundingRect() because it is not supposed + to imply any margin, and it is different from shape because it is a regular + rectangle, not a complex shape. */ QRectF PartPolygon::sceneGeometricRect() const { - return(mapToScene(m_polygon.boundingRect()).boundingRect()); + return(mapToScene(m_polygon.boundingRect()).boundingRect()); } /** - @brief PartPolygon::startUserTransformation - Start the user-induced transformation, provided this primitive is contained - within the initial_selection_rect bounding rectangle. - @param initial_selection_rect + @brief PartPolygon::startUserTransformation + Start the user-induced transformation, provided this primitive is contained + within the initial_selection_rect bounding rectangle. + @param initial_selection_rect */ void PartPolygon::startUserTransformation(const QRectF &initial_selection_rect) { - Q_UNUSED(initial_selection_rect) - saved_points_ = mapToScene(m_polygon).toList(); + Q_UNUSED(initial_selection_rect) + saved_points_ = mapToScene(m_polygon).toList(); } /** - @brief PartPolygon::handleUserTransformation - Handle the user-induced transformation from initial_selection_rect to new_selection_rect - @param initial_selection_rect - @param new_selection_rect + @brief PartPolygon::handleUserTransformation + Handle the user-induced transformation from initial_selection_rect to new_selection_rect + @param initial_selection_rect + @param new_selection_rect */ void PartPolygon::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) { - QList mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); - m_polygon = (mapFromScene(QPolygonF(mapped_points.toVector()))); + QList mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); + m_polygon = (mapFromScene(QPolygonF(mapped_points.toVector()))); } /** - @brief PartPolygon::preferredScalingMethod - This method is called by the decorator when it needs to determine the best - way to interactively scale a primitive. It is typically called when only a - single primitive is being scaled. - @return : This reimplementation systematically returns QET::RoundScaleRatios. + @brief PartPolygon::preferredScalingMethod + This method is called by the decorator when it needs to determine the best + way to interactively scale a primitive. It is typically called when only a + single primitive is being scaled. + @return : This reimplementation systematically returns QET::RoundScaleRatios. */ QET::ScalingMethod PartPolygon::preferredScalingMethod() const { - return(QET::RoundScaleRatios); + return(QET::RoundScaleRatios); } /** - @brief PartPolygon::polygon - @return the item's polygon, or an empty polygon if no polygon has been set. + @brief PartPolygon::polygon + @return the item's polygon, or an empty polygon if no polygon has been set. */ QPolygonF PartPolygon::polygon() const { - return m_polygon; + return m_polygon; } /** - @brief PartPolygon::setPolygon - Sets the item's polygon to be the given polygon. - @param polygon + @brief PartPolygon::setPolygon + Sets the item's polygon to be the given polygon. + @param polygon */ void PartPolygon::setPolygon(const QPolygonF &polygon) { - if (m_polygon == polygon) return; - prepareGeometryChange(); - m_polygon = polygon; - adjusteHandlerPos(); - emit polygonChanged(); + if (m_polygon == polygon) return; + prepareGeometryChange(); + m_polygon = polygon; + adjusteHandlerPos(); + emit polygonChanged(); } /** - @brief PartPolygon::addPoint - Add new point to polygon - @param point + @brief PartPolygon::addPoint + Add new point to polygon + @param point */ void PartPolygon::addPoint(const QPointF &point) { - prepareGeometryChange(); - m_polygon << point; + prepareGeometryChange(); + m_polygon << point; } /** - @brief PartPolygon::setLastPoint - Set the last point of polygon to point - @param point + @brief PartPolygon::setLastPoint + Set the last point of polygon to point + @param point */ void PartPolygon::setLastPoint(const QPointF &point) { - if (m_polygon.size()) - m_polygon.pop_back(); + if (m_polygon.size()) + m_polygon.pop_back(); - prepareGeometryChange(); - m_polygon << point; + prepareGeometryChange(); + m_polygon << point; } /** - @brief PartPolygon::removeLastPoint - Remove the last point of polygon + @brief PartPolygon::removeLastPoint + Remove the last point of polygon */ void PartPolygon::removeLastPoint() { - if (m_polygon.size()) - { - prepareGeometryChange(); - m_polygon.pop_back(); - } + if (m_polygon.size()) + { + prepareGeometryChange(); + m_polygon.pop_back(); + } } void PartPolygon::setClosed(bool close) { - if (m_closed == close) return; - prepareGeometryChange(); - m_closed = close; - emit closedChange(); + if (m_closed == close) return; + prepareGeometryChange(); + m_closed = close; + emit closedChange(); } /** - @brief PartPolygon::setHandlerColor - Set the handler at pos pos (in polygon coordinate) to color color. - @param pos - @param color + @brief PartPolygon::setHandlerColor + Set the handler at pos pos (in polygon coordinate) to color color. + @param pos + @param color */ void PartPolygon::setHandlerColor(QPointF pos, const QColor &color) { - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - if (qghi->pos() == mapToScene(pos)) { - qghi->setColor(color); - } - } + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + if (qghi->pos() == mapToScene(pos)) { + qghi->setColor(color); + } + } } /** - @brief PartPolygon::resetAllHandlerColor - Reset the color of every handlers + @brief PartPolygon::resetAllHandlerColor + Reset the color of every handlers */ void PartPolygon::resetAllHandlerColor() { - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::blue); - } + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::blue); + } } /** - @brief PartPolygon::itemChange - @param change - @param value - @return + @brief PartPolygon::itemChange + @param change + @param value + @return */ QVariant PartPolygon::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged && scene()) - { - if (value.toBool() == true) - { - //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, - //according to the number of selected items. - connect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); + if (change == ItemSelectedHasChanged && scene()) + { + if (value.toBool() == true) + { + //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, + //according to the number of selected items. + connect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); - if (scene()->selectedItems().size() == 1) - addHandler(); - } - else - { - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); - removeHandler(); - } - } - else if (change == ItemPositionHasChanged) - { - adjusteHandlerPos(); - } - else if (change == ItemSceneChange) - { - if(scene()) - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); + if (scene()->selectedItems().size() == 1) + addHandler(); + } + else + { + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); + removeHandler(); + } + } + else if (change == ItemPositionHasChanged) + { + adjusteHandlerPos(); + } + else if (change == ItemSceneChange) + { + if(scene()) + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); - setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed. - } + setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed. + } - return QGraphicsItem::itemChange(change, value); + return QGraphicsItem::itemChange(change, value); } /** - @brief PartPolygon::sceneEventFilter - @param watched - @param event - @return + @brief PartPolygon::sceneEventFilter + @param watched + @param event + @return */ bool PartPolygon::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(qghi, static_cast(event)); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(qghi, static_cast(event)); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(qghi, static_cast(event)); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(qghi, static_cast(event)); + return true; + } + } + } + } - return false; + return false; } void PartPolygon::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { - m_context_menu_pos = event->pos(); - event->ignore(); - if (isSelected() && elementScene() && (elementScene()->behavior() == ElementScene::Normal)) - { - QList list; - list << m_insert_point; - if (m_handler_vector.count() > 2) - { - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - { - if (qghi->contains(qghi->mapFromScene(event->scenePos()))) - { - list << m_remove_point; - break; - } - } - } - elementScene()->editor()->contextMenu(event->screenPos(), list); - event->accept(); - } + m_context_menu_pos = event->pos(); + event->ignore(); + if (isSelected() && elementScene() && (elementScene()->behavior() == ElementScene::Normal)) + { + QList list; + list << m_insert_point; + if (m_handler_vector.count() > 2) + { + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + { + if (qghi->contains(qghi->mapFromScene(event->scenePos()))) + { + list << m_remove_point; + break; + } + } + } + elementScene()->editor()->contextMenu(event->screenPos(), list); + event->accept(); + } } /** - @brief PartPolygon::adjusteHandlerPos + @brief PartPolygon::adjusteHandlerPos */ void PartPolygon::adjusteHandlerPos() { - if(m_handler_vector.isEmpty()) - return; + if(m_handler_vector.isEmpty()) + return; - if (m_handler_vector.size() == m_polygon.size()) - { - QVector points_vector = mapToScene(m_polygon); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } - else - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - } + if (m_handler_vector.size() == m_polygon.size()) + { + QVector points_vector = mapToScene(m_polygon); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } + else + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + } } /** - @brief PartPolygon::handlerMousePressEvent - @param qghi - @param event + @brief PartPolygon::handlerMousePressEvent + @param qghi + @param event */ void PartPolygon::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi); - Q_UNUSED(event); + Q_UNUSED(qghi); + Q_UNUSED(event); - m_undo_command = new QPropertyUndoCommand(this, "polygon", QVariant(m_polygon)); - m_undo_command->setText(tr("Modifier un polygone")); + m_undo_command = new QPropertyUndoCommand(this, "polygon", QVariant(m_polygon)); + m_undo_command->setText(tr("Modifier un polygone")); } /** - @brief PartPolygon::handlerMouseMoveEvent - @param qghi - @param event + @brief PartPolygon::handlerMouseMoveEvent + @param qghi + @param event */ void PartPolygon::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi); + Q_UNUSED(qghi); - QPointF new_pos = event->scenePos(); - if (event->modifiers() != Qt::ControlModifier) - new_pos = elementScene()->snapToGrid(event->scenePos()); - new_pos = mapFromScene(new_pos); + QPointF new_pos = event->scenePos(); + if (event->modifiers() != Qt::ControlModifier) + new_pos = elementScene()->snapToGrid(event->scenePos()); + new_pos = mapFromScene(new_pos); - prepareGeometryChange(); - m_polygon.replace(m_vector_index, new_pos); - adjusteHandlerPos(); - emit polygonChanged(); + prepareGeometryChange(); + m_polygon.replace(m_vector_index, new_pos); + adjusteHandlerPos(); + emit polygonChanged(); } /** - @brief PartPolygon::handlerMouseReleaseEvent - @param qghi - @param event + @brief PartPolygon::handlerMouseReleaseEvent + @param qghi + @param event */ void PartPolygon::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi); - Q_UNUSED(event); + Q_UNUSED(qghi); + Q_UNUSED(event); - m_undo_command->setNewValue(QVariant(m_polygon)); - elementScene()->undoStack().push(m_undo_command); - m_undo_command = nullptr; - m_vector_index = -1; + m_undo_command->setNewValue(QVariant(m_polygon)); + elementScene()->undoStack().push(m_undo_command); + m_undo_command = nullptr; + m_vector_index = -1; } /** - @brief PartPolygon::sceneSelectionChanged - When the scene selection change, if there are several primitive selected, we remove the handler of this item + @brief PartPolygon::sceneSelectionChanged + When the scene selection change, if there are several primitive selected, we remove the handler of this item */ void PartPolygon::sceneSelectionChanged() { - if (this->isSelected() && scene()->selectedItems().size() == 1) - addHandler(); - else - removeHandler(); + if (this->isSelected() && scene()->selectedItems().size() == 1) + addHandler(); + else + removeHandler(); } /** - @brief PartPolygon::addHandler - Add handlers for this item + @brief PartPolygon::addHandler + Add handlers for this item */ void PartPolygon::addHandler() { - if (m_handler_vector.isEmpty() && scene()) - { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(m_polygon)); + if (m_handler_vector.isEmpty() && scene()) + { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(m_polygon)); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - { - handler->setColor(Qt::blue); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - handler->setZValue(this->zValue()+1); - } - } + for(QetGraphicsHandlerItem *handler : m_handler_vector) + { + handler->setColor(Qt::blue); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + handler->setZValue(this->zValue()+1); + } + } } /** - @brief PartPolygon::removeHandler - Remove the handlers of this item + @brief PartPolygon::removeHandler + Remove the handlers of this item */ void PartPolygon::removeHandler() { - if (!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } + if (!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } } /** - @brief PartPolygon::insertPoint - Insert a point in this polygone + @brief PartPolygon::insertPoint + Insert a point in this polygone */ void PartPolygon::insertPoint() { - QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(m_polygon, m_closed, elementScene()->snapToGrid(m_context_menu_pos)); + QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(m_polygon, m_closed, elementScene()->snapToGrid(m_context_menu_pos)); - if(new_polygon != m_polygon) - { - //Wrap the undo for avoid to merge the undo commands when user add several points. - QUndoCommand *undo = new QUndoCommand(tr("Ajouter un point à un polygone")); - new QPropertyUndoCommand(this, "polygon", m_polygon, new_polygon, undo); - elementScene()->undoStack().push(undo); - } + if(new_polygon != m_polygon) + { + //Wrap the undo for avoid to merge the undo commands when user add several points. + QUndoCommand *undo = new QUndoCommand(tr("Ajouter un point ?? un polygone")); + new QPropertyUndoCommand(this, "polygon", m_polygon, new_polygon, undo); + elementScene()->undoStack().push(undo); + } } /** - @brief PartPolygon::removePoint - remove a point on this polygon + @brief PartPolygon::removePoint + remove a point on this polygon */ void PartPolygon::removePoint() { - if (m_handler_vector.size() == 2) - return; + if (m_handler_vector.size() == 2) + return; - QPointF point = mapToScene(m_context_menu_pos); - int index = -1; - for (int i=0 ; icontains(qghi->mapFromScene(point))) - { - index = i; - break; - } - } - if (index > -1 && indexpolygon(); - qDebug() << index; - polygon.removeAt(index); + QPointF point = mapToScene(m_context_menu_pos); + int index = -1; + for (int i=0 ; icontains(qghi->mapFromScene(point))) + { + index = i; + break; + } + } + if (index > -1 && indexpolygon(); + qDebug() << index; + polygon.removeAt(index); - //Wrap the undo for avoid to merge the undo commands when user add several points. - QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone")); - new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo); - elementScene()->undoStack().push(undo); - } + //Wrap the undo for avoid to merge the undo commands when user add several points. + QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone")); + new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo); + elementScene()->undoStack().push(undo); + } } /** - @brief PartPolygon::shape - @return the shape of this item + @brief PartPolygon::shape + @return the shape of this item */ QPainterPath PartPolygon::shape() const { - QPainterPath shape; - shape.addPolygon(m_polygon); + QPainterPath shape; + shape.addPolygon(m_polygon); - if (m_closed) - shape.lineTo(m_polygon.first()); + if (m_closed) + shape.lineTo(m_polygon.first()); - QPainterPathStroker pps; - pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); - shape = pps.createStroke(shape); + QPainterPathStroker pps; + pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); + shape = pps.createStroke(shape); - return shape; + return shape; } QPainterPath PartPolygon::shadowShape() const { - QPainterPath shape; - shape.addPolygon(m_polygon); + QPainterPath shape; + shape.addPolygon(m_polygon); - if (m_closed) - shape.lineTo(m_polygon.first()); + if (m_closed) + shape.lineTo(m_polygon.first()); - QPainterPathStroker pps; - pps.setWidth(penWeight()); + QPainterPathStroker pps; + pps.setWidth(penWeight()); - return (pps.createStroke(shape)); + return (pps.createStroke(shape)); } /** - @brief PartPolygon::boundingRect - @return the bounding rect of this item + @brief PartPolygon::boundingRect + @return the bounding rect of this item */ QRectF PartPolygon::boundingRect() const { - QRectF r = m_polygon.boundingRect(); + QRectF r = m_polygon.boundingRect(); - qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2; - //We add 0.5 because CustomElementGraphicPart::drawShadowShape - //draw a shape bigger of 0.5 when pen weight is to 0. - if (penWeight() == 0) adjust += 0.5; + qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2; + //We add 0.5 because CustomElementGraphicPart::drawShadowShape + //draw a shape bigger of 0.5 when pen weight is to 0. + if (penWeight() == 0) adjust += 0.5; - r.adjust(-adjust, -adjust, adjust, adjust); + r.adjust(-adjust, -adjust, adjust, adjust); - return(r); + return(r); } diff --git a/sources/editor/graphicspart/partpolygon.h b/sources/editor/graphicspart/partpolygon.h index 4922dc48a..6217eaf91 100644 --- a/sources/editor/graphicspart/partpolygon.h +++ b/sources/editor/graphicspart/partpolygon.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_POLYGON_H #define PART_POLYGON_H @@ -26,93 +26,93 @@ class QetGraphicsHandlerItem; class QAction; /** - @brief The PartPolygon class - This class represents a polygon primitive which may be used to compose the - drawing of an electrical element within the element editor. + @brief The PartPolygon class + This class represents a polygon primitive which may be used to compose the + drawing of an electrical element within the element editor. */ class PartPolygon : public CustomElementGraphicPart { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool closed READ isClosed WRITE setClosed) - Q_PROPERTY(QPolygonF polygon READ polygon WRITE setPolygon) + Q_PROPERTY(bool closed READ isClosed WRITE setClosed) + Q_PROPERTY(QPolygonF polygon READ polygon WRITE setPolygon) - // constructors, destructor - public: - PartPolygon(QETElementEditor *editor, QGraphicsItem *parent = nullptr); - ~PartPolygon() override; - - private: - PartPolygon(const PartPolygon &); + // constructors, destructor + public: + PartPolygon(QETElementEditor *editor, QGraphicsItem *parent = nullptr); + ~PartPolygon() override; + + private: + PartPolygon(const PartPolygon &); - signals: - void closedChange(); - void polygonChanged(); + signals: + void closedChange(); + void polygonChanged(); - // methods - public: - enum { Type = UserType + 1105 }; - /** - * Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartPolygon. - * @return the QGraphicsItem type - */ - int type() const override { return Type; } - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override; + // methods + public: + enum { Type = UserType + 1105 }; + /** + * Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartPolygon. + * @return the QGraphicsItem type + */ + int type() const override { return Type; } + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override; - QString name() const override { return(QObject::tr("polygone", "element part name")); } - QString xmlName() const override { return(QString("polygon")); } - void fromXml(const QDomElement &) override; - const QDomElement toXml(QDomDocument &) const override; + QString name() const override { return(QObject::tr("polygone", "element part name")); } + QString xmlName() const override { return(QString("polygon")); } + void fromXml(const QDomElement &) override; + const QDomElement toXml(QDomDocument &) const override; - QPainterPath shape () const override; - QPainterPath shadowShape() const override; - QRectF boundingRect() const override; - bool isUseless() const override; - QRectF sceneGeometricRect() const override; + QPainterPath shape () const override; + QPainterPath shadowShape() const override; + QRectF boundingRect() const override; + bool isUseless() const override; + QRectF sceneGeometricRect() const override; - void startUserTransformation(const QRectF &) override; - void handleUserTransformation(const QRectF &, const QRectF &) override; - QET::ScalingMethod preferredScalingMethod() const override; + void startUserTransformation(const QRectF &) override; + void handleUserTransformation(const QRectF &, const QRectF &) override; + QET::ScalingMethod preferredScalingMethod() const override; - QPolygonF polygon () const; - void setPolygon (const QPolygonF &polygon); + QPolygonF polygon () const; + void setPolygon (const QPolygonF &polygon); - void addPoint (const QPointF &point); - void setLastPoint (const QPointF &point); - void removeLastPoint (); + void addPoint (const QPointF &point); + void setLastPoint (const QPointF &point); + void removeLastPoint (); - bool isClosed () const {return m_closed;} - void setClosed (bool close); + bool isClosed () const {return m_closed;} + void setClosed (bool close); - void setHandlerColor(QPointF pos, const QColor &color) final; - void resetAllHandlerColor() final; + void setHandlerColor(QPointF pos, const QColor &color) final; + void resetAllHandlerColor() final; - protected: - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; - void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override; - - private: - void adjusteHandlerPos(); - void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void sceneSelectionChanged (); - - void addHandler(); - void removeHandler(); - void insertPoint(); - void removePoint(); - - - bool m_closed; - QList saved_points_; - QPolygonF m_polygon; - QPropertyUndoCommand *m_undo_command; - int m_vector_index = -1; - QVector m_handler_vector; - QAction *m_insert_point, - *m_remove_point; - QPointF m_context_menu_pos; + protected: + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; + void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override; + + private: + void adjusteHandlerPos(); + void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void sceneSelectionChanged (); + + void addHandler(); + void removeHandler(); + void insertPoint(); + void removePoint(); + + + bool m_closed; + QList saved_points_; + QPolygonF m_polygon; + QPropertyUndoCommand *m_undo_command; + int m_vector_index = -1; + QVector m_handler_vector; + QAction *m_insert_point, + *m_remove_point; + QPointF m_context_menu_pos; }; #endif diff --git a/sources/editor/graphicspart/partrectangle.cpp b/sources/editor/graphicspart/partrectangle.cpp index b087829cd..938685426 100644 --- a/sources/editor/graphicspart/partrectangle.cpp +++ b/sources/editor/graphicspart/partrectangle.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partrectangle.h" #include "elementscene.h" @@ -22,541 +22,541 @@ #include "QetGraphicsItemModeler/qetgraphicshandlerutility.h" /** - @brief PartRectangle::PartRectangle - Constructor - @param editor the QETElementEditor of this item - @param parent parent item + @brief PartRectangle::PartRectangle + Constructor + @param editor the QETElementEditor of this item + @param parent parent item */ PartRectangle::PartRectangle(QETElementEditor *editor, QGraphicsItem *parent) : - CustomElementGraphicPart(editor, parent) + CustomElementGraphicPart(editor, parent) {} /** - @brief PartRectangle::~PartRectangle + @brief PartRectangle::~PartRectangle */ PartRectangle::~PartRectangle() { - removeHandler(); + removeHandler(); } /** - @brief PartRectangle::paint - Draw this Rectangle - @param painter - @param options - @param widget + @brief PartRectangle::paint + Draw this Rectangle + @param painter + @param options + @param widget */ void PartRectangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget) { - Q_UNUSED(widget); - applyStylesToQPainter(*painter); - QPen t = painter -> pen(); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - t.setCosmetic(options && options -> levelOfDetail < 1.0); + Q_UNUSED(widget); + applyStylesToQPainter(*painter); + QPen t = painter -> pen(); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + t.setCosmetic(options && options -> levelOfDetail < 1.0); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); + t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0); #endif - if (isSelected()) - t.setColor(Qt::red); + if (isSelected()) + t.setColor(Qt::red); - t.setJoinStyle(Qt::MiterJoin); + t.setJoinStyle(Qt::MiterJoin); - //Force the pen to width 0 if one of dimension is null - if (!rect().width() || !rect().height()) - t.setWidth(0); + //Force the pen to width 0 if one of dimension is null + if (!rect().width() || !rect().height()) + t.setWidth(0); - painter->setPen(t); - painter->drawRoundedRect(m_rect, m_xRadius, m_yRadius); + painter->setPen(t); + painter->drawRoundedRect(m_rect, m_xRadius, m_yRadius); - if (m_hovered) - drawShadowShape(painter); + if (m_hovered) + drawShadowShape(painter); - if (isSelected()) - drawCross(m_rect.center(), painter); + if (isSelected()) + drawCross(m_rect.center(), painter); } /** - @brief PartRectangle::toXml - Export this rectangle in xml - @param xml_document : Xml document to use for create the xml element. - @return an xml element that describe this ellipse + @brief PartRectangle::toXml + Export this rectangle in xml + @param xml_document : Xml document to use for create the xml element. + @return an xml element that describe this ellipse */ const QDomElement PartRectangle::toXml(QDomDocument &xml_document) const { - QDomElement xml_element = xml_document.createElement("rect"); - QPointF top_left(sceneTopLeft()); - xml_element.setAttribute("x", QString("%1").arg(top_left.x())); - xml_element.setAttribute("y", QString("%1").arg(top_left.y())); - xml_element.setAttribute("width", QString("%1").arg(m_rect.width())); - xml_element.setAttribute("height", QString("%1").arg(m_rect.height())); + QDomElement xml_element = xml_document.createElement("rect"); + QPointF top_left(sceneTopLeft()); + xml_element.setAttribute("x", QString("%1").arg(top_left.x())); + xml_element.setAttribute("y", QString("%1").arg(top_left.y())); + xml_element.setAttribute("width", QString("%1").arg(m_rect.width())); + xml_element.setAttribute("height", QString("%1").arg(m_rect.height())); - QRectF rect = m_rect.normalized(); - qreal x = m_xRadius; - if (x > rect.width()/2) { - x = rect.width()/2; - } - qreal y = m_yRadius; - if (y > rect.height()/2) { - y = rect.height()/2; - } + QRectF rect = m_rect.normalized(); + qreal x = m_xRadius; + if (x > rect.width()/2) { + x = rect.width()/2; + } + qreal y = m_yRadius; + if (y > rect.height()/2) { + y = rect.height()/2; + } - xml_element.setAttribute("rx", QString::number(m_xRadius)); - xml_element.setAttribute("ry", QString::number(m_yRadius)); + xml_element.setAttribute("rx", QString::number(m_xRadius)); + xml_element.setAttribute("ry", QString::number(m_yRadius)); - stylesToXml(xml_element); - return(xml_element); + stylesToXml(xml_element); + return(xml_element); } /** - @brief PartRectangle::fromXml - Import the properties of this rectangle from a xml element. - @param qde : Xml document to use. + @brief PartRectangle::fromXml + Import the properties of this rectangle from a xml element. + @param qde : Xml document to use. */ void PartRectangle::fromXml(const QDomElement &qde) { - stylesFromXml(qde); - setPos(mapFromScene(qde.attribute("x", "0").toDouble(), - qde.attribute("y", "0").toDouble())); + stylesFromXml(qde); + setPos(mapFromScene(qde.attribute("x", "0").toDouble(), + qde.attribute("y", "0").toDouble())); - QRectF rect(QPointF(0,0), QSizeF(qde.attribute("width", "0").toDouble(), - qde.attribute("height", "0").toDouble())); + QRectF rect(QPointF(0,0), QSizeF(qde.attribute("width", "0").toDouble(), + qde.attribute("height", "0").toDouble())); - setRect(rect.normalized()); - setXRadius(qde.attribute("rx", "0").toDouble()); - setYRadius(qde.attribute("ry", "0").toDouble()); + setRect(rect.normalized()); + setXRadius(qde.attribute("rx", "0").toDouble()); + setYRadius(qde.attribute("ry", "0").toDouble()); } /** - @brief PartRectangle::rect - @return : Returns the item's rectangle. + @brief PartRectangle::rect + @return : Returns the item's rectangle. */ QRectF PartRectangle::rect() const { - return m_rect; + return m_rect; } /** - @brief PartRectangle::setRect - Sets the item's rectangle to be the given rectangle. - @param rect + @brief PartRectangle::setRect + Sets the item's rectangle to be the given rectangle. + @param rect */ void PartRectangle::setRect(const QRectF &rect) { - if (rect == m_rect) return; - prepareGeometryChange(); - m_rect = rect; - adjusteHandlerPos(); - emit rectChanged(); + if (rect == m_rect) return; + prepareGeometryChange(); + m_rect = rect; + adjusteHandlerPos(); + emit rectChanged(); } void PartRectangle::setXRadius(qreal X) { - m_xRadius = X; - update(); - adjusteHandlerPos(); - emit XRadiusChanged(); + m_xRadius = X; + update(); + adjusteHandlerPos(); + emit XRadiusChanged(); } void PartRectangle::setYRadius(qreal Y) { - m_yRadius = Y; - update(); - adjusteHandlerPos(); - emit YRadiusChanged(); + m_yRadius = Y; + update(); + adjusteHandlerPos(); + emit YRadiusChanged(); } /** - @brief PartRectangle::sceneGeometricRect - @return the minimum, margin-less rectangle this part can fit into, in scene - coordinates. It is different from boundingRect() because it is not supposed - to imply any margin, and it is different from shape because it is a regular - rectangle, not a complex shape. + @brief PartRectangle::sceneGeometricRect + @return the minimum, margin-less rectangle this part can fit into, in scene + coordinates. It is different from boundingRect() because it is not supposed + to imply any margin, and it is different from shape because it is a regular + rectangle, not a complex shape. */ QRectF PartRectangle::sceneGeometricRect() const { - return(mapToScene(rect()).boundingRect()); + return(mapToScene(rect()).boundingRect()); } /** - @brief PartRectangle::sceneTopLeft - @return the top left of rectangle, in scene coordinate + @brief PartRectangle::sceneTopLeft + @return the top left of rectangle, in scene coordinate */ QPointF PartRectangle::sceneTopLeft() const { - return(mapToScene(rect().topLeft())); + return(mapToScene(rect().topLeft())); } /** - @brief PartRectangle::shape - @return the shape of this item + @brief PartRectangle::shape + @return the shape of this item */ QPainterPath PartRectangle::shape() const { - QPainterPath shape; - shape.addRoundedRect(m_rect, m_xRadius, m_yRadius); + QPainterPath shape; + shape.addRoundedRect(m_rect, m_xRadius, m_yRadius); - QPainterPathStroker pps; - pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); - shape = pps.createStroke(shape); + QPainterPathStroker pps; + pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight()); + shape = pps.createStroke(shape); - return shape; + return shape; } QPainterPath PartRectangle::shadowShape() const { - QPainterPath shape; - shape.addRoundedRect(m_rect, m_xRadius, m_yRadius); + QPainterPath shape; + shape.addRoundedRect(m_rect, m_xRadius, m_yRadius); - QPainterPathStroker pps; - pps.setWidth(penWeight()); + QPainterPathStroker pps; + pps.setWidth(penWeight()); - return (pps.createStroke(shape)); + return (pps.createStroke(shape)); } /** - @brief PartRectangle::boundingRect - @return Bounding rectangle this part can fit into + @brief PartRectangle::boundingRect + @return Bounding rectangle this part can fit into */ QRectF PartRectangle::boundingRect() const { - qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2; - //We add 0.5 because CustomElementGraphicPart::drawShadowShape - //draw a shape bigger of 0.5 when pen weight is to 0. - if (penWeight() == 0) adjust += 0.5; + qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2; + //We add 0.5 because CustomElementGraphicPart::drawShadowShape + //draw a shape bigger of 0.5 when pen weight is to 0. + if (penWeight() == 0) adjust += 0.5; - QRectF r = m_rect.normalized(); - r.adjust(-adjust, -adjust, adjust, adjust); + QRectF r = m_rect.normalized(); + r.adjust(-adjust, -adjust, adjust, adjust); - return(r); + return(r); } /** - @brief PartRectangle::isUseless - @return true if this part is irrelevant and does not deserve to be Retained / registered. - An rectangle is relevant when he's not null. + @brief PartRectangle::isUseless + @return true if this part is irrelevant and does not deserve to be Retained / registered. + An rectangle is relevant when he's not null. */ bool PartRectangle::isUseless() const { - return(rect().isNull()); + return(rect().isNull()); } /** - @brief PartRectangle::startUserTransformation - Start the user-induced transformation, provided this primitive is contained - within the initial_selection_rect bounding rectangle. - @param initial_selection_rect + @brief PartRectangle::startUserTransformation + Start the user-induced transformation, provided this primitive is contained + within the initial_selection_rect bounding rectangle. + @param initial_selection_rect */ void PartRectangle::startUserTransformation(const QRectF &initial_selection_rect) { - Q_UNUSED(initial_selection_rect) - // we keep track of our own rectangle at the moment in scene coordinates too - saved_points_.clear(); - saved_points_ << mapToScene(rect().topLeft()) << mapToScene(rect().bottomRight()); + Q_UNUSED(initial_selection_rect) + // we keep track of our own rectangle at the moment in scene coordinates too + saved_points_.clear(); + saved_points_ << mapToScene(rect().topLeft()) << mapToScene(rect().bottomRight()); } /** - @brief PartRectangle::handleUserTransformation - Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect - @param initial_selection_rect - @param new_selection_rect + @brief PartRectangle::handleUserTransformation + Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect + @param initial_selection_rect + @param new_selection_rect */ void PartRectangle::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) { - QList mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); - setRect(QRectF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1)))); + QList mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); + setRect(QRectF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1)))); } /** - @brief PartRectangle::mouseReleaseEvent - Handle mouse release event - @param event + @brief PartRectangle::mouseReleaseEvent + Handle mouse release event + @param event */ void PartRectangle::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) - switchResizeMode(); + if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) + switchResizeMode(); - CustomElementGraphicPart::mouseReleaseEvent(event); + CustomElementGraphicPart::mouseReleaseEvent(event); } /** - @brief PartRectangle::itemChange - @param change - @param value - @return + @brief PartRectangle::itemChange + @param change + @param value + @return */ QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged && scene()) - { - if (value.toBool() == true) - { - //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, - //according to the number of selected items. - connect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); + if (change == ItemSelectedHasChanged && scene()) + { + if (value.toBool() == true) + { + //When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, + //according to the number of selected items. + connect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); - if (scene()->selectedItems().size() == 1) - addHandler(); - } - else - { - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); - removeHandler(); - } - } - else if (change == ItemPositionHasChanged) - { - adjusteHandlerPos(); - } - else if (change == ItemSceneChange) - { - if(scene()) - disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); + if (scene()->selectedItems().size() == 1) + addHandler(); + } + else + { + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); + removeHandler(); + } + } + else if (change == ItemPositionHasChanged) + { + adjusteHandlerPos(); + } + else if (change == ItemSceneChange) + { + if(scene()) + disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); - setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed. - } + setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed. + } - return QGraphicsItem::itemChange(change, value); + return QGraphicsItem::itemChange(change, value); } /** - @brief PartRectangle::sceneEventFilter - @param watched - @param event - @return + @brief PartRectangle::sceneEventFilter + @param watched + @param event + @return */ bool PartRectangle::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(qghi, static_cast(event)); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(qghi, static_cast(event)); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(qghi, static_cast(event)); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(qghi, static_cast(event)); + return true; + } + } + } + } - return false; + return false; } /** - @brief PartRectangle::switchResizeMode + @brief PartRectangle::switchResizeMode */ void PartRectangle::switchResizeMode() { - if (m_resize_mode == 1) - { - m_resize_mode = 2; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::darkGreen); - } - else if (m_resize_mode == 2) - { - m_resize_mode = 3; - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::magenta); - } - } - else if (m_resize_mode == 3) - { - m_resize_mode = 1; - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::blue); - } - } + if (m_resize_mode == 1) + { + m_resize_mode = 2; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::darkGreen); + } + else if (m_resize_mode == 2) + { + m_resize_mode = 3; + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::magenta); + } + } + else if (m_resize_mode == 3) + { + m_resize_mode = 1; + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::blue); + } + } } /** - @brief PartRectangle::adjusteHandlerPos + @brief PartRectangle::adjusteHandlerPos */ void PartRectangle::adjusteHandlerPos() { - if (m_handler_vector.isEmpty()) { - return; - } + if (m_handler_vector.isEmpty()) { + return; + } - QVector points_vector; + QVector points_vector; - if(m_resize_mode != 3) { - points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); - } - else { - points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius); - } + if(m_resize_mode != 3) { + points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); + } + else { + points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius); + } - if (m_handler_vector.size() == points_vector.size()) - { - points_vector = mapToScene(points_vector); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } - else - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - } + if (m_handler_vector.size() == points_vector.size()) + { + points_vector = mapToScene(points_vector); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } + else + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + } } /** - @brief PartRectangle::handlerMousePressEvent - @param qghi - @param event + @brief PartRectangle::handlerMousePressEvent + @param qghi + @param event */ void PartRectangle::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) - Q_UNUSED(event) + Q_UNUSED(qghi) + Q_UNUSED(event) - m_old_rect = m_rect; - m_old_xRadius = m_xRadius; - m_old_yRadius = m_yRadius; - if(m_xRadius == 0 && m_yRadius == 0) { - m_modifie_radius_equaly = true; - } + m_old_rect = m_rect; + m_old_xRadius = m_xRadius; + m_old_yRadius = m_yRadius; + if(m_xRadius == 0 && m_yRadius == 0) { + m_modifie_radius_equaly = true; + } } /** - @brief PartRectangle::handlerMouseMoveEvent - @param qghi - @param event + @brief PartRectangle::handlerMouseMoveEvent + @param qghi + @param event */ void PartRectangle::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) + Q_UNUSED(qghi) - QPointF new_pos = event->scenePos(); - if (event->modifiers() != Qt::ControlModifier) - new_pos = elementScene()->snapToGrid(event->scenePos()); - new_pos = mapFromScene(new_pos); + QPointF new_pos = event->scenePos(); + if (event->modifiers() != Qt::ControlModifier) + new_pos = elementScene()->snapToGrid(event->scenePos()); + new_pos = mapFromScene(new_pos); - if (m_resize_mode == 1) - setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); - else if (m_resize_mode == 2) - setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); - else - { - qreal radius = QetGraphicsHandlerUtility::radiusForPosAtIndex(m_rect, new_pos, m_vector_index); - if(m_modifie_radius_equaly) { - setXRadius(radius); - setYRadius(radius); - } - else if(m_vector_index == 0) { - setXRadius(radius); - } - else { - setYRadius(radius); - } - } + if (m_resize_mode == 1) + setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); + else if (m_resize_mode == 2) + setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); + else + { + qreal radius = QetGraphicsHandlerUtility::radiusForPosAtIndex(m_rect, new_pos, m_vector_index); + if(m_modifie_radius_equaly) { + setXRadius(radius); + setYRadius(radius); + } + else if(m_vector_index == 0) { + setXRadius(radius); + } + else { + setYRadius(radius); + } + } - adjusteHandlerPos(); + adjusteHandlerPos(); } void PartRectangle::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(qghi) - Q_UNUSED(event) + Q_UNUSED(qghi) + Q_UNUSED(event) - m_modifie_radius_equaly = false; + m_modifie_radius_equaly = false; - QUndoCommand *undo = new QUndoCommand("Modifier un rectangle"); - if (m_old_rect != m_rect) { - QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "rect", QVariant(m_old_rect.normalized()), QVariant(m_rect.normalized()), undo); - u->setAnimated(true, false); - } - if (m_old_xRadius != m_xRadius) { - QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "xRadius", QVariant(m_old_xRadius), QVariant(m_xRadius), undo); - u->setAnimated(); - } - if (m_old_yRadius != m_yRadius) { - QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "yRadius", QVariant(m_old_yRadius), QVariant(m_yRadius), undo); - u->setAnimated(); - } + QUndoCommand *undo = new QUndoCommand("Modifier un rectangle"); + if (m_old_rect != m_rect) { + QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "rect", QVariant(m_old_rect.normalized()), QVariant(m_rect.normalized()), undo); + u->setAnimated(true, false); + } + if (m_old_xRadius != m_xRadius) { + QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "xRadius", QVariant(m_old_xRadius), QVariant(m_xRadius), undo); + u->setAnimated(); + } + if (m_old_yRadius != m_yRadius) { + QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "yRadius", QVariant(m_old_yRadius), QVariant(m_yRadius), undo); + u->setAnimated(); + } - elementScene()->undoStack().push(undo); - m_vector_index = -1; + elementScene()->undoStack().push(undo); + m_vector_index = -1; } /** - @brief PartRectangle::sceneSelectionChanged - When the scene selection change, if there are several primitive selected, we remove the handler of this item + @brief PartRectangle::sceneSelectionChanged + When the scene selection change, if there are several primitive selected, we remove the handler of this item */ void PartRectangle::sceneSelectionChanged() { - if (this->isSelected() && scene()->selectedItems().size() == 1) - addHandler(); - else - removeHandler(); + if (this->isSelected() && scene()->selectedItems().size() == 1) + addHandler(); + else + removeHandler(); } /** - @brief PartRectangle::addHandler - Add handlers for this item + @brief PartRectangle::addHandler + Add handlers for this item */ void PartRectangle::addHandler() { - if (m_handler_vector.isEmpty() && scene()) - { - if (m_resize_mode != 3) { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); - } - else { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius))); - } + if (m_handler_vector.isEmpty() && scene()) + { + if (m_resize_mode != 3) { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); + } + else { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius))); + } - for (QetGraphicsHandlerItem *handler : m_handler_vector) - { - QColor color; - if(m_resize_mode == 1) {color = Qt::blue;} - else if (m_resize_mode == 2) {color = Qt::darkGreen;} - else {color = Qt::magenta;} + for (QetGraphicsHandlerItem *handler : m_handler_vector) + { + QColor color; + if(m_resize_mode == 1) {color = Qt::blue;} + else if (m_resize_mode == 2) {color = Qt::darkGreen;} + else {color = Qt::magenta;} - handler->setColor(color); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - handler->setZValue(this->zValue()+1); - } - } + handler->setColor(color); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + handler->setZValue(this->zValue()+1); + } + } } /** - @brief PartRectangle::removeHandler - Remove the handlers of this item + @brief PartRectangle::removeHandler + Remove the handlers of this item */ void PartRectangle::removeHandler() { - if (!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } + if (!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } } diff --git a/sources/editor/graphicspart/partrectangle.h b/sources/editor/graphicspart/partrectangle.h index 4c001fae6..5fbdcbb3e 100644 --- a/sources/editor/graphicspart/partrectangle.h +++ b/sources/editor/graphicspart/partrectangle.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_RECTANGLE_H #define PART_RECTANGLE_H @@ -23,91 +23,91 @@ class QetGraphicsHandlerItem; /** - This class represents a rectangle primitive which may be used to compose the - drawing of an electrical element within the element editor. - All coordinates is in item coordinate, except pos() + This class represents a rectangle primitive which may be used to compose the + drawing of an electrical element within the element editor. + All coordinates is in item coordinate, except pos() */ class PartRectangle : public CustomElementGraphicPart { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QRectF rect READ rect WRITE setRect) - Q_PROPERTY(qreal xRadius READ XRadius WRITE setXRadius NOTIFY XRadiusChanged) - Q_PROPERTY(qreal yRadius READ YRadius WRITE setYRadius NOTIFY YRadiusChanged) + Q_PROPERTY(QRectF rect READ rect WRITE setRect) + Q_PROPERTY(qreal xRadius READ XRadius WRITE setXRadius NOTIFY XRadiusChanged) + Q_PROPERTY(qreal yRadius READ YRadius WRITE setYRadius NOTIFY YRadiusChanged) - // constructors, destructor - public: - PartRectangle(QETElementEditor *, QGraphicsItem *parent = nullptr); - ~PartRectangle() override; - - private: - PartRectangle(const PartRectangle &); + // constructors, destructor + public: + PartRectangle(QETElementEditor *, QGraphicsItem *parent = nullptr); + ~PartRectangle() override; + + private: + PartRectangle(const PartRectangle &); - signals: - void rectChanged(); - void XRadiusChanged(); - void YRadiusChanged(); - - // methods - public: - enum { Type = UserType + 1109 }; - /** - Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartRectangle. - @return the QGraphicsItem type - */ - int type () const override { return Type; } - void paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; - QString name () const override { return(QObject::tr("rectangle", "element part name")); } + signals: + void rectChanged(); + void XRadiusChanged(); + void YRadiusChanged(); + + // methods + public: + enum { Type = UserType + 1109 }; + /** + Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartRectangle. + @return the QGraphicsItem type + */ + int type () const override { return Type; } + void paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; + QString name () const override { return(QObject::tr("rectangle", "element part name")); } - QString xmlName () const override { return(QString("rect")); } - const QDomElement toXml (QDomDocument &) const override; - void fromXml (const QDomElement &) override; + QString xmlName () const override { return(QString("rect")); } + const QDomElement toXml (QDomDocument &) const override; + void fromXml (const QDomElement &) override; - QRectF rect() const; - void setRect(const QRectF &rect); - qreal XRadius() const {return m_xRadius;} - void setXRadius(qreal X); - qreal YRadius() const {return m_yRadius;} - void setYRadius(qreal Y); + QRectF rect() const; + void setRect(const QRectF &rect); + qreal XRadius() const {return m_xRadius;} + void setXRadius(qreal X); + qreal YRadius() const {return m_yRadius;} + void setYRadius(qreal Y); - QRectF sceneGeometricRect() const override; - virtual QPointF sceneTopLeft() const; + QRectF sceneGeometricRect() const override; + virtual QPointF sceneTopLeft() const; - QPainterPath shape () const override; - QPainterPath shadowShape() const override; - QRectF boundingRect() const override; - bool isUseless() const override; + QPainterPath shape () const override; + QPainterPath shadowShape() const override; + QRectF boundingRect() const override; + bool isUseless() const override; - void startUserTransformation(const QRectF &) override; - void handleUserTransformation(const QRectF &, const QRectF &) override; + void startUserTransformation(const QRectF &) override; + void handleUserTransformation(const QRectF &, const QRectF &) override; - protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; + protected: + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; - private: - void switchResizeMode(); - void adjusteHandlerPos(); - void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); - void sceneSelectionChanged (); - - void addHandler(); - void removeHandler(); - - private: - QRectF m_rect, - m_old_rect; - QList saved_points_; - int m_resize_mode = 1, - m_vector_index = -1; - QVector m_handler_vector; - qreal m_xRadius = 0, - m_yRadius = 0, - m_old_xRadius, - m_old_yRadius; - bool m_modifie_radius_equaly = false; + private: + void switchResizeMode(); + void adjusteHandlerPos(); + void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event); + void sceneSelectionChanged (); + + void addHandler(); + void removeHandler(); + + private: + QRectF m_rect, + m_old_rect; + QList saved_points_; + int m_resize_mode = 1, + m_vector_index = -1; + QVector m_handler_vector; + qreal m_xRadius = 0, + m_yRadius = 0, + m_old_xRadius, + m_old_yRadius; + bool m_modifie_radius_equaly = false; }; #endif diff --git a/sources/editor/graphicspart/partterminal.cpp b/sources/editor/graphicspart/partterminal.cpp index 9fe3728a5..71dc90120 100644 --- a/sources/editor/graphicspart/partterminal.cpp +++ b/sources/editor/graphicspart/partterminal.cpp @@ -1,38 +1,38 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "partterminal.h" #include "terminal.h" /** - @brief PartTerminal::PartTerminal - @param editor : - L'editeur d'element concerne - @param parent : - Le QGraphicsItem parent de cette borne + @brief PartTerminal::PartTerminal + @param editor : + L'editeur d'element concerne + @param parent : + Le QGraphicsItem parent de cette borne */ PartTerminal::PartTerminal(QETElementEditor *editor, QGraphicsItem *parent) : - CustomElementGraphicPart(editor, parent) + CustomElementGraphicPart(editor, parent) { - d = new TerminalData(this); - d -> m_orientation = Qet::North; - d -> m_uuid = QUuid::createUuid(); // if part is loaded this uuid will be overwritten, but being sure that terminal has a uuid - updateSecondPoint(); - setZValue(100000); + d = new TerminalData(this); + d -> m_orientation = Qet::North; + d -> m_uuid = QUuid::createUuid(); // if part is loaded this uuid will be overwritten, but being sure that terminal has a uuid + updateSecondPoint(); + setZValue(100000); } /// Destructeur @@ -41,181 +41,181 @@ PartTerminal::~PartTerminal() } /** - Importe les proprietes d'une borne depuis un element XML - @param xml_elmt Element XML a lire + Importe les proprietes d'une borne depuis un element XML + @param xml_elmt Element XML a lire */ void PartTerminal::fromXml(const QDomElement &xml_elmt) { - d -> fromXml(xml_elmt); - setPos(d -> m_pos); - updateSecondPoint(); + d -> fromXml(xml_elmt); + setPos(d -> m_pos); + updateSecondPoint(); } /** - Exporte la borne en XML - @param xml_document Document XML a utiliser pour creer l'element XML - @return un element XML decrivant la borne + Exporte la borne en XML + @param xml_document Document XML a utiliser pour creer l'element XML + @return un element XML decrivant la borne */ const QDomElement PartTerminal::toXml(QDomDocument &xml_document) const { - return d -> toXml(xml_document); + return d -> toXml(xml_document); } /** - Dessine la borne - @param painter QPainter a utiliser pour rendre le dessin - @param options Options pour affiner le rendu - @param widget Widget sur lequel le rendu est effectue + Dessine la borne + @param painter QPainter a utiliser pour rendre le dessin + @param options Options pour affiner le rendu + @param widget Widget sur lequel le rendu est effectue */ void PartTerminal::paint( - QPainter *painter, - const QStyleOptionGraphicsItem *options, - QWidget *widget) + QPainter *painter, + const QStyleOptionGraphicsItem *options, + QWidget *widget) { - Q_UNUSED(widget); - painter -> save(); + Q_UNUSED(widget); + painter -> save(); - // annulation des renderhints - painter -> setRenderHint(QPainter::Antialiasing, false); - painter -> setRenderHint(QPainter::TextAntialiasing, false); - painter -> setRenderHint(QPainter::SmoothPixmapTransform, false); + // annulation des renderhints + painter -> setRenderHint(QPainter::Antialiasing, false); + painter -> setRenderHint(QPainter::TextAntialiasing, false); + painter -> setRenderHint(QPainter::SmoothPixmapTransform, false); - QPen t; - t.setWidthF(1.0); + QPen t; + t.setWidthF(1.0); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - t.setCosmetic(options && options -> levelOfDetail < 1.0); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + t.setCosmetic(options && options -> levelOfDetail < 1.0); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - t.setCosmetic( - options - && options->levelOfDetailFromTransform( - painter->worldTransform()) - < 1.0); + t.setCosmetic( + options + && options->levelOfDetailFromTransform( + painter->worldTransform()) + < 1.0); #endif - // dessin de la borne en rouge - t.setColor(isSelected() ? Terminal::neutralColor : Qt::red); - painter -> setPen(t); - painter -> drawLine(QPointF(0.0, 0.0), d -> second_point); + // dessin de la borne en rouge + t.setColor(isSelected() ? Terminal::neutralColor : Qt::red); + painter -> setPen(t); + painter -> drawLine(QPointF(0.0, 0.0), d -> second_point); - // dessin du point d'amarrage au conducteur en bleu - t.setColor(isSelected() ? Qt::red : Terminal::neutralColor); - painter -> setPen(t); - painter -> setBrush(Terminal::neutralColor); - painter -> drawPoint(QPointF(0.0, 0.0)); - painter -> restore(); + // dessin du point d'amarrage au conducteur en bleu + t.setColor(isSelected() ? Qt::red : Terminal::neutralColor); + painter -> setPen(t); + painter -> setBrush(Terminal::neutralColor); + painter -> drawPoint(QPointF(0.0, 0.0)); + painter -> restore(); - if (m_hovered) - drawShadowShape(painter); + if (m_hovered) + drawShadowShape(painter); } /** - @brief PartTerminal::shape - @return the shape of this item + @brief PartTerminal::shape + @return the shape of this item */ QPainterPath PartTerminal::shape() const { - QPainterPath shape; - shape.lineTo(d -> second_point); + QPainterPath shape; + shape.lineTo(d -> second_point); - QPainterPathStroker pps; - pps.setWidth(1); + QPainterPathStroker pps; + pps.setWidth(1); - return (pps.createStroke(shape)); + return (pps.createStroke(shape)); } /** - @brief PartTerminal::boundingRect - @return the bounding rect of this item + @brief PartTerminal::boundingRect + @return the bounding rect of this item */ QRectF PartTerminal::boundingRect() const { - QRectF br(QPointF(0, 0), d -> second_point); - br = br.normalized(); + QRectF br(QPointF(0, 0), d -> second_point); + br = br.normalized(); - qreal adjust = (SHADOWS_HEIGHT + 1) / 2; - br.adjust(-adjust, -adjust, adjust, adjust); - return(br); + qreal adjust = (SHADOWS_HEIGHT + 1) / 2; + br.adjust(-adjust, -adjust, adjust, adjust); + return(br); } /** - Definit l'orientation de la borne - @param ori la nouvelle orientation de la borne + Definit l'orientation de la borne + @param ori la nouvelle orientation de la borne */ void PartTerminal::setOrientation(Qet::Orientation ori) { - if (d -> m_orientation == ori) return; - prepareGeometryChange(); - d -> m_orientation = ori; - updateSecondPoint(); - emit orientationChanged(); + if (d -> m_orientation == ori) return; + prepareGeometryChange(); + d -> m_orientation = ori; + updateSecondPoint(); + emit orientationChanged(); } /** - @brief PartTerminal::setName - @param name + @brief PartTerminal::setName + @param name */ void PartTerminal::setName(QString& name) { - if (d -> m_name == name) return; - d -> m_name = name; - emit nameChanged(); + if (d -> m_name == name) return; + d -> m_name = name; + emit nameChanged(); } void PartTerminal::setNewUuid() { - d -> m_uuid = QUuid::createUuid(); + d -> m_uuid = QUuid::createUuid(); } /** - Met a jour la position du second point en fonction de la position et de - l'orientation de la borne. + Met a jour la position du second point en fonction de la position et de + l'orientation de la borne. */ void PartTerminal::updateSecondPoint() { - qreal ts = 4.0; // terminal size - switch(d -> m_orientation) { - case Qet::North: d -> second_point = QPointF(0.0, ts); break; - case Qet::East : d -> second_point = QPointF(-ts, 0.0); break; - case Qet::South: d -> second_point = QPointF(0.0, -ts); break; - case Qet::West : d -> second_point = QPointF(ts, 0.0); break; - } + qreal ts = 4.0; // terminal size + switch(d -> m_orientation) { + case Qet::North: d -> second_point = QPointF(0.0, ts); break; + case Qet::East : d -> second_point = QPointF(-ts, 0.0); break; + case Qet::South: d -> second_point = QPointF(0.0, -ts); break; + case Qet::West : d -> second_point = QPointF(ts, 0.0); break; + } } /** - @return true si cette partie n'est pas pertinente et ne merite pas d'etre - conservee / enregistree. - Une borne est toujours pertinente ; cette fonction renvoie donc - toujours false + @return true si cette partie n'est pas pertinente et ne merite pas d'etre + conservee / enregistree. + Une borne est toujours pertinente ; cette fonction renvoie donc + toujours false */ bool PartTerminal::isUseless() const { - return(false); + return(false); } /** - @return the minimum, margin-less rectangle this part can fit into, in scene - coordinates. It is different from boundingRect() because it is not supposed - to imply any margin, and it is different from shape because it is a regular - rectangle, not a complex shape. + @return the minimum, margin-less rectangle this part can fit into, in scene + coordinates. It is different from boundingRect() because it is not supposed + to imply any margin, and it is different from shape because it is a regular + rectangle, not a complex shape. */ QRectF PartTerminal::sceneGeometricRect() const { - return(sceneBoundingRect()); + return(sceneBoundingRect()); } /** - Start the user-induced transformation, provided this primitive is contained - within the \a initial_selection_rect bounding rectangle. + Start the user-induced transformation, provided this primitive is contained + within the \a initial_selection_rect bounding rectangle. */ void PartTerminal::startUserTransformation(const QRectF &initial_selection_rect) { - Q_UNUSED(initial_selection_rect) - saved_position_ = scenePos(); + Q_UNUSED(initial_selection_rect) + saved_position_ = scenePos(); } /** - Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect + Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect */ void PartTerminal::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) { - QPointF mapped_point = mapPoints( - initial_selection_rect, new_selection_rect, QList() << saved_position_).first(); - setPos(mapped_point); + QPointF mapped_point = mapPoints( + initial_selection_rect, new_selection_rect, QList() << saved_position_).first(); + setPos(mapped_point); } diff --git a/sources/editor/graphicspart/partterminal.h b/sources/editor/graphicspart/partterminal.h index 0f323acff..a99f30536 100644 --- a/sources/editor/graphicspart/partterminal.h +++ b/sources/editor/graphicspart/partterminal.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_TERMINAL_H #define PART_TERMINAL_H @@ -24,61 +24,61 @@ /** - This class represents a terminal which may be used to compose the drawing of - an electrical element within the element editor. + This class represents a terminal which may be used to compose the drawing of + an electrical element within the element editor. */ class PartTerminal : public CustomElementGraphicPart { - Q_OBJECT - Q_PROPERTY(Qet::Orientation orientation READ orientation WRITE setOrientation) - Q_PROPERTY(QString name READ name WRITE setName) + Q_OBJECT + Q_PROPERTY(Qet::Orientation orientation READ orientation WRITE setOrientation) + Q_PROPERTY(QString name READ name WRITE setName) - public: - // constructors, destructor - PartTerminal(QETElementEditor *editor, QGraphicsItem *parent = nullptr); - ~PartTerminal() override; - private: - PartTerminal(const PartTerminal &); + public: + // constructors, destructor + PartTerminal(QETElementEditor *editor, QGraphicsItem *parent = nullptr); + ~PartTerminal() override; + private: + PartTerminal(const PartTerminal &); - signals: - void orientationChanged(); - void nameChanged(); + signals: + void orientationChanged(); + void nameChanged(); - // methods - public: - enum { Type = UserType + 1106 }; - /** - Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartTerminal. - @return the QGraphicsItem type - */ - int type() const override { return Type; } - QString name() const override { return d -> m_name; } - QString xmlName() const override { return(QString("terminal")); } - void fromXml(const QDomElement &) override; - const QDomElement toXml(QDomDocument &) const override; - void paint( - QPainter *painter, - const QStyleOptionGraphicsItem *, - QWidget *) override; + // methods + public: + enum { Type = UserType + 1106 }; + /** + Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartTerminal. + @return the QGraphicsItem type + */ + int type() const override { return Type; } + QString name() const override { return d -> m_name; } + QString xmlName() const override { return(QString("terminal")); } + void fromXml(const QDomElement &) override; + const QDomElement toXml(QDomDocument &) const override; + void paint( + QPainter *painter, + const QStyleOptionGraphicsItem *, + QWidget *) override; - QPainterPath shape() const override; - QPainterPath shadowShape() const override {return shape();} - QRectF boundingRect() const override; - bool isUseless() const override; - QRectF sceneGeometricRect() const override; - void startUserTransformation(const QRectF &) override; - void handleUserTransformation(const QRectF &, const QRectF &) override; + QPainterPath shape() const override; + QPainterPath shadowShape() const override {return shape();} + QRectF boundingRect() const override; + bool isUseless() const override; + QRectF sceneGeometricRect() const override; + void startUserTransformation(const QRectF &) override; + void handleUserTransformation(const QRectF &, const QRectF &) override; - Qet::Orientation orientation() const {return d -> m_orientation;} - void setOrientation(Qet::Orientation ori); + Qet::Orientation orientation() const {return d -> m_orientation;} + void setOrientation(Qet::Orientation ori); - void setName(QString& name); - void setNewUuid(); + void setName(QString& name); + void setNewUuid(); - private: - void updateSecondPoint(); - TerminalData* d; // pointer to the terminal data + private: + void updateSecondPoint(); + TerminalData* d; // pointer to the terminal data - private: - QPointF saved_position_; + private: + QPointF saved_position_; }; #endif diff --git a/sources/editor/graphicspart/parttext.cpp b/sources/editor/graphicspart/parttext.cpp index 497d66b31..c255c9014 100644 --- a/sources/editor/graphicspart/parttext.cpp +++ b/sources/editor/graphicspart/parttext.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "parttext.h" #include "texteditor.h" @@ -23,38 +23,38 @@ #include "QPropertyUndoCommand/qpropertyundocommand.h" /** - Constructeur - @param editor L'editeur d'element concerne - @param parent Le QGraphicsItem parent de ce texte statique + Constructeur + @param editor L'editeur d'element concerne + @param parent Le QGraphicsItem parent de ce texte statique */ PartText::PartText(QETElementEditor *editor, QGraphicsItem *parent) : - QGraphicsTextItem(parent), - CustomElementPart(editor), - previous_text() + QGraphicsTextItem(parent), + CustomElementPart(editor), + previous_text() { - document() -> setDocumentMargin(1.0); - setDefaultTextColor(Qt::black); - setFont(QETApp::diagramTextsFont()); - real_font_size_ = font().pointSize(); - setFlags(QGraphicsItem::ItemIsSelectable - | QGraphicsItem::ItemSendsGeometryChanges - | QGraphicsItem::ItemIsMovable); - setAcceptHoverEvents(true); - setDefaultTextColor(Qt::black); - setPlainText(QObject::tr( - "T", - "default text when adding a text in the element editor")); + document() -> setDocumentMargin(1.0); + setDefaultTextColor(Qt::black); + setFont(QETApp::diagramTextsFont()); + real_font_size_ = font().pointSize(); + setFlags(QGraphicsItem::ItemIsSelectable + | QGraphicsItem::ItemSendsGeometryChanges + | QGraphicsItem::ItemIsMovable); + setAcceptHoverEvents(true); + setDefaultTextColor(Qt::black); + setPlainText(QObject::tr( + "T", + "default text when adding a text in the element editor")); - adjustItemPosition(1); - // adjust textfield position after line additions/deletions - connect(document(), - SIGNAL(blockCountChanged(int)), - this, - SLOT(adjustItemPosition(int))); - connect(document(), - SIGNAL(contentsChanged()), - this, - SLOT(adjustItemPosition())); + adjustItemPosition(1); + // adjust textfield position after line additions/deletions + connect(document(), + SIGNAL(blockCountChanged(int)), + this, + SLOT(adjustItemPosition(int))); + connect(document(), + SIGNAL(contentsChanged()), + this, + SLOT(adjustItemPosition())); } /// Destructeur @@ -63,303 +63,303 @@ PartText::~PartText() } /** - Importe les proprietes d'un texte statique depuis un element XML - @param xml_element Element XML a lire + Importe les proprietes d'un texte statique depuis un element XML + @param xml_element Element XML a lire */ void PartText::fromXml(const QDomElement &xml_element) { - bool ok; + bool ok; - if (xml_element.hasAttribute("size")) { - int font_size = xml_element.attribute("size").toInt(&ok); - if (!ok || font_size < 1) { - font_size = 20; - } - QFont font_ = this -> font(); - font_.setPointSize(font_size); - setFont(font_); - } - else if (xml_element.hasAttribute("font")) { - QFont font_; - font_.fromString(xml_element.attribute("font")); - setFont(font_); - } + if (xml_element.hasAttribute("size")) { + int font_size = xml_element.attribute("size").toInt(&ok); + if (!ok || font_size < 1) { + font_size = 20; + } + QFont font_ = this -> font(); + font_.setPointSize(font_size); + setFont(font_); + } + else if (xml_element.hasAttribute("font")) { + QFont font_; + font_.fromString(xml_element.attribute("font")); + setFont(font_); + } - setDefaultTextColor(QColor(xml_element.attribute("color", "#000000"))); - setPlainText(xml_element.attribute("text")); - setPos(xml_element.attribute("x").toDouble(), - xml_element.attribute("y").toDouble()); - setRotation(xml_element.attribute("rotation", QString::number(0)).toDouble()); + setDefaultTextColor(QColor(xml_element.attribute("color", "#000000"))); + setPlainText(xml_element.attribute("text")); + setPos(xml_element.attribute("x").toDouble(), + xml_element.attribute("y").toDouble()); + setRotation(xml_element.attribute("rotation", QString::number(0)).toDouble()); } /** - Exporte le texte statique en XML - @param xml_document Document XML a utiliser pour creer l'element XML - @return un element XML decrivant le texte statique + Exporte le texte statique en XML + @param xml_document Document XML a utiliser pour creer l'element XML + @return un element XML decrivant le texte statique */ const QDomElement PartText::toXml(QDomDocument &xml_document) const { - QDomElement xml_element = xml_document.createElement(xmlName()); + QDomElement xml_element = xml_document.createElement(xmlName()); - xml_element.setAttribute("x", QString::number(pos().x())); - xml_element.setAttribute("y", QString::number(pos().y())); - xml_element.setAttribute("text", toPlainText()); - xml_element.setAttribute("font", font().toString()); - xml_element.setAttribute("rotation", QString::number(rotation())); - xml_element.setAttribute("color", defaultTextColor().name()); + xml_element.setAttribute("x", QString::number(pos().x())); + xml_element.setAttribute("y", QString::number(pos().y())); + xml_element.setAttribute("text", toPlainText()); + xml_element.setAttribute("font", font().toString()); + xml_element.setAttribute("rotation", QString::number(rotation())); + xml_element.setAttribute("color", defaultTextColor().name()); - return(xml_element); + return(xml_element); } /** - @return Les coordonnees du point situe en bas a gauche du texte. + @return Les coordonnees du point situe en bas a gauche du texte. */ QPointF PartText::margin() const { - QFont used_font = font(); - QFontMetrics qfm(used_font); - qreal document_margin = document() -> documentMargin(); + QFont used_font = font(); + QFontMetrics qfm(used_font); + qreal document_margin = document() -> documentMargin(); - QPointF margin( - // marge autour du texte - document_margin, - // marge au-dessus du texte + distance entre le plafond du texte et la baseline - document_margin + qfm.ascent() - ); - return(margin); + QPointF margin( + // marge autour du texte + document_margin, + // marge au-dessus du texte + distance entre le plafond du texte et la baseline + document_margin + qfm.ascent() + ); + return(margin); } /** - @brief PartText::focusInEvent - @param e : The QFocusEvent object describing the focus gain. - Start text edition when the item gains focus. - @see QGraphicsItem::focusInEvent(QFocusEvent *) + @brief PartText::focusInEvent + @param e : The QFocusEvent object describing the focus gain. + Start text edition when the item gains focus. + @see QGraphicsItem::focusInEvent(QFocusEvent *) */ void PartText::focusInEvent(QFocusEvent *e) { - startEdition(); - QGraphicsTextItem::focusInEvent(e); + startEdition(); + QGraphicsTextItem::focusInEvent(e); } /** - @brief PartText::focusOutEvent - @param e : The QFocusEvent object describing the focus loss. - End text edition when the item loses focus. - @see QGraphicsItem::focusOutEvent(QFocusEvent *) + @brief PartText::focusOutEvent + @param e : The QFocusEvent object describing the focus loss. + End text edition when the item loses focus. + @see QGraphicsItem::focusOutEvent(QFocusEvent *) */ void PartText::focusOutEvent(QFocusEvent *e) { - QGraphicsTextItem::focusOutEvent(e); - endEdition(); + QGraphicsTextItem::focusOutEvent(e); + endEdition(); } /** - @brief PartText::keyPressEvent - Used to handle the escape key when the event is delivered to the field, - not to the decorator. - @param event - @see QGraphicsTextItem::keyPressEvent() + @brief PartText::keyPressEvent + Used to handle the escape key when the event is delivered to the field, + not to the decorator. + @param event + @see QGraphicsTextItem::keyPressEvent() */ void PartText::keyPressEvent(QKeyEvent *event) { - if (event -> key() == Qt::Key_Escape) { - endEdition(); - } - else { - QGraphicsTextItem::keyPressEvent(event); - } + if (event -> key() == Qt::Key_Escape) { + endEdition(); + } + else { + QGraphicsTextItem::keyPressEvent(event); + } } /** - Permet a l'element texte de devenir editable lorsqu'on double-clique dessus - @param e Le QGraphicsSceneMouseEvent qui decrit le double-clic + Permet a l'element texte de devenir editable lorsqu'on double-clique dessus + @param e Le QGraphicsSceneMouseEvent qui decrit le double-clic */ void PartText::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e) { - QGraphicsTextItem::mouseDoubleClickEvent(e); - if (e -> button() == Qt::LeftButton) { - setEditable(true); - } + QGraphicsTextItem::mouseDoubleClickEvent(e); + if (e -> button() == Qt::LeftButton) { + setEditable(true); + } } /** - Gere les changements intervenant sur cette partie - @param change Type de changement - @param value Valeur numerique relative au changement + Gere les changements intervenant sur cette partie + @param change Type de changement + @param value Valeur numerique relative au changement */ QVariant PartText::itemChange(GraphicsItemChange change, const QVariant &value) { - if (change == QGraphicsItem::ItemPositionHasChanged || - change == QGraphicsItem::ItemSceneHasChanged || - change == QGraphicsItem::ItemSelectedHasChanged) { - updateCurrentPartEditor(); - } - return(QGraphicsTextItem::itemChange(change, value)); + if (change == QGraphicsItem::ItemPositionHasChanged || + change == QGraphicsItem::ItemSceneHasChanged || + change == QGraphicsItem::ItemSelectedHasChanged) { + updateCurrentPartEditor(); + } + return(QGraphicsTextItem::itemChange(change, value)); } /** - @return le rectangle delimitant cette partie. + @return le rectangle delimitant cette partie. */ QRectF PartText::boundingRect() const { - QRectF r = QGraphicsTextItem::boundingRect(); - r.adjust(0.0, -1.1, 0.0, 0.0); - return(r); + QRectF r = QGraphicsTextItem::boundingRect(); + r.adjust(0.0, -1.1, 0.0, 0.0); + return(r); } /** - @return true si cette partie n'est pas pertinente et ne merite pas d'etre - conservee / enregistree. - Un texte statique n'est pas pertinent lorsque son texte est vide. + @return true si cette partie n'est pas pertinente et ne merite pas d'etre + conservee / enregistree. + Un texte statique n'est pas pertinent lorsque son texte est vide. */ bool PartText::isUseless() const { - return(toPlainText().isEmpty()); + return(toPlainText().isEmpty()); } /** - @return the minimum, margin-less rectangle this part can fit into, in scene - coordinates. It is different from boundingRect() because it is not supposed - to imply any margin, and it is different from shape because it is a regular - rectangle, not a complex shape. + @return the minimum, margin-less rectangle this part can fit into, in scene + coordinates. It is different from boundingRect() because it is not supposed + to imply any margin, and it is different from shape because it is a regular + rectangle, not a complex shape. */ QRectF PartText::sceneGeometricRect() const { - return(sceneBoundingRect()); + return(sceneBoundingRect()); } /** - Start the user-induced transformation, provided this primitive is contained - within the \a rect bounding rectangle. + Start the user-induced transformation, provided this primitive is contained + within the \a rect bounding rectangle. */ void PartText::startUserTransformation(const QRectF &rect) { - Q_UNUSED(rect) - saved_point_ = pos(); // scene coordinates, no need to mapFromScene() - saved_font_size_ = real_font_size_; + Q_UNUSED(rect) + saved_point_ = pos(); // scene coordinates, no need to mapFromScene() + saved_font_size_ = real_font_size_; } /** - Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect + Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect */ void PartText::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) { - // let's try the naive approach - QPointF new_pos = mapPoints(initial_selection_rect, new_selection_rect, QList() << saved_point_).first(); - setPos(new_pos); + // let's try the naive approach + QPointF new_pos = mapPoints(initial_selection_rect, new_selection_rect, QList() << saved_point_).first(); + setPos(new_pos); - // adjust the font size following the vertical scale factor - qreal sy = new_selection_rect.height() / initial_selection_rect.height(); - qreal new_font_size = saved_font_size_ * sy; - setProperty("real_size", qMax(1, qRound(new_font_size))); + // adjust the font size following the vertical scale factor + qreal sy = new_selection_rect.height() / initial_selection_rect.height(); + qreal new_font_size = saved_font_size_ * sy; + setProperty("real_size", qMax(1, qRound(new_font_size))); } void PartText::setDefaultTextColor(const QColor &color) { - if (color != this -> defaultTextColor()) { - QGraphicsTextItem::setDefaultTextColor(color); - emit colorChanged(color); - } + if (color != this -> defaultTextColor()) { + QGraphicsTextItem::setDefaultTextColor(color); + emit colorChanged(color); + } } void PartText::setPlainText(const QString &text) { - if (text != this -> toPlainText()) { - QGraphicsTextItem::setPlainText(text); - emit plainTextChanged(text); - } + if (text != this -> toPlainText()) { + QGraphicsTextItem::setPlainText(text); + emit plainTextChanged(text); + } } void PartText::setFont(const QFont &font) { - if (font != this -> font()) { - QGraphicsTextItem::setFont(font); - emit fontChanged(font); - } + if (font != this -> font()) { + QGraphicsTextItem::setFont(font); + emit fontChanged(font); + } } void PartText::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if((event -> buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) { - QPointF pos = event -> scenePos() + (m_origine_pos - event -> buttonDownScenePos(Qt::LeftButton)); - event -> modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene() -> snapToGrid(pos)); - } - else { - QGraphicsObject::mouseMoveEvent(event); - } + if((event -> buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) { + QPointF pos = event -> scenePos() + (m_origine_pos - event -> buttonDownScenePos(Qt::LeftButton)); + event -> modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene() -> snapToGrid(pos)); + } + else { + QGraphicsObject::mouseMoveEvent(event); + } } void PartText::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if(event -> button() == Qt::LeftButton) - m_origine_pos = this -> pos(); + if(event -> button() == Qt::LeftButton) + m_origine_pos = this -> pos(); - QGraphicsObject::mousePressEvent(event); + QGraphicsObject::mousePressEvent(event); } void PartText::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if((event -> button() & Qt::LeftButton) && - (flags() & QGraphicsItem::ItemIsMovable) && - m_origine_pos != pos()) - { - QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "pos", QVariant(m_origine_pos), QVariant(pos())); - undo -> setText(tr("Déplacer un texte")); - undo -> enableAnimation(); - elementScene() -> undoStack().push(undo); - } + if((event -> button() & Qt::LeftButton) && + (flags() & QGraphicsItem::ItemIsMovable) && + m_origine_pos != pos()) + { + QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "pos", QVariant(m_origine_pos), QVariant(pos())); + undo -> setText(tr("Déplacer un texte")); + undo -> enableAnimation(); + elementScene() -> undoStack().push(undo); + } - QGraphicsObject::mouseReleaseEvent(event); + QGraphicsObject::mouseReleaseEvent(event); } /** - Cette methode s'assure que la position du champ de texte est coherente - en repositionnant son origine (c-a-d le milieu du bord gauche du champ de - texte) a la position originale. Cela est notamment utile lorsque le champ - de texte est agrandi ou retreci verticalement (ajout ou retrait de lignes). - @param new_block_count Nombre de blocs dans le PartText + Cette methode s'assure que la position du champ de texte est coherente + en repositionnant son origine (c-a-d le milieu du bord gauche du champ de + texte) a la position originale. Cela est notamment utile lorsque le champ + de texte est agrandi ou retreci verticalement (ajout ou retrait de lignes). + @param new_block_count Nombre de blocs dans le PartText */ void PartText::adjustItemPosition(int new_block_count) { - Q_UNUSED(new_block_count); - QPointF origin_offset = margin(); + Q_UNUSED(new_block_count); + QPointF origin_offset = margin(); - QTransform base_translation; - base_translation.translate(-origin_offset.x(), -origin_offset.y()); - setTransform(base_translation, false); - setTransformOriginPoint(origin_offset); + QTransform base_translation; + base_translation.translate(-origin_offset.x(), -origin_offset.y()); + setTransform(base_translation, false); + setTransformOriginPoint(origin_offset); } /** - @param editable Whether this text item should be interactively editable. + @param editable Whether this text item should be interactively editable. */ void PartText::setEditable(bool editable) { - if (editable) { - setFlag(QGraphicsItem::ItemIsFocusable, true); - setTextInteractionFlags(Qt::TextEditorInteraction); - setFocus(Qt::MouseFocusReason); - } - else { - setTextInteractionFlags(Qt::NoTextInteraction); - setFlag(QGraphicsItem::ItemIsFocusable, false); - } + if (editable) { + setFlag(QGraphicsItem::ItemIsFocusable, true); + setTextInteractionFlags(Qt::TextEditorInteraction); + setFocus(Qt::MouseFocusReason); + } + else { + setTextInteractionFlags(Qt::NoTextInteraction); + setFlag(QGraphicsItem::ItemIsFocusable, false); + } } /** - Start text edition by storing the former value of the text. + Start text edition by storing the former value of the text. */ void PartText::startEdition() { - // !previous_text.isNull() means the text is being edited - previous_text = toPlainText(); + // !previous_text.isNull() means the text is being edited + previous_text = toPlainText(); } /** - End text edition, potentially generating a ChangePartCommand if the text - has changed. + End text edition, potentially generating a ChangePartCommand if the text + has changed. */ void PartText::endEdition() { - if (!previous_text.isNull()) { - // the text was being edited - QString new_text = toPlainText(); - if (previous_text != new_text) { - QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "text", previous_text, new_text); - undo -> setText(tr("Modifier un champ texte")); - undoStack().push(undo); - previous_text = QString(); - } - } + if (!previous_text.isNull()) { + // the text was being edited + QString new_text = toPlainText(); + if (previous_text != new_text) { + QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "text", previous_text, new_text); + undo -> setText(tr("Modifier un champ texte")); + undoStack().push(undo); + previous_text = QString(); + } + } - // deselectionne le texte - QTextCursor qtc = textCursor(); - qtc.clearSelection(); - setTextCursor(qtc); + // deselectionne le texte + QTextCursor qtc = textCursor(); + qtc.clearSelection(); + setTextCursor(qtc); - setEditable(false); + setEditable(false); } diff --git a/sources/editor/graphicspart/parttext.h b/sources/editor/graphicspart/parttext.h index cdadfbfab..f48db3a30 100644 --- a/sources/editor/graphicspart/parttext.h +++ b/sources/editor/graphicspart/parttext.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PART_TEXT_H #define PART_TEXT_H @@ -24,81 +24,81 @@ class TextEditor; class ElementPrimitiveDecorator; /** - This class represents an static text primitive which may be used to compose - the drawing of an electrical element within the element editor. + This class represents an static text primitive which may be used to compose + the drawing of an electrical element within the element editor. */ class PartText : public QGraphicsTextItem, public CustomElementPart { - Q_OBJECT - Q_PROPERTY(qreal real_size READ realSize WRITE setRealSize) - Q_PROPERTY(QColor color READ defaultTextColor WRITE setDefaultTextColor NOTIFY colorChanged) - Q_PROPERTY(QString text READ toPlainText WRITE setPlainText NOTIFY plainTextChanged) - Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged) + Q_OBJECT + Q_PROPERTY(qreal real_size READ realSize WRITE setRealSize) + Q_PROPERTY(QColor color READ defaultTextColor WRITE setDefaultTextColor NOTIFY colorChanged) + Q_PROPERTY(QString text READ toPlainText WRITE setPlainText NOTIFY plainTextChanged) + Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged) - signals: - void fontChanged(const QFont &font); - void colorChanged(const QColor &color); - void plainTextChanged(const QString &text); + signals: + void fontChanged(const QFont &font); + void colorChanged(const QColor &color); + void plainTextChanged(const QString &text); - // constructors, destructor - public: - PartText(QETElementEditor *, QGraphicsItem * = nullptr); - ~PartText() override; + // constructors, destructor + public: + PartText(QETElementEditor *, QGraphicsItem * = nullptr); + ~PartText() override; - private: - PartText(const PartText &); + private: + PartText(const PartText &); - // methods - public: - enum { Type = UserType + 1107 }; - /** - Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a - PartText. - @return the QGraphicsItem type - */ - int type() const override { return Type; } - QString name() const override { return(QObject::tr("texte", "element part name")); } - QString xmlName() const override { return(QString("text")); } - void fromXml(const QDomElement &) override; - const QDomElement toXml(QDomDocument &) const override; - void setRotation(qreal angle) {(QGraphicsObject::setRotation(QET::correctAngle(angle)));} - bool isUseless() const override; - QRectF sceneGeometricRect() const override; - void startUserTransformation(const QRectF &) override; - void handleUserTransformation(const QRectF &, const QRectF &) override; + // methods + public: + enum { Type = UserType + 1107 }; + /** + Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a + PartText. + @return the QGraphicsItem type + */ + int type() const override { return Type; } + QString name() const override { return(QObject::tr("texte", "element part name")); } + QString xmlName() const override { return(QString("text")); } + void fromXml(const QDomElement &) override; + const QDomElement toXml(QDomDocument &) const override; + void setRotation(qreal angle) {(QGraphicsObject::setRotation(QET::correctAngle(angle)));} + bool isUseless() const override; + QRectF sceneGeometricRect() const override; + void startUserTransformation(const QRectF &) override; + void handleUserTransformation(const QRectF &, const QRectF &) override; - void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);} - QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);} + void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);} + QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);} - qreal realSize() const {return real_font_size_;} - void setRealSize(qreal rs) {real_font_size_ = rs;} - void setDefaultTextColor(const QColor &color); - void setPlainText(const QString &text); - void setFont(const QFont &font); + qreal realSize() const {return real_font_size_;} + void setRealSize(qreal rs) {real_font_size_ = rs;} + void setDefaultTextColor(const QColor &color); + void setPlainText(const QString &text); + void setFont(const QFont &font); - public slots: - void adjustItemPosition(int = 0); - void setEditable(bool); - void startEdition(); - void endEdition(); + public slots: + void adjustItemPosition(int = 0); + void setEditable(bool); + void startEdition(); + void endEdition(); - protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - void focusInEvent(QFocusEvent *) override; - void focusOutEvent(QFocusEvent *) override; - void keyPressEvent(QKeyEvent *) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override; - QVariant itemChange(GraphicsItemChange, const QVariant &) override; - QRectF boundingRect() const override; + protected: + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void focusInEvent(QFocusEvent *) override; + void focusOutEvent(QFocusEvent *) override; + void keyPressEvent(QKeyEvent *) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override; + QVariant itemChange(GraphicsItemChange, const QVariant &) override; + QRectF boundingRect() const override; - private: - QPointF margin() const; - QString previous_text; - qreal real_font_size_; - QPointF saved_point_; - qreal saved_font_size_; - QGraphicsItem *decorator_; - QPointF m_origine_pos; + private: + QPointF margin() const; + QString previous_text; + qreal real_font_size_; + QPointF saved_point_; + qreal saved_font_size_; + QGraphicsItem *decorator_; + QPointF m_origine_pos; }; #endif diff --git a/sources/elementtextpattern.cpp b/sources/elementtextpattern.cpp index 6e35ce502..0de39099d 100644 --- a/sources/elementtextpattern.cpp +++ b/sources/elementtextpattern.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "elementtextpattern.h" #include "qetapp.h" @@ -35,239 +35,239 @@ #include /** - @brief ExportElementTextPattern::ExportElementTextPattern - Constructor - @param elmt + @brief ExportElementTextPattern::ExportElementTextPattern + Constructor + @param elmt */ ExportElementTextPattern::ExportElementTextPattern(Element *elmt) : - m_element(elmt) + m_element(elmt) { - //Create the conf dir if not yet. - QDir dir(QETApp::configDir()+ "/element_texts_pattern"); - if(!dir.exists()) - { - dir.cdUp(); - dir.mkdir("element_texts_pattern"); - dir.cd("element_texts_pattern"); - } - - //Get the name of conf - bool ok; - m_name = getName(ok); - if(ok == false) - return; - - //Check if a conf with the same name already exist - if (QFileInfo::exists(dir.absoluteFilePath(m_name + ".xml"))) - { - bool r = QMessageBox::question(parentWidget(), - QObject::tr("Configuration de textes"), - QObject::tr("Une configuration de textes nommée << %1 >> existe déjà.\n" - "Voulez-vous la remplacer ?").arg(m_name)); - - if(r == false) - return; - } - - QDomDocument doc = xmlConf(); - QET::writeXmlFile(doc, dir.absoluteFilePath(m_name + ".xml")); + //Create the conf dir if not yet. + QDir dir(QETApp::configDir()+ "/element_texts_pattern"); + if(!dir.exists()) + { + dir.cdUp(); + dir.mkdir("element_texts_pattern"); + dir.cd("element_texts_pattern"); + } + + //Get the name of conf + bool ok; + m_name = getName(ok); + if(ok == false) + return; + + //Check if a conf with the same name already exist + if (QFileInfo::exists(dir.absoluteFilePath(m_name + ".xml"))) + { + bool r = QMessageBox::question(parentWidget(), + QObject::tr("Configuration de textes"), + QObject::tr("Une configuration de textes nommée << %1 >> existe déjà.\n" + "Voulez-vous la remplacer ?").arg(m_name)); + + if(r == false) + return; + } + + QDomDocument doc = xmlConf(); + QET::writeXmlFile(doc, dir.absoluteFilePath(m_name + ".xml")); } /** - @brief ExportElementTextConf::getName - Open a dialog to let user set the name of the conf and return it - @return + @brief ExportElementTextConf::getName + Open a dialog to let user set the name of the conf and return it + @return */ QString ExportElementTextPattern::getName(bool &ok) const -{ - QString text = QInputDialog::getText(parentWidget(), - QObject::tr("Nom de la configuration"), - QObject::tr("Entrer le nom de la configuration à créer"), - QLineEdit::Normal, - QString(), - &ok); - - text.replace(" ", "_"); - text.replace(".",""); - return text; +{ + QString text = QInputDialog::getText(parentWidget(), + QObject::tr("Nom de la configuration"), + QObject::tr("Entrer le nom de la configuration à créer"), + QLineEdit::Normal, + QString(), + &ok); + + text.replace(" ", "_"); + text.replace(".",""); + return text; } QWidget *ExportElementTextPattern::parentWidget() const { - QWidget *parent = nullptr; - if(m_element->scene() && !m_element->scene()->views().isEmpty()) - parent = m_element->scene()->views().first(); - - return parent; + QWidget *parent = nullptr; + if(m_element->scene() && !m_element->scene()->views().isEmpty()) + parent = m_element->scene()->views().first(); + + return parent; } QDomDocument ExportElementTextPattern::xmlConf() const { - QDomDocument doc; - QDomElement root = doc.createElement("Element_texts_pattern"); - root.setAttribute("name", m_name); - doc.appendChild(root); - - QHash H; - QDomElement elmt = m_element->toXml(doc, H); - QDomElement texts = elmt.firstChildElement("dynamic_texts"); - QDomElement groups = elmt.firstChildElement("texts_groups"); - - if(texts.tagName() == "dynamic_texts") - root.appendChild(texts); - if(groups.tagName() == "texts_groups") - root.appendChild(groups); - - return doc; + QDomDocument doc; + QDomElement root = doc.createElement("Element_texts_pattern"); + root.setAttribute("name", m_name); + doc.appendChild(root); + + QHash H; + QDomElement elmt = m_element->toXml(doc, H); + QDomElement texts = elmt.firstChildElement("dynamic_texts"); + QDomElement groups = elmt.firstChildElement("texts_groups"); + + if(texts.tagName() == "dynamic_texts") + root.appendChild(texts); + if(groups.tagName() == "texts_groups") + root.appendChild(groups); + + return doc; } //*******************// //******IMPORT*******// //*******************// ImportElementTextPattern::ImportElementTextPattern(Element *elmt): - m_element(elmt) + m_element(elmt) { - bool exist = true; - QDir dir(QETApp::configDir()+ "/element_texts_pattern"); - - if(!dir.exists()) - exist = false; + bool exist = true; + QDir dir(QETApp::configDir()+ "/element_texts_pattern"); + + if(!dir.exists()) + exist = false; - QStringList entry = dir.entryList(QDir::Files | QDir::NoDotAndDotDot); - QStringList result = entry.filter(".xml"); - if(result.isEmpty()) - exist = false; - - if(!exist) - { - QMessageBox::information( - parentWidget(), - QObject::tr("Configuration de textes"), - QObject::tr("Aucune configuration de textes existante.")); - return; - } - - bool ok=false; - bool erase = false; - //Remove the .xml extention of the files - result.replaceInStrings(".xml", ""); - QString name = getName(result, &ok, &erase); - - if(!ok || name.isEmpty()) - return; - else - apply(name, erase); + QStringList entry = dir.entryList(QDir::Files | QDir::NoDotAndDotDot); + QStringList result = entry.filter(".xml"); + if(result.isEmpty()) + exist = false; + + if(!exist) + { + QMessageBox::information( + parentWidget(), + QObject::tr("Configuration de textes"), + QObject::tr("Aucune configuration de textes existante.")); + return; + } + + bool ok=false; + bool erase = false; + //Remove the .xml extention of the files + result.replaceInStrings(".xml", ""); + QString name = getName(result, &ok, &erase); + + if(!ok || name.isEmpty()) + return; + else + apply(name, erase); } /** - @brief ImportElementTextPattern::getName - Open a dialog to let user select a conf - @param list - @param ok - @param erase - @return + @brief ImportElementTextPattern::getName + Open a dialog to let user select a conf + @param list + @param ok + @param erase + @return */ QString ImportElementTextPattern::getName(const QStringList& list, - bool *ok, - bool *erase) const + bool *ok, + bool *erase) const { - return ImportElementTextPatternDialog::getItem( - parentWidget(), - QObject::tr("Sélectionner une configuration de textes"), - QObject::tr("Sélectionner la configuration de textes à ajouter à l'élément"), - list, - ok, - erase); + return ImportElementTextPatternDialog::getItem( + parentWidget(), + QObject::tr("Sélectionner une configuration de textes"), + QObject::tr("Sélectionner la configuration de textes à ajouter à l'élément"), + list, + ok, + erase); } QWidget *ImportElementTextPattern::parentWidget() const { - QWidget *parent = nullptr; - if(m_element->scene() && !m_element->scene()->views().isEmpty()) - parent = m_element->scene()->views().first(); - - return parent; + QWidget *parent = nullptr; + if(m_element->scene() && !m_element->scene()->views().isEmpty()) + parent = m_element->scene()->views().first(); + + return parent; } /** - @brief ImportElementTextPattern::apply - Apply the user choice - @param name : the name of the selected pattern - @param erase : erase the existing texts and groups of element. + @brief ImportElementTextPattern::apply + Apply the user choice + @param name : the name of the selected pattern + @param erase : erase the existing texts and groups of element. */ void ImportElementTextPattern::apply(QString name, bool erase) const { - if(!name.endsWith(".xml")) - name.append(".xml"); - - QFile conf_file(QETApp::configDir() + "/element_texts_pattern/" + name); - if(!conf_file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - //Load the content of the xml file - QDomDocument xml_conf; - if(!xml_conf.setContent(&conf_file)) - return; - - QDomElement root = xml_conf.firstChildElement("Element_texts_pattern"); - - //Get the text - QList texts = QET::findInDomElement(root, "dynamic_texts", "dynamic_elmt_text"); - if (texts.isEmpty()) - return; - - //Replace the original uuid of texts in the xml description, by a new one for every texts - QHash uuid_hash; - for(QDomElement text : texts) - { - QUuid original_uuid(text.attribute("uuid")); - QUuid new_uuid = QUuid::createUuid(); - text.setAttribute("uuid", new_uuid.toString()); - - uuid_hash.insert(original_uuid, new_uuid); - } - - //In each group of the xml description, replace the original uuids, by the news created upper. - QList groups = QET::findInDomElement(root, "texts_groups", "texts_group"); - for(const QDomElement& group : groups) - { - for(QDomElement text : QET::findInDomElement(group, "texts", "text")) - { - QUuid original_uuid(text.attribute("uuid")); - QUuid new_uuid = uuid_hash.value(original_uuid); - if(!new_uuid.isNull()) - text.setAttribute("uuid", new_uuid.toString()); - } - } - - QUndoStack &undo_stack = m_element->diagram()->undoStack(); - undo_stack.beginMacro(QObject::tr("Importer la configuration de texte : %1").arg(name.remove(".xml"))); - - //erase existing texts and groups - if (erase) - { - for (ElementTextItemGroup *group : m_element->textGroups()) { - undo_stack.push(new RemoveTextsGroupCommand(m_element, group)); - } - for (DynamicElementTextItem *deti : m_element->dynamicTextItems()) - { - DiagramContent dc; - dc.m_element_texts << deti; - undo_stack.push(new DeleteQGraphicsItemCommand(m_element->diagram(), dc)); - } - } - - //Add the texts to element - for(const QDomElement& text : texts) - { - DynamicElementTextItem *deti = new DynamicElementTextItem(m_element); - undo_stack.push(new AddElementTextCommand(m_element, deti)); - deti->fromXml(text); - } - //Add the groups to element - for(const QDomElement& xml_group : groups) - undo_stack.push(new AddTextsGroupCommand(m_element, xml_group)); - - undo_stack.endMacro(); + if(!name.endsWith(".xml")) + name.append(".xml"); + + QFile conf_file(QETApp::configDir() + "/element_texts_pattern/" + name); + if(!conf_file.open(QIODevice::ReadOnly | QIODevice::Text)) + return; + + //Load the content of the xml file + QDomDocument xml_conf; + if(!xml_conf.setContent(&conf_file)) + return; + + QDomElement root = xml_conf.firstChildElement("Element_texts_pattern"); + + //Get the text + QList texts = QET::findInDomElement(root, "dynamic_texts", "dynamic_elmt_text"); + if (texts.isEmpty()) + return; + + //Replace the original uuid of texts in the xml description, by a new one for every texts + QHash uuid_hash; + for(QDomElement text : texts) + { + QUuid original_uuid(text.attribute("uuid")); + QUuid new_uuid = QUuid::createUuid(); + text.setAttribute("uuid", new_uuid.toString()); + + uuid_hash.insert(original_uuid, new_uuid); + } + + //In each group of the xml description, replace the original uuids, by the news created upper. + QList groups = QET::findInDomElement(root, "texts_groups", "texts_group"); + for(const QDomElement& group : groups) + { + for(QDomElement text : QET::findInDomElement(group, "texts", "text")) + { + QUuid original_uuid(text.attribute("uuid")); + QUuid new_uuid = uuid_hash.value(original_uuid); + if(!new_uuid.isNull()) + text.setAttribute("uuid", new_uuid.toString()); + } + } + + QUndoStack &undo_stack = m_element->diagram()->undoStack(); + undo_stack.beginMacro(QObject::tr("Importer la configuration de texte : %1").arg(name.remove(".xml"))); + + //erase existing texts and groups + if (erase) + { + for (ElementTextItemGroup *group : m_element->textGroups()) { + undo_stack.push(new RemoveTextsGroupCommand(m_element, group)); + } + for (DynamicElementTextItem *deti : m_element->dynamicTextItems()) + { + DiagramContent dc; + dc.m_element_texts << deti; + undo_stack.push(new DeleteQGraphicsItemCommand(m_element->diagram(), dc)); + } + } + + //Add the texts to element + for(const QDomElement& text : texts) + { + DynamicElementTextItem *deti = new DynamicElementTextItem(m_element); + undo_stack.push(new AddElementTextCommand(m_element, deti)); + deti->fromXml(text); + } + //Add the groups to element + for(const QDomElement& xml_group : groups) + undo_stack.push(new AddTextsGroupCommand(m_element, xml_group)); + + undo_stack.endMacro(); } diff --git a/sources/properties/propertiesinterface.cpp b/sources/properties/propertiesinterface.cpp index 9555292ca..d72941027 100644 --- a/sources/properties/propertiesinterface.cpp +++ b/sources/properties/propertiesinterface.cpp @@ -1,30 +1,30 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "propertiesinterface.h" /** - @brief PropertiesInterface::PropertiesInterface + @brief PropertiesInterface::PropertiesInterface */ PropertiesInterface::PropertiesInterface() { } /** - @brief PropertiesInterface::~PropertiesInterface + @brief PropertiesInterface::~PropertiesInterface */ PropertiesInterface::~PropertiesInterface() { diff --git a/sources/properties/propertiesinterface.h b/sources/properties/propertiesinterface.h index e6c4724ab..645d7b11e 100644 --- a/sources/properties/propertiesinterface.h +++ b/sources/properties/propertiesinterface.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef PROPERTIESINTERFACE_H #define PROPERTIESINTERFACE_H @@ -23,47 +23,47 @@ #include /** - @brief The PropertiesInterface class - This class is an interface for have common way - to use properties in QElectroTech + @brief The PropertiesInterface class + This class is an interface for have common way + to use properties in QElectroTech */ class PropertiesInterface { - public: - PropertiesInterface(); - virtual ~PropertiesInterface(); - /** - @brief toSettings - Save properties to setting file. - @param settings : is use for prefix a word - befor the name of each paramètre - @param QString - */ - virtual void toSettings (QSettings &settings, - const QString = QString()) const =0; - /** - @brief fromSettings - load properties to setting file. - @param settings : is use for prefix a word - befor the name of each paramètre - @param QString - */ - virtual void fromSettings (const QSettings &settings, - const QString = QString()) =0; - /** - @brief toXml - Save properties to xml element - @param xml_document - @return QDomElement - */ - virtual QDomElement toXml (QDomDocument &xml_document) const =0; - /** - @brief fromXml - load properties to xml element - @param xml_element - @return true / false - */ - virtual bool fromXml (const QDomElement &xml_element) =0; + public: + PropertiesInterface(); + virtual ~PropertiesInterface(); + /** + @brief toSettings + Save properties to setting file. + @param settings : is use for prefix a word + befor the name of each paramètre + @param QString + */ + virtual void toSettings (QSettings &settings, + const QString = QString()) const =0; + /** + @brief fromSettings + load properties to setting file. + @param settings : is use for prefix a word + befor the name of each paramètre + @param QString + */ + virtual void fromSettings (const QSettings &settings, + const QString = QString()) =0; + /** + @brief toXml + Save properties to xml element + @param xml_document + @return QDomElement + */ + virtual QDomElement toXml (QDomDocument &xml_document) const =0; + /** + @brief fromXml + load properties to xml element + @param xml_element + @return true / false + */ + virtual bool fromXml (const QDomElement &xml_element) =0; }; #endif // PROPERTIESINTERFACE_H diff --git a/sources/properties/terminaldata.cpp b/sources/properties/terminaldata.cpp index 5fc00d72e..45859541d 100644 --- a/sources/properties/terminaldata.cpp +++ b/sources/properties/terminaldata.cpp @@ -3,16 +3,16 @@ #include TerminalData::TerminalData(): - PropertiesInterface() + PropertiesInterface() { - init(); + init(); } TerminalData::TerminalData(QGraphicsObject *parent): - PropertiesInterface(), - q(parent) + PropertiesInterface(), + q(parent) { - init(); + init(); } void TerminalData::init() @@ -25,117 +25,117 @@ TerminalData::~TerminalData() } /** - @brief TerminalData::setParent - @param parent + @brief TerminalData::setParent + @param parent */ void TerminalData::setParent(QGraphicsObject* parent) { - q = parent; + q = parent; } /** - @brief TerminalData::toSettings - Save properties to setting file. + @brief TerminalData::toSettings + Save properties to setting file. - QString is use for prefix a word befor the name of each paramètre - @param settings UNUSED - @param prefix UNUSED + QString is use for prefix a word befor the name of each paramètre + @param settings UNUSED + @param prefix UNUSED */ void TerminalData::toSettings(QSettings &settings, const QString prefix) const { - Q_UNUSED(settings); - Q_UNUSED(prefix); + Q_UNUSED(settings); + Q_UNUSED(prefix); } /** - @brief TerminalData::fromSettings - load properties to setting file. + @brief TerminalData::fromSettings + load properties to setting file. - QString is use for prefix a word befor the name of each paramètre - @param settings UNUSED - @param prefix UNUSED + QString is use for prefix a word befor the name of each paramètre + @param settings UNUSED + @param prefix UNUSED */ void TerminalData::fromSettings(const QSettings &settings, const QString prefix) { - Q_UNUSED(settings); - Q_UNUSED(prefix); + Q_UNUSED(settings); + Q_UNUSED(prefix); } /** - @brief TerminalData::toXml - Save properties to xml element - write the name, number, position and orientation of the terminal - to xml_element + @brief TerminalData::toXml + Save properties to xml element + write the name, number, position and orientation of the terminal + to xml_element - @note This method is only called from the PartTerminal - and should never called from the Terminal class - @param xml_document - @return xml_element : DomElement with - the name, number, position and orientation of the terminal + @note This method is only called from the PartTerminal + and should never called from the Terminal class + @param xml_document + @return xml_element : DomElement with + the name, number, position and orientation of the terminal */ QDomElement TerminalData::toXml(QDomDocument &xml_document) const { - QDomElement xml_element = xml_document.createElement("terminal"); + QDomElement xml_element = xml_document.createElement("terminal"); - // write the position of the terminal - // ecrit la position de la borne - xml_element.setAttribute("x", QString("%1").arg(q->scenePos().x())); - xml_element.setAttribute("y", QString("%1").arg(q->scenePos().y())); + // write the position of the terminal + // ecrit la position de la borne + xml_element.setAttribute("x", QString("%1").arg(q->scenePos().x())); + xml_element.setAttribute("y", QString("%1").arg(q->scenePos().y())); - // Write name and number to XML - xml_element.setAttribute("uuid", m_uuid.toString()); - xml_element.setAttribute("name", m_name); + // Write name and number to XML + xml_element.setAttribute("uuid", m_uuid.toString()); + xml_element.setAttribute("name", m_name); - // write the orientation of the terminal - // ecrit l'orientation de la borne - xml_element.setAttribute("orientation", - Qet::orientationToString(m_orientation)); + // write the orientation of the terminal + // ecrit l'orientation de la borne + xml_element.setAttribute("orientation", + Qet::orientationToString(m_orientation)); - return(xml_element); + return(xml_element); } /** - @brief TerminalData::fromXml - load properties to xml element + @brief TerminalData::fromXml + load properties to xml element - @note This method is only called from the PartTerminal - and should never called from the Terminal class - @param xml_element - @return true if succeeded / false if the attribute is not real + @note This method is only called from the PartTerminal + and should never called from the Terminal class + @param xml_element + @return true if succeeded / false if the attribute is not real */ bool TerminalData::fromXml (const QDomElement &xml_element) { - qreal term_x = 0.0; - qreal term_y = 0.0; + qreal term_x = 0.0; + qreal term_y = 0.0; - // reads the position of the terminal - // lit la position de la borne - if (!QET::attributeIsAReal(xml_element, "x", &term_x)) - return false; + // reads the position of the terminal + // lit la position de la borne + if (!QET::attributeIsAReal(xml_element, "x", &term_x)) + return false; - if (!QET::attributeIsAReal(xml_element, "y", &term_y)) - return false; + if (!QET::attributeIsAReal(xml_element, "y", &term_y)) + return false; - m_pos = QPointF(term_x, term_y); + m_pos = QPointF(term_x, term_y); - //emit posFromXML(QPointF(term_x, term_y)); + //emit posFromXML(QPointF(term_x, term_y)); - QString uuid = xml_element.attribute("uuid"); - // update part and add uuid, which is used in the new version - // to connect terminals together - // if the attribute not exists, means, the element is created with an - // older version of qet. So use the legacy approach - // to identify terminals - if (!uuid.isEmpty()) - m_uuid = QUuid(uuid); + QString uuid = xml_element.attribute("uuid"); + // update part and add uuid, which is used in the new version + // to connect terminals together + // if the attribute not exists, means, the element is created with an + // older version of qet. So use the legacy approach + // to identify terminals + if (!uuid.isEmpty()) + m_uuid = QUuid(uuid); - m_name = xml_element.attribute("name"); + m_name = xml_element.attribute("name"); - // read the orientation of the terminal - // lit l'orientation de la borne - m_orientation = Qet::orientationFromString( - xml_element.attribute("orientation")); + // read the orientation of the terminal + // lit l'orientation de la borne + m_orientation = Qet::orientationFromString( + xml_element.attribute("orientation")); - return true; + return true; } diff --git a/sources/properties/terminaldata.h b/sources/properties/terminaldata.h index f54344e61..58d90f484 100644 --- a/sources/properties/terminaldata.h +++ b/sources/properties/terminaldata.h @@ -10,78 +10,78 @@ class QGraphicsObject; /** - @brief The TerminalData class - Data of the terminal. - Stored in extra class so it can be used by PartTerminal - and Terminal without defining everything again. - @note tis class needs to be work on + @brief The TerminalData class + Data of the terminal. + Stored in extra class so it can be used by PartTerminal + and Terminal without defining everything again. + @note tis class needs to be work on */ class TerminalData : public PropertiesInterface { - public: - TerminalData(); - TerminalData(QGraphicsObject* parent); - ~TerminalData(); + public: + TerminalData(); + TerminalData(QGraphicsObject* parent); + ~TerminalData(); - void init(); + void init(); - void setParent(QGraphicsObject* parent); - void toSettings(QSettings &settings, - const QString prefix = QString()) const override; - void fromSettings(const QSettings &settings, - const QString prefix = QString()) override; - QDomElement toXml(QDomDocument &xml_element) const override; - bool fromXml(const QDomElement &xml_element) override; + void setParent(QGraphicsObject* parent); + void toSettings(QSettings &settings, + const QString prefix = QString()) const override; + void fromSettings(const QSettings &settings, + const QString prefix = QString()) override; + QDomElement toXml(QDomDocument &xml_element) const override; + bool fromXml(const QDomElement &xml_element) override; - // must be public, because this class is a private member - // of PartTerminal/Terminal and they must access this data - public: - /** - @brief m_orientation - Orientation of the terminal - */ - Qet::Orientation m_orientation; - /** - @brief second_point - Position of the second point of the terminal - in scene coordinates - */ - QPointF second_point; - /** - @brief m_uuid - Uuid of the terminal. + // must be public, because this class is a private member + // of PartTerminal/Terminal and they must access this data + public: + /** + @brief m_orientation + Orientation of the terminal + */ + Qet::Orientation m_orientation; + /** + @brief second_point + Position of the second point of the terminal + in scene coordinates + */ + QPointF second_point; + /** + @brief m_uuid + Uuid of the terminal. - In elementscene.cpp an element gets a new uuid when - saving the element. In the current state - each connection is made by using the local position - of the terminal and a dynamic id. In the new - case, each terminal should have it's own uuid to - identify it uniquely. When changing each time this - uuid, the conductor after updating the part is anymore - valid. So if in the loaded document a uuid exists, - use this one and don't create a new one. - */ - QUuid m_uuid; - /** - @brief m_name - Name of the element. - It can be used to create wiring harness tables - */ - QString m_name; + In elementscene.cpp an element gets a new uuid when + saving the element. In the current state + each connection is made by using the local position + of the terminal and a dynamic id. In the new + case, each terminal should have it's own uuid to + identify it uniquely. When changing each time this + uuid, the conductor after updating the part is anymore + valid. So if in the loaded document a uuid exists, + use this one and don't create a new one. + */ + QUuid m_uuid; + /** + @brief m_name + Name of the element. + It can be used to create wiring harness tables + */ + QString m_name; - /** - @brief m_pos - Position of the terminal. The second point is calculated - from this position and the orientation - @note - Important: this variable is only updated during read - from xml and not during mouse move! - It is used to store the initial position so that - PartTerminal and Terminal have access to it. - */ - QPointF m_pos; - private: - QGraphicsObject* q{nullptr}; + /** + @brief m_pos + Position of the terminal. The second point is calculated + from this position and the orientation + @note + Important: this variable is only updated during read + from xml and not during mouse move! + It is used to store the initial position so that + PartTerminal and Terminal have access to it. + */ + QPointF m_pos; + private: + QGraphicsObject* q{nullptr}; }; #endif // TERMINALDATA_H diff --git a/sources/properties/xrefproperties.cpp b/sources/properties/xrefproperties.cpp index dd864f5b0..9f5af155d 100644 --- a/sources/properties/xrefproperties.cpp +++ b/sources/properties/xrefproperties.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include #include @@ -22,182 +22,182 @@ #include "qetapp.h" /** - @brief XRefProperties::XRefProperties - Default Constructor + @brief XRefProperties::XRefProperties + Default Constructor */ XRefProperties::XRefProperties() { - m_show_power_ctc = true; - m_display = Cross; - m_snap_to = Bottom; - m_prefix_keys << "power" << "delay" << "switch"; - m_master_label = "%f-%l%c"; - m_slave_label = "(%f-%l%c)"; - m_offset = 0; - m_xref_pos = Qt::AlignBottom; + m_show_power_ctc = true; + m_display = Cross; + m_snap_to = Bottom; + m_prefix_keys << "power" << "delay" << "switch"; + m_master_label = "%f-%l%c"; + m_slave_label = "(%f-%l%c)"; + m_offset = 0; + m_xref_pos = Qt::AlignBottom; } /** - @brief XRefProperties::toSettings - Save to settings - @param settings: QSettings to use - @param prefix: prefix before properties name + @brief XRefProperties::toSettings + Save to settings + @param settings: QSettings to use + @param prefix: prefix before properties name */ void XRefProperties::toSettings(QSettings &settings, - const QString prefix) const + const QString prefix) const { - settings.setValue(prefix + "showpowerctc", m_show_power_ctc); - QString display = m_display == Cross? "cross" : "contacts"; - settings.setValue(prefix + "displayhas", display); - QString snap = m_snap_to == Bottom? "bottom" : "label"; - settings.setValue(prefix + "snapto", snap); - int offset = m_offset; - settings.setValue(prefix + "offset", offset); - QString master_label = m_master_label; - settings.setValue(prefix + "master_label", master_label); - QString slave_label = m_slave_label; - settings.setValue(prefix + "slave_label", slave_label); + settings.setValue(prefix + "showpowerctc", m_show_power_ctc); + QString display = m_display == Cross? "cross" : "contacts"; + settings.setValue(prefix + "displayhas", display); + QString snap = m_snap_to == Bottom? "bottom" : "label"; + settings.setValue(prefix + "snapto", snap); + int offset = m_offset; + settings.setValue(prefix + "offset", offset); + QString master_label = m_master_label; + settings.setValue(prefix + "master_label", master_label); + QString slave_label = m_slave_label; + settings.setValue(prefix + "slave_label", slave_label); - QMetaEnum var = QMetaEnum::fromType(); - settings.setValue(prefix + "xrefpos", var.valueToKey(m_xref_pos)); + QMetaEnum var = QMetaEnum::fromType(); + settings.setValue(prefix + "xrefpos", var.valueToKey(m_xref_pos)); - foreach (QString key, m_prefix.keys()) { - settings.setValue(prefix + key + "prefix", m_prefix.value(key)); - } + foreach (QString key, m_prefix.keys()) { + settings.setValue(prefix + key + "prefix", m_prefix.value(key)); + } } /** - @brief XRefProperties::fromSettings - load from settings - @param settings: QSettings to use - @param prefix: prefix before properties name + @brief XRefProperties::fromSettings + load from settings + @param settings: QSettings to use + @param prefix: prefix before properties name */ void XRefProperties::fromSettings(const QSettings &settings, - const QString prefix) + const QString prefix) { - m_show_power_ctc = settings.value(prefix + "showpowerctc", true).toBool(); - QString display = settings.value(prefix + "displayhas", "cross").toString(); - display == "cross"? m_display = Cross : m_display = Contacts; - QString snap = settings.value(prefix + "snapto", "label").toString(); - snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label; - m_offset = settings.value(prefix + "offset", "0").toInt(); - m_master_label = settings.value(prefix + "master_label", "%f-%l%c").toString(); - m_slave_label = settings.value(prefix + "slave_label", "(%f-%l%c)").toString(); + m_show_power_ctc = settings.value(prefix + "showpowerctc", true).toBool(); + QString display = settings.value(prefix + "displayhas", "cross").toString(); + display == "cross"? m_display = Cross : m_display = Contacts; + QString snap = settings.value(prefix + "snapto", "label").toString(); + snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label; + m_offset = settings.value(prefix + "offset", "0").toInt(); + m_master_label = settings.value(prefix + "master_label", "%f-%l%c").toString(); + m_slave_label = settings.value(prefix + "slave_label", "(%f-%l%c)").toString(); - QMetaEnum var = QMetaEnum::fromType(); - m_xref_pos = Qt::AlignmentFlag(var.keyToValue((settings.value(prefix + "xrefpos").toString()).toStdString().data())); + QMetaEnum var = QMetaEnum::fromType(); + m_xref_pos = Qt::AlignmentFlag(var.keyToValue((settings.value(prefix + "xrefpos").toString()).toStdString().data())); - for (QString key : m_prefix_keys) { - m_prefix.insert(key, settings.value(prefix + key + "prefix").toString()); - } + for (QString key : m_prefix_keys) { + m_prefix.insert(key, settings.value(prefix + key + "prefix").toString()); + } } /** - @brief XRefProperties::toXml - Save to xml - @param xml_document : QDomElement to use for saving - @return QDomElement + @brief XRefProperties::toXml + Save to xml + @param xml_document : QDomElement to use for saving + @return QDomElement */ QDomElement XRefProperties::toXml(QDomDocument &xml_document) const { - QDomElement xml_element = xml_document.createElement("xref"); - xml_element.setAttribute("type", m_key); + QDomElement xml_element = xml_document.createElement("xref"); + xml_element.setAttribute("type", m_key); - xml_element.setAttribute("showpowerctc", m_show_power_ctc? "true" : "false"); - QString display = m_display == Cross? "cross" : "contacts"; - xml_element.setAttribute("displayhas", display); - QString snap = m_snap_to == Bottom? "bottom" : "label"; - xml_element.setAttribute("snapto", snap); + xml_element.setAttribute("showpowerctc", m_show_power_ctc? "true" : "false"); + QString display = m_display == Cross? "cross" : "contacts"; + xml_element.setAttribute("displayhas", display); + QString snap = m_snap_to == Bottom? "bottom" : "label"; + xml_element.setAttribute("snapto", snap); - QString xrefpos; + QString xrefpos; - QMetaEnum var = QMetaEnum::fromType(); - xml_element.setAttribute("xrefpos", var.valueToKey(m_xref_pos)); + QMetaEnum var = QMetaEnum::fromType(); + xml_element.setAttribute("xrefpos", var.valueToKey(m_xref_pos)); - int offset = m_offset; - xml_element.setAttribute("offset", QString::number(offset)); - QString master_label = m_master_label; - xml_element.setAttribute("master_label", master_label); - QString slave_label = m_slave_label; - xml_element.setAttribute("slave_label", slave_label); - foreach (QString key, m_prefix.keys()) { - xml_element.setAttribute(key + "prefix", m_prefix.value(key)); - } + int offset = m_offset; + xml_element.setAttribute("offset", QString::number(offset)); + QString master_label = m_master_label; + xml_element.setAttribute("master_label", master_label); + QString slave_label = m_slave_label; + xml_element.setAttribute("slave_label", slave_label); + foreach (QString key, m_prefix.keys()) { + xml_element.setAttribute(key + "prefix", m_prefix.value(key)); + } - return xml_element; + return xml_element; } /** - @brief XRefProperties::fromXml - Load from xml - @param xml_element: QDomElement to use for load + @brief XRefProperties::fromXml + Load from xml + @param xml_element: QDomElement to use for load */ bool XRefProperties::fromXml(const QDomElement &xml_element) { - m_show_power_ctc = xml_element.attribute("showpowerctc") == "true"; - QString display = xml_element.attribute("displayhas", "cross"); - display == "cross"? m_display = Cross : m_display = Contacts; - QString snap = xml_element.attribute("snapto", "label"); - snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label; + m_show_power_ctc = xml_element.attribute("showpowerctc") == "true"; + QString display = xml_element.attribute("displayhas", "cross"); + display == "cross"? m_display = Cross : m_display = Contacts; + QString snap = xml_element.attribute("snapto", "label"); + snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label; - QString xrefpos = xml_element.attribute("xrefpos","Left"); + QString xrefpos = xml_element.attribute("xrefpos","Left"); - QMetaEnum var = QMetaEnum::fromType(); + QMetaEnum var = QMetaEnum::fromType(); - if(xml_element.hasAttribute("xrefpos")) - m_xref_pos = Qt::AlignmentFlag(var.keyToValue(xml_element.attribute("xrefpos").toStdString().data())); - else - m_xref_pos = Qt::AlignBottom; + if(xml_element.hasAttribute("xrefpos")) + m_xref_pos = Qt::AlignmentFlag(var.keyToValue(xml_element.attribute("xrefpos").toStdString().data())); + else + m_xref_pos = Qt::AlignBottom; - m_offset = xml_element.attribute("offset", "0").toInt(); - m_master_label = xml_element.attribute("master_label", "%f-%l%c"); - m_slave_label = xml_element.attribute("slave_label","(%f-%l%c)"); - foreach (QString key, m_prefix_keys) { - m_prefix.insert(key, xml_element.attribute(key + "prefix")); - } - return true; + m_offset = xml_element.attribute("offset", "0").toInt(); + m_master_label = xml_element.attribute("master_label", "%f-%l%c"); + m_slave_label = xml_element.attribute("slave_label","(%f-%l%c)"); + foreach (QString key, m_prefix_keys) { + m_prefix.insert(key, xml_element.attribute(key + "prefix")); + } + return true; } /** - @brief XRefProperties::defaultProperties - @return the default properties stored in the setting file - For the xref, there is 2 propreties. - For coil, stored with the string "coil" in the returned QHash. - For protection, stored with the string "protection" in the returned QHash. + @brief XRefProperties::defaultProperties + @return the default properties stored in the setting file + For the xref, there is 2 propreties. + For coil, stored with the string "coil" in the returned QHash. + For protection, stored with the string "protection" in the returned QHash. */ QHash XRefProperties::defaultProperties() { - QHash hash; - QStringList keys; - keys << "coil" << "protection" << "commutator"; + QHash hash; + QStringList keys; + keys << "coil" << "protection" << "commutator"; - QSettings settings; + QSettings settings; - foreach (QString key, keys) - { - XRefProperties properties; - QString str("diagrameditor/defaultxref"); - properties.fromSettings(settings, str += key); - hash.insert(key, properties); - } + foreach (QString key, keys) + { + XRefProperties properties; + QString str("diagrameditor/defaultxref"); + properties.fromSettings(settings, str += key); + hash.insert(key, properties); + } - return hash; + return hash; } bool XRefProperties::operator ==(const XRefProperties &xrp) const{ - return (m_show_power_ctc == xrp.m_show_power_ctc && - m_display == xrp.m_display && - m_snap_to == xrp.m_snap_to && - m_prefix == xrp.m_prefix && - m_master_label == xrp.m_master_label && - m_offset == xrp.m_offset && - m_xref_pos == xrp.m_xref_pos ); + return (m_show_power_ctc == xrp.m_show_power_ctc && + m_display == xrp.m_display && + m_snap_to == xrp.m_snap_to && + m_prefix == xrp.m_prefix && + m_master_label == xrp.m_master_label && + m_offset == xrp.m_offset && + m_xref_pos == xrp.m_xref_pos ); } bool XRefProperties::operator !=(const XRefProperties &xrp) const { - return (! (*this == xrp)); + return (! (*this == xrp)); } diff --git a/sources/properties/xrefproperties.h b/sources/properties/xrefproperties.h index 446060f52..f32683246 100644 --- a/sources/properties/xrefproperties.h +++ b/sources/properties/xrefproperties.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef XREFPROPERTIES_H #define XREFPROPERTIES_H @@ -24,72 +24,72 @@ #include "propertiesinterface.h" /** - @brief The XRefProperties class - this class store properties used by XrefItem + @brief The XRefProperties class + this class store properties used by XrefItem */ class XRefProperties : public PropertiesInterface { - public: - XRefProperties(); + public: + XRefProperties(); - enum DisplayHas { - Cross, - Contacts - }; + enum DisplayHas { + Cross, + Contacts + }; - enum SnapTo { - Bottom, - Label - }; + enum SnapTo { + Bottom, + Label + }; - void toSettings (QSettings &settings, - const QString = QString()) const override; - void fromSettings (const QSettings &settings, - const QString = QString()) override; - QDomElement toXml (QDomDocument &xml_document) const override; - bool fromXml(const QDomElement &xml_element) override; + void toSettings (QSettings &settings, + const QString = QString()) const override; + void fromSettings (const QSettings &settings, + const QString = QString()) override; + QDomElement toXml (QDomDocument &xml_document) const override; + bool fromXml(const QDomElement &xml_element) override; - static QHash defaultProperties(); + static QHash defaultProperties(); - bool operator == (const XRefProperties &xrp) const; - bool operator != (const XRefProperties &xrp) const; + bool operator == (const XRefProperties &xrp) const; + bool operator != (const XRefProperties &xrp) const; - void setShowPowerContac (const bool a) {m_show_power_ctc = a;} - bool showPowerContact () const {return m_show_power_ctc;} + void setShowPowerContac (const bool a) {m_show_power_ctc = a;} + bool showPowerContact () const {return m_show_power_ctc;} - void setDisplayHas (const DisplayHas dh) {m_display = dh;} - DisplayHas displayHas () const {return m_display;} + void setDisplayHas (const DisplayHas dh) {m_display = dh;} + DisplayHas displayHas () const {return m_display;} - void setSnapTo (const SnapTo st) {m_snap_to = st;} - SnapTo snapTo () const {return m_snap_to;} + void setSnapTo (const SnapTo st) {m_snap_to = st;} + SnapTo snapTo () const {return m_snap_to;} - void setXrefPos(const Qt::AlignmentFlag xref) {m_xref_pos = xref;} - Qt::AlignmentFlag getXrefPos() const {return m_xref_pos;} - void setPrefix (const QString &key, const QString &value) {m_prefix.insert(key, value);} - QString prefix (const QString &key) const {return m_prefix.value(key);} + void setXrefPos(const Qt::AlignmentFlag xref) {m_xref_pos = xref;} + Qt::AlignmentFlag getXrefPos() const {return m_xref_pos;} + void setPrefix (const QString &key, const QString &value) {m_prefix.insert(key, value);} + QString prefix (const QString &key) const {return m_prefix.value(key);} - void setMasterLabel (const QString master) {m_master_label = master;} - QString masterLabel () const {return m_master_label;} + void setMasterLabel (const QString master) {m_master_label = master;} + QString masterLabel () const {return m_master_label;} - void setSlaveLabel(const QString slave) {m_slave_label = slave;} - QString slaveLabel () const {return m_slave_label;} + void setSlaveLabel(const QString slave) {m_slave_label = slave;} + QString slaveLabel () const {return m_slave_label;} - void setOffset(const int offset) {m_offset = offset;} - int offset() const {return m_offset;} + void setOffset(const int offset) {m_offset = offset;} + int offset() const {return m_offset;} - void setKey(QString& key) {m_key = key;} + void setKey(QString& key) {m_key = key;} - private: - bool m_show_power_ctc; - DisplayHas m_display; - SnapTo m_snap_to; - Qt::AlignmentFlag m_xref_pos; - QHash m_prefix; - QStringList m_prefix_keys; - QString m_master_label; - QString m_slave_label; - int m_offset; - QString m_key; + private: + bool m_show_power_ctc; + DisplayHas m_display; + SnapTo m_snap_to; + Qt::AlignmentFlag m_xref_pos; + QHash m_prefix; + QStringList m_prefix_keys; + QString m_master_label; + QString m_slave_label; + int m_offset; + QString m_key; }; #endif // XREFPROPERTIES_H diff --git a/sources/qet.cpp b/sources/qet.cpp index 23f5fe2d9..7d136cf48 100644 --- a/sources/qet.cpp +++ b/sources/qet.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "qet.h" #include "qeticons.h" @@ -28,752 +28,752 @@ #include /** - Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w") - en orientation. Si la chaine fait plusieurs caracteres, seul le - premier est pris en compte. En cas d'incoherence, Qet::North est - retourne. - @param s Chaine de caractere cense representer une orientation - @return l'orientation designee par la chaine de caractere + Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w") + en orientation. Si la chaine fait plusieurs caracteres, seul le + premier est pris en compte. En cas d'incoherence, Qet::North est + retourne. + @param s Chaine de caractere cense representer une orientation + @return l'orientation designee par la chaine de caractere */ Qet::Orientation Qet::orientationFromString(const QString &s) { - QChar c = s[0]; - if (c == 'e') return(Qet::East); - else if (c == 's') return(Qet::South); - else if (c == 'w') return (Qet::West); - else return(Qet::North); + QChar c = s[0]; + if (c == 'e') return(Qet::East); + else if (c == 's') return(Qet::South); + else if (c == 'w') return (Qet::West); + else return(Qet::North); } /** - @param o une orientation - @return une chaine de caractere representant l'orientation + @param o une orientation + @return une chaine de caractere representant l'orientation */ QString Qet::orientationToString(Qet::Orientation o) { - QString ret; - switch(o) { - case Qet::North: ret = "n"; break; - case Qet::East : ret = "e"; break; - case Qet::South: ret = "s"; break; - case Qet::West : ret = "w"; break; - } - return(ret); + QString ret; + switch(o) { + case Qet::North: ret = "n"; break; + case Qet::East : ret = "e"; break; + case Qet::South: ret = "s"; break; + case Qet::West : ret = "w"; break; + } + return(ret); } /** - Indique si deux orientations de Borne sont sur le meme axe (Vertical / Horizontal). - @param a La premiere orientation de Borne - @param b La seconde orientation de Borne - @return Un booleen a true si les deux orientations de bornes sont sur le meme axe + Indique si deux orientations de Borne sont sur le meme axe (Vertical / Horizontal). + @param a La premiere orientation de Borne + @param b La seconde orientation de Borne + @return Un booleen a true si les deux orientations de bornes sont sur le meme axe */ bool Qet::surLeMemeAxe(Qet::Orientation a, Qet::Orientation b) { - if ((a == Qet::North || a == Qet::South) && (b == Qet::North || b == Qet::South)) return(true); - else if ((a == Qet::East || a == Qet::West) && (b == Qet::East || b == Qet::West)) return(true); - else return(false); + if ((a == Qet::North || a == Qet::South) && (b == Qet::North || b == Qet::South)) return(true); + else if ((a == Qet::East || a == Qet::West) && (b == Qet::East || b == Qet::West)) return(true); + else return(false); } /** - @brief Qet::isOpposed - @param a - @param b - @return true if a and b is opposed, else false; + @brief Qet::isOpposed + @param a + @param b + @return true if a and b is opposed, else false; */ bool Qet::isOpposed(Qet::Orientation a, Qet::Orientation b) { - bool result = false; + bool result = false; - switch (a) - { - case Qet::North: - if (b == Qet::South) result = true; - break; - case Qet::East: - if (b == Qet::West) result = true; - break; - case Qet::South: - if (b == Qet::North) result = true; - break; - case Qet::West: - if (b == Qet::East) result = true; - break; - default: - break; - } + switch (a) + { + case Qet::North: + if (b == Qet::South) result = true; + break; + case Qet::East: + if (b == Qet::West) result = true; + break; + case Qet::South: + if (b == Qet::North) result = true; + break; + case Qet::West: + if (b == Qet::East) result = true; + break; + default: + break; + } - return result; + return result; } /** - @brief Qet::isHorizontal - @param a - @return true if @a is horizontal, else false. + @brief Qet::isHorizontal + @param a + @return true if @a is horizontal, else false. */ bool Qet::isHorizontal(Qet::Orientation a) { - return(a == Qet::East || a == Qet::West); + return(a == Qet::East || a == Qet::West); } /** - @brief Qet::isVertical - @param a - @return true if @a is vertical, else false. + @brief Qet::isVertical + @param a + @return true if @a is vertical, else false. */ bool Qet::isVertical(Qet::Orientation a) { - return(a == Qet::North || a == Qet::South); + return(a == Qet::North || a == Qet::South); } /** - Permet de connaitre l'orientation suivante apres celle donnee en parametre. - Les orientations sont generalement presentees dans l'ordre suivant : Nord, - Est, Sud, Ouest. - @param o une orientation - @return l'orientation suivante + Permet de connaitre l'orientation suivante apres celle donnee en parametre. + Les orientations sont generalement presentees dans l'ordre suivant : Nord, + Est, Sud, Ouest. + @param o une orientation + @return l'orientation suivante */ Qet::Orientation Qet::nextOrientation(Qet::Orientation o) { - if (o < 0 || o > 2) return(Qet::North); - return((Qet::Orientation)(o + 1)); + if (o < 0 || o > 2) return(Qet::North); + return((Qet::Orientation)(o + 1)); } /** - Permet de connaitre l'orientation precedant celle donnee en parametre. - Les orientations sont generalement presentees dans l'ordre suivant : Nord, - Est, Sud, Ouest. - @param o une orientation - @return l'orientation precedente + Permet de connaitre l'orientation precedant celle donnee en parametre. + Les orientations sont generalement presentees dans l'ordre suivant : Nord, + Est, Sud, Ouest. + @param o une orientation + @return l'orientation precedente */ Qet::Orientation Qet::previousOrientation(Qet::Orientation o) { - if (o < 0 || o > 3) return(Qet::North); - if (o == Qet::North) return(Qet::West); - return((Qet::Orientation)(o - 1)); + if (o < 0 || o > 3) return(Qet::North); + if (o == Qet::North) return(Qet::West); + return((Qet::Orientation)(o - 1)); } /** - @param line Un segment de droite - @param point Un point - @return true si le point appartient au segment de droite, false sinon + @param line Un segment de droite + @param point Un point + @return true si le point appartient au segment de droite, false sinon */ bool QET::lineContainsPoint(const QLineF &line, const QPointF &point) { - if (point == line.p1()) return(true); - QLineF point_line(line.p1(), point); - if (point_line.unitVector() != line.unitVector()) return(false); - return(point_line.length() <= line.length()); + if (point == line.p1()) return(true); + QLineF point_line(line.p1(), point); + if (point_line.unitVector() != line.unitVector()) return(false); + return(point_line.length() <= line.length()); } /** - @param point Un point donne - @param line Un segment de droite donnee - @param intersection si ce pointeur est different de 0, le QPointF ainsi - designe contiendra les coordonnees du projete orthogonal, meme si celui-ci - n'appartient pas au segment de droite - @return true si le projete orthogonal du point sur la droite appartient au - segment de droite. + @param point Un point donne + @param line Un segment de droite donnee + @param intersection si ce pointeur est different de 0, le QPointF ainsi + designe contiendra les coordonnees du projete orthogonal, meme si celui-ci + n'appartient pas au segment de droite + @return true si le projete orthogonal du point sur la droite appartient au + segment de droite. */ bool QET::orthogonalProjection( - const QPointF &point,const QLineF &line,QPointF *intersection) + const QPointF &point,const QLineF &line,QPointF *intersection) { - // recupere le vecteur normal de `line' - QLineF line_normal_vector(line.normalVector()); - QPointF normal_vector(line_normal_vector.dx(), line_normal_vector.dy()); + // recupere le vecteur normal de `line' + QLineF line_normal_vector(line.normalVector()); + QPointF normal_vector(line_normal_vector.dx(), line_normal_vector.dy()); - // cree une droite perpendiculaire a `line' passant par `point' - QLineF perpendicular_line(point, point + normal_vector); + // cree une droite perpendiculaire a `line' passant par `point' + QLineF perpendicular_line(point, point + normal_vector); - // determine le point d'intersection des deux droites = le projete orthogonal - QPointF intersection_point; + // determine le point d'intersection des deux droites = le projete orthogonal + QPointF intersection_point; #if TODO_LIST #pragma message("@TODO remove code for QT 5.14 or later") #endif - QLineF::IntersectType it = line. + QLineF::IntersectType it = line. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - intersect // ### Qt 6: remove + intersect // ### Qt 6: remove #else - intersects + intersects #endif - (perpendicular_line, &intersection_point); + (perpendicular_line, &intersection_point); - // ne devrait pas arriver (mais bon...) - if (it == QLineF::NoIntersection) return(false); + // ne devrait pas arriver (mais bon...) + if (it == QLineF::NoIntersection) return(false); - // fournit le point d'intersection a l'appelant si necessaire - if (intersection) { - *intersection = intersection_point; - } + // fournit le point d'intersection a l'appelant si necessaire + if (intersection) { + *intersection = intersection_point; + } - // determine si le point d'intersection appartient au segment de droite - if (QET::lineContainsPoint(line, intersection_point)) { - return(true); - } - return(false); + // determine si le point d'intersection appartient au segment de droite + if (QET::lineContainsPoint(line, intersection_point)) { + return(true); + } + return(false); } /** - Permet de savoir si l'attribut nom_attribut d'un element XML e est bien un - entier. Si oui, sa valeur est copiee dans entier. - @param e Element XML - @param nom_attribut Nom de l'attribut a analyser - @param entier Pointeur facultatif vers un entier - @return true si l'attribut est bien un entier, false sinon + Permet de savoir si l'attribut nom_attribut d'un element XML e est bien un + entier. Si oui, sa valeur est copiee dans entier. + @param e Element XML + @param nom_attribut Nom de l'attribut a analyser + @param entier Pointeur facultatif vers un entier + @return true si l'attribut est bien un entier, false sinon */ bool QET::attributeIsAnInteger( - const QDomElement &e,const QString& nom_attribut,int *entier) + const QDomElement &e,const QString& nom_attribut,int *entier) { - // verifie la presence de l'attribut - if (!e.hasAttribute(nom_attribut)) return(false); - // verifie la validite de l'attribut - bool ok; - int tmp = e.attribute(nom_attribut).toInt(&ok); - if (!ok) return(false); - if (entier != nullptr) *entier = tmp; - return(true); + // verifie la presence de l'attribut + if (!e.hasAttribute(nom_attribut)) return(false); + // verifie la validite de l'attribut + bool ok; + int tmp = e.attribute(nom_attribut).toInt(&ok); + if (!ok) return(false); + if (entier != nullptr) *entier = tmp; + return(true); } /** - Permet de savoir si l'attribut nom_attribut d'un element XML e est bien un - reel. Si oui, sa valeur est copiee dans reel. - @param e Element XML - @param nom_attribut Nom de l'attribut a analyser - @param reel Pointeur facultatif vers un double - @return true si l'attribut est bien un reel, false sinon + Permet de savoir si l'attribut nom_attribut d'un element XML e est bien un + reel. Si oui, sa valeur est copiee dans reel. + @param e Element XML + @param nom_attribut Nom de l'attribut a analyser + @param reel Pointeur facultatif vers un double + @return true si l'attribut est bien un reel, false sinon */ bool QET::attributeIsAReal( - const QDomElement &e,const QString& nom_attribut,qreal *reel) + const QDomElement &e,const QString& nom_attribut,qreal *reel) { - // verifie la presence de l'attribut - if (!e.hasAttribute(nom_attribut)) return(false); - // verifie la validite de l'attribut - bool ok; - qreal tmp = e.attribute(nom_attribut).toDouble(&ok); - if (!ok) return(false); - if (reel != nullptr) *reel = tmp; - return(true); + // verifie la presence de l'attribut + if (!e.hasAttribute(nom_attribut)) return(false); + // verifie la validite de l'attribut + bool ok; + qreal tmp = e.attribute(nom_attribut).toDouble(&ok); + if (!ok) return(false); + if (reel != nullptr) *reel = tmp; + return(true); } /** - @brief QET::ElementsAndConductorsSentence - Permet de composer rapidement la proposition "x elements et y conducteurs" - ou encore "x elements, y conducteurs et z champs de texte". - @param elements_count nombre d'elements - @param conductors_count nombre de conducteurs - @param texts_count nombre de champs de texte - @param images_count nombre d'images - @param shapes_count - @param element_text_count - @param tables_count - @return la proposition decrivant le nombre d'elements, de conducteurs et de - textes + @brief QET::ElementsAndConductorsSentence + Permet de composer rapidement la proposition "x elements et y conducteurs" + ou encore "x elements, y conducteurs et z champs de texte". + @param elements_count nombre d'elements + @param conductors_count nombre de conducteurs + @param texts_count nombre de champs de texte + @param images_count nombre d'images + @param shapes_count + @param element_text_count + @param tables_count + @return la proposition decrivant le nombre d'elements, de conducteurs et de + textes */ QString QET::ElementsAndConductorsSentence( - int elements_count, - int conductors_count, - int texts_count, - int images_count, - int shapes_count, - int element_text_count, - int tables_count) + int elements_count, + int conductors_count, + int texts_count, + int images_count, + int shapes_count, + int element_text_count, + int tables_count) { - QString text; - if (elements_count) { - text += QObject::tr( - "%n élément(s)", - "part of a sentence listing the content of a diagram", - elements_count - ); - } + QString text; + if (elements_count) { + text += QObject::tr( + "%n élément(s)", + "part of a sentence listing the content of a diagram", + elements_count + ); + } - if (conductors_count) { - if (!text.isEmpty()) text += ", "; - text += QObject::tr( - "%n conducteur(s)", - "part of a sentence listing the content of a diagram", - conductors_count - ); - } + if (conductors_count) { + if (!text.isEmpty()) text += ", "; + text += QObject::tr( + "%n conducteur(s)", + "part of a sentence listing the content of a diagram", + conductors_count + ); + } - if (texts_count) { - if (!text.isEmpty()) text += ", "; - text += QObject::tr( - "%n champ(s) de texte", - "part of a sentence listing the content of a diagram", - texts_count - ); - } + if (texts_count) { + if (!text.isEmpty()) text += ", "; + text += QObject::tr( + "%n champ(s) de texte", + "part of a sentence listing the content of a diagram", + texts_count + ); + } - if (images_count) { - if (!text.isEmpty()) text += ", "; - text += QObject::tr( - "%n image(s)", - "part of a sentence listing the content of a diagram", - images_count - ); - } + if (images_count) { + if (!text.isEmpty()) text += ", "; + text += QObject::tr( + "%n image(s)", + "part of a sentence listing the content of a diagram", + images_count + ); + } - if (shapes_count) { - if (!text.isEmpty()) text += ", "; - text += QObject::tr( - "%n forme(s)", - "part of a sentence listing the content of a diagram", - shapes_count - ); - } + if (shapes_count) { + if (!text.isEmpty()) text += ", "; + text += QObject::tr( + "%n forme(s)", + "part of a sentence listing the content of a diagram", + shapes_count + ); + } - if (element_text_count) { - if (!text.isEmpty()) text += ", "; - text += QObject::tr( - "%n texte(s) d'élément", - "part of a sentence listing the content of a diagram", - element_text_count); - } + if (element_text_count) { + if (!text.isEmpty()) text += ", "; + text += QObject::tr( + "%n texte(s) d'élément", + "part of a sentence listing the content of a diagram", + element_text_count); + } - if (tables_count) { - if (!text.isEmpty()) text += ", "; - text += QObject::tr( - "%n tableau(s)", - "part of a sentence listing the content of diagram", - tables_count); - } + if (tables_count) { + if (!text.isEmpty()) text += ", "; + text += QObject::tr( + "%n tableau(s)", + "part of a sentence listing the content of diagram", + tables_count); + } - return(text); + return(text); } /** - @return the list of \a tag_name elements directly under the \a e XML element. + @return the list of \a tag_name elements directly under the \a e XML element. */ QList QET::findInDomElement( - const QDomElement &e, const QString &tag_name) + const QDomElement &e, const QString &tag_name) { - QList return_list; - for (QDomNode node = e.firstChild() ; - !node.isNull() ; - node = node.nextSibling()) - { - if (!node.isElement()) continue; - QDomElement element = node.toElement(); - if (element.isNull() || element.tagName() != tag_name) continue; - return_list << element; - } - return(return_list); + QList return_list; + for (QDomNode node = e.firstChild() ; + !node.isNull() ; + node = node.nextSibling()) + { + if (!node.isElement()) continue; + QDomElement element = node.toElement(); + if (element.isNull() || element.tagName() != tag_name) continue; + return_list << element; + } + return(return_list); } /** - Etant donne un element XML e, renvoie la liste de tous les elements - children imbriques dans les elements parent, eux-memes enfants de l'elememt e - @param e Element XML a explorer - @param parent tag XML intermediaire - @param children tag XML a rechercher - @return La liste des elements XML children + Etant donne un element XML e, renvoie la liste de tous les elements + children imbriques dans les elements parent, eux-memes enfants de l'elememt e + @param e Element XML a explorer + @param parent tag XML intermediaire + @param children tag XML a rechercher + @return La liste des elements XML children */ QList QET::findInDomElement( - const QDomElement &e,const QString &parent,const QString &children) + const QDomElement &e,const QString &parent,const QString &children) { - QList return_list; + QList return_list; - // parcours des elements parents - for (QDomNode enfant = e.firstChild() ; - !enfant.isNull() ; - enfant = enfant.nextSibling()) - { - // on s'interesse a l'element XML "parent" - QDomElement parents = enfant.toElement(); - if (parents.isNull() || parents.tagName() != parent) continue; - // parcours des enfants de l'element XML "parent" - for (QDomNode node_children = parents.firstChild() ; - !node_children.isNull() ; - node_children = node_children.nextSibling()) - { - // on s'interesse a l'element XML "children" - QDomElement n_children = node_children.toElement(); - if (!n_children.isNull() && n_children.tagName() == children) return_list.append(n_children); - } - } - return(return_list); + // parcours des elements parents + for (QDomNode enfant = e.firstChild() ; + !enfant.isNull() ; + enfant = enfant.nextSibling()) + { + // on s'interesse a l'element XML "parent" + QDomElement parents = enfant.toElement(); + if (parents.isNull() || parents.tagName() != parent) continue; + // parcours des enfants de l'element XML "parent" + for (QDomNode node_children = parents.firstChild() ; + !node_children.isNull() ; + node_children = node_children.nextSibling()) + { + // on s'interesse a l'element XML "children" + QDomElement n_children = node_children.toElement(); + if (!n_children.isNull() && n_children.tagName() == children) return_list.append(n_children); + } + } + return(return_list); } /// @return le texte de la licence de QElectroTech (GNU/GPL) QString QET::license() { - // Recuperation du texte de la GNU/GPL dans un fichier integre a l'application - QFile *file_license = new QFile(":/LICENSE"); - QString txt_license; - // verifie que le fichier existe - if (!file_license -> exists()) { - txt_license = QString(QObject::tr("Le fichier texte contenant la licence GNU/GPL est introuvable - bon bah de toute façon, vous la connaissez par coeur non ?")); - } else { - // ouvre le fichier en mode texte et en lecture seule - if (!file_license -> open(QIODevice::ReadOnly | QIODevice::Text)) { - txt_license = QString(QObject::tr("Le fichier texte contenant la licence GNU/GPL existe mais n'a pas pu être ouvert - bon bah de toute façon, vous la connaissez par coeur non ?")); - } else { - // charge le contenu du fichier dans une QString - QTextStream in(file_license); - txt_license = QString(""); - while (!in.atEnd()) txt_license += in.readLine()+"\n"; - // ferme le fichier - file_license -> close(); - } - } - return(txt_license); + // Recuperation du texte de la GNU/GPL dans un fichier integre a l'application + QFile *file_license = new QFile(":/LICENSE"); + QString txt_license; + // verifie que le fichier existe + if (!file_license -> exists()) { + txt_license = QString(QObject::tr("Le fichier texte contenant la licence GNU/GPL est introuvable - bon bah de toute façon, vous la connaissez par coeur non ?")); + } else { + // ouvre le fichier en mode texte et en lecture seule + if (!file_license -> open(QIODevice::ReadOnly | QIODevice::Text)) { + txt_license = QString(QObject::tr("Le fichier texte contenant la licence GNU/GPL existe mais n'a pas pu être ouvert - bon bah de toute façon, vous la connaissez par coeur non ?")); + } else { + // charge le contenu du fichier dans une QString + QTextStream in(file_license); + txt_license = QString(""); + while (!in.atEnd()) txt_license += in.readLine()+"\n"; + // ferme le fichier + file_license -> close(); + } + } + return(txt_license); }; /** - @return la liste des caracteres interdits dans les noms de fichiers sous - Windows + @return la liste des caracteres interdits dans les noms de fichiers sous + Windows */ QList QET::forbiddenCharacters() { - return(QList() - << '\\' << '/' << ':' << '*' << '?' << '"'<< '<' << '>' << '|'); + return(QList() + << '\\' << '/' << ':' << '*' << '?' << '"'<< '<' << '>' << '|'); } /** - Cette fonction transforme une chaine de caracteres (typiquement : un nom de - schema, de projet, d'element) en un nom de fichier potable. - Par nom de fichier potable, on entend un nom : - * ne comprenant pas de caracteres interdits sous Windows - * ne comprenant pas d'espace - @param name Chaine de caractere a transformer en nom de fichier potable - @todo virer les caracteres accentues ? + Cette fonction transforme une chaine de caracteres (typiquement : un nom de + schema, de projet, d'element) en un nom de fichier potable. + Par nom de fichier potable, on entend un nom : + * ne comprenant pas de caracteres interdits sous Windows + * ne comprenant pas d'espace + @param name Chaine de caractere a transformer en nom de fichier potable + @todo virer les caracteres accentues ? */ QString QET::stringToFileName(const QString &name) { #if TODO_LIST #pragma message("@TODO virer les caracteres accentues ?") #endif - QString file_name(name.toLower()); + QString file_name(name.toLower()); - // remplace les caracteres interdits par des tirets - foreach(QChar c, QET::forbiddenCharacters()) { - file_name.replace(c, '-'); - } + // remplace les caracteres interdits par des tirets + foreach(QChar c, QET::forbiddenCharacters()) { + file_name.replace(c, '-'); + } - // remplace les espaces par des underscores - file_name.replace(' ', '_'); + // remplace les espaces par des underscores + file_name.replace(' ', '_'); - return(file_name); + return(file_name); } /** - @param string une chaine de caracteres - @return la meme chaine de caracteres, mais avec les espaces et backslashes - echappes + @param string une chaine de caracteres + @return la meme chaine de caracteres, mais avec les espaces et backslashes + echappes */ QString QET::escapeSpaces(const QString &string) { - return(QString(string).replace('\\', "\\\\").replace(' ', "\\ ")); + return(QString(string).replace('\\', "\\\\").replace(' ', "\\ ")); } /** - @param string une chaine de caracteres - @return la meme chaine de caracteres, mais avec les espaces et backslashes - non echappes + @param string une chaine de caracteres + @return la meme chaine de caracteres, mais avec les espaces et backslashes + non echappes */ QString QET::unescapeSpaces(const QString &string) { - return(QString(string).replace("\\\\", "\\").replace("\\ ", " ")); + return(QString(string).replace("\\\\", "\\").replace("\\ ", " ")); } /** - Assemble une liste de chaines en une seule. Un espace separe chaque chaine. - Les espaces et backslashes des chaines sont echappes. - @param string_list une liste de chaine - @return l'assemblage des chaines + Assemble une liste de chaines en une seule. Un espace separe chaque chaine. + Les espaces et backslashes des chaines sont echappes. + @param string_list une liste de chaine + @return l'assemblage des chaines */ QString QET::joinWithSpaces(const QStringList &string_list) { - QString returned_string; + QString returned_string; - for (int i = 0 ; i < string_list.count() ; ++ i) { - returned_string += QET::escapeSpaces(string_list.at(i)); - if (i != string_list.count() - 1) returned_string += " "; - } + for (int i = 0 ; i < string_list.count() ; ++ i) { + returned_string += QET::escapeSpaces(string_list.at(i)); + if (i != string_list.count() - 1) returned_string += " "; + } - return(returned_string); + return(returned_string); } /** - @param string Une chaine de caracteres contenant des sous-chaines a - extraire separees par des espaces non echappes. Les espaces des sous-chaines - sont echappes. - @return La liste des sous-chaines, sans echappement. + @param string Une chaine de caracteres contenant des sous-chaines a + extraire separees par des espaces non echappes. Les espaces des sous-chaines + sont echappes. + @return La liste des sous-chaines, sans echappement. */ QStringList QET::splitWithSpaces(const QString &string) { - // les chaines sont separees par des espaces non echappes - // = avec un nombre nul ou pair de backslashes devant + // les chaines sont separees par des espaces non echappes + // = avec un nombre nul ou pair de backslashes devant #if TODO_LIST #pragma message("@TODO remove code for QT 5.14 or later") #endif - QStringList escaped_strings = string.split(QRegularExpression("[^\\]?(?:\\\\)* "), -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove - QString + QStringList escaped_strings = string.split(QRegularExpression("[^\\]?(?:\\\\)* "), +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove + QString #else - Qt + Qt #endif - ::SkipEmptyParts); + ::SkipEmptyParts); - QStringList returned_list; - foreach(QString escaped_string, escaped_strings) { - returned_list << QET::unescapeSpaces(escaped_string); - } - return(returned_list); + QStringList returned_list; + foreach(QString escaped_string, escaped_strings) { + returned_list << QET::unescapeSpaces(escaped_string); + } + return(returned_list); } /** - @param end_type un type d'extremite - @return une chaine representant le type d'extremite + @param end_type un type d'extremite + @return une chaine representant le type d'extremite */ QString Qet::endTypeToString(const Qet::EndType &end_type) { - switch(end_type) { - case Qet::Simple: return("simple"); - case Qet::Triangle: return("triangle"); - case Qet::Circle: return("circle"); - case Qet::Diamond: return("diamond"); - case Qet::None: - default: - return("none"); - } + switch(end_type) { + case Qet::Simple: return("simple"); + case Qet::Triangle: return("triangle"); + case Qet::Circle: return("circle"); + case Qet::Diamond: return("diamond"); + case Qet::None: + default: + return("none"); + } } /** - @param string une chaine representant un type d'extremite - @return le type d'extremite correspondant ; si la chaine est invalide, - QET::None est retourne. + @param string une chaine representant un type d'extremite + @return le type d'extremite correspondant ; si la chaine est invalide, + QET::None est retourne. */ Qet::EndType Qet::endTypeFromString(const QString &string) { - if (string == "simple") return(Qet::Simple); - else if (string == "triangle") return(Qet::Triangle); - else if (string == "circle") return(Qet::Circle); - else if (string == "diamond") return(Qet::Diamond); - else return(Qet::None); + if (string == "simple") return(Qet::Simple); + else if (string == "triangle") return(Qet::Triangle); + else if (string == "circle") return(Qet::Circle); + else if (string == "diamond") return(Qet::Diamond); + else return(Qet::None); } /** - @param diagram_area un type de zone de schema - @return une chaine representant le type de zone de schema + @param diagram_area un type de zone de schema + @return une chaine representant le type de zone de schema */ QString QET::diagramAreaToString(const QET::DiagramArea &diagram_area) { - if (diagram_area == ElementsArea) return("elements"); - else return("border"); + if (diagram_area == ElementsArea) return("elements"); + else return("border"); } /** - @param string une chaine representant un type de zone de schema - @return le type de zone de schema correspondant ; si la chaine est invalide, - QET::ElementsArea est retourne. + @param string une chaine representant un type de zone de schema + @return le type de zone de schema correspondant ; si la chaine est invalide, + QET::ElementsArea est retourne. */ QET::DiagramArea QET::diagramAreaFromString(const QString &string) { - if (!string.compare("border", Qt::CaseInsensitive)) return(QET::BorderArea); - else return(QET::ElementsArea); + if (!string.compare("border", Qt::CaseInsensitive)) return(QET::BorderArea); + else return(QET::ElementsArea); } /** - Round \a x to the nearest multiple of the invert of \a epsilon. - For instance, epsilon = 10 will round to 1/10 = 0.1 + Round \a x to the nearest multiple of the invert of \a epsilon. + For instance, epsilon = 10 will round to 1/10 = 0.1 */ qreal QET::round(qreal x, qreal epsilon) { - return(int(x * epsilon) / epsilon); + return(int(x * epsilon) / epsilon); } /** - @param angle Un angle quelconque - @return l'angle passe en parametre, mais ramene entre -360.0 + 360.0 degres + @param angle Un angle quelconque + @return l'angle passe en parametre, mais ramene entre -360.0 + 360.0 degres */ qreal QET::correctAngle(const qreal &angle) { - // ramene l'angle demande entre -360.0 et +360.0 degres - qreal corrected_angle = angle; - while (corrected_angle <= -360.0) corrected_angle += 360.0; - while (corrected_angle >= 360.0) corrected_angle -= 360.0; - return(corrected_angle); + // ramene l'angle demande entre -360.0 et +360.0 degres + qreal corrected_angle = angle; + while (corrected_angle <= -360.0) corrected_angle += 360.0; + while (corrected_angle >= 360.0) corrected_angle -= 360.0; + return(corrected_angle); } /** - @param first Un premier chemin vers un fichier - @param second Un second chemin vers un fichier - @return true si les deux chemins existent existent et sont identiques - lorsqu'ils sont exprimes sous forme canonique + @param first Un premier chemin vers un fichier + @param second Un second chemin vers un fichier + @return true si les deux chemins existent existent et sont identiques + lorsqu'ils sont exprimes sous forme canonique */ bool QET::compareCanonicalFilePaths(const QString &first, const QString &second) { - QString first_canonical_path = QFileInfo(first).canonicalFilePath(); - if (first_canonical_path.isEmpty()) return(false); + QString first_canonical_path = QFileInfo(first).canonicalFilePath(); + if (first_canonical_path.isEmpty()) return(false); - QString second_canonical_path = QFileInfo(second).canonicalFilePath(); - if (second_canonical_path.isEmpty()) return(false); + QString second_canonical_path = QFileInfo(second).canonicalFilePath(); + if (second_canonical_path.isEmpty()) return(false); #ifdef Q_OS_WIN - // sous Windows, on ramene les chemins en minuscules - first_canonical_path = first_canonical_path.toLower(); - second_canonical_path = second_canonical_path.toLower(); + // sous Windows, on ramene les chemins en minuscules + first_canonical_path = first_canonical_path.toLower(); + second_canonical_path = second_canonical_path.toLower(); #endif - return(first_canonical_path == second_canonical_path); + return(first_canonical_path == second_canonical_path); } /** - Export an XML document to an UTF-8 text file indented with 4 spaces, with LF - end of lines and no BOM. - @param xml_doc An XML document to be exported - @param filepath Path to the file to be written - @param error_message If non-zero, will contain an error message explaining - what happened when this function returns false. - @return false if an error occurred, true otherwise + Export an XML document to an UTF-8 text file indented with 4 spaces, with LF + end of lines and no BOM. + @param xml_doc An XML document to be exported + @param filepath Path to the file to be written + @param error_message If non-zero, will contain an error message explaining + what happened when this function returns false. + @return false if an error occurred, true otherwise */ bool QET::writeXmlFile(QDomDocument &xml_doc, const QString &filepath, QString *error_message) { - QSaveFile file(filepath); + QSaveFile file(filepath); - // Note: we do not set QIODevice::Text to avoid generating CRLF end of lines - bool file_opening = file.open(QIODevice::WriteOnly); - if (!file_opening) - { - if (error_message) - { - *error_message = QString(QObject::tr( - "Impossible d'ouvrir le fichier %1 en écriture, erreur %2 rencontrée.", - "error message when attempting to write an XML file")).arg(filepath).arg(file.error()); - } - return(false); - } + // Note: we do not set QIODevice::Text to avoid generating CRLF end of lines + bool file_opening = file.open(QIODevice::WriteOnly); + if (!file_opening) + { + if (error_message) + { + *error_message = QString(QObject::tr( + "Impossible d'ouvrir le fichier %1 en écriture, erreur %2 rencontrée.", + "error message when attempting to write an XML file")).arg(filepath).arg(file.error()); + } + return(false); + } - QTextStream out(&file); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - out.setCodec("UTF-8"); + QTextStream out(&file); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + out.setCodec("UTF-8"); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - out.setEncoding(QStringConverter::Utf8); + out.setEncoding(QStringConverter::Utf8); #endif - out.setGenerateByteOrderMark(false); - out << xml_doc.toString(4); - if (!file.commit()) - { - if (error_message) { - *error_message = QString(QObject::tr( - "Une erreur est survenue lors de l'écriture du fichier %1, erreur %2 rencontrée.", - "error message when attempting to write an XML file")).arg(filepath).arg(file.error()); - } + out.setGenerateByteOrderMark(false); + out << xml_doc.toString(4); + if (!file.commit()) + { + if (error_message) { + *error_message = QString(QObject::tr( + "Une erreur est survenue lors de l'écriture du fichier %1, erreur %2 rencontrée.", + "error message when attempting to write an XML file")).arg(filepath).arg(file.error()); + } - return false; - } + return false; + } - return(true); + return(true); } /** - @brief QET::eachStrIsEqual - @param qsl list of string to compare - @return true if every string is identical, else false; - The list must not be empty - If the list can be empty, call isEmpty() before calling this function + @brief QET::eachStrIsEqual + @param qsl list of string to compare + @return true if every string is identical, else false; + The list must not be empty + If the list can be empty, call isEmpty() before calling this function */ bool QET::eachStrIsEqual(const QStringList &qsl) { - if (qsl.size() == 1) return true; - foreach (const QString t, qsl) { - if (qsl.at(0) != t) return false; - } - return true; + if (qsl.size() == 1) return true; + foreach (const QString t, qsl) { + if (qsl.at(0) != t) return false; + } + return true; } /** - @brief QET::qetCollectionToString - @param c QetCollection value to convert - @return The QetCollection enum value converted to a QString + @brief QET::qetCollectionToString + @param c QetCollection value to convert + @return The QetCollection enum value converted to a QString */ QString QET::qetCollectionToString(const QET::QetCollection &c) { - switch (c) - { - case Common : - return "common"; - case Custom : - return "custom"; - case Embedded : - return "embedded"; - default: - return "common"; - } + switch (c) + { + case Common : + return "common"; + case Custom : + return "custom"; + case Embedded : + return "embedded"; + default: + return "common"; + } } /** - @brief QET::qetCollectionFromString - @param str string to convert - @return The corresponding QetCollection value from a string. - If the string don't match anything, we return the failsafe value QetCollection::Common + @brief QET::qetCollectionFromString + @param str string to convert + @return The corresponding QetCollection value from a string. + If the string don't match anything, we return the failsafe value QetCollection::Common */ QET::QetCollection QET::qetCollectionFromString(const QString &str) { - if (str == "common") - return QetCollection::Common; - else if (str == "custom") - return QetCollection::Custom; - else if (str == "embedded") - return QetCollection::Embedded; - else - return QetCollection::Common; + if (str == "common") + return QetCollection::Common; + else if (str == "custom") + return QetCollection::Custom; + else if (str == "embedded") + return QetCollection::Embedded; + else + return QetCollection::Common; } /** - @brief QET::depthActionGroup - @param parent - @return an action group which contain 4 actions (forward, raise, lower, backward) - already made with icon, shortcut and data (see QET::DepthOption) + @brief QET::depthActionGroup + @param parent + @return an action group which contain 4 actions (forward, raise, lower, backward) + already made with icon, shortcut and data (see QET::DepthOption) */ QActionGroup *QET::depthActionGroup(QObject *parent) { - QActionGroup *action_group = new QActionGroup(parent); + QActionGroup *action_group = new QActionGroup(parent); - QAction *edit_forward = new QAction(QET::Icons::BringForward, QObject::tr("Amener au premier plan"), action_group); - QAction *edit_raise = new QAction(QET::Icons::Raise, QObject::tr("Rapprocher"), action_group); - QAction *edit_lower = new QAction(QET::Icons::Lower, QObject::tr("Éloigner"), action_group); - QAction *edit_backward = new QAction(QET::Icons::SendBackward, QObject::tr("Envoyer au fond"), action_group); + QAction *edit_forward = new QAction(QET::Icons::BringForward, QObject::tr("Amener au premier plan"), action_group); + QAction *edit_raise = new QAction(QET::Icons::Raise, QObject::tr("Rapprocher"), action_group); + QAction *edit_lower = new QAction(QET::Icons::Lower, QObject::tr("Éloigner"), action_group); + QAction *edit_backward = new QAction(QET::Icons::SendBackward, QObject::tr("Envoyer au fond"), action_group); - edit_forward ->setStatusTip(QObject::tr("Ramène la ou les sélections au premier plan")); - edit_raise ->setStatusTip(QObject::tr("Rapproche la ou les sélections")); - edit_lower ->setStatusTip(QObject::tr("Éloigne la ou les sélections")); - edit_backward->setStatusTip(QObject::tr("Envoie en arrière plan la ou les sélections")); + edit_forward ->setStatusTip(QObject::tr("Ramène la ou les sélections au premier plan")); + edit_raise ->setStatusTip(QObject::tr("Rapproche la ou les sélections")); + edit_lower ->setStatusTip(QObject::tr("Éloigne la ou les sélections")); + edit_backward->setStatusTip(QObject::tr("Envoie en arrière plan la ou les sélections")); - edit_raise ->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+Up"))); - edit_lower ->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+Down"))); - edit_backward->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+End"))); - edit_forward ->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+Home"))); + edit_raise ->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+Up"))); + edit_lower ->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+Down"))); + edit_backward->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+End"))); + edit_forward ->setShortcut(QKeySequence(QObject::tr("Ctrl+Shift+Home"))); - edit_forward ->setData(QET::BringForward); - edit_raise ->setData(QET::Raise); - edit_lower ->setData(QET::Lower); - edit_backward->setData(QET::SendBackward); + edit_forward ->setData(QET::BringForward); + edit_raise ->setData(QET::Raise); + edit_lower ->setData(QET::Lower); + edit_backward->setData(QET::SendBackward); - return action_group; + return action_group; } bool QET::writeToFile(QDomDocument &xml_doc, QFile *file, QString *error_message) { - bool opened_here = file->isOpen() ? false : true; + bool opened_here = file->isOpen() ? false : true; - if (!file->isOpen()) - { - bool open_ = file->open(QIODevice::WriteOnly); - if (!open_) - { - if (error_message) - { - QFileInfo info_(*file); - *error_message = QString( - QObject::tr( - "Impossible d'ouvrir le fichier %1 en écriture, erreur %2 rencontrée.", - "error message when attempting to write an XML file") - ).arg(info_.absoluteFilePath()).arg(file->error()); - } - return false; - } - } + if (!file->isOpen()) + { + bool open_ = file->open(QIODevice::WriteOnly); + if (!open_) + { + if (error_message) + { + QFileInfo info_(*file); + *error_message = QString( + QObject::tr( + "Impossible d'ouvrir le fichier %1 en écriture, erreur %2 rencontrée.", + "error message when attempting to write an XML file") + ).arg(info_.absoluteFilePath()).arg(file->error()); + } + return false; + } + } - QTextStream out(file); - out.seek(0); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - out.setCodec("UTF-8"); + QTextStream out(file); + out.seek(0); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + out.setCodec("UTF-8"); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - out.setEncoding(QStringConverter::Utf8); + out.setEncoding(QStringConverter::Utf8); #endif - out.setGenerateByteOrderMark(false); - out << xml_doc.toString(4); - if (opened_here) { - file->close(); - } + out.setGenerateByteOrderMark(false); + out << xml_doc.toString(4); + if (opened_here) { + file->close(); + } - return(true); + return(true); } diff --git a/sources/qetgraphicsitem/conductor.cpp b/sources/qetgraphicsitem/conductor.cpp index b77fa014f..e79671d8e 100644 --- a/sources/qetgraphicsitem/conductor.cpp +++ b/sources/qetgraphicsitem/conductor.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include #include @@ -41,2032 +41,2032 @@ QBrush Conductor::conductor_brush = QBrush(); class ConductorXmlRetroCompatibility { - friend class Conductor; + friend class Conductor; - static void loadSequential(const QDomElement &dom_element, const QString& seq, QStringList* list) - { - int i = 0; - while (!dom_element.attribute(seq + QString::number(i+1)).isEmpty()) - { - list->append(dom_element.attribute(seq + QString::number(i+1))); - i++; - } - } + static void loadSequential(const QDomElement &dom_element, const QString& seq, QStringList* list) + { + int i = 0; + while (!dom_element.attribute(seq + QString::number(i+1)).isEmpty()) + { + list->append(dom_element.attribute(seq + QString::number(i+1))); + i++; + } + } - static void loadSequential(const QDomElement &dom_element, Conductor *conductor) - { - autonum::sequentialNumbers sn; + static void loadSequential(const QDomElement &dom_element, Conductor *conductor) + { + autonum::sequentialNumbers sn; - loadSequential(dom_element,"sequ_",&sn.unit); - loadSequential(dom_element,"sequf_",&sn.unit_folio); - loadSequential(dom_element,"seqt_",&sn.ten); - loadSequential(dom_element,"seqtf_",&sn.ten_folio); - loadSequential(dom_element,"seqh_",&sn.hundred); - loadSequential(dom_element,"seqhf_",&sn.hundred_folio); + loadSequential(dom_element,"sequ_",&sn.unit); + loadSequential(dom_element,"sequf_",&sn.unit_folio); + loadSequential(dom_element,"seqt_",&sn.ten); + loadSequential(dom_element,"seqtf_",&sn.ten_folio); + loadSequential(dom_element,"seqh_",&sn.hundred); + loadSequential(dom_element,"seqhf_",&sn.hundred_folio); - conductor->rSequenceNum() = sn; - } + conductor->rSequenceNum() = sn; + } }; /** - @brief Conductor::Conductor - Default constructor. - @param p1 : first terminal of this conductor. - @param p2 : second terminal of this conductor. + @brief Conductor::Conductor + Default constructor. + @param p1 : first terminal of this conductor. + @param p2 : second terminal of this conductor. */ Conductor::Conductor(Terminal *p1, Terminal* p2) : - terminal1(p1), - terminal2(p2), - m_mouse_over(false), - m_text_item(nullptr), - segments(nullptr), - m_moving_segment(false), - modified_path(false), - has_to_save_profile(false), - must_highlight_(Conductor::None) + terminal1(p1), + terminal2(p2), + m_mouse_over(false), + m_text_item(nullptr), + segments(nullptr), + m_moving_segment(false), + modified_path(false), + has_to_save_profile(false), + must_highlight_(Conductor::None) { - //set Zvalue at 11 to be upper than the DiagramImageItem and element - setZValue(11); - m_previous_z_value = zValue(); + //set Zvalue at 11 to be upper than the DiagramImageItem and element + setZValue(11); + m_previous_z_value = zValue(); - //Add this conductor to the list of conductor of each of the two terminal - bool ajout_p1 = terminal1 -> addConductor(this); - bool ajout_p2 = terminal2 -> addConductor(this); - //m_valid become false if the conductor can't be added to terminal (conductor already exist) - m_valid = (!ajout_p1 || !ajout_p2) ? false : true; + //Add this conductor to the list of conductor of each of the two terminal + bool ajout_p1 = terminal1 -> addConductor(this); + bool ajout_p2 = terminal2 -> addConductor(this); + //m_valid become false if the conductor can't be added to terminal (conductor already exist) + m_valid = (!ajout_p1 || !ajout_p2) ? false : true; - //Default attribut for paint a conductor - if (!pen_and_brush_initialized) - { - conductor_pen.setJoinStyle(Qt::MiterJoin); - conductor_pen.setCapStyle(Qt::SquareCap); - conductor_pen.setColor(Qt::black); - conductor_pen.setStyle(Qt::SolidLine); - conductor_pen.setWidthF(1.0); - conductor_brush.setColor(Qt::white); - conductor_brush.setStyle(Qt::NoBrush); - pen_and_brush_initialized = true; - } + //Default attribut for paint a conductor + if (!pen_and_brush_initialized) + { + conductor_pen.setJoinStyle(Qt::MiterJoin); + conductor_pen.setCapStyle(Qt::SquareCap); + conductor_pen.setColor(Qt::black); + conductor_pen.setStyle(Qt::SolidLine); + conductor_pen.setWidthF(1.0); + conductor_brush.setColor(Qt::white); + conductor_brush.setStyle(Qt::NoBrush); + pen_and_brush_initialized = true; + } - //By default, the 4 profils are nuls -> we must to use priv_calculeConductor - conductor_profiles.insert(Qt::TopLeftCorner, ConductorProfile()); - conductor_profiles.insert(Qt::TopRightCorner, ConductorProfile()); - conductor_profiles.insert(Qt::BottomLeftCorner, ConductorProfile()); - conductor_profiles.insert(Qt::BottomRightCorner, ConductorProfile()); + //By default, the 4 profils are nuls -> we must to use priv_calculeConductor + conductor_profiles.insert(Qt::TopLeftCorner, ConductorProfile()); + conductor_profiles.insert(Qt::TopRightCorner, ConductorProfile()); + conductor_profiles.insert(Qt::BottomLeftCorner, ConductorProfile()); + conductor_profiles.insert(Qt::BottomRightCorner, ConductorProfile()); - //Generate the path of this conductor. - generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); - setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsScenePositionChanges); - setAcceptHoverEvents(true); + //Generate the path of this conductor. + generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); + setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsScenePositionChanges); + setAcceptHoverEvents(true); - // Add the text field - m_text_item = new ConductorTextItem(m_properties.text, this); - connect(m_text_item, &ConductorTextItem::textEdited, this, &Conductor::displayedTextChanged); + // Add the text field + m_text_item = new ConductorTextItem(m_properties.text, this); + connect(m_text_item, &ConductorTextItem::textEdited, this, &Conductor::displayedTextChanged); - //Set the default conductor properties. - if (p1->diagram()) - setProperties(p1->diagram()->defaultConductorProperties); - else if (p2->diagram()) - setProperties(p2->diagram()->defaultConductorProperties); + //Set the default conductor properties. + if (p1->diagram()) + setProperties(p1->diagram()->defaultConductorProperties); + else if (p2->diagram()) + setProperties(p2->diagram()->defaultConductorProperties); } /** - @brief Conductor::~Conductor - Destructor. The conductor is removed from is terminal + @brief Conductor::~Conductor + Destructor. The conductor is removed from is terminal */ Conductor::~Conductor() { - removeHandler(); - terminal1->removeConductor(this); - terminal2->removeConductor(this); - deleteSegments(); + removeHandler(); + terminal1->removeConductor(this); + terminal2->removeConductor(this); + deleteSegments(); } /** - @brief Conductor::isValid - @return true if conductor is valid else false; - A non valid conductor, is a conductor without two terminal + @brief Conductor::isValid + @return true if conductor is valid else false; + A non valid conductor, is a conductor without two terminal */ bool Conductor::isValid() const { - return m_valid; + return m_valid; } /** - Met a jour la representation graphique du conducteur en recalculant son - trace. Cette fonction est typiquement appelee lorsqu'une seule des bornes du - conducteur a change de position. - @param rect Rectangle a mettre a jour - @see QGraphicsPathItem::update() + Met a jour la representation graphique du conducteur en recalculant son + trace. Cette fonction est typiquement appelee lorsqu'une seule des bornes du + conducteur a change de position. + @param rect Rectangle a mettre a jour + @see QGraphicsPathItem::update() */ void Conductor::updatePath(const QRectF &rect) { - QPointF p1, p2; - p1 = terminal1 -> dockConductor(); - p2 = terminal2 -> dockConductor(); - if (segmentsCount() && !conductor_profiles[currentPathType()].isNull()) - updateConductorPath(p1, terminal1 -> orientation(), p2, terminal2 -> orientation()); - else - generateConductorPath(p1, terminal1 -> orientation(), p2, terminal2 -> orientation()); - calculateTextItemPosition(); - QGraphicsObject::update(rect); + QPointF p1, p2; + p1 = terminal1 -> dockConductor(); + p2 = terminal2 -> dockConductor(); + if (segmentsCount() && !conductor_profiles[currentPathType()].isNull()) + updateConductorPath(p1, terminal1 -> orientation(), p2, terminal2 -> orientation()); + else + generateConductorPath(p1, terminal1 -> orientation(), p2, terminal2 -> orientation()); + calculateTextItemPosition(); + QGraphicsObject::update(rect); } /** - @brief Conductor::segmentsToPath - Generate the QPainterPath from the list of points + @brief Conductor::segmentsToPath + Generate the QPainterPath from the list of points */ void Conductor::segmentsToPath() { - QPainterPath path; + QPainterPath path; - if (segments == nullptr) - setPath(path); + if (segments == nullptr) + setPath(path); - //Start the path - path.moveTo(segments -> firstPoint()); - //Each segments - ConductorSegment *segment = segments; - while(segment -> hasNextSegment()) { - path.lineTo(segment -> secondPoint()); - segment = segment -> nextSegment(); - } - //Finish the path - path.lineTo(segment -> secondPoint()); + //Start the path + path.moveTo(segments -> firstPoint()); + //Each segments + ConductorSegment *segment = segments; + while(segment -> hasNextSegment()) { + path.lineTo(segment -> secondPoint()); + segment = segment -> nextSegment(); + } + //Finish the path + path.lineTo(segment -> secondPoint()); - setPath(path); + setPath(path); - //If conductor is selected and he's not being modified - //we update the position of the handlers - if (isSelected() && !m_moving_segment) - { - if(handlerPoints().size() == m_handler_vector.size()) - adjusteHandlerPos(); - else - { - removeHandler(); - addHandler(); - } - } + //If conductor is selected and he's not being modified + //we update the position of the handlers + if (isSelected() && !m_moving_segment) + { + if(handlerPoints().size() == m_handler_vector.size()) + adjusteHandlerPos(); + else + { + removeHandler(); + addHandler(); + } + } } /** - Gere les updates - @param p1 Coordonnees du point d'amarrage de la borne 1 - @param o1 Orientation de la borne 1 - @param p2 Coordonnees du point d'amarrage de la borne 2 - @param o2 Orientation de la borne 2 + Gere les updates + @param p1 Coordonnees du point d'amarrage de la borne 1 + @param o1 Orientation de la borne 1 + @param p2 Coordonnees du point d'amarrage de la borne 2 + @param o2 Orientation de la borne 2 */ void Conductor::updateConductorPath(const QPointF &p1, Qet::Orientation o1, const QPointF &p2, Qet::Orientation o2) { - Q_UNUSED(o1); - Q_UNUSED(o2); + Q_UNUSED(o1); + Q_UNUSED(o2); - ConductorProfile &conductor_profile = conductor_profiles[currentPathType()]; + ConductorProfile &conductor_profile = conductor_profiles[currentPathType()]; - Q_ASSERT_X(conductor_profile.segmentsCount(QET::Both) > 1, "Conductor::priv_modifieConductor", "pas de points a modifier"); - Q_ASSERT_X(!conductor_profile.isNull(), "Conductor::priv_modifieConductor", "pas de profil utilisable"); + Q_ASSERT_X(conductor_profile.segmentsCount(QET::Both) > 1, "Conductor::priv_modifieConductor", "pas de points a modifier"); + Q_ASSERT_X(!conductor_profile.isNull(), "Conductor::priv_modifieConductor", "pas de profil utilisable"); - // recupere les coordonnees fournies des bornes - QPointF new_p1 = mapFromScene(p1); - QPointF new_p2 = mapFromScene(p2); - QRectF new_rect = QRectF(new_p1, new_p2); + // recupere les coordonnees fournies des bornes + QPointF new_p1 = mapFromScene(p1); + QPointF new_p2 = mapFromScene(p2); + QRectF new_rect = QRectF(new_p1, new_p2); - // recupere la largeur et la hauteur du profil - qreal profile_width = conductor_profile.width(); - qreal profile_height = conductor_profile.height(); + // recupere la largeur et la hauteur du profil + qreal profile_width = conductor_profile.width(); + qreal profile_height = conductor_profile.height(); - // calcule les differences verticales et horizontales a appliquer - qreal h_diff = (qAbs(new_rect.width()) - qAbs(profile_width) ) * getSign(profile_width); - qreal v_diff = (qAbs(new_rect.height()) - qAbs(profile_height)) * getSign(profile_height); + // calcule les differences verticales et horizontales a appliquer + qreal h_diff = (qAbs(new_rect.width()) - qAbs(profile_width) ) * getSign(profile_width); + qreal v_diff = (qAbs(new_rect.height()) - qAbs(profile_height)) * getSign(profile_height); - // applique les differences aux segments - QMultiHash segments_lengths; - segments_lengths.unite(shareOffsetBetweenSegments(h_diff, conductor_profile.horizontalSegments())); - segments_lengths.unite(shareOffsetBetweenSegments(v_diff, conductor_profile.verticalSegments())); + // applique les differences aux segments + QMultiHash segments_lengths; + segments_lengths.unite(shareOffsetBetweenSegments(h_diff, conductor_profile.horizontalSegments())); + segments_lengths.unite(shareOffsetBetweenSegments(v_diff, conductor_profile.verticalSegments())); - // en deduit egalement les coefficients d'inversion (-1 pour une inversion, +1 pour conserver le meme sens) - int horiz_coeff = getCoeff(new_rect.width(), profile_width); - int verti_coeff = getCoeff(new_rect.height(), profile_height); + // en deduit egalement les coefficients d'inversion (-1 pour une inversion, +1 pour conserver le meme sens) + int horiz_coeff = getCoeff(new_rect.width(), profile_width); + int verti_coeff = getCoeff(new_rect.height(), profile_height); - // genere les nouveaux points - QList points; - points << new_p1; - int limit = conductor_profile.segments.count() - 1; - for (int i = 0 ; i < limit ; ++ i) { - // dernier point - QPointF previous_point = points.last(); + // genere les nouveaux points + QList points; + points << new_p1; + int limit = conductor_profile.segments.count() - 1; + for (int i = 0 ; i < limit ; ++ i) { + // dernier point + QPointF previous_point = points.last(); - // profil de segment de conducteur en cours - ConductorSegmentProfile *csp = conductor_profile.segments.at(i); + // profil de segment de conducteur en cours + ConductorSegmentProfile *csp = conductor_profile.segments.at(i); - // coefficient et offset a utiliser pour ce point - qreal coeff = csp -> isHorizontal ? horiz_coeff : verti_coeff; - qreal offset_applied = segments_lengths.value(csp); + // coefficient et offset a utiliser pour ce point + qreal coeff = csp -> isHorizontal ? horiz_coeff : verti_coeff; + qreal offset_applied = segments_lengths.value(csp); - // applique l'offset et le coeff au point - if (csp -> isHorizontal) { - points << QPointF ( - previous_point.x() + (coeff * offset_applied), - previous_point.y() - ); - } else { - points << QPointF ( - previous_point.x(), - previous_point.y() + (coeff * offset_applied) - ); - } - } - points << new_p2; - pointsToSegments(points); - segmentsToPath(); + // applique l'offset et le coeff au point + if (csp -> isHorizontal) { + points << QPointF ( + previous_point.x() + (coeff * offset_applied), + previous_point.y() + ); + } else { + points << QPointF ( + previous_point.x(), + previous_point.y() + (coeff * offset_applied) + ); + } + } + points << new_p2; + pointsToSegments(points); + segmentsToPath(); } /** - @param offset Longueur a repartir entre les segments - @param segments_list Segments sur lesquels il faut repartir la longueur - @param precision seuil en-deca duquel on considere qu'il ne reste rien a repartir + @param offset Longueur a repartir entre les segments + @param segments_list Segments sur lesquels il faut repartir la longueur + @param precision seuil en-deca duquel on considere qu'il ne reste rien a repartir */ QHash Conductor::shareOffsetBetweenSegments( - const qreal &offset, - const QList &segments_list, - const qreal &precision + const qreal &offset, + const QList &segments_list, + const qreal &precision ) const { - // construit le QHash qui sera retourne - QHash segments_hash; - foreach(ConductorSegmentProfile *csp, segments_list) { - segments_hash.insert(csp, csp -> length); - } + // construit le QHash qui sera retourne + QHash segments_hash; + foreach(ConductorSegmentProfile *csp, segments_list) { + segments_hash.insert(csp, csp -> length); + } - // memorise le signe de la longueur de chaque segement - QHash segments_signs; - foreach(ConductorSegmentProfile *csp, segments_hash.keys()) { - segments_signs.insert(csp, getSign(csp -> length)); - } + // memorise le signe de la longueur de chaque segement + QHash segments_signs; + foreach(ConductorSegmentProfile *csp, segments_hash.keys()) { + segments_signs.insert(csp, getSign(csp -> length)); + } - //qDebug() << "repartition d'un offset de" << offset << "px sur" << segments_list.count() << "segments"; + //qDebug() << "repartition d'un offset de" << offset << "px sur" << segments_list.count() << "segments"; - // repartit l'offset sur les segments - qreal remaining_offset = offset; - while (remaining_offset > precision || remaining_offset < -precision) { - // recupere le nombre de segments differents ayant une longueur non nulle - uint segments_count = 0; - foreach(ConductorSegmentProfile *csp, segments_hash.keys()) if (segments_hash[csp]) ++ segments_count; - //qDebug() << " remaining_offset =" << remaining_offset; - qreal local_offset = remaining_offset / segments_count; - //qDebug() << " repartition d'un offset local de" << local_offset << "px sur" << segments_count << "segments"; - remaining_offset = 0.0; - foreach(ConductorSegmentProfile *csp, segments_hash.keys()) { - // ignore les segments de longueur nulle - if (!segments_hash[csp]) continue; - // applique l'offset au segment - //qreal segment_old_length = segments_hash[csp]; - segments_hash[csp] += local_offset; + // repartit l'offset sur les segments + qreal remaining_offset = offset; + while (remaining_offset > precision || remaining_offset < -precision) { + // recupere le nombre de segments differents ayant une longueur non nulle + uint segments_count = 0; + foreach(ConductorSegmentProfile *csp, segments_hash.keys()) if (segments_hash[csp]) ++ segments_count; + //qDebug() << " remaining_offset =" << remaining_offset; + qreal local_offset = remaining_offset / segments_count; + //qDebug() << " repartition d'un offset local de" << local_offset << "px sur" << segments_count << "segments"; + remaining_offset = 0.0; + foreach(ConductorSegmentProfile *csp, segments_hash.keys()) { + // ignore les segments de longueur nulle + if (!segments_hash[csp]) continue; + // applique l'offset au segment + //qreal segment_old_length = segments_hash[csp]; + segments_hash[csp] += local_offset; - // (la longueur du segment change de signe) <=> (le segment n'a pu absorbe tout l'offset) - if (segments_signs[csp] != getSign(segments_hash[csp])) { + // (la longueur du segment change de signe) <=> (le segment n'a pu absorbe tout l'offset) + if (segments_signs[csp] != getSign(segments_hash[csp])) { - // on remet le trop-plein dans la reserve d'offset - remaining_offset += qAbs(segments_hash[csp]) * getSign(local_offset); - //qDebug() << " trop-plein de" << qAbs(segments_hash[csp]) * getSign(local_offset) << "remaining_offset =" << remaining_offset; - segments_hash[csp] = 0.0; - } else { - //qDebug() << " offset local de" << local_offset << "accepte"; - } - } - } + // on remet le trop-plein dans la reserve d'offset + remaining_offset += qAbs(segments_hash[csp]) * getSign(local_offset); + //qDebug() << " trop-plein de" << qAbs(segments_hash[csp]) * getSign(local_offset) << "remaining_offset =" << remaining_offset; + segments_hash[csp] = 0.0; + } else { + //qDebug() << " offset local de" << local_offset << "accepte"; + } + } + } - return(segments_hash); + return(segments_hash); } /** - Calcule un trajet "par defaut" pour le conducteur - @param p1 Coordonnees du point d'amarrage de la borne 1 - @param o1 Orientation de la borne 1 - @param p2 Coordonnees du point d'amarrage de la borne 2 - @param o2 Orientation de la borne 2 + Calcule un trajet "par defaut" pour le conducteur + @param p1 Coordonnees du point d'amarrage de la borne 1 + @param o1 Orientation de la borne 1 + @param p2 Coordonnees du point d'amarrage de la borne 2 + @param o2 Orientation de la borne 2 */ void Conductor::generateConductorPath(const QPointF &p1, Qet::Orientation o1, const QPointF &p2, Qet::Orientation o2) { - QPointF sp1, sp2, depart, newp1, newp2, arrivee, depart0, arrivee0; - Qet::Orientation ori_depart, ori_arrivee; + QPointF sp1, sp2, depart, newp1, newp2, arrivee, depart0, arrivee0; + Qet::Orientation ori_depart, ori_arrivee; - // s'assure qu'il n'y a ni points - QList points; + // s'assure qu'il n'y a ni points + QList points; - // mappe les points par rapport a la scene - sp1 = mapFromScene(p1); - sp2 = mapFromScene(p2); + // mappe les points par rapport a la scene + sp1 = mapFromScene(p1); + sp2 = mapFromScene(p2); - // prolonge les bornes - newp1 = extendTerminal(sp1, o1); - newp2 = extendTerminal(sp2, o2); + // prolonge les bornes + newp1 = extendTerminal(sp1, o1); + newp2 = extendTerminal(sp2, o2); - // distingue le depart de l'arrivee : le trajet se fait toujours de gauche a droite (apres prolongation) - if (newp1.x() <= newp2.x()) { - depart = newp1; - arrivee = newp2; - depart0 = sp1; - arrivee0 = sp2; - ori_depart = o1; - ori_arrivee = o2; - } else { - depart = newp2; - arrivee = newp1; - depart0 = sp2; - arrivee0 = sp1; - ori_depart = o2; - ori_arrivee = o1; - } + // distingue le depart de l'arrivee : le trajet se fait toujours de gauche a droite (apres prolongation) + if (newp1.x() <= newp2.x()) { + depart = newp1; + arrivee = newp2; + depart0 = sp1; + arrivee0 = sp2; + ori_depart = o1; + ori_arrivee = o2; + } else { + depart = newp2; + arrivee = newp1; + depart0 = sp2; + arrivee0 = sp1; + ori_depart = o2; + ori_arrivee = o1; + } - // debut du trajet - points << depart0; + // debut du trajet + points << depart0; - // prolongement de la borne de depart - points << depart; + // prolongement de la borne de depart + points << depart; - // commence le vrai trajet - if (depart.y() < arrivee.y()) { - // trajet descendant - if ((ori_depart == Qet::North && (ori_arrivee == Qet::South || ori_arrivee == Qet::West)) || (ori_depart == Qet::East && ori_arrivee == Qet::West)) { - // cas "3" - int ligne_inter_x = qRound(depart.x() + arrivee.x()) / 2; - while (ligne_inter_x % Diagram::xGrid) -- ligne_inter_x; - points << QPointF(ligne_inter_x, depart.y()); - points << QPointF(ligne_inter_x, arrivee.y()); - } else if ((ori_depart == Qet::South && (ori_arrivee == Qet::North || ori_arrivee == Qet::East)) || (ori_depart == Qet::West && ori_arrivee == Qet::East)) { - // cas "4" - int ligne_inter_y = qRound(depart.y() + arrivee.y()) / 2; - while (ligne_inter_y % Diagram::yGrid) -- ligne_inter_y; - points << QPointF(depart.x(), ligne_inter_y); - points << QPointF(arrivee.x(), ligne_inter_y); - } else if ((ori_depart == Qet::North || ori_depart == Qet::East) && (ori_arrivee == Qet::North || ori_arrivee == Qet::East)) { - points << QPointF(arrivee.x(), depart.y()); // cas "2" - } else { - points << QPointF(depart.x(), arrivee.y()); // cas "1" - } - } else { - // trajet montant - if ((ori_depart == Qet::West && (ori_arrivee == Qet::East || ori_arrivee == Qet::South)) || (ori_depart == Qet::North && ori_arrivee == Qet::South)) { - // cas "3" - int ligne_inter_y = qRound(depart.y() + arrivee.y()) / 2; - while (ligne_inter_y % Diagram::yGrid) -- ligne_inter_y; - points << QPointF(depart.x(), ligne_inter_y); - points << QPointF(arrivee.x(), ligne_inter_y); - } else if ((ori_depart == Qet::East && (ori_arrivee == Qet::West || ori_arrivee == Qet::North)) || (ori_depart == Qet::South && ori_arrivee == Qet::North)) { - // cas "4" - int ligne_inter_x = qRound(depart.x() + arrivee.x()) / 2; - while (ligne_inter_x % Diagram::xGrid) -- ligne_inter_x; - points << QPointF(ligne_inter_x, depart.y()); - points << QPointF(ligne_inter_x, arrivee.y()); - } else if ((ori_depart == Qet::West || ori_depart == Qet::North) && (ori_arrivee == Qet::West || ori_arrivee == Qet::North)) { - points << QPointF(depart.x(), arrivee.y()); // cas "2" - } else { - points << QPointF(arrivee.x(), depart.y()); // cas "1" - } - } + // commence le vrai trajet + if (depart.y() < arrivee.y()) { + // trajet descendant + if ((ori_depart == Qet::North && (ori_arrivee == Qet::South || ori_arrivee == Qet::West)) || (ori_depart == Qet::East && ori_arrivee == Qet::West)) { + // cas "3" + int ligne_inter_x = qRound(depart.x() + arrivee.x()) / 2; + while (ligne_inter_x % Diagram::xGrid) -- ligne_inter_x; + points << QPointF(ligne_inter_x, depart.y()); + points << QPointF(ligne_inter_x, arrivee.y()); + } else if ((ori_depart == Qet::South && (ori_arrivee == Qet::North || ori_arrivee == Qet::East)) || (ori_depart == Qet::West && ori_arrivee == Qet::East)) { + // cas "4" + int ligne_inter_y = qRound(depart.y() + arrivee.y()) / 2; + while (ligne_inter_y % Diagram::yGrid) -- ligne_inter_y; + points << QPointF(depart.x(), ligne_inter_y); + points << QPointF(arrivee.x(), ligne_inter_y); + } else if ((ori_depart == Qet::North || ori_depart == Qet::East) && (ori_arrivee == Qet::North || ori_arrivee == Qet::East)) { + points << QPointF(arrivee.x(), depart.y()); // cas "2" + } else { + points << QPointF(depart.x(), arrivee.y()); // cas "1" + } + } else { + // trajet montant + if ((ori_depart == Qet::West && (ori_arrivee == Qet::East || ori_arrivee == Qet::South)) || (ori_depart == Qet::North && ori_arrivee == Qet::South)) { + // cas "3" + int ligne_inter_y = qRound(depart.y() + arrivee.y()) / 2; + while (ligne_inter_y % Diagram::yGrid) -- ligne_inter_y; + points << QPointF(depart.x(), ligne_inter_y); + points << QPointF(arrivee.x(), ligne_inter_y); + } else if ((ori_depart == Qet::East && (ori_arrivee == Qet::West || ori_arrivee == Qet::North)) || (ori_depart == Qet::South && ori_arrivee == Qet::North)) { + // cas "4" + int ligne_inter_x = qRound(depart.x() + arrivee.x()) / 2; + while (ligne_inter_x % Diagram::xGrid) -- ligne_inter_x; + points << QPointF(ligne_inter_x, depart.y()); + points << QPointF(ligne_inter_x, arrivee.y()); + } else if ((ori_depart == Qet::West || ori_depart == Qet::North) && (ori_arrivee == Qet::West || ori_arrivee == Qet::North)) { + points << QPointF(depart.x(), arrivee.y()); // cas "2" + } else { + points << QPointF(arrivee.x(), depart.y()); // cas "1" + } + } - // fin du vrai trajet - points << arrivee; + // fin du vrai trajet + points << arrivee; - // prolongement de la borne d'arrivee - points << arrivee0; + // prolongement de la borne d'arrivee + points << arrivee0; - // inverse eventuellement l'ordre des points afin que le trajet soit exprime de la borne 1 vers la borne 2 - if (newp1.x() > newp2.x()) { - QList points2; - for (int i = points.size() - 1 ; i >= 0 ; -- i) points2 << points.at(i); - points = points2; - } + // inverse eventuellement l'ordre des points afin que le trajet soit exprime de la borne 1 vers la borne 2 + if (newp1.x() > newp2.x()) { + QList points2; + for (int i = points.size() - 1 ; i >= 0 ; -- i) points2 << points.at(i); + points = points2; + } - pointsToSegments(points); - segmentsToPath(); + pointsToSegments(points); + segmentsToPath(); } /** - Prolonge une borne. - @param terminal Le point correspondant a la borne - @param terminal_orientation L'orientation de la borne - @param ext_size la taille de la prolongation - @return le point correspondant a la borne apres prolongation + Prolonge une borne. + @param terminal Le point correspondant a la borne + @param terminal_orientation L'orientation de la borne + @param ext_size la taille de la prolongation + @return le point correspondant a la borne apres prolongation */ QPointF Conductor::extendTerminal(const QPointF &terminal, Qet::Orientation terminal_orientation, qreal ext_size) { - QPointF extended_terminal; - switch(terminal_orientation) { - case Qet::North: - extended_terminal = QPointF(terminal.x(), terminal.y() - ext_size); - break; - case Qet::East: - extended_terminal = QPointF(terminal.x() + ext_size, terminal.y()); - break; - case Qet::South: - extended_terminal = QPointF(terminal.x(), terminal.y() + ext_size); - break; - case Qet::West: - extended_terminal = QPointF(terminal.x() - ext_size, terminal.y()); - break; - default: extended_terminal = terminal; - } - return(extended_terminal); + QPointF extended_terminal; + switch(terminal_orientation) { + case Qet::North: + extended_terminal = QPointF(terminal.x(), terminal.y() - ext_size); + break; + case Qet::East: + extended_terminal = QPointF(terminal.x() + ext_size, terminal.y()); + break; + case Qet::South: + extended_terminal = QPointF(terminal.x(), terminal.y() + ext_size); + break; + case Qet::West: + extended_terminal = QPointF(terminal.x() - ext_size, terminal.y()); + break; + default: extended_terminal = terminal; + } + return(extended_terminal); } /** - Dessine le conducteur sans antialiasing. - @param painter Le QPainter a utiliser pour dessiner le conducteur - @param options Les options de style pour le conducteur - @param qw Le QWidget sur lequel on dessine + Dessine le conducteur sans antialiasing. + @param painter Le QPainter a utiliser pour dessiner le conducteur + @param options Les options de style pour le conducteur + @param qw Le QWidget sur lequel on dessine */ void Conductor::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *qw) { - Q_UNUSED(qw); - painter -> save(); - painter -> setRenderHint(QPainter::Antialiasing, false); + Q_UNUSED(qw); + painter -> save(); + painter -> setRenderHint(QPainter::Antialiasing, false); - // Set the color of conductor - QColor final_conductor_color(m_properties.color); - if (must_highlight_ == Normal) { - final_conductor_color = QColor::fromRgb(69, 137, 255, 255); - } else if (must_highlight_ == Alert) { - final_conductor_color =QColor::fromRgb(255, 69, 0, 255); - } else if (isSelected()) { - final_conductor_color = Qt::red; - } else { - if (Diagram *parent_diagram = diagram()) { - if (!parent_diagram -> drawColoredConductors()) { - final_conductor_color = Qt::black; - } - } - } + // Set the color of conductor + QColor final_conductor_color(m_properties.color); + if (must_highlight_ == Normal) { + final_conductor_color = QColor::fromRgb(69, 137, 255, 255); + } else if (must_highlight_ == Alert) { + final_conductor_color =QColor::fromRgb(255, 69, 0, 255); + } else if (isSelected()) { + final_conductor_color = Qt::red; + } else { + if (Diagram *parent_diagram = diagram()) { + if (!parent_diagram -> drawColoredConductors()) { + final_conductor_color = Qt::black; + } + } + } - //Draw the conductor bigger when is hovered - conductor_pen.setWidthF(m_mouse_over? (m_properties.cond_size) +4 : (m_properties.cond_size)); + //Draw the conductor bigger when is hovered + conductor_pen.setWidthF(m_mouse_over? (m_properties.cond_size) +4 : (m_properties.cond_size)); - //Set the QPen and QBrush to the QPainter - painter -> setBrush(conductor_brush); - QPen final_conductor_pen = conductor_pen; + //Set the QPen and QBrush to the QPainter + painter -> setBrush(conductor_brush); + QPen final_conductor_pen = conductor_pen; - //Set the conductor style - final_conductor_pen.setColor(final_conductor_color); - final_conductor_pen.setStyle(m_properties.style); - final_conductor_pen.setJoinStyle(Qt::SvgMiterJoin); // better rendering with dot + //Set the conductor style + final_conductor_pen.setColor(final_conductor_color); + final_conductor_pen.setStyle(m_properties.style); + final_conductor_pen.setJoinStyle(Qt::SvgMiterJoin); // better rendering with dot - //Use a cosmetique line, below a certain zoom -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - if (options && options -> levelOfDetail < 1.0) + //Use a cosmetique line, below a certain zoom +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + if (options && options -> levelOfDetail < 1.0) #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0) + if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0) #endif - { - final_conductor_pen.setCosmetic(true); - } + { + final_conductor_pen.setCosmetic(true); + } - painter -> setPen(final_conductor_pen); + painter -> setPen(final_conductor_pen); - //Draw the conductor - painter -> drawPath(path()); - //Draw the second color - if(m_properties.m_bicolor) - { - final_conductor_pen.setColor(m_properties.m_color_2); - final_conductor_pen.setStyle(Qt::CustomDashLine); - QVector dash_pattern; - dash_pattern << m_properties.m_dash_size-2 << m_properties.m_dash_size; - final_conductor_pen.setDashPattern(dash_pattern); - painter->save(); - painter->setPen(final_conductor_pen); - painter->drawPath(path()); - painter->restore(); - } + //Draw the conductor + painter -> drawPath(path()); + //Draw the second color + if(m_properties.m_bicolor) + { + final_conductor_pen.setColor(m_properties.m_color_2); + final_conductor_pen.setStyle(Qt::CustomDashLine); + QVector dash_pattern; + dash_pattern << m_properties.m_dash_size-2 << m_properties.m_dash_size; + final_conductor_pen.setDashPattern(dash_pattern); + painter->save(); + painter->setPen(final_conductor_pen); + painter->drawPath(path()); + painter->restore(); + } - if (m_properties.type == ConductorProperties::Single) { - painter -> setBrush(final_conductor_color); - m_properties.singleLineProperties.draw( - painter, - middleSegment() -> isHorizontal() ? QET::Horizontal : QET::Vertical, - QRectF(middleSegment() -> middle() - QPointF(12.0, 12.0), QSizeF(24.0, 24.0)) - ); - if (isSelected()) painter -> setBrush(Qt::NoBrush); - } + if (m_properties.type == ConductorProperties::Single) { + painter -> setBrush(final_conductor_color); + m_properties.singleLineProperties.draw( + painter, + middleSegment() -> isHorizontal() ? QET::Horizontal : QET::Vertical, + QRectF(middleSegment() -> middle() - QPointF(12.0, 12.0), QSizeF(24.0, 24.0)) + ); + if (isSelected()) painter -> setBrush(Qt::NoBrush); + } - //Draw the junctions - QList junctions_list = junctions(); - if (!junctions_list.isEmpty()) { - final_conductor_pen.setStyle(Qt::SolidLine); - QBrush junction_brush(final_conductor_color, Qt::SolidPattern); - painter -> setPen(final_conductor_pen); - painter -> setBrush(junction_brush); - painter -> setRenderHint(QPainter::Antialiasing, true); - foreach(QPointF point, junctions_list) { - painter -> drawEllipse(QRectF(point.x() - 1.5, point.y() - 1.5, 3.0, 3.0)); - } - } + //Draw the junctions + QList junctions_list = junctions(); + if (!junctions_list.isEmpty()) { + final_conductor_pen.setStyle(Qt::SolidLine); + QBrush junction_brush(final_conductor_color, Qt::SolidPattern); + painter -> setPen(final_conductor_pen); + painter -> setBrush(junction_brush); + painter -> setRenderHint(QPainter::Antialiasing, true); + foreach(QPointF point, junctions_list) { + painter -> drawEllipse(QRectF(point.x() - 1.5, point.y() - 1.5, 3.0, 3.0)); + } + } - painter -> restore(); + painter -> restore(); } /// @return le Diagram auquel ce conducteur appartient, ou 0 si ce conducteur est independant Diagram *Conductor::diagram() const { - return(qobject_cast(scene())); + return(qobject_cast(scene())); } /**4 - @return le champ de texte associe a ce conducteur + @return le champ de texte associe a ce conducteur */ ConductorTextItem *Conductor::textItem() const { - return(m_text_item); + return(m_text_item); } /** - Methode de validation d'element XML - @param e Un element XML sense represente un Conducteur - @return true si l'element XML represente bien un Conducteur ; false sinon + Methode de validation d'element XML + @param e Un element XML sense represente un Conducteur + @return true si l'element XML represente bien un Conducteur ; false sinon */ bool Conductor::valideXml(QDomElement &e){ - // verifie le nom du tag - if (e.tagName() != "conductor") return(false); + // verifie le nom du tag + if (e.tagName() != "conductor") return(false); - // verifie la presence des attributs minimaux - if (!e.hasAttribute("terminal1")) return(false); - if (!e.hasAttribute("terminal2")) return(false); + // verifie la presence des attributs minimaux + if (!e.hasAttribute("terminal1")) return(false); + if (!e.hasAttribute("terminal2")) return(false); - bool conv_ok; - // parse l'abscisse - if (e.hasAttribute("element1")) { - if (QUuid(e.attribute("element1")).isNull()) - return false; - if (QUuid(e.attribute("terminal1")).isNull()) - return false; - } else { - e.attribute("terminal1").toInt(&conv_ok); - if (!conv_ok) return(false); - } + bool conv_ok; + // parse l'abscisse + if (e.hasAttribute("element1")) { + if (QUuid(e.attribute("element1")).isNull()) + return false; + if (QUuid(e.attribute("terminal1")).isNull()) + return false; + } else { + e.attribute("terminal1").toInt(&conv_ok); + if (!conv_ok) return(false); + } - // parse l'ordonnee - if (e.hasAttribute("element2")) { - if (QUuid(e.attribute("element2")).isNull()) - return false; - if (QUuid(e.attribute("terminal2")).isNull()) - return false; - } else { - e.attribute("terminal2").toInt(&conv_ok); - if (!conv_ok) return(false); - } - return(true); + // parse l'ordonnee + if (e.hasAttribute("element2")) { + if (QUuid(e.attribute("element2")).isNull()) + return false; + if (QUuid(e.attribute("terminal2")).isNull()) + return false; + } else { + e.attribute("terminal2").toInt(&conv_ok); + if (!conv_ok) return(false); + } + return(true); } /** - @brief Conductor::mouseDoubleClickEvent - Manage the mouse double click - @param event + @brief Conductor::mouseDoubleClickEvent + Manage the mouse double click + @param event */ void Conductor::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { - event->accept(); - editProperty(); + event->accept(); + editProperty(); } /** - @brief Conductor::mousePressEvent - Manage the mouse press event - @param event + @brief Conductor::mousePressEvent + Manage the mouse press event + @param event */ void Conductor::mousePressEvent(QGraphicsSceneMouseEvent *event) { - QGraphicsObject::mousePressEvent(event); + QGraphicsObject::mousePressEvent(event); - if (event->modifiers() & Qt::ControlModifier) - setSelected(!isSelected()); + if (event->modifiers() & Qt::ControlModifier) + setSelected(!isSelected()); } /** - @brief Conductor::mouseReleaseEvent - @param event + @brief Conductor::mouseReleaseEvent + @param event */ void Conductor::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (!(event -> modifiers() & Qt::ControlModifier)) - QGraphicsObject::mouseReleaseEvent(event); + if (!(event -> modifiers() & Qt::ControlModifier)) + QGraphicsObject::mouseReleaseEvent(event); } /** - @brief Conductor::hoverEnterEvent - Manage the hover enter event - @param event + @brief Conductor::hoverEnterEvent + Manage the hover enter event + @param event */ void Conductor::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - Q_UNUSED(event); - m_mouse_over = true; - update(); + Q_UNUSED(event); + m_mouse_over = true; + update(); } /** - @brief Conductor::hoverLeaveEvent - Manage the mouse leave event - @param event + @brief Conductor::hoverLeaveEvent + Manage the mouse leave event + @param event */ void Conductor::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - Q_UNUSED(event); - update(); - m_mouse_over = false; + Q_UNUSED(event); + update(); + m_mouse_over = false; } /** - @brief Conductor::itemChange - @param change - @param value - @return + @brief Conductor::itemChange + @param change + @param value + @return */ QVariant Conductor::itemChange(GraphicsItemChange change, const QVariant &value) { - if (change == QGraphicsItem::ItemSelectedChange) - { - if (value.toBool()) - { - m_previous_z_value = zValue(); - setZValue(qAbs(m_previous_z_value) + 10000); - addHandler(); - } - else - { - setZValue(m_previous_z_value); - removeHandler(); - } - } - else if (change == QGraphicsItem::ItemSceneHasChanged) - { - calculateTextItemPosition(); + if (change == QGraphicsItem::ItemSelectedChange) + { + if (value.toBool()) + { + m_previous_z_value = zValue(); + setZValue(qAbs(m_previous_z_value) + 10000); + addHandler(); + } + else + { + setZValue(m_previous_z_value); + removeHandler(); + } + } + else if (change == QGraphicsItem::ItemSceneHasChanged) + { + calculateTextItemPosition(); - if(!scene()) - removeHandler(); - else if (scene() && isSelected()) - addHandler(); - } - else if (change == QGraphicsItem::ItemVisibleHasChanged) { - calculateTextItemPosition(); - } - else if (change == QGraphicsItem::ItemPositionHasChanged && isSelected()) { - adjusteHandlerPos(); - } + if(!scene()) + removeHandler(); + else if (scene() && isSelected()) + addHandler(); + } + else if (change == QGraphicsItem::ItemVisibleHasChanged) { + calculateTextItemPosition(); + } + else if (change == QGraphicsItem::ItemPositionHasChanged && isSelected()) { + adjusteHandlerPos(); + } - return(QGraphicsObject::itemChange(change, value)); + return(QGraphicsObject::itemChange(change, value)); } /** - @brief Conductor::sceneEventFilter - @param watched - @param event - @return + @brief Conductor::sceneEventFilter + @param watched + @param event + @return */ bool Conductor::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(qghi, static_cast(event)); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(qghi, static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseDoubleClick) //Double click - { - editProperty(); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(qghi, static_cast(event)); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(qghi, static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseDoubleClick) //Double click + { + editProperty(); + return true; + } + } + } + } - return false; + return false; } /** - @brief Conductor::adjusteHandlerPos - Adjust the position of the handler item + @brief Conductor::adjusteHandlerPos + Adjust the position of the handler item */ void Conductor::adjusteHandlerPos() { - if (m_handler_vector.isEmpty()) - return; + if (m_handler_vector.isEmpty()) + return; - if (m_handler_vector.size() == handlerPoints().size()) - { - QVector points_vector = mapToScene(handlerPoints()); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } + if (m_handler_vector.size() == handlerPoints().size()) + { + QVector points_vector = mapToScene(handlerPoints()); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } } /** - @brief Conductor::handlerMousePressEvent - @param qghi - @param event + @brief Conductor::handlerMousePressEvent + @param qghi + @param event */ void Conductor::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(event); + Q_UNUSED(event); - //we get the segment corresponding to the handler - if (m_vector_index > -1) - { - qghi->setColor(Qt::cyan); - m_moving_segment = true; - m_moved_segment = segmentsList().at(m_vector_index+1); - before_mov_text_pos_ = m_text_item -> pos(); + //we get the segment corresponding to the handler + if (m_vector_index > -1) + { + qghi->setColor(Qt::cyan); + m_moving_segment = true; + m_moved_segment = segmentsList().at(m_vector_index+1); + before_mov_text_pos_ = m_text_item -> pos(); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - if(handler != qghi) - handler->hide(); - } + for(QetGraphicsHandlerItem *handler : m_handler_vector) + if(handler != qghi) + handler->hide(); + } } /** - @brief Conductor::handlerMouseMoveEvent - @param qghi - @param event + @brief Conductor::handlerMouseMoveEvent + @param qghi + @param event */ void Conductor::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - if (m_moving_segment) - { - //Snap the mouse pos to grid - QPointF pos_ = Diagram::snapToGrid(mapFromScene(event->scenePos())); + if (m_moving_segment) + { + //Snap the mouse pos to grid + QPointF pos_ = Diagram::snapToGrid(mapFromScene(event->scenePos())); - //Position of the last point - QPointF p = m_moved_segment -> middle(); + //Position of the last point + QPointF p = m_moved_segment -> middle(); - //Calcul the movement - m_moved_segment -> moveX(pos_.x() - p.x()); - m_moved_segment -> moveY(pos_.y() - p.y()); + //Calcul the movement + m_moved_segment -> moveX(pos_.x() - p.x()); + m_moved_segment -> moveY(pos_.y() - p.y()); - //Apply the movement - modified_path = true; - has_to_save_profile = true; - segmentsToPath(); - calculateTextItemPosition(); - qghi->setPos(mapToScene(m_moved_segment->middle())); - } + //Apply the movement + modified_path = true; + has_to_save_profile = true; + segmentsToPath(); + calculateTextItemPosition(); + qghi->setPos(mapToScene(m_moved_segment->middle())); + } } /** - @brief Conductor::handlerMouseReleaseEvent - @param qghi - @param event + @brief Conductor::handlerMouseReleaseEvent + @param qghi + @param event */ void Conductor::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) { - Q_UNUSED(event); - Q_UNUSED(qghi); + Q_UNUSED(event); + Q_UNUSED(qghi); - m_vector_index = -1; + m_vector_index = -1; - m_moving_segment = false; - if (has_to_save_profile) - { - saveProfile(); - has_to_save_profile = false; - } - //When handler is released, the conductor can have more segment than befor the handler was moved - //then we remove all handles and new ones are added - removeHandler(); - addHandler(); + m_moving_segment = false; + if (has_to_save_profile) + { + saveProfile(); + has_to_save_profile = false; + } + //When handler is released, the conductor can have more segment than befor the handler was moved + //then we remove all handles and new ones are added + removeHandler(); + addHandler(); } /** - @brief Conductor::addHandler - Add handlers for this item + @brief Conductor::addHandler + Add handlers for this item */ void Conductor::addHandler() { - if (m_handler_vector.isEmpty() && scene()) - { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(handlerPoints())); + if (m_handler_vector.isEmpty() && scene()) + { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(handlerPoints())); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - { - handler->setColor(Qt::blue); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - handler->setZValue(this->zValue()+1); - } - } + for(QetGraphicsHandlerItem *handler : m_handler_vector) + { + handler->setColor(Qt::blue); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + handler->setZValue(this->zValue()+1); + } + } } /** - @brief Conductor::removeHandler - Remove the handlers of this item + @brief Conductor::removeHandler + Remove the handlers of this item */ void Conductor::removeHandler() { - if (!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } + if (!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } } /** - @brief Conductor::boundingRect - @return + @brief Conductor::boundingRect + @return */ QRectF Conductor::boundingRect() const { - QRectF br = shape().boundingRect(); - return br.adjusted(-10, -10, 10, 10); + QRectF br = shape().boundingRect(); + return br.adjusted(-10, -10, 10, 10); } /** - @brief Conductor::shape - @return the shape of conductor. - The shape thickness is bigger when conductor is hovered + @brief Conductor::shape + @return the shape of conductor. + The shape thickness is bigger when conductor is hovered */ QPainterPath Conductor::shape() const { - QPainterPathStroker pps; - pps.setWidth(m_mouse_over? 5 : 1); - pps.setJoinStyle(conductor_pen.joinStyle()); + QPainterPathStroker pps; + pps.setWidth(m_mouse_over? 5 : 1); + pps.setJoinStyle(conductor_pen.joinStyle()); - QPainterPath shape_(pps.createStroke(path())); + QPainterPath shape_(pps.createStroke(path())); - return shape_; + return shape_; } /** - @brief Conductor::nearShape - @return : An area in which it is considered a point is near this conductor. + @brief Conductor::nearShape + @return : An area in which it is considered a point is near this conductor. */ QPainterPath Conductor::nearShape() const { - QPainterPathStroker pps; - pps.setWidth(1300); - pps.setJoinStyle(conductor_pen.joinStyle()); - return pps.createStroke(path()); + QPainterPathStroker pps; + pps.setWidth(1300); + pps.setJoinStyle(conductor_pen.joinStyle()); + return pps.createStroke(path()); } /** - @param type Type de Segments - @return Le nombre de segments composant le conducteur. + @param type Type de Segments + @return Le nombre de segments composant le conducteur. */ uint Conductor::segmentsCount(QET::ConductorSegmentType type) const { - QList segments_list = segmentsList(); - if (type == QET::Both) return(segments_list.count()); - uint nb_seg = 0; - foreach(ConductorSegment *conductor_segment, segments_list) { - if (conductor_segment -> type() == type) ++ nb_seg; - } - return(nb_seg); + QList segments_list = segmentsList(); + if (type == QET::Both) return(segments_list.count()); + uint nb_seg = 0; + foreach(ConductorSegment *conductor_segment, segments_list) { + if (conductor_segment -> type() == type) ++ nb_seg; + } + return(nb_seg); } /** - Genere une liste de points a partir des segments de ce conducteur - @return La liste de points representant ce conducteur + Genere une liste de points a partir des segments de ce conducteur + @return La liste de points representant ce conducteur */ QList Conductor::segmentsToPoints() const { - // liste qui sera retournee - QList points_list; + // liste qui sera retournee + QList points_list; - // on retourne la liste tout de suite s'il n'y a pas de segments - if (segments == nullptr) return(points_list); + // on retourne la liste tout de suite s'il n'y a pas de segments + if (segments == nullptr) return(points_list); - // recupere le premier point - points_list << segments -> firstPoint(); + // recupere le premier point + points_list << segments -> firstPoint(); - // parcourt les segments pour recuperer les autres points - ConductorSegment *segment = segments; - while(segment -> hasNextSegment()) { - points_list << segment -> secondPoint(); - segment = segment -> nextSegment(); - } + // parcourt les segments pour recuperer les autres points + ConductorSegment *segment = segments; + while(segment -> hasNextSegment()) { + points_list << segment -> secondPoint(); + segment = segment -> nextSegment(); + } - // recupere le dernier point - points_list << segment -> secondPoint(); + // recupere le dernier point + points_list << segment -> secondPoint(); - //retourne la liste - return(points_list); + //retourne la liste + return(points_list); } /** - Regenere les segments de ce conducteur a partir de la liste de points passee en parametre - @param points_list Liste de points a utiliser pour generer les segments + Regenere les segments de ce conducteur a partir de la liste de points passee en parametre + @param points_list Liste de points a utiliser pour generer les segments */ void Conductor::pointsToSegments(const QList& points_list) { - // supprime les segments actuels - deleteSegments(); + // supprime les segments actuels + deleteSegments(); - // cree les segments a partir de la liste de points - ConductorSegment *last_segment = nullptr; - for (int i = 0 ; i < points_list.size() - 1 ; ++ i) { - last_segment = new ConductorSegment(points_list.at(i), points_list.at(i + 1), last_segment); - if (!i) segments = last_segment; - } + // cree les segments a partir de la liste de points + ConductorSegment *last_segment = nullptr; + for (int i = 0 ; i < points_list.size() - 1 ; ++ i) { + last_segment = new ConductorSegment(points_list.at(i), points_list.at(i + 1), last_segment); + if (!i) segments = last_segment; + } } /** - @brief Conductor::fromXml - Load the conductor and her information from xml element - @param dom_element - @return true is loading success else return false + @brief Conductor::fromXml + Load the conductor and her information from xml element + @param dom_element + @return true is loading success else return false */ bool Conductor::fromXml(QDomElement &dom_element) { - setPos(dom_element.attribute("x", nullptr).toDouble(), - dom_element.attribute("y", nullptr).toDouble()); + setPos(dom_element.attribute("x", nullptr).toDouble(), + dom_element.attribute("y", nullptr).toDouble()); - bool return_ = pathFromXml(dom_element); + bool return_ = pathFromXml(dom_element); - m_text_item -> fromXml(dom_element); - ConductorProperties pr; - pr.fromXml(dom_element); + m_text_item -> fromXml(dom_element); + ConductorProperties pr; + pr.fromXml(dom_element); - //Load Sequential Values - if (dom_element.hasAttribute("sequ_1") || dom_element.hasAttribute("sequf_1") || dom_element.hasAttribute("seqt_1") || dom_element.hasAttribute("seqtf_1") || dom_element.hasAttribute("seqh_1") || dom_element.hasAttribute("sequf_1")) - ConductorXmlRetroCompatibility::loadSequential(dom_element, this); - else - m_autoNum_seq.fromXml(dom_element.firstChildElement("sequentialNumbers")); + //Load Sequential Values + if (dom_element.hasAttribute("sequ_1") || dom_element.hasAttribute("sequf_1") || dom_element.hasAttribute("seqt_1") || dom_element.hasAttribute("seqtf_1") || dom_element.hasAttribute("seqh_1") || dom_element.hasAttribute("sequf_1")) + ConductorXmlRetroCompatibility::loadSequential(dom_element, this); + else + m_autoNum_seq.fromXml(dom_element.firstChildElement("sequentialNumbers")); - m_freeze_label = dom_element.attribute("freezeLabel") == "true"? true : false; + m_freeze_label = dom_element.attribute("freezeLabel") == "true"? true : false; - setProperties(pr); + setProperties(pr); - return return_; + return return_; } /** - @brief Conductor::toXml - Exporte les caracteristiques du conducteur sous forme d'une element XML. - @param dom_document : - Le document XML a utiliser pour creer l'element XML - @param table_adr_id : - Hash stockant les correspondances entre les ids des - bornes dans le document XML et leur adresse en memoire - @return Un element XML representant le conducteur + @brief Conductor::toXml + Exporte les caracteristiques du conducteur sous forme d'une element XML. + @param dom_document : + Le document XML a utiliser pour creer l'element XML + @param table_adr_id : + Hash stockant les correspondances entre les ids des + bornes dans le document XML et leur adresse en memoire + @return Un element XML representant le conducteur */ QDomElement Conductor::toXml(QDomDocument &dom_document, - QHash &table_adr_id) const + QHash &table_adr_id) const { - QDomElement dom_element = dom_document.createElement("conductor"); + QDomElement dom_element = dom_document.createElement("conductor"); - dom_element.setAttribute("x", QString::number(pos().x())); - dom_element.setAttribute("y", QString::number(pos().y())); + dom_element.setAttribute("x", QString::number(pos().x())); + dom_element.setAttribute("y", QString::number(pos().y())); - // Terminal is uniquely identified by the uuid of the terminal and the element - if (terminal1->uuid().isNull()) { - // legacy method to identify the terminal - dom_element.setAttribute("terminal1", table_adr_id.value(terminal1)); // for backward compability - } else { - dom_element.setAttribute("element1", terminal1->parentElement()->uuid().toString()); - dom_element.setAttribute("terminal1", terminal1->uuid().toString()); - } + // Terminal is uniquely identified by the uuid of the terminal and the element + if (terminal1->uuid().isNull()) { + // legacy method to identify the terminal + dom_element.setAttribute("terminal1", table_adr_id.value(terminal1)); // for backward compability + } else { + dom_element.setAttribute("element1", terminal1->parentElement()->uuid().toString()); + dom_element.setAttribute("terminal1", terminal1->uuid().toString()); + } - if (terminal2->uuid().isNull()) { - // legacy method to identify the terminal - dom_element.setAttribute("terminal2", table_adr_id.value(terminal2)); // for backward compability - } else { - dom_element.setAttribute("element2", terminal2->parentElement()->uuid().toString()); - dom_element.setAttribute("terminal2", terminal2->uuid().toString()); - } - dom_element.setAttribute("freezeLabel", m_freeze_label? "true" : "false"); + if (terminal2->uuid().isNull()) { + // legacy method to identify the terminal + dom_element.setAttribute("terminal2", table_adr_id.value(terminal2)); // for backward compability + } else { + dom_element.setAttribute("element2", terminal2->parentElement()->uuid().toString()); + dom_element.setAttribute("terminal2", terminal2->uuid().toString()); + } + dom_element.setAttribute("freezeLabel", m_freeze_label? "true" : "false"); - // on n'exporte les segments du conducteur que si ceux-ci ont - // ete modifies par l'utilisateur - if (modified_path) - { - // parcours et export des segments - QDomElement current_segment; - foreach(ConductorSegment *segment, segmentsList()) - { - current_segment = dom_document.createElement("segment"); - current_segment.setAttribute("orientation", segment -> isHorizontal() ? "horizontal" : "vertical"); - current_segment.setAttribute("length", QString("%1").arg(segment -> length())); - dom_element.appendChild(current_segment); - } - } + // on n'exporte les segments du conducteur que si ceux-ci ont + // ete modifies par l'utilisateur + if (modified_path) + { + // parcours et export des segments + QDomElement current_segment; + foreach(ConductorSegment *segment, segmentsList()) + { + current_segment = dom_document.createElement("segment"); + current_segment.setAttribute("orientation", segment -> isHorizontal() ? "horizontal" : "vertical"); + current_segment.setAttribute("length", QString("%1").arg(segment -> length())); + dom_element.appendChild(current_segment); + } + } - QDomElement dom_seq = m_autoNum_seq.toXml(dom_document); - dom_element.appendChild(dom_seq); + QDomElement dom_seq = m_autoNum_seq.toXml(dom_document); + dom_element.appendChild(dom_seq); - // Export the properties and text - m_properties. toXml(dom_element); - if(m_text_item->wasMovedByUser()) - { - dom_element.setAttribute("userx", QString::number(m_text_item->pos().x())); - dom_element.setAttribute("usery", QString::number(m_text_item->pos().y())); - } - if(m_text_item->wasRotateByUser()) - dom_element.setAttribute("rotation", QString::number(m_text_item->rotation())); + // Export the properties and text + m_properties. toXml(dom_element); + if(m_text_item->wasMovedByUser()) + { + dom_element.setAttribute("userx", QString::number(m_text_item->pos().x())); + dom_element.setAttribute("usery", QString::number(m_text_item->pos().y())); + } + if(m_text_item->wasRotateByUser()) + dom_element.setAttribute("rotation", QString::number(m_text_item->rotation())); - return(dom_element); + return(dom_element); } /** - @brief Conductor::pathFromXml - Generate the path (of the line) from xml file by checking the segments in the xml - file - @param e - @return true if generate path success else return false + @brief Conductor::pathFromXml + Generate the path (of the line) from xml file by checking the segments in the xml + file + @param e + @return true if generate path success else return false */ bool Conductor::pathFromXml(const QDomElement &e) { - // parcourt les elements XML "segment" et en extrait deux listes de longueurs - // les segments non valides sont ignores - QList segments_x, segments_y; - for (QDomNode node = e.firstChild() ; !node.isNull() ; node = node.nextSibling()) { - // on s'interesse aux elements XML "segment" - QDomElement current_segment = node.toElement(); - if (current_segment.isNull() || current_segment.tagName() != "segment") continue; + // parcourt les elements XML "segment" et en extrait deux listes de longueurs + // les segments non valides sont ignores + QList segments_x, segments_y; + for (QDomNode node = e.firstChild() ; !node.isNull() ; node = node.nextSibling()) { + // on s'interesse aux elements XML "segment" + QDomElement current_segment = node.toElement(); + if (current_segment.isNull() || current_segment.tagName() != "segment") continue; - // le segment doit avoir une longueur - if (!current_segment.hasAttribute("length")) continue; + // le segment doit avoir une longueur + if (!current_segment.hasAttribute("length")) continue; - // cette longueur doit etre un reel - bool ok; - qreal segment_length = current_segment.attribute("length").toDouble(&ok); - if (!ok) continue; + // cette longueur doit etre un reel + bool ok; + qreal segment_length = current_segment.attribute("length").toDouble(&ok); + if (!ok) continue; - if (current_segment.attribute("orientation") == "horizontal") { - segments_x << segment_length; - segments_y << 0.0; - } else { - segments_x << 0.0; - segments_y << segment_length; - } - } + if (current_segment.attribute("orientation") == "horizontal") { + segments_x << segment_length; + segments_y << 0.0; + } else { + segments_x << 0.0; + segments_y << segment_length; + } + } - //If there isn't segment we generate automatic path and return true - if (!segments_x.size()) { - generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); - return(true); - } + //If there isn't segment we generate automatic path and return true + if (!segments_x.size()) { + generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); + return(true); + } - // les longueurs recueillies doivent etre coherentes avec les positions des bornes - qreal width = 0.0, height = 0.0; - foreach (qreal t, segments_x) width += t; - foreach (qreal t, segments_y) height += t; - QPointF t1 = terminal1 -> dockConductor(); - QPointF t2 = terminal2 -> dockConductor(); - qreal expected_width = t2.x() - t1.x(); - qreal expected_height = t2.y() - t1.y(); + // les longueurs recueillies doivent etre coherentes avec les positions des bornes + qreal width = 0.0, height = 0.0; + foreach (qreal t, segments_x) width += t; + foreach (qreal t, segments_y) height += t; + QPointF t1 = terminal1 -> dockConductor(); + QPointF t2 = terminal2 -> dockConductor(); + qreal expected_width = t2.x() - t1.x(); + qreal expected_height = t2.y() - t1.y(); - // on considere que le trajet est incoherent a partir d'une unite de difference avec l'espacement entre les bornes - if ( - qAbs(expected_width - width) > 1.0 || - qAbs(expected_height - height) > 1.0 - ) { - qDebug() << "Conductor::fromXml : les segments du conducteur ne semblent pas coherents - utilisation d'un trajet automatique"; - return(false); - } + // on considere que le trajet est incoherent a partir d'une unite de difference avec l'espacement entre les bornes + if ( + qAbs(expected_width - width) > 1.0 || + qAbs(expected_height - height) > 1.0 + ) { + qDebug() << "Conductor::fromXml : les segments du conducteur ne semblent pas coherents - utilisation d'un trajet automatique"; + return(false); + } - /* on recree les segments a partir des donnes XML */ - // cree la liste de points - QList points_list; - points_list << mapFromScene(t1); - for (int i = 0 ; i < segments_x.size() ; ++ i) { - points_list << QPointF( - points_list.last().x() + segments_x.at(i), - points_list.last().y() + segments_y.at(i) - ); - } + /* on recree les segments a partir des donnes XML */ + // cree la liste de points + QList points_list; + points_list << mapFromScene(t1); + for (int i = 0 ; i < segments_x.size() ; ++ i) { + points_list << QPointF( + points_list.last().x() + segments_x.at(i), + points_list.last().y() + segments_y.at(i) + ); + } - pointsToSegments(points_list); + pointsToSegments(points_list); - // initialise divers parametres lies a la modification des conducteurs - modified_path = true; - saveProfile(false); + // initialise divers parametres lies a la modification des conducteurs + modified_path = true; + saveProfile(false); - segmentsToPath(); - return(true); + segmentsToPath(); + return(true); } /** - @brief Conductor::handlerPoints - @return The points used to draw the handler square, used to modify - the path of the conductor. - The points stored in the QVector are the middle point of each segments that compose the conductor, - at exception of the first and last segment because there just here to extend the terminal. + @brief Conductor::handlerPoints + @return The points used to draw the handler square, used to modify + the path of the conductor. + The points stored in the QVector are the middle point of each segments that compose the conductor, + at exception of the first and last segment because there just here to extend the terminal. */ QVector Conductor::handlerPoints() const { - QList sl = segmentsList(); - if (sl.size() >= 3) - { - sl.removeFirst(); - sl.removeLast(); - } + QList sl = segmentsList(); + if (sl.size() >= 3) + { + sl.removeFirst(); + sl.removeLast(); + } - QVector middle_points; + QVector middle_points; - foreach(ConductorSegment *segment, sl) - middle_points.append(segment->middle()); + foreach(ConductorSegment *segment, sl) + middle_points.append(segment->middle()); - return middle_points; + return middle_points; } /// @return les segments de ce conducteur const QList Conductor::segmentsList() const { - if (segments == nullptr) return(QList()); + if (segments == nullptr) return(QList()); - QList segments_vector; - ConductorSegment *segment = segments; + QList segments_vector; + ConductorSegment *segment = segments; - while (segment -> hasNextSegment()) { - segments_vector << segment; - segment = segment -> nextSegment(); - } - segments_vector << segment; - return(segments_vector); + while (segment -> hasNextSegment()) { + segments_vector << segment; + segment = segment -> nextSegment(); + } + segments_vector << segment; + return(segments_vector); } /** - @brief Conductor::length - @return the length of this conductor + @brief Conductor::length + @return the length of this conductor */ qreal Conductor::length() const{ - return path().length(); + return path().length(); } /** - @return Le segment qui contient le point au milieu du conducteur + @return Le segment qui contient le point au milieu du conducteur */ ConductorSegment *Conductor::middleSegment() { - if (segments == nullptr) return(nullptr); + if (segments == nullptr) return(nullptr); - qreal half_length = length() / 2.0; + qreal half_length = length() / 2.0; - ConductorSegment *s = segments; - qreal l = 0; + ConductorSegment *s = segments; + qreal l = 0; - while (s -> hasNextSegment()) { - l += qAbs(s -> length()); - if (l >= half_length) break; - s = s -> nextSegment(); - } - // s est le segment qui contient le point au milieu du conducteur - return(s); + while (s -> hasNextSegment()) { + l += qAbs(s -> length()); + if (l >= half_length) break; + s = s -> nextSegment(); + } + // s est le segment qui contient le point au milieu du conducteur + return(s); } /** - @brief Conductor::posForText - Calculate and return the better pos for text. - @param flag : flag is used to know if text pos is near of - a vertical or horizontal conductor segment. + @brief Conductor::posForText + Calculate and return the better pos for text. + @param flag : flag is used to know if text pos is near of + a vertical or horizontal conductor segment. */ QPointF Conductor::posForText(Qt::Orientations &flag) { - ConductorSegment *segment = segments; - bool all_segment_is_vertical = true; - bool all_segment_is_horizontal = true; + ConductorSegment *segment = segments; + bool all_segment_is_vertical = true; + bool all_segment_is_horizontal = true; - //Go to first segement - while (!segment->isFirstSegment()) { - segment = segment->previousSegment(); - } + //Go to first segement + while (!segment->isFirstSegment()) { + segment = segment->previousSegment(); + } - QPointF p1 = segment -> firstPoint(); // firstPoint(); // firstPoint().x() != segment -> secondPoint().x()) - all_segment_is_vertical = false; - if (segment -> firstPoint().y() != segment -> secondPoint().y()) - all_segment_is_horizontal = false; + if (segment -> firstPoint().x() != segment -> secondPoint().x()) + all_segment_is_vertical = false; + if (segment -> firstPoint().y() != segment -> secondPoint().y()) + all_segment_is_horizontal = false; - while (segment -> hasNextSegment()) - { - segment = segment -> nextSegment(); + while (segment -> hasNextSegment()) + { + segment = segment -> nextSegment(); - if (segment -> firstPoint().x() != segment -> secondPoint().x()) - all_segment_is_vertical = false; - if (segment -> firstPoint().y() != segment -> secondPoint().y()) - all_segment_is_horizontal = false; + if (segment -> firstPoint().x() != segment -> secondPoint().x()) + all_segment_is_vertical = false; + if (segment -> firstPoint().y() != segment -> secondPoint().y()) + all_segment_is_horizontal = false; - //We must to compare length segment, but they can be negative - //so we multiply by -1 to make it positive. - int saved = biggest_segment -> length(); - if (saved < 0) saved *= -1; - int curent = segment->length(); - if (curent < 0) curent *= -1; + //We must to compare length segment, but they can be negative + //so we multiply by -1 to make it positive. + int saved = biggest_segment -> length(); + if (saved < 0) saved *= -1; + int curent = segment->length(); + if (curent < 0) curent *= -1; - if (curent > saved) biggest_segment = segment; - } + if (curent > saved) biggest_segment = segment; + } - QPointF p2 = segment -> secondPoint();// secondPoint();// p2.y()) { - p1.setY(p1.y() - (length()/2)); - } else { - p1.setY(p1.y() + (length()/2)); - } - } else if (all_segment_is_horizontal) { // p2.x()) { - p1.setX(p1.x() - (length()/2)); - } else { - p1.setX(p1.x() + (length()/2)); - } - } else { //Return the point at the middle of biggest segment. - p1 = biggest_segment->middle(); - flag = (biggest_segment->isHorizontal())? Qt::Horizontal : Qt::Vertical; - } - return p1; + //If the conductor is horizontal or vertical + //Return the point at the middle of conductor + if (all_segment_is_vertical) { // p2.y()) { + p1.setY(p1.y() - (length()/2)); + } else { + p1.setY(p1.y() + (length()/2)); + } + } else if (all_segment_is_horizontal) { // p2.x()) { + p1.setX(p1.x() - (length()/2)); + } else { + p1.setX(p1.x() + (length()/2)); + } + } else { //Return the point at the middle of biggest segment. + p1 = biggest_segment->middle(); + flag = (biggest_segment->isHorizontal())? Qt::Horizontal : Qt::Vertical; + } + return p1; } /** - @brief Conductor::calculateTextItemPosition - Move the text at middle of conductor (if is vertical or horizontal) - otherwise, move conductor at the middle of the longest segment of conductor. - If text was moved by user, this function do nothing, except check if text is near conductor. + @brief Conductor::calculateTextItemPosition + Move the text at middle of conductor (if is vertical or horizontal) + otherwise, move conductor at the middle of the longest segment of conductor. + If text was moved by user, this function do nothing, except check if text is near conductor. */ void Conductor::calculateTextItemPosition() { - if (!m_text_item || !diagram() || m_properties.type != ConductorProperties::Multi) - return; + if (!m_text_item || !diagram() || m_properties.type != ConductorProperties::Multi) + return; - if (diagram() -> defaultConductorProperties.m_one_text_per_folio == true && - relatedPotentialConductors(false).size() > 0) - { + if (diagram() -> defaultConductorProperties.m_one_text_per_folio == true && + relatedPotentialConductors(false).size() > 0) + { - Conductor *longuest_conductor = longuestConductorInPotential(this); + Conductor *longuest_conductor = longuestConductorInPotential(this); - //The longuest conductor isn't this conductor - //we call calculateTextItemPosition of the longuest conductor - if(longuest_conductor != this) - { - longuest_conductor -> calculateTextItemPosition(); - return; - } + //The longuest conductor isn't this conductor + //we call calculateTextItemPosition of the longuest conductor + if(longuest_conductor != this) + { + longuest_conductor -> calculateTextItemPosition(); + return; + } - //At this point this conductor is the longuest conductor we hide all text of conductor_list - foreach (Conductor *c, relatedPotentialConductors(false)) { - c -> textItem() -> setVisible(false); - } - //Make sure text item is visible - m_text_item -> setVisible(true); - } + //At this point this conductor is the longuest conductor we hide all text of conductor_list + foreach (Conductor *c, relatedPotentialConductors(false)) { + c -> textItem() -> setVisible(false); + } + //Make sure text item is visible + m_text_item -> setVisible(true); + } - //position - if (m_text_item -> wasMovedByUser()) - { - //Text field was moved by user : - //we check if text field is yet near the conductor - QPointF text_item_pos = m_text_item -> pos(); - QPainterPath near_shape = nearShape(); - if (!near_shape.contains(text_item_pos)) { - m_text_item -> setPos(movePointIntoPolygon(text_item_pos, near_shape)); - } - } - else - { - //Position and rotation of text is calculated. - Qt::Orientations rotation; - QPointF text_pos = posForText(rotation); + //position + if (m_text_item -> wasMovedByUser()) + { + //Text field was moved by user : + //we check if text field is yet near the conductor + QPointF text_item_pos = m_text_item -> pos(); + QPainterPath near_shape = nearShape(); + if (!near_shape.contains(text_item_pos)) { + m_text_item -> setPos(movePointIntoPolygon(text_item_pos, near_shape)); + } + } + else + { + //Position and rotation of text is calculated. + Qt::Orientations rotation; + QPointF text_pos = posForText(rotation); - if (!m_text_item -> wasRotateByUser()) - { - rotation == Qt::Vertical ? m_text_item -> setRotation(m_properties.verti_rotate_text): - m_text_item -> setRotation(m_properties.horiz_rotate_text); - } + if (!m_text_item -> wasRotateByUser()) + { + rotation == Qt::Vertical ? m_text_item -> setRotation(m_properties.verti_rotate_text): + m_text_item -> setRotation(m_properties.horiz_rotate_text); + } - //Adjust the position of text if his rotation - //is 0° or 270°, to be exactly centered to the conductor - if (m_text_item -> rotation() == 0) - { - text_pos.rx() -= m_text_item -> boundingRect().width()/2; - if(m_properties.m_horizontal_alignment == Qt::AlignTop) - text_pos.ry() -= m_text_item->boundingRect().height(); - } - else if (m_text_item -> rotation() == 270) - { - text_pos.ry() += m_text_item -> boundingRect().width()/2; - if(m_properties.m_vertical_alignment == Qt::AlignLeft) - text_pos.rx() -= m_text_item->boundingRect().height(); - } + //Adjust the position of text if his rotation + //is 0?? or 270??, to be exactly centered to the conductor + if (m_text_item -> rotation() == 0) + { + text_pos.rx() -= m_text_item -> boundingRect().width()/2; + if(m_properties.m_horizontal_alignment == Qt::AlignTop) + text_pos.ry() -= m_text_item->boundingRect().height(); + } + else if (m_text_item -> rotation() == 270) + { + text_pos.ry() += m_text_item -> boundingRect().width()/2; + if(m_properties.m_vertical_alignment == Qt::AlignLeft) + text_pos.rx() -= m_text_item->boundingRect().height(); + } - m_text_item -> setPos(text_pos); + m_text_item -> setPos(text_pos); - //Ensure text item don't collide with this conductor - while (m_text_item->collidesWithItem(this)) - { - if(rotation == Qt::Vertical) - { - if(m_properties.m_vertical_alignment == Qt::AlignRight) - m_text_item->setX(m_text_item->x()+1); - else if (m_properties.m_vertical_alignment == Qt::AlignLeft) - m_text_item->setX(m_text_item->x()-1); - else - return; //avoid infinite loop - } - else if (rotation == Qt::Horizontal) - { - if(m_properties.m_horizontal_alignment == Qt::AlignTop) - m_text_item->setY(m_text_item->y()-1); - else if (m_properties.m_horizontal_alignment == Qt::AlignBottom) - m_text_item->setY(m_text_item->y()+1); - else - return; //avoid infinite loop - } - } - } + //Ensure text item don't collide with this conductor + while (m_text_item->collidesWithItem(this)) + { + if(rotation == Qt::Vertical) + { + if(m_properties.m_vertical_alignment == Qt::AlignRight) + m_text_item->setX(m_text_item->x()+1); + else if (m_properties.m_vertical_alignment == Qt::AlignLeft) + m_text_item->setX(m_text_item->x()-1); + else + return; //avoid infinite loop + } + else if (rotation == Qt::Horizontal) + { + if(m_properties.m_horizontal_alignment == Qt::AlignTop) + m_text_item->setY(m_text_item->y()-1); + else if (m_properties.m_horizontal_alignment == Qt::AlignBottom) + m_text_item->setY(m_text_item->y()+1); + else + return; //avoid infinite loop + } + } + } } /** - Sauvegarde le profil courant du conducteur pour l'utiliser ulterieurement - dans priv_modifieConductor. + Sauvegarde le profil courant du conducteur pour l'utiliser ulterieurement + dans priv_modifieConductor. */ void Conductor::saveProfile(bool undo) { - Qt::Corner current_path_type = currentPathType(); - ConductorProfile old_profile(conductor_profiles[current_path_type]); - conductor_profiles[current_path_type].fromConductor(this); - Diagram *dia = diagram(); - if (undo && dia) { - ChangeConductorCommand *undo_object = new ChangeConductorCommand( - this, - old_profile, - conductor_profiles[current_path_type], - current_path_type - ); - undo_object -> setConductorTextItemMove(before_mov_text_pos_, m_text_item -> pos()); - dia -> undoStack().push(undo_object); - } + Qt::Corner current_path_type = currentPathType(); + ConductorProfile old_profile(conductor_profiles[current_path_type]); + conductor_profiles[current_path_type].fromConductor(this); + Diagram *dia = diagram(); + if (undo && dia) { + ChangeConductorCommand *undo_object = new ChangeConductorCommand( + this, + old_profile, + conductor_profiles[current_path_type], + current_path_type + ); + undo_object -> setConductorTextItemMove(before_mov_text_pos_, m_text_item -> pos()); + dia -> undoStack().push(undo_object); + } } /** - @param value1 Premiere valeur - @param value2 Deuxieme valeur - @return 1 si les deux valeurs sont de meme signe, -1 sinon + @param value1 Premiere valeur + @param value2 Deuxieme valeur + @return 1 si les deux valeurs sont de meme signe, -1 sinon */ int Conductor::getCoeff(const qreal &value1, const qreal &value2) { - return(getSign(value1) * getSign(value2)); + return(getSign(value1) * getSign(value2)); } /** - @param value valeur - @return 1 si valeur est negatif, 1 s'il est positif ou nul + @param value valeur + @return 1 si valeur est negatif, 1 s'il est positif ou nul */ int Conductor::getSign(const qreal &value) { - return(value < 0 ? -1 : 1); + return(value < 0 ? -1 : 1); } /** - Applique un nouveau profil a ce conducteur - @param cp Profil a appliquer a ce conducteur - @param path_type Type de trajet pour lequel ce profil convient + Applique un nouveau profil a ce conducteur + @param cp Profil a appliquer a ce conducteur + @param path_type Type de trajet pour lequel ce profil convient */ void Conductor::setProfile(const ConductorProfile &cp, Qt::Corner path_type) { - conductor_profiles[path_type] = cp; - // si le type de trajet correspond a l'actuel - if (currentPathType() == path_type) { - if (conductor_profiles[path_type].isNull()) { - generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); - modified_path = false; - } else { - updateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); - modified_path = true; - } - if (type() == ConductorProperties::Multi) { - calculateTextItemPosition(); - } - } + conductor_profiles[path_type] = cp; + // si le type de trajet correspond a l'actuel + if (currentPathType() == path_type) { + if (conductor_profiles[path_type].isNull()) { + generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); + modified_path = false; + } else { + updateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); + modified_path = true; + } + if (type() == ConductorProperties::Multi) { + calculateTextItemPosition(); + } + } } /// @return le profil de ce conducteur ConductorProfile Conductor::profile(Qt::Corner path_type) const { - return(conductor_profiles[path_type]); + return(conductor_profiles[path_type]); } /** - @brief Conductor::refreshText - Refresh the text of this conductor. - recalcule and set the text according to the formula. + @brief Conductor::refreshText + Refresh the text of this conductor. + recalcule and set the text according to the formula. */ void Conductor::refreshText() { - if (m_freeze_label) - { - m_text_item->setPlainText(m_properties.text); - } - else - { - if (!m_properties.m_formula.isEmpty()) - { - if (diagram()) - { - QString text = autonum::AssignVariables::formulaToLabel(m_properties.m_formula, m_autoNum_seq, diagram()); - m_properties.text = text; - m_text_item->setPlainText(text); - } - else - { - m_properties.text = m_properties.m_formula; - m_text_item->setPlainText(m_properties.text); - } - } - else - { - m_text_item->setPlainText(m_properties.text); - } - } + if (m_freeze_label) + { + m_text_item->setPlainText(m_properties.text); + } + else + { + if (!m_properties.m_formula.isEmpty()) + { + if (diagram()) + { + QString text = autonum::AssignVariables::formulaToLabel(m_properties.m_formula, m_autoNum_seq, diagram()); + m_properties.text = text; + m_text_item->setPlainText(text); + } + else + { + m_properties.text = m_properties.m_formula; + m_text_item->setPlainText(m_properties.text); + } + } + else + { + m_text_item->setPlainText(m_properties.text); + } + } } void Conductor::setPath(const QPainterPath &path) { - if(path == m_path) - return; + if(path == m_path) + return; - prepareGeometryChange(); - m_path = path; - update(); + prepareGeometryChange(); + m_path = path; + update(); } QPainterPath Conductor::path() const { - return m_path; + return m_path; } /** - @brief Conductor::setPropertiesToPotential - @param property - @param only_text - Set propertie to conductor and every conductors in - the same potential of conductor. - If only_text is true only formula, text, - function and tension/protocol is set - to other conductor in the same potential, - the other values of property stay unmodified + @brief Conductor::setPropertiesToPotential + @param property + @param only_text + Set propertie to conductor and every conductors in + the same potential of conductor. + If only_text is true only formula, text, + function and tension/protocol is set + to other conductor in the same potential, + the other values of property stay unmodified */ void Conductor::setPropertyToPotential(const ConductorProperties &property, - bool only_text) + bool only_text) { - setProperties(property); - QSet potential_list = relatedPotentialConductors(); + setProperties(property); + QSet potential_list = relatedPotentialConductors(); - foreach(Conductor *other_conductor, potential_list) - { - if (only_text) - { - ConductorProperties other_properties = other_conductor->properties(); - other_properties.m_formula = m_properties.m_formula; - other_properties.text = m_properties.text; - other_properties.m_function = m_properties.m_function; - other_properties.m_tension_protocol = m_properties.m_tension_protocol; - other_properties.m_wire_color = m_properties.m_wire_color; - other_properties.m_wire_section = m_properties.m_wire_section; - other_conductor->setProperties(other_properties); - } - else - { - other_conductor->setProperties(property); - } - } + foreach(Conductor *other_conductor, potential_list) + { + if (only_text) + { + ConductorProperties other_properties = other_conductor->properties(); + other_properties.m_formula = m_properties.m_formula; + other_properties.text = m_properties.text; + other_properties.m_function = m_properties.m_function; + other_properties.m_tension_protocol = m_properties.m_tension_protocol; + other_properties.m_wire_color = m_properties.m_wire_color; + other_properties.m_wire_section = m_properties.m_wire_section; + other_conductor->setProperties(other_properties); + } + else + { + other_conductor->setProperties(property); + } + } } /** - @brief Conductor::setProperties - Set property as current property of conductor - @param property : properties + @brief Conductor::setProperties + Set property as current property of conductor + @param property : properties */ void Conductor::setProperties(const ConductorProperties &property) { - if (m_properties == property) return; + if (m_properties == property) return; - QString formula = m_properties.m_formula; - m_properties = property; + QString formula = m_properties.m_formula; + m_properties = property; - if (!m_properties.m_formula.isEmpty()) - { - if (diagram()) - { - QString text = autonum::AssignVariables::formulaToLabel(m_properties.m_formula, m_autoNum_seq, diagram()); - m_properties.text = text; - } - else if (m_properties.text.isEmpty()) - { - m_properties.text = m_properties.m_formula; - } + if (!m_properties.m_formula.isEmpty()) + { + if (diagram()) + { + QString text = autonum::AssignVariables::formulaToLabel(m_properties.m_formula, m_autoNum_seq, diagram()); + m_properties.text = text; + } + else if (m_properties.text.isEmpty()) + { + m_properties.text = m_properties.m_formula; + } - setUpConnectionForFormula(formula, m_properties.m_formula); - } + setUpConnectionForFormula(formula, m_properties.m_formula); + } - m_text_item->setPlainText(m_properties.text); - QFont font = m_text_item->font(); - font.setPointSize(m_properties.text_size); - m_text_item->setFont(font); - m_text_item->setColor(m_properties.text_color); + m_text_item->setPlainText(m_properties.text); + QFont font = m_text_item->font(); + font.setPointSize(m_properties.text_size); + m_text_item->setFont(font); + m_text_item->setColor(m_properties.text_color); - if (m_properties.type != ConductorProperties::Multi) - m_text_item->setVisible(false); - else - m_text_item->setVisible(m_properties.m_show_text); + if (m_properties.type != ConductorProperties::Multi) + m_text_item->setVisible(false); + else + m_text_item->setVisible(m_properties.m_show_text); - calculateTextItemPosition(); - update(); + calculateTextItemPosition(); + update(); - emit propertiesChange(); + emit propertiesChange(); } /** - @brief Conductor::properties - @return the properties of this Conductor + @brief Conductor::properties + @return the properties of this Conductor */ ConductorProperties Conductor::properties() const { - return(m_properties); + return(m_properties); } /** - @return true si le conducteur est mis en evidence + @return true si le conducteur est mis en evidence */ Conductor::Highlight Conductor::highlight() const { - return(must_highlight_); + return(must_highlight_); } /** - @param hl true pour mettre le conducteur en evidence, false sinon + @param hl true pour mettre le conducteur en evidence, false sinon */ void Conductor::setHighlighted(Conductor::Highlight hl) { - must_highlight_ = hl; - update(); + must_highlight_ = hl; + update(); } /** - @brief Conductor::displayedTextChanged - Update the properties (text) of this conductor and other conductors - at the same potential of this conductor. + @brief Conductor::displayedTextChanged + Update the properties (text) of this conductor and other conductors + at the same potential of this conductor. */ void Conductor::displayedTextChanged() { - QVariant old_value, new_value; - old_value.setValue(m_properties); - ConductorProperties new_properties(m_properties); - new_properties.m_formula = m_text_item->toPlainText(); - new_properties.text = m_text_item->toPlainText(); - new_value.setValue(new_properties); + QVariant old_value, new_value; + old_value.setValue(m_properties); + ConductorProperties new_properties(m_properties); + new_properties.m_formula = m_text_item->toPlainText(); + new_properties.text = m_text_item->toPlainText(); + new_value.setValue(new_properties); - QUndoCommand *undo = new QUndoCommand(tr("Modifier les propriétés d'un conducteur", "undo caption")); - new QPropertyUndoCommand(this, "properties", old_value, new_value, undo); + QUndoCommand *undo = new QUndoCommand(tr("Modifier les propri??t??s d'un conducteur", "undo caption")); + new QPropertyUndoCommand(this, "properties", old_value, new_value, undo); - if (!relatedPotentialConductors().isEmpty()) - { - undo->setText(tr("Modifier les propriétés de plusieurs conducteurs", "undo caption")); + if (!relatedPotentialConductors().isEmpty()) + { + undo->setText(tr("Modifier les propri??t??s de plusieurs conducteurs", "undo caption")); - foreach (Conductor *potential_conductor, relatedPotentialConductors()) - { - old_value.setValue(potential_conductor->properties()); - ConductorProperties new_properties = potential_conductor->properties(); - new_properties.m_formula = m_text_item->toPlainText(); - new_properties.text = m_text_item->toPlainText(); - new_value.setValue(new_properties); - new QPropertyUndoCommand (potential_conductor, "properties", old_value, new_value, undo); - } - } + foreach (Conductor *potential_conductor, relatedPotentialConductors()) + { + old_value.setValue(potential_conductor->properties()); + ConductorProperties new_properties = potential_conductor->properties(); + new_properties.m_formula = m_text_item->toPlainText(); + new_properties.text = m_text_item->toPlainText(); + new_value.setValue(new_properties); + new QPropertyUndoCommand (potential_conductor, "properties", old_value, new_value, undo); + } + } - diagram()->undoStack().push(undo); + diagram()->undoStack().push(undo); } /** - @brief Conductor::relatedPotentialConductors - Return all conductors at the same potential of this conductor, - this conductor isn't part of the returned QSet. - @param all_diagram : if true search in all diagram of the project, - false search only in the parent diagram of this conductor - @param t_list : a list of terminal already found for this potential. - @return a QSet of conductor at the same potential. + @brief Conductor::relatedPotentialConductors + Return all conductors at the same potential of this conductor, + this conductor isn't part of the returned QSet. + @param all_diagram : if true search in all diagram of the project, + false search only in the parent diagram of this conductor + @param t_list : a list of terminal already found for this potential. + @return a QSet of conductor at the same potential. */ QSet Conductor::relatedPotentialConductors(const bool all_diagram, QList *t_list) { - bool declar_t_list = false; - if (t_list == nullptr) - { - declar_t_list = true; - t_list = new QList ; - } + bool declar_t_list = false; + if (t_list == nullptr) + { + declar_t_list = true; + t_list = new QList ; + } - QSet other_conductors; - QList this_terminal; - this_terminal << terminal1 << terminal2; + QSet other_conductors; + QList this_terminal; + this_terminal << terminal1 << terminal2; - // Return all conductors of terminal 1 and 2 - for (Terminal *terminal : this_terminal) - { - if (!t_list->contains(terminal)) - { - t_list->append(terminal); - QList other_conductors_list_t = terminal->conductors(); + // Return all conductors of terminal 1 and 2 + for (Terminal *terminal : this_terminal) + { + if (!t_list->contains(terminal)) + { + t_list->append(terminal); + QList other_conductors_list_t = terminal->conductors(); - //Get the other terminals of the parent element of @terminal, who share the same potential - //This is use for element type "folio report" and "terminal element" - for (Terminal *t : relatedPotentialTerminal(terminal, all_diagram)) - { - if (!t_list->contains(t)) - { - t_list -> append(t); - other_conductors_list_t += t->conductors(); - } - } + //Get the other terminals of the parent element of @terminal, who share the same potential + //This is use for element type "folio report" and "terminal element" + for (Terminal *t : relatedPotentialTerminal(terminal, all_diagram)) + { + if (!t_list->contains(t)) + { + t_list -> append(t); + other_conductors_list_t += t->conductors(); + } + } - other_conductors_list_t.removeAll(this); - //Get the conductors at the same potential for each conductors of other_conductors_list_t - for (Conductor *c : other_conductors_list_t) { - other_conductors += c->relatedPotentialConductors(all_diagram, t_list); - } -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove - other_conductors += other_conductors_list_t.toSet(); + other_conductors_list_t.removeAll(this); + //Get the conductors at the same potential for each conductors of other_conductors_list_t + for (Conductor *c : other_conductors_list_t) { + other_conductors += c->relatedPotentialConductors(all_diagram, t_list); + } +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove + other_conductors += other_conductors_list_t.toSet(); #else #if TODO_LIST #pragma message("@TODO remove code for QT 5.14 or later") #endif - other_conductors += QSet(other_conductors_list_t.begin(),other_conductors_list_t.end()); + other_conductors += QSet(other_conductors_list_t.begin(),other_conductors_list_t.end()); #endif - } - } + } + } - other_conductors.remove(this); + other_conductors.remove(this); - if (declar_t_list) delete t_list; - return(other_conductors); + if (declar_t_list) delete t_list; + return(other_conductors); } /** - @brief Conductor::diagramEditor - @return The parent diagram editor or nullptr; + @brief Conductor::diagramEditor + @return The parent diagram editor or nullptr; */ QETDiagramEditor* Conductor::diagramEditor() const { - if (!diagram()) return nullptr; - if (diagram() -> views().isEmpty()) return nullptr; + if (!diagram()) return nullptr; + if (diagram() -> views().isEmpty()) return nullptr; - QWidget *w = const_cast(diagram() -> views().at(0)); - while (w -> parentWidget() && !w -> isWindow()) { - w = w -> parentWidget(); - } - return(qobject_cast(w)); + QWidget *w = const_cast(diagram() -> views().at(0)); + while (w -> parentWidget() && !w -> isWindow()) { + w = w -> parentWidget(); + } + return(qobject_cast(w)); } /** - @brief Conductor::editProperty + @brief Conductor::editProperty */ void Conductor::editProperty() { - ConductorPropertiesDialog::PropertiesDialog(this, diagramEditor()); + ConductorPropertiesDialog::PropertiesDialog(this, diagramEditor()); } void Conductor::setSequenceNum(const autonum::sequentialNumbers& sn) { - m_autoNum_seq = sn; - refreshText(); + m_autoNum_seq = sn; + refreshText(); } /** - @brief Conductor::setUpConnectionForFormula - setup connection according to the variable of formula - @param old_formula - @param new_formula + @brief Conductor::setUpConnectionForFormula + setup connection according to the variable of formula + @param old_formula + @param new_formula */ void Conductor::setUpConnectionForFormula(QString old_formula, QString new_formula) { - if (diagram()) - { - //Because the variable %F is a reference to another text which can contain variables, - //we must to replace %F by the real text, to check if the real text contain the variable %id - if (old_formula.contains("%F")) - old_formula.replace("%F", diagram()->border_and_titleblock.folio()); + if (diagram()) + { + //Because the variable %F is a reference to another text which can contain variables, + //we must to replace %F by the real text, to check if the real text contain the variable %id + if (old_formula.contains("%F")) + old_formula.replace("%F", diagram()->border_and_titleblock.folio()); - if (old_formula.contains("%id")) - disconnect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText); + if (old_formula.contains("%id")) + disconnect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText); - //Label is frozen, so we don't update it. - if (m_freeze_label == true) - return; + //Label is frozen, so we don't update it. + if (m_freeze_label == true) + return; - if (new_formula.contains("%F")) - new_formula.replace("%F", diagram()->border_and_titleblock.folio()); + if (new_formula.contains("%F")) + new_formula.replace("%F", diagram()->border_and_titleblock.folio()); - if (new_formula.contains("%id")) - connect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText); - } + if (new_formula.contains("%id")) + connect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText); + } } /** - @param a point - @param b point - @param c point - @return true si le point a est contenu dans le rectangle delimite par les points b et c + @param a point + @param b point + @param c point + @return true si le point a est contenu dans le rectangle delimite par les points b et c */ bool isContained(const QPointF &a, const QPointF &b, const QPointF &c) { - return( - isBetween(a.x(), b.x(), c.x()) && - isBetween(a.y(), b.y(), c.y()) - ); + return( + isBetween(a.x(), b.x(), c.x()) && + isBetween(a.y(), b.y(), c.y()) + ); } /** - @return la liste des positions des jonctions avec d'autres conducteurs + @return la liste des positions des jonctions avec d'autres conducteurs */ QList Conductor::junctions() const { - QList junctions_list; + QList junctions_list; - // pour qu'il y ait des jonctions, il doit y avoir d'autres conducteurs et des bifurcations - QList other_conductors = relatedConductors(this); - QList bends_list = bends(); - if (other_conductors.isEmpty() || bends_list.isEmpty()) { - return(junctions_list); - } + // pour qu'il y ait des jonctions, il doit y avoir d'autres conducteurs et des bifurcations + QList other_conductors = relatedConductors(this); + QList bends_list = bends(); + if (other_conductors.isEmpty() || bends_list.isEmpty()) { + return(junctions_list); + } - QList points = segmentsToPoints(); - for (int i = 1 ; i < (points.size() -1) ; ++ i) { - QPointF point = points.at(i); + QList points = segmentsToPoints(); + for (int i = 1 ; i < (points.size() -1) ; ++ i) { + QPointF point = points.at(i); - // determine si le point est une bifurcation ou non - bool is_bend = false; - Qt::Corner current_bend_type = Qt::TopLeftCorner; - foreach(ConductorBend cb, bends_list) - { - if (cb.first == point) - { - is_bend = true; - current_bend_type = cb.second; - break; - } - } - // si le point n'est pas une bifurcation, il ne peut etre une jonction (enfin pas au niveau de ce conducteur) - if (!is_bend) continue; + // determine si le point est une bifurcation ou non + bool is_bend = false; + Qt::Corner current_bend_type = Qt::TopLeftCorner; + foreach(ConductorBend cb, bends_list) + { + if (cb.first == point) + { + is_bend = true; + current_bend_type = cb.second; + break; + } + } + // si le point n'est pas une bifurcation, il ne peut etre une jonction (enfin pas au niveau de ce conducteur) + if (!is_bend) continue; - bool is_junction = false; - QPointF scene_point = mapToScene(point); - foreach(Conductor *c, other_conductors) - { - // exprime le point dans les coordonnees de l'autre conducteur - QPointF conductor_point = c -> mapFromScene(scene_point); - // recupere les segments de l'autre conducteur - QList c_segments = c -> segmentsList(); - if (c_segments.isEmpty()) - continue; - // parcoure les segments a la recherche d'un point commun - for (int j = 0 ; j < c_segments.count() ; ++ j) - { - ConductorSegment *segment = c_segments[j]; - // un point commun a ete trouve sur ce segment - if (isContained(conductor_point, segment -> firstPoint(), segment -> secondPoint())) - { - is_junction = true; - // ce point commun ne doit pas etre une bifurcation identique a celle-ci - QList other_conductor_bends = c -> bends(); - foreach(ConductorBend cb, other_conductor_bends) - { - if (cb.first == conductor_point && cb.second == current_bend_type) - { - is_junction = false; - } - } - } - if (is_junction) junctions_list << point; - } - } - } - return(junctions_list); + bool is_junction = false; + QPointF scene_point = mapToScene(point); + foreach(Conductor *c, other_conductors) + { + // exprime le point dans les coordonnees de l'autre conducteur + QPointF conductor_point = c -> mapFromScene(scene_point); + // recupere les segments de l'autre conducteur + QList c_segments = c -> segmentsList(); + if (c_segments.isEmpty()) + continue; + // parcoure les segments a la recherche d'un point commun + for (int j = 0 ; j < c_segments.count() ; ++ j) + { + ConductorSegment *segment = c_segments[j]; + // un point commun a ete trouve sur ce segment + if (isContained(conductor_point, segment -> firstPoint(), segment -> secondPoint())) + { + is_junction = true; + // ce point commun ne doit pas etre une bifurcation identique a celle-ci + QList other_conductor_bends = c -> bends(); + foreach(ConductorBend cb, other_conductor_bends) + { + if (cb.first == conductor_point && cb.second == current_bend_type) + { + is_junction = false; + } + } + } + if (is_junction) junctions_list << point; + } + } + } + return(junctions_list); } /** - @return la liste des bifurcations de ce conducteur ; ConductorBend est un - typedef pour une QPair\. Le point indique la position - (en coordonnees locales) de la bifurcation tandis que le Corner indique le - type de bifurcation. + @return la liste des bifurcations de ce conducteur ; ConductorBend est un + typedef pour une QPair\. Le point indique la position + (en coordonnees locales) de la bifurcation tandis que le Corner indique le + type de bifurcation. */ QList Conductor::bends() const { - QList points; - if (!segments) return(points); + QList points; + if (!segments) return(points); - // recupere la liste des segments de taille non nulle - QList visible_segments; - ConductorSegment *segment = segments; - while (segment -> hasNextSegment()) { - if (!segment -> isPoint()) visible_segments << segment; - segment = segment -> nextSegment(); - } - if (!segment -> isPoint()) visible_segments << segment; + // recupere la liste des segments de taille non nulle + QList visible_segments; + ConductorSegment *segment = segments; + while (segment -> hasNextSegment()) { + if (!segment -> isPoint()) visible_segments << segment; + segment = segment -> nextSegment(); + } + if (!segment -> isPoint()) visible_segments << segment; - ConductorSegment *next_segment; - for (int i = 0 ; i < visible_segments.count() -1 ; ++ i) { - segment = visible_segments[i]; - next_segment = visible_segments[i + 1]; - if (!segment -> isPoint() && !next_segment -> isPoint()) { - // si les deux segments ne sont pas dans le meme sens, on a une bifurcation - if (next_segment -> type() != segment -> type()) { - Qt::Corner bend_type; - qreal sl = segment -> length(); - qreal nsl = next_segment -> length(); + ConductorSegment *next_segment; + for (int i = 0 ; i < visible_segments.count() -1 ; ++ i) { + segment = visible_segments[i]; + next_segment = visible_segments[i + 1]; + if (!segment -> isPoint() && !next_segment -> isPoint()) { + // si les deux segments ne sont pas dans le meme sens, on a une bifurcation + if (next_segment -> type() != segment -> type()) { + Qt::Corner bend_type; + qreal sl = segment -> length(); + qreal nsl = next_segment -> length(); - if (segment -> isHorizontal()) { - if (sl < 0 && nsl < 0) { - bend_type = Qt::BottomLeftCorner; - } else if (sl < 0 && nsl > 0) { - bend_type = Qt::TopLeftCorner; - } else if (sl > 0 && nsl < 0) { - bend_type = Qt::BottomRightCorner; - } else { - bend_type = Qt::TopRightCorner; - } - } else { - if (sl < 0 && nsl < 0) { - bend_type = Qt::TopRightCorner; - } else if (sl < 0 && nsl > 0) { - bend_type = Qt::TopLeftCorner; - } else if (sl > 0 && nsl < 0) { - bend_type = Qt::BottomRightCorner; - } else { - bend_type = Qt::BottomLeftCorner; - } - } - points << qMakePair(segment -> secondPoint(), bend_type); - } - } - } - return(points); + if (segment -> isHorizontal()) { + if (sl < 0 && nsl < 0) { + bend_type = Qt::BottomLeftCorner; + } else if (sl < 0 && nsl > 0) { + bend_type = Qt::TopLeftCorner; + } else if (sl > 0 && nsl < 0) { + bend_type = Qt::BottomRightCorner; + } else { + bend_type = Qt::TopRightCorner; + } + } else { + if (sl < 0 && nsl < 0) { + bend_type = Qt::TopRightCorner; + } else if (sl < 0 && nsl > 0) { + bend_type = Qt::TopLeftCorner; + } else if (sl > 0 && nsl < 0) { + bend_type = Qt::BottomRightCorner; + } else { + bend_type = Qt::BottomLeftCorner; + } + } + points << qMakePair(segment -> secondPoint(), bend_type); + } + } + } + return(points); } /** - @param start Point de depart - @param end Point d'arrivee - @return le coin vers lequel se dirige le trajet de start vers end + @param start Point de depart + @param end Point d'arrivee + @return le coin vers lequel se dirige le trajet de start vers end */ Qt::Corner Conductor::movementType(const QPointF &start, const QPointF &end) { - Qt::Corner result = Qt::BottomRightCorner; - if (start.x() <= end.x()) { - result = start.y() <= end.y() ? Qt::BottomRightCorner : Qt::TopRightCorner; - } else { - result = start.y() <= end.y() ? Qt::BottomLeftCorner : Qt::TopLeftCorner; - } - return(result); + Qt::Corner result = Qt::BottomRightCorner; + if (start.x() <= end.x()) { + result = start.y() <= end.y() ? Qt::BottomRightCorner : Qt::TopRightCorner; + } else { + result = start.y() <= end.y() ? Qt::BottomLeftCorner : Qt::TopLeftCorner; + } + return(result); } /// @return le type de trajet actuel de ce conducteur Qt::Corner Conductor::currentPathType() const { - return(movementType(terminal1 -> dockConductor(), terminal2 -> dockConductor())); + return(movementType(terminal1 -> dockConductor(), terminal2 -> dockConductor())); } /// @return les profils de ce conducteur ConductorProfilesGroup Conductor::profiles() const { - return(conductor_profiles); + return(conductor_profiles); } /** - @brief Conductor::setProfiles - @param cpg : the new profils of conductor + @brief Conductor::setProfiles + @param cpg : the new profils of conductor */ void Conductor::setProfiles(const ConductorProfilesGroup &cpg) { - conductor_profiles = cpg; - if (conductor_profiles[currentPathType()].isNull()) { - generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); - modified_path = false; - } else { - updateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); - modified_path = true; - } - if (properties().type == ConductorProperties::Multi) { - calculateTextItemPosition(); - } + conductor_profiles = cpg; + if (conductor_profiles[currentPathType()].isNull()) { + generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); + modified_path = false; + } else { + updateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); + modified_path = true; + } + if (properties().type == ConductorProperties::Multi) { + calculateTextItemPosition(); + } } /// Supprime les segments void Conductor::deleteSegments() { - if (segments != nullptr) { - while (segments -> hasNextSegment()) delete segments -> nextSegment(); - delete segments; - segments = nullptr; - } + if (segments != nullptr) { + while (segments -> hasNextSegment()) delete segments -> nextSegment(); + delete segments; + segments = nullptr; + } } /** - @param point Un point situe a l'exterieur du polygone - @param polygon Le polygone dans lequel on veut rapatrier le point - @return la position du point, une fois ramene dans le polygone, ou plus - exactement sur le bord du polygone + @param point Un point situe a l'exterieur du polygone + @param polygon Le polygone dans lequel on veut rapatrier le point + @return la position du point, une fois ramene dans le polygone, ou plus + exactement sur le bord du polygone */ QPointF Conductor::movePointIntoPolygon(const QPointF &point, const QPainterPath &polygon) { - // decompose le polygone en lignes et points - QList polygons = polygon.simplified().toSubpathPolygons(); - QList lines; - QList points; - foreach(QPolygonF polygon, polygons) { - if (polygon.count() <= 1) continue; + // decompose le polygone en lignes et points + QList polygons = polygon.simplified().toSubpathPolygons(); + QList lines; + QList points; + foreach(QPolygonF polygon, polygons) { + if (polygon.count() <= 1) continue; - // on recense les lignes et les points - for (int i = 1 ; i < polygon.count() ; ++ i) { - lines << QLineF(polygon.at(i - 1), polygon.at(i)); - points << polygon.at(i -1); - } - } + // on recense les lignes et les points + for (int i = 1 ; i < polygon.count() ; ++ i) { + lines << QLineF(polygon.at(i - 1), polygon.at(i)); + points << polygon.at(i -1); + } + } - // on fait des projetes orthogonaux du point sur les differents segments du - // polygone, en les triant par longueur croissante - QMap intersections; - foreach (QLineF line, lines) { - QPointF intersection_point; - if (QET::orthogonalProjection(point, line, &intersection_point)) { - intersections.insert(QLineF(intersection_point, point).length(), intersection_point); - } - } - if (intersections.count()) { - // on determine la plus courte longueur pour un projete orthogonal - QPointF the_point = intersections[intersections.keys().first()]; - return(the_point); - } else { - // determine le coin du polygone le plus proche du point exterieur - qreal minimum_length = -1; - int point_index = -1; - for (int i = 0 ; i < points.count() ; ++ i) { - qreal length = qAbs(QLineF(points.at(i), point).length()); - if (minimum_length < 0 || length < minimum_length) { - minimum_length = length; - point_index = i; - } - } - // on connait desormais le coin le plus proche du texte + // on fait des projetes orthogonaux du point sur les differents segments du + // polygone, en les triant par longueur croissante + QMap intersections; + foreach (QLineF line, lines) { + QPointF intersection_point; + if (QET::orthogonalProjection(point, line, &intersection_point)) { + intersections.insert(QLineF(intersection_point, point).length(), intersection_point); + } + } + if (intersections.count()) { + // on determine la plus courte longueur pour un projete orthogonal + QPointF the_point = intersections[intersections.keys().first()]; + return(the_point); + } else { + // determine le coin du polygone le plus proche du point exterieur + qreal minimum_length = -1; + int point_index = -1; + for (int i = 0 ; i < points.count() ; ++ i) { + qreal length = qAbs(QLineF(points.at(i), point).length()); + if (minimum_length < 0 || length < minimum_length) { + minimum_length = length; + point_index = i; + } + } + // on connait desormais le coin le plus proche du texte - // aucun projete orthogonal n'a donne quoi que ce soit, on met le texte sur un des coins du polygone - return(points.at(point_index)); - } + // aucun projete orthogonal n'a donne quoi que ce soit, on met le texte sur un des coins du polygone + return(points.at(point_index)); + } } /** - @brief longuestConductorInPotential - @param conductor : a conductor in the potential to search - @param all_diagram : true -> search in the whole project, false -> search only in the diagram of conductor - @return the longuest conductor in the same potential of conductor + @brief longuestConductorInPotential + @param conductor : a conductor in the potential to search + @param all_diagram : true -> search in the whole project, false -> search only in the diagram of conductor + @return the longuest conductor in the same potential of conductor */ Conductor * longuestConductorInPotential(Conductor *conductor, bool all_diagram) { - Conductor *longuest_conductor = conductor; - //Search the longuest conductor - foreach (Conductor *c, conductor -> relatedPotentialConductors(all_diagram)) - if (c -> length() > longuest_conductor -> length()) - longuest_conductor = c; + Conductor *longuest_conductor = conductor; + //Search the longuest conductor + foreach (Conductor *c, conductor -> relatedPotentialConductors(all_diagram)) + if (c -> length() > longuest_conductor -> length()) + longuest_conductor = c; - return longuest_conductor; + return longuest_conductor; } /** - @brief relatedConductors - @param conductor - @return return all conductors who share the same terminals - of conductor given as parametre, - except conductor himself. + @brief relatedConductors + @param conductor + @return return all conductors who share the same terminals + of conductor given as parametre, + except conductor himself. */ QList relatedConductors(const Conductor *conductor) { - QList other_conductors_list = conductor -> terminal1 -> conductors(); - other_conductors_list << conductor -> terminal2->conductors(); - other_conductors_list.removeAll(const_cast (conductor)); - return(other_conductors_list); + QList other_conductors_list = conductor -> terminal1 -> conductors(); + other_conductors_list << conductor -> terminal2->conductors(); + other_conductors_list.removeAll(const_cast (conductor)); + return(other_conductors_list); } /** - @brief Conductor::setFreezeLabel - Freeze this conductor label if true - Unfreeze this conductor label if false - @param freeze + @brief Conductor::setFreezeLabel + Freeze this conductor label if true + Unfreeze this conductor label if false + @param freeze */ void Conductor::setFreezeLabel(bool freeze) { - m_freeze_label = freeze; + m_freeze_label = freeze; - if (m_freeze_label != freeze) - { - m_freeze_label = freeze; - QString f = m_properties.m_formula; - setUpConnectionForFormula(f,f); - } + if (m_freeze_label != freeze) + { + m_freeze_label = freeze; + QString f = m_properties.m_formula; + setUpConnectionForFormula(f,f); + } } diff --git a/sources/qetgraphicsitem/conductor.h b/sources/qetgraphicsitem/conductor.h index 2bc04ac8e..8680343f6 100644 --- a/sources/qetgraphicsitem/conductor.h +++ b/sources/qetgraphicsitem/conductor.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef CONDUCTOR_H #define CONDUCTOR_H @@ -36,200 +36,200 @@ class QetGraphicsHandlerItem; typedef QPair ConductorBend; typedef QHash ConductorProfilesGroup; /** - This class represents a conductor, i.e. a wire between two element - terminals. + This class represents a conductor, i.e. a wire between two element + terminals. */ class Conductor : public QGraphicsObject { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QPointF pos READ pos WRITE setPos) - Q_PROPERTY(int animPath READ fakePath WRITE updatePathAnimate) - Q_PROPERTY(ConductorProperties properties READ properties WRITE setProperties) - Q_PROPERTY(autonum::sequentialNumbers sequenceNum READ sequenceNum WRITE setSequenceNum) + Q_PROPERTY(QPointF pos READ pos WRITE setPos) + Q_PROPERTY(int animPath READ fakePath WRITE updatePathAnimate) + Q_PROPERTY(ConductorProperties properties READ properties WRITE setProperties) + Q_PROPERTY(autonum::sequentialNumbers sequenceNum READ sequenceNum WRITE setSequenceNum) - signals: - void propertiesChange(); - - public: - Conductor(Terminal *, Terminal *); - ~Conductor() override; + signals: + void propertiesChange(); + + public: + Conductor(Terminal *, Terminal *); + ~Conductor() override; - bool isValid() const; - - private: - Conductor(const Conductor &); + bool isValid() const; + + private: + Conductor(const Conductor &); - public: - enum { Type = UserType + 1001 }; - enum Highlight { None, Normal, Alert }; + public: + enum { Type = UserType + 1001 }; + enum Highlight { None, Normal, Alert }; - Terminal *terminal1; - Terminal *terminal2; - - public: - /** - @brief type - Enable the use of qgraphicsitem_cast - to safely cast a QGraphicsItem into a conductor. - @return the QGraphicsItem type - */ - int type() const override { return Type; } - Diagram *diagram() const; - ConductorTextItem *textItem() const; - void updatePath(const QRectF & = QRectF()); + Terminal *terminal1; + Terminal *terminal2; + + public: + /** + @brief type + Enable the use of qgraphicsitem_cast + to safely cast a QGraphicsItem into a conductor. + @return the QGraphicsItem type + */ + int type() const override { return Type; } + Diagram *diagram() const; + ConductorTextItem *textItem() const; + void updatePath(const QRectF & = QRectF()); - //This method do nothing, it's only made to be used with Q_PROPERTY - //It's used to anim the path when is change - void updatePathAnimate(const int = 1) {updatePath();} - int fakePath() {return 1;} + //This method do nothing, it's only made to be used with Q_PROPERTY + //It's used to anim the path when is change + void updatePathAnimate(const int = 1) {updatePath();} + int fakePath() {return 1;} - void paint( - QPainter *, - const QStyleOptionGraphicsItem *, - QWidget *) override; - QRectF boundingRect() const override; - QPainterPath shape() const override; - virtual QPainterPath nearShape() const; - qreal length() const; - ConductorSegment *middleSegment(); - QPointF posForText(Qt::Orientations &flag); - void refreshText(); - void setPath(const QPainterPath &path); - QPainterPath path() const; + void paint( + QPainter *, + const QStyleOptionGraphicsItem *, + QWidget *) override; + QRectF boundingRect() const override; + QPainterPath shape() const override; + virtual QPainterPath nearShape() const; + qreal length() const; + ConductorSegment *middleSegment(); + QPointF posForText(Qt::Orientations &flag); + void refreshText(); + void setPath(const QPainterPath &path); + QPainterPath path() const; - public: - static bool valideXml (QDomElement &); - bool fromXml (QDomElement &); - QDomElement toXml ( - QDomDocument &, - QHash &) const; - private: - bool pathFromXml(const QDomElement &); + public: + static bool valideXml (QDomElement &); + bool fromXml (QDomElement &); + QDomElement toXml ( + QDomDocument &, + QHash &) const; + private: + bool pathFromXml(const QDomElement &); - public: - QVector handlerPoints() const; - const QList segmentsList() const; + public: + QVector handlerPoints() const; + const QList segmentsList() const; - void setPropertyToPotential( - const ConductorProperties &property, - bool only_text = false); - void setProperties(const ConductorProperties &property); - ConductorProperties properties() const; + void setPropertyToPotential( + const ConductorProperties &property, + bool only_text = false); + void setProperties(const ConductorProperties &property); + ConductorProperties properties() const; - void setProfile(const ConductorProfile &, Qt::Corner); - ConductorProfile profile(Qt::Corner) const; - void setProfiles(const ConductorProfilesGroup &); - ConductorProfilesGroup profiles() const; - void calculateTextItemPosition(); - virtual Highlight highlight() const; - virtual void setHighlighted(Highlight); - QSet relatedPotentialConductors( - const bool all_diagram = true, - QList *t_list=nullptr); - QETDiagramEditor* diagramEditor() const; - void editProperty (); + void setProfile(const ConductorProfile &, Qt::Corner); + ConductorProfile profile(Qt::Corner) const; + void setProfiles(const ConductorProfilesGroup &); + ConductorProfilesGroup profiles() const; + void calculateTextItemPosition(); + virtual Highlight highlight() const; + virtual void setHighlighted(Highlight); + QSet relatedPotentialConductors( + const bool all_diagram = true, + QList *t_list=nullptr); + QETDiagramEditor* diagramEditor() const; + void editProperty (); - autonum::sequentialNumbers sequenceNum () const - {return m_autoNum_seq;} - autonum::sequentialNumbers& rSequenceNum() - {return m_autoNum_seq;} - void setSequenceNum(const autonum::sequentialNumbers& sn); + autonum::sequentialNumbers sequenceNum () const + {return m_autoNum_seq;} + autonum::sequentialNumbers& rSequenceNum() + {return m_autoNum_seq;} + void setSequenceNum(const autonum::sequentialNumbers& sn); QList junctions() const; - private: - void setUpConnectionForFormula( - QString old_formula, QString new_formula); - autonum::sequentialNumbers m_autoNum_seq; + private: + void setUpConnectionForFormula( + QString old_formula, QString new_formula); + autonum::sequentialNumbers m_autoNum_seq; - public: - void setFreezeLabel(bool freeze); - - public slots: - void displayedTextChanged(); - - protected: - void mouseDoubleClickEvent( - QGraphicsSceneMouseEvent *event) override; - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent( - QGraphicsSceneMouseEvent *event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - QVariant itemChange( - GraphicsItemChange, const QVariant &) override; - bool sceneEventFilter( - QGraphicsItem *watched, QEvent *event) override; + public: + void setFreezeLabel(bool freeze); + + public slots: + void displayedTextChanged(); + + protected: + void mouseDoubleClickEvent( + QGraphicsSceneMouseEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent( + QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + QVariant itemChange( + GraphicsItemChange, const QVariant &) override; + bool sceneEventFilter( + QGraphicsItem *watched, QEvent *event) override; - private: - void adjusteHandlerPos(); - - void handlerMousePressEvent( - QetGraphicsHandlerItem *qghi, - QGraphicsSceneMouseEvent *event); - void handlerMouseMoveEvent( - QetGraphicsHandlerItem *qghi, - QGraphicsSceneMouseEvent *event); - void handlerMouseReleaseEvent( - QetGraphicsHandlerItem *qghi, - QGraphicsSceneMouseEvent *event); - void addHandler(); - void removeHandler(); - - - QVector m_handler_vector; - int m_vector_index = -1; - bool m_mouse_over; - /// Functional properties - ConductorProperties m_properties; - /// Text input for non simple, non-singleline conductors - ConductorTextItem *m_text_item; - /// Segments composing the conductor - ConductorSegment *segments; - /// Attributs related to mouse interaction - bool m_moving_segment; - int moved_point; - qreal m_previous_z_value; - ConductorSegment *m_moved_segment; - QPointF before_mov_text_pos_; - /// Whether the conductor was manually modified by users - bool modified_path; - /// Whether the current profile should be saved as soon as possible - bool has_to_save_profile; - /// conductor profile: "photography" of what the conductor is supposed to look - /// like - there is one profile per kind of traject - ConductorProfilesGroup conductor_profiles; - /// Define whether and how the conductor should be highlighted - Highlight must_highlight_; - bool m_valid; - bool m_freeze_label = false; + private: + void adjusteHandlerPos(); + + void handlerMousePressEvent( + QetGraphicsHandlerItem *qghi, + QGraphicsSceneMouseEvent *event); + void handlerMouseMoveEvent( + QetGraphicsHandlerItem *qghi, + QGraphicsSceneMouseEvent *event); + void handlerMouseReleaseEvent( + QetGraphicsHandlerItem *qghi, + QGraphicsSceneMouseEvent *event); + void addHandler(); + void removeHandler(); + + + QVector m_handler_vector; + int m_vector_index = -1; + bool m_mouse_over; + /// Functional properties + ConductorProperties m_properties; + /// Text input for non simple, non-singleline conductors + ConductorTextItem *m_text_item; + /// Segments composing the conductor + ConductorSegment *segments; + /// Attributs related to mouse interaction + bool m_moving_segment; + int moved_point; + qreal m_previous_z_value; + ConductorSegment *m_moved_segment; + QPointF before_mov_text_pos_; + /// Whether the conductor was manually modified by users + bool modified_path; + /// Whether the current profile should be saved as soon as possible + bool has_to_save_profile; + /// conductor profile: "photography" of what the conductor is supposed to look + /// like - there is one profile per kind of traject + ConductorProfilesGroup conductor_profiles; + /// Define whether and how the conductor should be highlighted + Highlight must_highlight_; + bool m_valid; + bool m_freeze_label = false; - /// QPen et QBrush objects used to draw conductors - static QPen conductor_pen; - static QBrush conductor_brush; - static bool pen_and_brush_initialized; - QPainterPath m_path; - - private: - void segmentsToPath(); - void saveProfile(bool = true); - void generateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation); - void updateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation); - uint segmentsCount(QET::ConductorSegmentType = QET::Both) const; - QList segmentsToPoints() const; - QList bends() const; + /// QPen et QBrush objects used to draw conductors + static QPen conductor_pen; + static QBrush conductor_brush; + static bool pen_and_brush_initialized; + QPainterPath m_path; + + private: + void segmentsToPath(); + void saveProfile(bool = true); + void generateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation); + void updateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation); + uint segmentsCount(QET::ConductorSegmentType = QET::Both) const; + QList segmentsToPoints() const; + QList bends() const; - void pointsToSegments(const QList&); - Qt::Corner currentPathType() const; - void deleteSegments(); - static int getCoeff(const qreal &, const qreal &); - static int getSign(const qreal &); - QHash shareOffsetBetweenSegments(const qreal &offset, const QList &, const qreal & = 0.01) const; - static QPointF extendTerminal(const QPointF &, Qet::Orientation, qreal = 9.0); - static Qt::Corner movementType(const QPointF &, const QPointF &); - static QPointF movePointIntoPolygon(const QPointF &, const QPainterPath &); + void pointsToSegments(const QList&); + Qt::Corner currentPathType() const; + void deleteSegments(); + static int getCoeff(const qreal &, const qreal &); + static int getSign(const qreal &); + QHash shareOffsetBetweenSegments(const qreal &offset, const QList &, const qreal & = 0.01) const; + static QPointF extendTerminal(const QPointF &, Qet::Orientation, qreal = 9.0); + static Qt::Corner movementType(const QPointF &, const QPointF &); + static QPointF movePointIntoPolygon(const QPointF &, const QPainterPath &); }; Conductor * longuestConductorInPotential (Conductor *conductor, bool all_diagram = false); @@ -239,7 +239,7 @@ QList relatedConductors (const Conductor *conductor); //return true if @a is between or at @b and @c. template bool isBetween (const T a, const T b, const T c) { - return (b <= c)? (a >= b && a <= c) : (a <= b && a >= c); + return (b <= c)? (a >= b && a <= c) : (a <= b && a >= c); } #endif diff --git a/sources/qetgraphicsitem/conductortextitem.cpp b/sources/qetgraphicsitem/conductortextitem.cpp index e15c24429..66d05c69b 100644 --- a/sources/qetgraphicsitem/conductortextitem.cpp +++ b/sources/qetgraphicsitem/conductortextitem.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "conductortextitem.h" #include "conductor.h" @@ -21,245 +21,245 @@ #include "diagram.h" /** - Constructeur - @param parent_conductor Conducteur auquel ce texte est rattache + Constructeur + @param parent_conductor Conducteur auquel ce texte est rattache */ ConductorTextItem::ConductorTextItem(Conductor *parent_conductor) : - DiagramTextItem(parent_conductor), - parent_conductor_(parent_conductor), - moved_by_user_(false), - rotate_by_user_(false) + DiagramTextItem(parent_conductor), + parent_conductor_(parent_conductor), + moved_by_user_(false), + rotate_by_user_(false) { - setAcceptHoverEvents(true); + setAcceptHoverEvents(true); } /** - Constructeur - @param text Le texte affiche par le champ de texte - @param parent_conductor Conducteur auquel ce texte est rattache + Constructeur + @param text Le texte affiche par le champ de texte + @param parent_conductor Conducteur auquel ce texte est rattache */ ConductorTextItem::ConductorTextItem( - const QString &text, Conductor *parent_conductor) : - DiagramTextItem(text, parent_conductor), - parent_conductor_(parent_conductor), - moved_by_user_(false), - rotate_by_user_(false) + const QString &text, Conductor *parent_conductor) : + DiagramTextItem(text, parent_conductor), + parent_conductor_(parent_conductor), + moved_by_user_(false), + rotate_by_user_(false) {} /** - Destructeur + Destructeur */ ConductorTextItem::~ConductorTextItem() { } /** - @return le conducteur parent de ce champ de texte, ou 0 si celui-ci n'en a - pas + @return le conducteur parent de ce champ de texte, ou 0 si celui-ci n'en a + pas */ Conductor *ConductorTextItem::parentConductor() const { - return(parent_conductor_); + return(parent_conductor_); } /** - @brief ConductorTextItem::fromXml - Read the properties stored in the xml element given in parameter - @param e + @brief ConductorTextItem::fromXml + Read the properties stored in the xml element given in parameter + @param e */ void ConductorTextItem::fromXml(const QDomElement &e) { - if (e.hasAttribute("userx")) { - setPos(e.attribute("userx").toDouble(), - e.attribute("usery").toDouble()); - moved_by_user_ = true; - } - if (e.hasAttribute("rotation")) { - setRotation(e.attribute("rotation").toDouble()); - rotate_by_user_ = true; - } + if (e.hasAttribute("userx")) { + setPos(e.attribute("userx").toDouble(), + e.attribute("usery").toDouble()); + moved_by_user_ = true; + } + if (e.hasAttribute("rotation")) { + setRotation(e.attribute("rotation").toDouble()); + rotate_by_user_ = true; + } } /** - @return true si ce champ de texte a ete explictement deplace par - l'utilisateur, false sinon + @return true si ce champ de texte a ete explictement deplace par + l'utilisateur, false sinon */ bool ConductorTextItem::wasMovedByUser() const { - return(moved_by_user_); + return(moved_by_user_); } /** - @brief ConductorTextItem::wasRotateByUser - @return true if text was explicit moved by user else false + @brief ConductorTextItem::wasRotateByUser + @return true if text was explicit moved by user else false */ bool ConductorTextItem::wasRotateByUser() const { - return(rotate_by_user_); + return(rotate_by_user_); } /** - @param moved_by_user true pour que la position du texte soit consideree - comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false - pour remettre le texte a sa position originelle + @param moved_by_user true pour que la position du texte soit consideree + comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false + pour remettre le texte a sa position originelle */ void ConductorTextItem::forceMovedByUser(bool moved_by_user) { - if (moved_by_user == moved_by_user_) return; - - moved_by_user_ = moved_by_user; - if (!moved_by_user && parent_conductor_) { - parent_conductor_ -> calculateTextItemPosition(); - } - + if (moved_by_user == moved_by_user_) return; + + moved_by_user_ = moved_by_user; + if (!moved_by_user && parent_conductor_) { + parent_conductor_ -> calculateTextItemPosition(); + } + } /** - @brief ConductorTextItem::forceRotateByUser - @param rotate_by_user true pour que la rotation du texte soit consideree - comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false - pour remettre le texte a sont angle originelle + @brief ConductorTextItem::forceRotateByUser + @param rotate_by_user true pour que la rotation du texte soit consideree + comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false + pour remettre le texte a sont angle originelle */ void ConductorTextItem::forceRotateByUser(bool rotate_by_user) { - if (rotate_by_user == rotate_by_user_) return; + if (rotate_by_user == rotate_by_user_) return; - rotate_by_user_ = rotate_by_user; - if (!rotate_by_user && parent_conductor_) { - parent_conductor_ -> calculateTextItemPosition(); - } + rotate_by_user_ = rotate_by_user; + if (!rotate_by_user && parent_conductor_) { + parent_conductor_ -> calculateTextItemPosition(); + } } /** - @brief ConductorTextItem::setPos - @param pos + @brief ConductorTextItem::setPos + @param pos */ void ConductorTextItem::setPos(const QPointF &pos) { - /* - * In some condition the conductor text item is outside the border of folio in the left. - * They cause a margin on the left of folio and in most case this margin is unwanted and annoying the user. - * If the text is empty and the scene position is outside the border (left and top), - * we can say that this position, is unwanted by user. - * So we move this text item to the top left of the bounding rect of parent conductors, because we sure this position is wanted by user. - */ - DiagramTextItem::setPos(pos); - if(toPlainText().isEmpty() && (scenePos().x() < 0 || scenePos().y() < 0)) - { - Conductor *cond = parentConductor(); - if(cond) - DiagramTextItem::setPos(cond->boundingRect().topLeft()); - else - DiagramTextItem::setPos(0,0); - } + /* + * In some condition the conductor text item is outside the border of folio in the left. + * They cause a margin on the left of folio and in most case this margin is unwanted and annoying the user. + * If the text is empty and the scene position is outside the border (left and top), + * we can say that this position, is unwanted by user. + * So we move this text item to the top left of the bounding rect of parent conductors, because we sure this position is wanted by user. + */ + DiagramTextItem::setPos(pos); + if(toPlainText().isEmpty() && (scenePos().x() < 0 || scenePos().y() < 0)) + { + Conductor *cond = parentConductor(); + if(cond) + DiagramTextItem::setPos(cond->boundingRect().topLeft()); + else + DiagramTextItem::setPos(0,0); + } } /** - @brief ConductorTextItem::setPos - @param x - @param y + @brief ConductorTextItem::setPos + @param x + @param y */ void ConductorTextItem::setPos(qreal x, qreal y) { - QPointF p(x,y); - setPos(p); + QPointF p(x,y); + setPos(p); } /** - @brief ConductorTextItem::mousePressEvent - @param event + @brief ConductorTextItem::mousePressEvent + @param event */ void ConductorTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - before_mov_pos_ = pos(); - DiagramTextItem::mousePressEvent(event); + before_mov_pos_ = pos(); + DiagramTextItem::mousePressEvent(event); } /** - @brief ConductorTextItem::mouseMoveEvent - @param event + @brief ConductorTextItem::mouseMoveEvent + @param event */ void ConductorTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (textInteractionFlags() & Qt::TextEditable) QGraphicsTextItem::mouseMoveEvent(event); + if (textInteractionFlags() & Qt::TextEditable) QGraphicsTextItem::mouseMoveEvent(event); - else if ((flags() & QGraphicsItem::ItemIsMovable) && (event -> buttons() & Qt::LeftButton)) { + else if ((flags() & QGraphicsItem::ItemIsMovable) && (event -> buttons() & Qt::LeftButton)) { - QPointF intended_pos = event ->scenePos() + m_mouse_to_origin_movement; + QPointF intended_pos = event ->scenePos() + m_mouse_to_origin_movement; - if (parent_conductor_) { - if (parent_conductor_->nearShape().contains(intended_pos)) { - event->modifiers() == Qt::ControlModifier ? setPos(intended_pos) : setPos(Diagram::snapToGrid(intended_pos)); - parent_conductor_ -> setHighlighted(Conductor::Normal); - } else { - parent_conductor_ -> setHighlighted(Conductor::Alert); - } - } - - } + if (parent_conductor_) { + if (parent_conductor_->nearShape().contains(intended_pos)) { + event->modifiers() == Qt::ControlModifier ? setPos(intended_pos) : setPos(Diagram::snapToGrid(intended_pos)); + parent_conductor_ -> setHighlighted(Conductor::Normal); + } else { + parent_conductor_ -> setHighlighted(Conductor::Alert); + } + } + + } - else event -> ignore(); + else event -> ignore(); } /** - @brief ConductorTextItem::mouseReleaseEvent - @param e + @brief ConductorTextItem::mouseReleaseEvent + @param e */ void ConductorTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) { - if (flags() & QGraphicsItem::ItemIsMovable) { + if (flags() & QGraphicsItem::ItemIsMovable) { - if (Diagram *diagram_ptr = diagram()) { - QPointF applied_movement = pos() - before_mov_pos_; - - if (!applied_movement.isNull()) { - //Create an undo object - MoveConductorsTextsCommand *undo_object = new MoveConductorsTextsCommand(diagram_ptr); - undo_object -> addTextMovement(this, before_mov_pos_, pos(), moved_by_user_); + if (Diagram *diagram_ptr = diagram()) { + QPointF applied_movement = pos() - before_mov_pos_; + + if (!applied_movement.isNull()) { + //Create an undo object + MoveConductorsTextsCommand *undo_object = new MoveConductorsTextsCommand(diagram_ptr); + undo_object -> addTextMovement(this, before_mov_pos_, pos(), moved_by_user_); - moved_by_user_ = true; - - diagram_ptr -> undoStack().push(undo_object); - } - - if (parent_conductor_) { - parent_conductor_ -> setHighlighted(Conductor::None); - } - } - } - if (!(e -> modifiers() & Qt::ControlModifier)) { - QGraphicsTextItem::mouseReleaseEvent(e); - } + moved_by_user_ = true; + + diagram_ptr -> undoStack().push(undo_object); + } + + if (parent_conductor_) { + parent_conductor_ -> setHighlighted(Conductor::None); + } + } + } + if (!(e -> modifiers() & Qt::ControlModifier)) { + QGraphicsTextItem::mouseReleaseEvent(e); + } } /** - When mouse over element - change m_mouse_hover to true (used in paint() function ) - @param e QGraphicsSceneHoverEvent + When mouse over element + change m_mouse_hover to true (used in paint() function ) + @param e QGraphicsSceneHoverEvent */ void ConductorTextItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) { - Q_UNUSED(e); + Q_UNUSED(e); - m_mouse_hover = true; - QString str_ToolTip = toPlainText(); - setToolTip( str_ToolTip ); - update(); + m_mouse_hover = true; + QString str_ToolTip = toPlainText(); + setToolTip( str_ToolTip ); + update(); } /** - When mouse over element leave the position - change m_mouse_hover to false(used in paint() function ) - @param e QGraphicsSceneHoverEvent + When mouse over element leave the position + change m_mouse_hover to false(used in paint() function ) + @param e QGraphicsSceneHoverEvent */ void ConductorTextItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *e) { - Q_UNUSED(e); - qDebug() << "Leave mouse over"; - m_mouse_hover = false; - update(); + Q_UNUSED(e); + qDebug() << "Leave mouse over"; + m_mouse_hover = false; + update(); } /** - Do nothing default function . - @param e QGraphicsSceneHoverEvent + Do nothing default function . + @param e QGraphicsSceneHoverEvent */ void ConductorTextItem::hoverMoveEvent(QGraphicsSceneHoverEvent *e) { - QGraphicsTextItem::hoverMoveEvent(e); + QGraphicsTextItem::hoverMoveEvent(e); } diff --git a/sources/qetgraphicsitem/conductortextitem.h b/sources/qetgraphicsitem/conductortextitem.h index a183c2be9..7d57d2d60 100644 --- a/sources/qetgraphicsitem/conductortextitem.h +++ b/sources/qetgraphicsitem/conductortextitem.h @@ -1,68 +1,68 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef CONDUCTOR_TEXT_ITEM_H #define CONDUCTOR_TEXT_ITEM_H #include "diagramtextitem.h" class Conductor; /** - This class represents a text item attached to a parent conductor. - It may be moved and edited by users. - It may also be rotated to any angle. - Its movements are however limited to a particular distance around its - parent conductor. + This class represents a text item attached to a parent conductor. + It may be moved and edited by users. + It may also be rotated to any angle. + Its movements are however limited to a particular distance around its + parent conductor. */ class ConductorTextItem : public DiagramTextItem { - Q_OBJECT + Q_OBJECT - // constructors, destructor - public: - ConductorTextItem(Conductor * = nullptr); - ConductorTextItem(const QString &, Conductor * = nullptr); - ~ConductorTextItem() override; - private: - ConductorTextItem(const ConductorTextItem &); + // constructors, destructor + public: + ConductorTextItem(Conductor * = nullptr); + ConductorTextItem(const QString &, Conductor * = nullptr); + ~ConductorTextItem() override; + private: + ConductorTextItem(const ConductorTextItem &); - public: - enum { Type = UserType + 1006 }; - Conductor *parentConductor() const; - void fromXml(const QDomElement &) override; - int type() const override { return Type; } - virtual bool wasMovedByUser() const; - virtual bool wasRotateByUser() const; - virtual void forceMovedByUser(bool); - virtual void forceRotateByUser(bool); - virtual void setPos(const QPointF &pos); - virtual void setPos(qreal x, qreal y); + public: + enum { Type = UserType + 1006 }; + Conductor *parentConductor() const; + void fromXml(const QDomElement &) override; + int type() const override { return Type; } + virtual bool wasMovedByUser() const; + virtual bool wasRotateByUser() const; + virtual void forceMovedByUser(bool); + virtual void forceRotateByUser(bool); + virtual void setPos(const QPointF &pos); + virtual void setPos(qreal x, qreal y); - protected: - void mousePressEvent (QGraphicsSceneMouseEvent *event) override; - void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent (QGraphicsSceneMouseEvent *event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override; - void hoverMoveEvent(QGraphicsSceneHoverEvent *) override; + protected: + void mousePressEvent (QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent (QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override; + void hoverMoveEvent(QGraphicsSceneHoverEvent *) override; - // attributes - private: - Conductor *parent_conductor_; - bool moved_by_user_; - bool rotate_by_user_; - QPointF before_mov_pos_; + // attributes + private: + Conductor *parent_conductor_; + bool moved_by_user_; + bool rotate_by_user_; + QPointF before_mov_pos_; }; #endif diff --git a/sources/qetgraphicsitem/dynamicelementtextitem.cpp b/sources/qetgraphicsitem/dynamicelementtextitem.cpp index f47840960..43901195b 100644 --- a/sources/qetgraphicsitem/dynamicelementtextitem.cpp +++ b/sources/qetgraphicsitem/dynamicelementtextitem.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "dynamicelementtextitem.h" #include "qet.h" @@ -31,1394 +31,1394 @@ #include /** - @brief DynamicElementTextItem::DynamicElementTextItem - Constructor - @param parent_element + @brief DynamicElementTextItem::DynamicElementTextItem + Constructor + @param parent_element */ DynamicElementTextItem::DynamicElementTextItem(Element *parent_element) : - m_parent_element(parent_element), - m_uuid(QUuid::createUuid()) + m_parent_element(parent_element), + m_uuid(QUuid::createUuid()) { - setFont(QETApp::dynamicTextsItemFont()); - setText(tr("Texte")); - setParentItem(parent_element); - QSettings settings; - setRotation(settings.value("dynamic_text_rotation", 0).toInt()); - setTextWidth(settings.value("dynamic_text_widht", -1).toInt()); - connect(this, &DynamicElementTextItem::textEdited, [this](const QString &old_str, const QString &new_str) - { - if(this->m_parent_element && this->m_parent_element->diagram()) - { - QUndoCommand *undo = new QPropertyUndoCommand(this, "text", old_str, new_str); - undo->setText(tr("Éditer un texte d'élément")); - this->m_parent_element->diagram()->undoStack().push(undo); - } - }); - - //Option when text is displayed in multiple line - QTextOption option = document()->defaultTextOption(); - option.setAlignment(Qt::AlignHCenter); - option.setWrapMode(QTextOption::WordWrap); - document()->setDefaultTextOption(option); + setFont(QETApp::dynamicTextsItemFont()); + setText(tr("Texte")); + setParentItem(parent_element); + QSettings settings; + setRotation(settings.value("dynamic_text_rotation", 0).toInt()); + setTextWidth(settings.value("dynamic_text_widht", -1).toInt()); + connect(this, &DynamicElementTextItem::textEdited, [this](const QString &old_str, const QString &new_str) + { + if(this->m_parent_element && this->m_parent_element->diagram()) + { + QUndoCommand *undo = new QPropertyUndoCommand(this, "text", old_str, new_str); + undo->setText(tr("Éditer un texte d'élément")); + this->m_parent_element->diagram()->undoStack().push(undo); + } + }); + + //Option when text is displayed in multiple line + QTextOption option = document()->defaultTextOption(); + option.setAlignment(Qt::AlignHCenter); + option.setWrapMode(QTextOption::WordWrap); + document()->setDefaultTextOption(option); } DynamicElementTextItem::~DynamicElementTextItem() {} /** - @brief DynamicElementTextItem::textFromMetaEnum - @return The QMetaEnum of the enum TextFrom + @brief DynamicElementTextItem::textFromMetaEnum + @return The QMetaEnum of the enum TextFrom */ QMetaEnum DynamicElementTextItem::textFromMetaEnum() { - DynamicElementTextItem deti; - return deti.metaObject()->enumerator(deti.metaObject()->indexOfEnumerator("TextFrom")); + DynamicElementTextItem deti; + return deti.metaObject()->enumerator(deti.metaObject()->indexOfEnumerator("TextFrom")); } DynamicElementTextItem::DynamicElementTextItem() {} /** - @brief DynamicElementTextItem::toXml - Export this text to xml - @param dom_doc - @return + @brief DynamicElementTextItem::toXml + Export this text to xml + @param dom_doc + @return */ QDomElement DynamicElementTextItem::toXml(QDomDocument &dom_doc) const { - QDomElement root_element = dom_doc.createElement(xmlTagName()); - - root_element.setAttribute("x", QString::number(pos().x())); - root_element.setAttribute("y", QString::number(pos().y())); - root_element.setAttribute("rotation", QString::number(QET::correctAngle(rotation()))); - root_element.setAttribute("uuid", m_uuid.toString()); - root_element.setAttribute("frame", m_frame? "true" : "false"); - root_element.setAttribute("text_width", QString::number(m_text_width)); - root_element.setAttribute("font", font().toString()); - - QMetaEnum me = textFromMetaEnum(); - root_element.setAttribute("text_from", me.valueToKey(m_text_from)); - - me = QMetaEnum::fromType(); - if(this->alignment() &Qt::AlignRight) - root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignRight)); - else if(this->alignment() &Qt::AlignLeft) - root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignLeft)); - else if(this->alignment() &Qt::AlignHCenter) - root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignHCenter)); - - if(this->alignment() &Qt::AlignBottom) - root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignBottom)); - else if(this->alignment() & Qt::AlignTop) - root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignTop)); - else if(this->alignment() &Qt::AlignVCenter) - root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignVCenter)); - - - QDomElement dom_text = dom_doc.createElement("text"); - dom_text.appendChild(dom_doc.createTextNode(toPlainText())); - root_element.appendChild(dom_text); - - //Info name - if(!m_info_name.isEmpty()) - { - QDomElement dom_info_name = dom_doc.createElement("info_name"); - dom_info_name.appendChild(dom_doc.createTextNode(m_info_name)); - root_element.appendChild(dom_info_name); - } - - //Composite text - if(!m_composite_text.isEmpty()) - { - QDomElement dom_comp_text = dom_doc.createElement("composite_text"); - dom_comp_text.appendChild(dom_doc.createTextNode(m_composite_text)); - root_element.appendChild(dom_comp_text); - } - - //Color - if(color() != QColor(Qt::black)) - { - QDomElement dom_color = dom_doc.createElement("color"); - dom_color.appendChild(dom_doc.createTextNode(color().name())); - root_element.appendChild(dom_color); - } - - return root_element; + QDomElement root_element = dom_doc.createElement(xmlTagName()); + + root_element.setAttribute("x", QString::number(pos().x())); + root_element.setAttribute("y", QString::number(pos().y())); + root_element.setAttribute("rotation", QString::number(QET::correctAngle(rotation()))); + root_element.setAttribute("uuid", m_uuid.toString()); + root_element.setAttribute("frame", m_frame? "true" : "false"); + root_element.setAttribute("text_width", QString::number(m_text_width)); + root_element.setAttribute("font", font().toString()); + + QMetaEnum me = textFromMetaEnum(); + root_element.setAttribute("text_from", me.valueToKey(m_text_from)); + + me = QMetaEnum::fromType(); + if(this->alignment() &Qt::AlignRight) + root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignRight)); + else if(this->alignment() &Qt::AlignLeft) + root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignLeft)); + else if(this->alignment() &Qt::AlignHCenter) + root_element.setAttribute("Halignment", me.valueToKey(Qt::AlignHCenter)); + + if(this->alignment() &Qt::AlignBottom) + root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignBottom)); + else if(this->alignment() & Qt::AlignTop) + root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignTop)); + else if(this->alignment() &Qt::AlignVCenter) + root_element.setAttribute("Valignment", me.valueToKey(Qt::AlignVCenter)); + + + QDomElement dom_text = dom_doc.createElement("text"); + dom_text.appendChild(dom_doc.createTextNode(toPlainText())); + root_element.appendChild(dom_text); + + //Info name + if(!m_info_name.isEmpty()) + { + QDomElement dom_info_name = dom_doc.createElement("info_name"); + dom_info_name.appendChild(dom_doc.createTextNode(m_info_name)); + root_element.appendChild(dom_info_name); + } + + //Composite text + if(!m_composite_text.isEmpty()) + { + QDomElement dom_comp_text = dom_doc.createElement("composite_text"); + dom_comp_text.appendChild(dom_doc.createTextNode(m_composite_text)); + root_element.appendChild(dom_comp_text); + } + + //Color + if(color() != QColor(Qt::black)) + { + QDomElement dom_color = dom_doc.createElement("color"); + dom_color.appendChild(dom_doc.createTextNode(color().name())); + root_element.appendChild(dom_color); + } + + return root_element; } /** - @brief DynamicElementTextItem::fromXml - Import this text from xml - @param dom_elmt + @brief DynamicElementTextItem::fromXml + Import this text from xml + @param dom_elmt */ void DynamicElementTextItem::fromXml(const QDomElement &dom_elmt) { - if (dom_elmt.tagName() != xmlTagName()) { - qDebug() << "DynamicElementTextItem::fromXml : Wrong tagg name"; - return; - } - - QGraphicsTextItem::setRotation(dom_elmt.attribute("rotation", QString::number(0)).toDouble()); + if (dom_elmt.tagName() != xmlTagName()) { + qDebug() << "DynamicElementTextItem::fromXml : Wrong tagg name"; + return; + } + + QGraphicsTextItem::setRotation(dom_elmt.attribute("rotation", QString::number(0)).toDouble()); - if (dom_elmt.hasAttribute("font")) - { - QFont font; - font.fromString(dom_elmt.attribute("font")); - setFont(font); - } - else //Retrocompatibility during the 0.7 dev because the font property was added lately. TODO remove this part in futur - { - QFont font_(dom_elmt.attribute("font_family", font().family()), - dom_elmt.attribute("font_size", QString::number(9)).toInt()); - font_.setStyleName(dom_elmt.attribute("dynamicitemstyle", font().styleName())); - setFont(font_); - } + if (dom_elmt.hasAttribute("font")) + { + QFont font; + font.fromString(dom_elmt.attribute("font")); + setFont(font); + } + else //Retrocompatibility during the 0.7 dev because the font property was added lately. TODO remove this part in futur + { + QFont font_(dom_elmt.attribute("font_family", font().family()), + dom_elmt.attribute("font_size", QString::number(9)).toInt()); + font_.setStyleName(dom_elmt.attribute("dynamicitemstyle", font().styleName())); + setFont(font_); + } - m_uuid = QUuid(dom_elmt.attribute("uuid", QUuid::createUuid().toString())); - setFrame(dom_elmt.attribute("frame", "false") == "true"? true : false); - setTextWidth(dom_elmt.attribute("text_width", QString::number(-1)).toDouble()); - - //Text from - QMetaEnum me = textFromMetaEnum(); - setTextFrom(DynamicElementTextItem::TextFrom(me.keyToValue(dom_elmt.attribute("text_from").toStdString().data()))); - - me = QMetaEnum::fromType(); - if(dom_elmt.hasAttribute("Halignment")) - setAlignment(Qt::Alignment(me.keyToValue(dom_elmt.attribute("Halignment").toStdString().data()))); - if(dom_elmt.hasAttribute(("Valignment"))) - setAlignment(Qt::Alignment(me.keyToValue(dom_elmt.attribute("Valignment").toStdString().data())) | this->alignment()); + m_uuid = QUuid(dom_elmt.attribute("uuid", QUuid::createUuid().toString())); + setFrame(dom_elmt.attribute("frame", "false") == "true"? true : false); + setTextWidth(dom_elmt.attribute("text_width", QString::number(-1)).toDouble()); + + //Text from + QMetaEnum me = textFromMetaEnum(); + setTextFrom(DynamicElementTextItem::TextFrom(me.keyToValue(dom_elmt.attribute("text_from").toStdString().data()))); + + me = QMetaEnum::fromType(); + if(dom_elmt.hasAttribute("Halignment")) + setAlignment(Qt::Alignment(me.keyToValue(dom_elmt.attribute("Halignment").toStdString().data()))); + if(dom_elmt.hasAttribute(("Valignment"))) + setAlignment(Qt::Alignment(me.keyToValue(dom_elmt.attribute("Valignment").toStdString().data())) | this->alignment()); - //Text - QDomElement dom_text = dom_elmt.firstChildElement("text"); - //Clear the current text. - setPlainText(""); - if (!dom_text.isNull()) { - setText(dom_text.text()); - } + //Text + QDomElement dom_text = dom_elmt.firstChildElement("text"); + //Clear the current text. + setPlainText(""); + if (!dom_text.isNull()) { + setText(dom_text.text()); + } - //Info name - QDomElement dom_info_name = dom_elmt.firstChildElement("info_name"); - if(!dom_info_name.isNull()) - setInfoName(dom_info_name.text()); - - //Composite text - QDomElement dom_comp_text = dom_elmt.firstChildElement("composite_text"); - if(!dom_comp_text.isNull()) - setCompositeText(dom_comp_text.text()); + //Info name + QDomElement dom_info_name = dom_elmt.firstChildElement("info_name"); + if(!dom_info_name.isNull()) + setInfoName(dom_info_name.text()); + + //Composite text + QDomElement dom_comp_text = dom_elmt.firstChildElement("composite_text"); + if(!dom_comp_text.isNull()) + setCompositeText(dom_comp_text.text()); - //Color - QDomElement dom_color = dom_elmt.firstChildElement("color"); - if(!dom_color.isNull()) - setColor(QColor(dom_color.text())); - - //Force the update of the displayed text - setTextFrom(m_text_from); - - QGraphicsTextItem::setPos(dom_elmt.attribute("x", QString::number(0)).toDouble(), - dom_elmt.attribute("y", QString::number(0)).toDouble()); + //Color + QDomElement dom_color = dom_elmt.firstChildElement("color"); + if(!dom_color.isNull()) + setColor(QColor(dom_color.text())); + + //Force the update of the displayed text + setTextFrom(m_text_from); + + QGraphicsTextItem::setPos(dom_elmt.attribute("x", QString::number(0)).toDouble(), + dom_elmt.attribute("y", QString::number(0)).toDouble()); } /** - @brief DynamicElementTextItem::ParentElement - @return a pointer to the parent element. Note the pointer can be null. - Note that the text can return a parent element, - even if the text belong to a group of this same element. + @brief DynamicElementTextItem::ParentElement + @return a pointer to the parent element. Note the pointer can be null. + Note that the text can return a parent element, + even if the text belong to a group of this same element. */ Element *DynamicElementTextItem::parentElement() const { - return m_parent_element; + return m_parent_element; } /** - @brief DynamicElementTextItem::parentGroup - @return The group where this text belong, if this item - is note in a group, return nullptr. + @brief DynamicElementTextItem::parentGroup + @return The group where this text belong, if this item + is note in a group, return nullptr. */ ElementTextItemGroup *DynamicElementTextItem::parentGroup() const { - if(parentItem()) - { - if(ElementTextItemGroup *grp = dynamic_cast(parentItem())) - return grp; - } - - return nullptr; + if(parentItem()) + { + if(ElementTextItemGroup *grp = dynamic_cast(parentItem())) + return grp; + } + + return nullptr; } /** - @brief DynamicElementTextItem::elementUseForInfo - @return a pointer to the element we must use for the variable information. - If this text is owned by a simple element, the simple element is returned, this is the same element returned by the function parentElement(). - If this text is owned by a master element, the master element is returned, this is the same element returned by the function parentElement(). - If this text is owned by a report element, the report element is returned, this is the same element returned by the function parentElement(). - If this text is owned by a terminal element, the terminal element is returned, this is the same element returned by the function parentElement(). - If this text is owned by a slave element, we return the master element set as master of the parent slave element, - if the parent slave is not linked to a master, this function return a nullptr. - If this text have no parent element, return nullptr + @brief DynamicElementTextItem::elementUseForInfo + @return a pointer to the element we must use for the variable information. + If this text is owned by a simple element, the simple element is returned, this is the same element returned by the function parentElement(). + If this text is owned by a master element, the master element is returned, this is the same element returned by the function parentElement(). + If this text is owned by a report element, the report element is returned, this is the same element returned by the function parentElement(). + If this text is owned by a terminal element, the terminal element is returned, this is the same element returned by the function parentElement(). + If this text is owned by a slave element, we return the master element set as master of the parent slave element, + if the parent slave is not linked to a master, this function return a nullptr. + If this text have no parent element, return nullptr */ Element *DynamicElementTextItem::elementUseForInfo() const { - Element *elmt = parentElement(); - if(!elmt) - return nullptr; - - switch (elmt->linkType()) - { - case Element::Simple: - return elmt; - case Element::NextReport: - return elmt; - case Element::PreviousReport: - return elmt; - case Element::Master: - return elmt; - case Element::Slave: - { - if(elmt->linkedElements().isEmpty()) - return nullptr; - else - return elmt->linkedElements().first(); - } - case Element::Terminale: - return elmt; - default: - return elmt; - } + Element *elmt = parentElement(); + if(!elmt) + return nullptr; + + switch (elmt->linkType()) + { + case Element::Simple: + return elmt; + case Element::NextReport: + return elmt; + case Element::PreviousReport: + return elmt; + case Element::Master: + return elmt; + case Element::Slave: + { + if(elmt->linkedElements().isEmpty()) + return nullptr; + else + return elmt->linkedElements().first(); + } + case Element::Terminale: + return elmt; + default: + return elmt; + } } /** - @brief DynamicElementTextItem::refreshLabelConnection - Refresh the connection of this text when the source of text is label, - or composite text, with a variable %{label} + @brief DynamicElementTextItem::refreshLabelConnection + Refresh the connection of this text when the source of text is label, + or composite text, with a variable %{label} */ void DynamicElementTextItem::refreshLabelConnection() { - if ((m_text_from == ElementInfo && m_info_name == "label") || - (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) - { - if(m_parent_element.data()->linkType() & Element::AllReport) - { - updateReportFormulaConnection(); - updateReportText(); - } - else - { - setupFormulaConnection(); - updateLabel(); - } - } + if ((m_text_from == ElementInfo && m_info_name == "label") || + (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) + { + if(m_parent_element.data()->linkType() & Element::AllReport) + { + updateReportFormulaConnection(); + updateReportText(); + } + else + { + setupFormulaConnection(); + updateLabel(); + } + } } /** - @brief DynamicElementTextItem::textFrom - @return what the final text is created from. + @brief DynamicElementTextItem::textFrom + @return what the final text is created from. */ DynamicElementTextItem::TextFrom DynamicElementTextItem::textFrom() const { - return m_text_from; + return m_text_from; } /** - @brief DynamicElementTextItem::setTextFrom - Set the final text is created from. - @param text_from + @brief DynamicElementTextItem::setTextFrom + Set the final text is created from. + @param text_from */ void DynamicElementTextItem::setTextFrom(DynamicElementTextItem::TextFrom text_from) { - if(m_text_from == text_from) - return; - - setNoEditable(text_from == UserText? false : true); - clearFormulaConnection(); - - TextFrom old_text_from = m_text_from; - m_text_from = text_from; - - if(m_text_from == UserText) - { - setPlainText(m_text); - disconnect(m_parent_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); - } - else if (m_text_from == ElementInfo && elementUseForInfo()) - { - if(m_info_name == "label") - { - setupFormulaConnection(); - updateLabel(); - } - else - setPlainText(elementUseForInfo()->elementInformations().value(m_info_name).toString()); - - if(old_text_from == UserText) - connect(elementUseForInfo(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); - } - else if (m_text_from == CompositeText && elementUseForInfo()) - { - if(m_composite_text.contains("%{label}")) - { - setupFormulaConnection(); - updateLabel(); - } - else - setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, elementUseForInfo()->elementInformations())); - - if(old_text_from == UserText) - connect(elementUseForInfo(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); - } - - if(m_parent_element.data()->linkType() == Element::Master || - m_parent_element.data()->linkType() == Element::Slave) - updateXref(); - - emit textFromChanged(m_text_from); + if(m_text_from == text_from) + return; + + setNoEditable(text_from == UserText? false : true); + clearFormulaConnection(); + + TextFrom old_text_from = m_text_from; + m_text_from = text_from; + + if(m_text_from == UserText) + { + setPlainText(m_text); + disconnect(m_parent_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); + } + else if (m_text_from == ElementInfo && elementUseForInfo()) + { + if(m_info_name == "label") + { + setupFormulaConnection(); + updateLabel(); + } + else + setPlainText(elementUseForInfo()->elementInformations().value(m_info_name).toString()); + + if(old_text_from == UserText) + connect(elementUseForInfo(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); + } + else if (m_text_from == CompositeText && elementUseForInfo()) + { + if(m_composite_text.contains("%{label}")) + { + setupFormulaConnection(); + updateLabel(); + } + else + setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, elementUseForInfo()->elementInformations())); + + if(old_text_from == UserText) + connect(elementUseForInfo(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); + } + + if(m_parent_element.data()->linkType() == Element::Master || + m_parent_element.data()->linkType() == Element::Slave) + updateXref(); + + emit textFromChanged(m_text_from); } /** - @brief DynamicElementTextItem::text - @return the text of this text + @brief DynamicElementTextItem::text + @return the text of this text */ QString DynamicElementTextItem::text() const { - return m_text; + return m_text; } /** - @brief DynamicElementTextItem::setText - Set the text of this text - @param text + @brief DynamicElementTextItem::setText + Set the text of this text + @param text */ void DynamicElementTextItem::setText(const QString &text) { - m_text = text; - if(m_text_from == DynamicElementTextItem::UserText) - setPlainText(m_text); - emit textChanged(m_text); + m_text = text; + if(m_text_from == DynamicElementTextItem::UserText) + setPlainText(m_text); + emit textChanged(m_text); } /** - @brief DynamicElementTextItem::setInfoName - Set the information name of the parent element. - @param info_name + @brief DynamicElementTextItem::setInfoName + Set the information name of the parent element. + @param info_name */ void DynamicElementTextItem::setInfoName(const QString &info_name) { - QString old_info_name = m_info_name; - m_info_name = info_name; + QString old_info_name = m_info_name; + m_info_name = info_name; - - if(old_info_name == "label") - { - clearFormulaConnection(); - updateXref(); - } + + if(old_info_name == "label") + { + clearFormulaConnection(); + updateXref(); + } - if (m_parent_element && (m_parent_element.data()->linkType() & Element::AllReport)) //special treatment for report - { - if(old_info_name != info_name) - { - if(old_info_name == "label") { - removeConnectionForReportFormula(m_report_formula); - } - if(info_name == "label") - { - setConnectionForReportFormula(m_report_formula); - updateReportText(); - } - else - conductorPropertiesChanged(); - } - } - else if (m_info_name == "label" && elementUseForInfo()) - { - setupFormulaConnection(); - updateLabel(); - updateXref(); - } - else if(elementUseForInfo() && m_text_from == DynamicElementTextItem::ElementInfo) { - setPlainText(elementUseForInfo()->elementInformations().value(info_name).toString()); - } - - emit infoNameChanged(info_name); + if (m_parent_element && (m_parent_element.data()->linkType() & Element::AllReport)) //special treatment for report + { + if(old_info_name != info_name) + { + if(old_info_name == "label") { + removeConnectionForReportFormula(m_report_formula); + } + if(info_name == "label") + { + setConnectionForReportFormula(m_report_formula); + updateReportText(); + } + else + conductorPropertiesChanged(); + } + } + else if (m_info_name == "label" && elementUseForInfo()) + { + setupFormulaConnection(); + updateLabel(); + updateXref(); + } + else if(elementUseForInfo() && m_text_from == DynamicElementTextItem::ElementInfo) { + setPlainText(elementUseForInfo()->elementInformations().value(info_name).toString()); + } + + emit infoNameChanged(info_name); } /** - @brief DynamicElementTextItem::infoName - @return the info name of this text + @brief DynamicElementTextItem::infoName + @return the info name of this text */ QString DynamicElementTextItem::infoName() const { - return m_info_name; + return m_info_name; } /** - @brief DynamicElementTextItem::setCompositeText - Set the composite text of this text item to text - @param text + @brief DynamicElementTextItem::setCompositeText + Set the composite text of this text item to text + @param text */ void DynamicElementTextItem::setCompositeText(const QString &text) { - QString old_composite_text = m_composite_text; - m_composite_text = text; - - if(old_composite_text.contains("%{label}")) - { - clearFormulaConnection(); - updateXref(); - } + QString old_composite_text = m_composite_text; + m_composite_text = text; + + if(old_composite_text.contains("%{label}")) + { + clearFormulaConnection(); + updateXref(); + } - if (m_parent_element && (m_parent_element.data()->linkType() & Element::AllReport)) //special treatment for report - { - /* - * May be in some case the old and new composite text have both the var %{label}, - * and so we don't have to remove connection and after set conection, - * but for that we must to do several check and because I'm lazy, - * in every case I remove connection and set it after ;) - */ - if(old_composite_text.contains("%{label}")) - removeConnectionForReportFormula(m_report_formula); - if(m_composite_text.contains("%{label}")) - setConnectionForReportFormula(m_report_formula); - - updateReportText(); - } - else if (m_composite_text.contains("%{label}") && elementUseForInfo()) - { - setupFormulaConnection(); - updateLabel(); - updateXref(); - } - else if (m_text_from == DynamicElementTextItem::CompositeText) - { - DiagramContext dc; - if(elementUseForInfo()) - dc = elementUseForInfo()->elementInformations(); - setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, dc)); - } - - emit compositeTextChanged(m_composite_text); + if (m_parent_element && (m_parent_element.data()->linkType() & Element::AllReport)) //special treatment for report + { + /* + * May be in some case the old and new composite text have both the var %{label}, + * and so we don't have to remove connection and after set conection, + * but for that we must to do several check and because I'm lazy, + * in every case I remove connection and set it after ;) + */ + if(old_composite_text.contains("%{label}")) + removeConnectionForReportFormula(m_report_formula); + if(m_composite_text.contains("%{label}")) + setConnectionForReportFormula(m_report_formula); + + updateReportText(); + } + else if (m_composite_text.contains("%{label}") && elementUseForInfo()) + { + setupFormulaConnection(); + updateLabel(); + updateXref(); + } + else if (m_text_from == DynamicElementTextItem::CompositeText) + { + DiagramContext dc; + if(elementUseForInfo()) + dc = elementUseForInfo()->elementInformations(); + setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, dc)); + } + + emit compositeTextChanged(m_composite_text); } /** - @brief DynamicElementTextItem::compositeText - @return + @brief DynamicElementTextItem::compositeText + @return */ QString DynamicElementTextItem::compositeText() const { - return m_composite_text; + return m_composite_text; } void DynamicElementTextItem::setFrame(const bool frame) { - m_frame = frame; - update(); - emit frameChanged(m_frame); + m_frame = frame; + update(); + emit frameChanged(m_frame); } bool DynamicElementTextItem::frame() const { - return m_frame; + return m_frame; } QUuid DynamicElementTextItem::uuid() const { - return m_uuid; + return m_uuid; } /** - @brief DynamicElementTextItem::mousePressEvent - @param event + @brief DynamicElementTextItem::mousePressEvent + @param event */ void DynamicElementTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - //The text become selected, we set the real color, otherwise the editor will display the color of text as blue, - //but this is not the color set by the user. - if(m_user_color.isValid()) - { - setDefaultTextColor(m_user_color); - m_user_color = QColor(); //m_user_color is now invalid - if(m_slave_Xref_item) - m_slave_Xref_item->setDefaultTextColor(Qt::black); - } - - DiagramTextItem::mousePressEvent(event); + //The text become selected, we set the real color, otherwise the editor will display the color of text as blue, + //but this is not the color set by the user. + if(m_user_color.isValid()) + { + setDefaultTextColor(m_user_color); + m_user_color = QColor(); //m_user_color is now invalid + if(m_slave_Xref_item) + m_slave_Xref_item->setDefaultTextColor(Qt::black); + } + + DiagramTextItem::mousePressEvent(event); } /** - @brief DynamicElementTextItem::mouseMoveEvent - @param event + @brief DynamicElementTextItem::mouseMoveEvent + @param event */ void DynamicElementTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - if((event->buttons() & Qt::LeftButton) && (flags() & ItemIsMovable)) - { - if(diagram() && m_first_move) - diagram()->elementTextsMover().beginMovement(diagram(), this); - - if(m_first_move) - { - m_initial_position = pos(); - if(parentElement()) - parentElement()->setHighlighted(true); - } - - QPointF current_parent_pos; - QPointF button_down_parent_pos; - current_parent_pos = mapToParent(mapFromScene(event->scenePos())); - button_down_parent_pos = mapToParent(mapFromScene(event->buttonDownScenePos(Qt::LeftButton))); - - QPointF new_pos = m_initial_position + current_parent_pos - button_down_parent_pos; - event->modifiers() == Qt::ControlModifier ? setPos(new_pos) : setPos(Diagram::snapToGrid(new_pos)); - - if(diagram()) - diagram()->elementTextsMover().continueMovement(event); - } else { - event->ignore(); - } - - if(m_first_move) - m_first_move = false; +{ + if((event->buttons() & Qt::LeftButton) && (flags() & ItemIsMovable)) + { + if(diagram() && m_first_move) + diagram()->elementTextsMover().beginMovement(diagram(), this); + + if(m_first_move) + { + m_initial_position = pos(); + if(parentElement()) + parentElement()->setHighlighted(true); + } + + QPointF current_parent_pos; + QPointF button_down_parent_pos; + current_parent_pos = mapToParent(mapFromScene(event->scenePos())); + button_down_parent_pos = mapToParent(mapFromScene(event->buttonDownScenePos(Qt::LeftButton))); + + QPointF new_pos = m_initial_position + current_parent_pos - button_down_parent_pos; + event->modifiers() == Qt::ControlModifier ? setPos(new_pos) : setPos(Diagram::snapToGrid(new_pos)); + + if(diagram()) + diagram()->elementTextsMover().continueMovement(event); + } else { + event->ignore(); + } + + if(m_first_move) + m_first_move = false; } /** - @brief DynamicElementTextItem::mouseReleaseEvent - @param event + @brief DynamicElementTextItem::mouseReleaseEvent + @param event */ void DynamicElementTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (m_parent_element) - m_parent_element->setHighlighted(false); - - if(m_parent_element && m_parent_element->diagram()) - m_parent_element.data()->diagram()->elementTextsMover().endMovement(); - - if(!(event->modifiers() & Qt::ControlModifier)) - QGraphicsTextItem::mouseReleaseEvent(event); + if (m_parent_element) + m_parent_element->setHighlighted(false); + + if(m_parent_element && m_parent_element->diagram()) + m_parent_element.data()->diagram()->elementTextsMover().endMovement(); + + if(!(event->modifiers() & Qt::ControlModifier)) + QGraphicsTextItem::mouseReleaseEvent(event); } /** - @brief DynamicElementTextItem::mouseDoubleClickEvent - Reimplemented functions, for add extra feature when this text is owned by a slave. - In this case if the parent slave element is linked to a master, and this text display the label of the master - (both if the 'text from' is 'element info' or 'composite text') the QGraphicsView go to master and select it. - @param event + @brief DynamicElementTextItem::mouseDoubleClickEvent + Reimplemented functions, for add extra feature when this text is owned by a slave. + In this case if the parent slave element is linked to a master, and this text display the label of the master + (both if the 'text from' is 'element info' or 'composite text') the QGraphicsView go to master and select it. + @param event */ void DynamicElementTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { - DiagramTextItem::mouseDoubleClickEvent(event); - zoomToLinkedElement(); + DiagramTextItem::mouseDoubleClickEvent(event); + zoomToLinkedElement(); } /** - @brief DynamicElementTextItem::hoverEnterEvent - If the parent element of this text is a folio report or a slave element, the element is linked - and the text display the variable "label" we set the text blue for signal the user that the text act like - a link when we double click on. - @param event + @brief DynamicElementTextItem::hoverEnterEvent + If the parent element of this text is a folio report or a slave element, the element is linked + and the text display the variable "label" we set the text blue for signal the user that the text act like + a link when we double click on. + @param event */ void DynamicElementTextItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - DiagramTextItem::hoverEnterEvent(event); - - //If the text is selected we set the real color, otherwise the editor will display the color of text as blue, - //but this is not the color set by the user. - if(isSelected()) - return; - - if ((parentElement()->linkType() & Element::AllReport) && m_other_report) - { - if( (m_text_from == ElementInfo && m_info_name == "label") || - (m_text_from == CompositeText && m_composite_text.contains("%{label}")) ) - { - m_user_color = color(); - setDefaultTextColor(Qt::blue); - } - } + DiagramTextItem::hoverEnterEvent(event); + + //If the text is selected we set the real color, otherwise the editor will display the color of text as blue, + //but this is not the color set by the user. + if(isSelected()) + return; + + if ((parentElement()->linkType() & Element::AllReport) && m_other_report) + { + if( (m_text_from == ElementInfo && m_info_name == "label") || + (m_text_from == CompositeText && m_composite_text.contains("%{label}")) ) + { + m_user_color = color(); + setDefaultTextColor(Qt::blue); + } + } } /** - @brief DynamicElementTextItem::hoverLeaveEvent - @param event + @brief DynamicElementTextItem::hoverLeaveEvent + @param event */ void DynamicElementTextItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - DiagramTextItem::hoverLeaveEvent(event); - - if(m_user_color.isValid()) - { - setDefaultTextColor(m_user_color); - m_user_color = QColor(); //m_user_color is now invalid - } - + DiagramTextItem::hoverLeaveEvent(event); + + if(m_user_color.isValid()) + { + setDefaultTextColor(m_user_color); + m_user_color = QColor(); //m_user_color is now invalid + } + } void DynamicElementTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - DiagramTextItem::paint(painter, option, widget); - - if (m_frame) - { - painter->save(); - painter->setFont(QETApp::dynamicTextsItemFont(font().pointSize())); - - //Adjust the thickness according to the font size, - qreal w=0.3; - if(font().pointSize() >= 5) - { - w = font().pointSizeF()*0.1; - if(w > 2.5) - w = 2.5; - } - - QPen pen; - pen.setColor(color()); - pen.setWidthF(w); - painter->setPen(pen); - painter->setRenderHint(QPainter::Antialiasing); + DiagramTextItem::paint(painter, option, widget); + + if (m_frame) + { + painter->save(); + painter->setFont(QETApp::dynamicTextsItemFont(font().pointSize())); + + //Adjust the thickness according to the font size, + qreal w=0.3; + if(font().pointSize() >= 5) + { + w = font().pointSizeF()*0.1; + if(w > 2.5) + w = 2.5; + } + + QPen pen; + pen.setColor(color()); + pen.setWidthF(w); + painter->setPen(pen); + painter->setRenderHint(QPainter::Antialiasing); - //Adjust the rounding of the rectangle according to the size of the font - qreal ro = font().pointSizeF()/3; - painter->drawRoundedRect(frameRect(), ro, ro); - - painter->restore(); - } + //Adjust the rounding of the rectangle according to the size of the font + qreal ro = font().pointSizeF()/3; + painter->drawRoundedRect(frameRect(), ro, ro); + + painter->restore(); + } } QVariant DynamicElementTextItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - //The first time this text is added to a scene, we make several cheking and connection - //according to the link type of the parent element - if(change == QGraphicsItem::ItemSceneHasChanged && m_first_scene_change) - { - if(m_parent_element.isNull()) - return QGraphicsObject::itemChange(change, value); - - //If the parent is slave, we keep aware about the changement of master. - if(m_parent_element.data()->linkType() == Element::Slave) - { - connect(m_parent_element.data(), &Element::linkedElementChanged, this, &DynamicElementTextItem::masterChanged); - //The parent is already linked, wa call master changed for init the connection - if(!m_parent_element.data()->linkedElements().isEmpty()) - masterChanged(); - } - else if(m_parent_element.data()->linkType() & Element::AllReport) - { - //Get the report formula, and add connection to keep up to date the formula. - if (m_parent_element.data()->diagram() && m_parent_element.data()->diagram()->project()) - { - m_report_formula = m_parent_element.data()->diagram()->project()->defaultReportProperties(); - m_report_formula_con = connect(m_parent_element.data()->diagram()->project(), &QETProject::reportPropertiesChanged, this, &DynamicElementTextItem::reportFormulaChanged); - } - - //Add connection to keep up to date the status of the element linked to the parent folio report of this text. - connect(m_parent_element.data(), &Element::linkedElementChanged, this, &DynamicElementTextItem::reportChanged); - //The parent is already linked, we call reportChanged for init the connection - if(!m_parent_element.data()->linkedElements().isEmpty()) - reportChanged(); - - if(m_parent_element.data()->terminals().size()) - { - //Add connection to keep up date the conductors added or removed to the parent folio report element - connect(m_parent_element.data()->terminals().first(), &Terminal::conductorWasAdded, this, &DynamicElementTextItem::conductorWasAdded); - connect(m_parent_element.data()->terminals().first(), &Terminal::conductorWasRemoved, this, &DynamicElementTextItem::conductorWasRemoved); - } - //Get a conductor in the potential - setPotentialConductor(); - } - else if(m_parent_element.data()->linkType() == Element::Master) - { - connect(m_parent_element.data(), &Element::linkedElementChanged, this, &DynamicElementTextItem::updateXref); - if(m_parent_element.data()->diagram()) - connect(m_parent_element.data()->diagram()->project(), &QETProject::XRefPropertiesChanged, this, &DynamicElementTextItem::updateXref); - if(!m_parent_element.data()->linkedElements().isEmpty()) - updateXref(); - } - - m_first_scene_change = false; - return QGraphicsObject::itemChange(change, value); - } - else if (change == QGraphicsItem::ItemParentHasChanged) - { - updateXref(); - updateXref(); - } - - return QGraphicsObject::itemChange(change, value); + //The first time this text is added to a scene, we make several cheking and connection + //according to the link type of the parent element + if(change == QGraphicsItem::ItemSceneHasChanged && m_first_scene_change) + { + if(m_parent_element.isNull()) + return QGraphicsObject::itemChange(change, value); + + //If the parent is slave, we keep aware about the changement of master. + if(m_parent_element.data()->linkType() == Element::Slave) + { + connect(m_parent_element.data(), &Element::linkedElementChanged, this, &DynamicElementTextItem::masterChanged); + //The parent is already linked, wa call master changed for init the connection + if(!m_parent_element.data()->linkedElements().isEmpty()) + masterChanged(); + } + else if(m_parent_element.data()->linkType() & Element::AllReport) + { + //Get the report formula, and add connection to keep up to date the formula. + if (m_parent_element.data()->diagram() && m_parent_element.data()->diagram()->project()) + { + m_report_formula = m_parent_element.data()->diagram()->project()->defaultReportProperties(); + m_report_formula_con = connect(m_parent_element.data()->diagram()->project(), &QETProject::reportPropertiesChanged, this, &DynamicElementTextItem::reportFormulaChanged); + } + + //Add connection to keep up to date the status of the element linked to the parent folio report of this text. + connect(m_parent_element.data(), &Element::linkedElementChanged, this, &DynamicElementTextItem::reportChanged); + //The parent is already linked, we call reportChanged for init the connection + if(!m_parent_element.data()->linkedElements().isEmpty()) + reportChanged(); + + if(m_parent_element.data()->terminals().size()) + { + //Add connection to keep up date the conductors added or removed to the parent folio report element + connect(m_parent_element.data()->terminals().first(), &Terminal::conductorWasAdded, this, &DynamicElementTextItem::conductorWasAdded); + connect(m_parent_element.data()->terminals().first(), &Terminal::conductorWasRemoved, this, &DynamicElementTextItem::conductorWasRemoved); + } + //Get a conductor in the potential + setPotentialConductor(); + } + else if(m_parent_element.data()->linkType() == Element::Master) + { + connect(m_parent_element.data(), &Element::linkedElementChanged, this, &DynamicElementTextItem::updateXref); + if(m_parent_element.data()->diagram()) + connect(m_parent_element.data()->diagram()->project(), &QETProject::XRefPropertiesChanged, this, &DynamicElementTextItem::updateXref); + if(!m_parent_element.data()->linkedElements().isEmpty()) + updateXref(); + } + + m_first_scene_change = false; + return QGraphicsObject::itemChange(change, value); + } + else if (change == QGraphicsItem::ItemParentHasChanged) + { + updateXref(); + updateXref(); + } + + return QGraphicsObject::itemChange(change, value); } bool DynamicElementTextItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - if(watched != m_slave_Xref_item) - return false; - - if(event->type() == QEvent::GraphicsSceneHoverEnter) { - m_slave_Xref_item->setDefaultTextColor(Qt::blue); - return true; - } - else if(event->type() == QEvent::GraphicsSceneHoverLeave) { - m_slave_Xref_item->setDefaultTextColor(Qt::black); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseDoubleClick) { - zoomToLinkedElement(); - return true; - } - - return false; + if(watched != m_slave_Xref_item) + return false; + + if(event->type() == QEvent::GraphicsSceneHoverEnter) { + m_slave_Xref_item->setDefaultTextColor(Qt::blue); + return true; + } + else if(event->type() == QEvent::GraphicsSceneHoverLeave) { + m_slave_Xref_item->setDefaultTextColor(Qt::black); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseDoubleClick) { + zoomToLinkedElement(); + return true; + } + + return false; } void DynamicElementTextItem::elementInfoChanged() { - DiagramContext dc; - Element *element = elementUseForInfo(); - if(element) { - dc = element->elementInformations(); - } - - QString final_text; + DiagramContext dc; + Element *element = elementUseForInfo(); + if(element) { + dc = element->elementInformations(); + } + + QString final_text; - if (m_text_from == ElementInfo) - { - //If the info is the label, then we must to make some connection - //if the label is created from a formula - if(m_info_name == "label") - { - setupFormulaConnection(); + if (m_text_from == ElementInfo) + { + //If the info is the label, then we must to make some connection + //if the label is created from a formula + if(m_info_name == "label") + { + setupFormulaConnection(); - if (element) { - final_text = element->actualLabel(); - } - } - else { - final_text = dc.value(m_info_name).toString(); - } - } - else if (m_text_from == CompositeText) - { - //If the composite have the label variable, we must to make some - //connection if the label is created from a formula - if (m_composite_text.contains("%{label}")) - setupFormulaConnection(); - - final_text = autonum::AssignVariables::replaceVariable(m_composite_text, dc); - } - else if (m_text_from == UserText) - final_text = m_text; - - setPlainText(final_text); - emit plainTextChanged(); + if (element) { + final_text = element->actualLabel(); + } + } + else { + final_text = dc.value(m_info_name).toString(); + } + } + else if (m_text_from == CompositeText) + { + //If the composite have the label variable, we must to make some + //connection if the label is created from a formula + if (m_composite_text.contains("%{label}")) + setupFormulaConnection(); + + final_text = autonum::AssignVariables::replaceVariable(m_composite_text, dc); + } + else if (m_text_from == UserText) + final_text = m_text; + + setPlainText(final_text); + emit plainTextChanged(); } /** - @brief DynamicElementTextItem::masterChanged - This function is only use when the parent element is a slave. - Call when the master element linked to the parent slave element of this text change + @brief DynamicElementTextItem::masterChanged + This function is only use when the parent element is a slave. + Call when the master element linked to the parent slave element of this text change */ void DynamicElementTextItem::masterChanged() { - //First we remove the old connection - if(!m_master_element.isNull() && (m_text_from == ElementInfo || m_text_from == CompositeText)) - { - disconnect(m_master_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); - m_master_element.clear(); - updateXref(); - } - - if(elementUseForInfo()) - { - m_master_element = elementUseForInfo(); - if(m_text_from == ElementInfo || m_text_from == CompositeText) - connect(m_master_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); - - updateXref(); - } - - //Because master changed we update this text - elementInfoChanged(); + //First we remove the old connection + if(!m_master_element.isNull() && (m_text_from == ElementInfo || m_text_from == CompositeText)) + { + disconnect(m_master_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); + m_master_element.clear(); + updateXref(); + } + + if(elementUseForInfo()) + { + m_master_element = elementUseForInfo(); + if(m_text_from == ElementInfo || m_text_from == CompositeText) + connect(m_master_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::elementInfoChanged); + + updateXref(); + } + + //Because master changed we update this text + elementInfoChanged(); } /** - @brief DynamicElementTextItem::reportChanged - This function is only use when parent element of this text is a folio report - The linked report of the parent element was changed + @brief DynamicElementTextItem::reportChanged + This function is only use when parent element of this text is a folio report + The linked report of the parent element was changed */ void DynamicElementTextItem::reportChanged() { - /* - * When the dynamic text are added by a drag & drop from the element panel, - * the connection below are made in the constructor. - * If the text are added at load of a .qet file, the text is not yet added to a diagram then the connection is not made. - * We make it now, because when the linked report changed, that mean this text is in a diagram - */ - if(!m_report_formula_con) - { - //Get the report formula, and add connection to keep up to date the formula. - if (parentElement()->diagram() && parentElement()->diagram()->project()) - { - m_report_formula = parentElement()->diagram()->project()->defaultReportProperties(); - m_report_formula_con = connect(parentElement()->diagram()->project(), &QETProject::reportPropertiesChanged, this, &DynamicElementTextItem::reportFormulaChanged); - } - } - - bool text_have_label = false; - - if((textFrom() == ElementInfo && m_info_name == "label") || - (textFrom() == CompositeText && m_composite_text.contains("%{label}"))) - text_have_label = true; - - if(text_have_label) - removeConnectionForReportFormula(m_report_formula); - - m_other_report.clear(); - if(!m_parent_element.data()->linkedElements().isEmpty()) - m_other_report = m_parent_element.data()->linkedElements().first(); - - //Because linked report was changed, we ensure there is a conductor watched - setPotentialConductor(); - - if(text_have_label) - { - setConnectionForReportFormula(m_report_formula); - updateReportText(); - } + /* + * When the dynamic text are added by a drag & drop from the element panel, + * the connection below are made in the constructor. + * If the text are added at load of a .qet file, the text is not yet added to a diagram then the connection is not made. + * We make it now, because when the linked report changed, that mean this text is in a diagram + */ + if(!m_report_formula_con) + { + //Get the report formula, and add connection to keep up to date the formula. + if (parentElement()->diagram() && parentElement()->diagram()->project()) + { + m_report_formula = parentElement()->diagram()->project()->defaultReportProperties(); + m_report_formula_con = connect(parentElement()->diagram()->project(), &QETProject::reportPropertiesChanged, this, &DynamicElementTextItem::reportFormulaChanged); + } + } + + bool text_have_label = false; + + if((textFrom() == ElementInfo && m_info_name == "label") || + (textFrom() == CompositeText && m_composite_text.contains("%{label}"))) + text_have_label = true; + + if(text_have_label) + removeConnectionForReportFormula(m_report_formula); + + m_other_report.clear(); + if(!m_parent_element.data()->linkedElements().isEmpty()) + m_other_report = m_parent_element.data()->linkedElements().first(); + + //Because linked report was changed, we ensure there is a conductor watched + setPotentialConductor(); + + if(text_have_label) + { + setConnectionForReportFormula(m_report_formula); + updateReportText(); + } } /** - @brief DynamicElementTextItem::reportFormulaChanged - The report formula use in the project was changed + @brief DynamicElementTextItem::reportFormulaChanged + The report formula use in the project was changed */ void DynamicElementTextItem::reportFormulaChanged() { - m_report_formula = parentElement()->diagram()->project()->defaultReportProperties(); - - if(m_text_from == ElementInfo && m_info_name == "label") - updateReportText(); + m_report_formula = parentElement()->diagram()->project()->defaultReportProperties(); + + if(m_text_from == ElementInfo && m_info_name == "label") + updateReportText(); } void DynamicElementTextItem::setConnectionForReportFormula(const QString &formula) { - if(m_other_report.isNull() || formula.isEmpty()) - return; - - Element *other_elmt = m_other_report.data(); - QString string = formula; - Diagram *other_diagram = m_other_report.data()->diagram(); - - //Because the variable %F is a reference to another text which can contain variables, - //we must to replace %F by the real text, to check if the real text contain the variable %id - if (other_diagram && string.contains("%F")) - { - m_F_str = other_diagram->border_and_titleblock.folio(); - string.replace("%F", other_diagram->border_and_titleblock.folio()); - connect(&other_diagram->border_and_titleblock, &BorderTitleBlock::titleBlockFolioChanged, this, &DynamicElementTextItem::updateReportFormulaConnection); - } - - if (other_diagram && (string.contains("%f") || string.contains("%id"))) - { - connect(other_diagram->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateReportText); - connect(other_diagram->project(), &QETProject::diagramRemoved, this, &DynamicElementTextItem::updateReportText); - } - if (string.contains("%l")) - connect(other_elmt, &Element::yChanged, this, &DynamicElementTextItem::updateReportText); - if (string.contains("%c")) - connect(other_elmt, &Element::xChanged, this, &DynamicElementTextItem::updateReportText); + if(m_other_report.isNull() || formula.isEmpty()) + return; + + Element *other_elmt = m_other_report.data(); + QString string = formula; + Diagram *other_diagram = m_other_report.data()->diagram(); + + //Because the variable %F is a reference to another text which can contain variables, + //we must to replace %F by the real text, to check if the real text contain the variable %id + if (other_diagram && string.contains("%F")) + { + m_F_str = other_diagram->border_and_titleblock.folio(); + string.replace("%F", other_diagram->border_and_titleblock.folio()); + connect(&other_diagram->border_and_titleblock, &BorderTitleBlock::titleBlockFolioChanged, this, &DynamicElementTextItem::updateReportFormulaConnection); + } + + if (other_diagram && (string.contains("%f") || string.contains("%id"))) + { + connect(other_diagram->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateReportText); + connect(other_diagram->project(), &QETProject::diagramRemoved, this, &DynamicElementTextItem::updateReportText); + } + if (string.contains("%l")) + connect(other_elmt, &Element::yChanged, this, &DynamicElementTextItem::updateReportText); + if (string.contains("%c")) + connect(other_elmt, &Element::xChanged, this, &DynamicElementTextItem::updateReportText); } void DynamicElementTextItem::removeConnectionForReportFormula(const QString &formula) { - if(m_other_report.isNull() || formula.isEmpty()) - return; - - Element *other_element = m_other_report.data(); - QString string = formula; - Diagram *other_diagram = m_other_report.data()->diagram(); - - //Because the variable %F is a reference to another text which can contain variables, - //we must to replace %F by the real text, to check if the real text contain the variable %id - if (other_diagram && string.contains("%F")) - { - string.replace("%F", m_F_str); - disconnect(&other_diagram->border_and_titleblock, &BorderTitleBlock::titleBlockFolioChanged, this, &DynamicElementTextItem::updateReportFormulaConnection); - } - - if (other_diagram && (string.contains("%f") || string.contains("%id"))) - disconnect(other_diagram->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateReportText); - if (string.contains("%l")) - disconnect(other_element, &Element::yChanged, this, &DynamicElementTextItem::updateReportText); - if (string.contains("%c")) - disconnect(other_element, &Element::xChanged, this, &DynamicElementTextItem::updateReportText); - + if(m_other_report.isNull() || formula.isEmpty()) + return; + + Element *other_element = m_other_report.data(); + QString string = formula; + Diagram *other_diagram = m_other_report.data()->diagram(); + + //Because the variable %F is a reference to another text which can contain variables, + //we must to replace %F by the real text, to check if the real text contain the variable %id + if (other_diagram && string.contains("%F")) + { + string.replace("%F", m_F_str); + disconnect(&other_diagram->border_and_titleblock, &BorderTitleBlock::titleBlockFolioChanged, this, &DynamicElementTextItem::updateReportFormulaConnection); + } + + if (other_diagram && (string.contains("%f") || string.contains("%id"))) + disconnect(other_diagram->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateReportText); + if (string.contains("%l")) + disconnect(other_element, &Element::yChanged, this, &DynamicElementTextItem::updateReportText); + if (string.contains("%c")) + disconnect(other_element, &Element::xChanged, this, &DynamicElementTextItem::updateReportText); + } /** - @brief DynamicElementTextItem::setupFormulaConnection - Setup the required connection for the formula of the label. + @brief DynamicElementTextItem::setupFormulaConnection + Setup the required connection for the formula of the label. */ void DynamicElementTextItem::setupFormulaConnection() { - if ((m_text_from == ElementInfo && m_info_name == "label") || - (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) - { - clearFormulaConnection(); - - Element *element = elementUseForInfo(); - if (!element) - return; - - Diagram *diagram = element->diagram(); - QString formula = element->elementInformations().value("formula").toString(); + if ((m_text_from == ElementInfo && m_info_name == "label") || + (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) + { + clearFormulaConnection(); + + Element *element = elementUseForInfo(); + if (!element) + return; + + Diagram *diagram = element->diagram(); + QString formula = element->elementInformations().value("formula").toString(); - //Label is frozen, so we don't update it. - if (element->isFreezeLabel()) - return; - - if (diagram && formula.contains("%F")) - { - m_F_str = diagram->border_and_titleblock.folio(); - formula.replace("%F", m_F_str); - m_formula_connection << connect(&diagram->border_and_titleblock, &BorderTitleBlock::titleBlockFolioChanged, this, &DynamicElementTextItem::updateLabel); - } - - if (diagram && (formula.contains("%f") || formula.contains("%id"))) - { - m_formula_connection << connect(diagram->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateLabel); - m_formula_connection << connect(diagram->project(), &QETProject::diagramRemoved, this, &DynamicElementTextItem::updateLabel); - } - if (formula.contains("%l")) - m_formula_connection << connect(element, &Element::yChanged, this, &DynamicElementTextItem::updateLabel); - if (formula.contains("%c")) - m_formula_connection << connect(element, &Element::xChanged, this, &DynamicElementTextItem::updateLabel); - - } + //Label is frozen, so we don't update it. + if (element->isFreezeLabel()) + return; + + if (diagram && formula.contains("%F")) + { + m_F_str = diagram->border_and_titleblock.folio(); + formula.replace("%F", m_F_str); + m_formula_connection << connect(&diagram->border_and_titleblock, &BorderTitleBlock::titleBlockFolioChanged, this, &DynamicElementTextItem::updateLabel); + } + + if (diagram && (formula.contains("%f") || formula.contains("%id"))) + { + m_formula_connection << connect(diagram->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateLabel); + m_formula_connection << connect(diagram->project(), &QETProject::diagramRemoved, this, &DynamicElementTextItem::updateLabel); + } + if (formula.contains("%l")) + m_formula_connection << connect(element, &Element::yChanged, this, &DynamicElementTextItem::updateLabel); + if (formula.contains("%c")) + m_formula_connection << connect(element, &Element::xChanged, this, &DynamicElementTextItem::updateLabel); + + } } void DynamicElementTextItem::clearFormulaConnection() { - for (const QMetaObject::Connection& con : m_formula_connection) - disconnect(con); - m_formula_connection.clear(); + for (const QMetaObject::Connection& con : m_formula_connection) + disconnect(con); + m_formula_connection.clear(); } void DynamicElementTextItem::updateReportFormulaConnection() { - if(!(m_parent_element.data()->linkType() & Element::AllReport)) - return; - - removeConnectionForReportFormula(m_report_formula); - setConnectionForReportFormula(m_report_formula); - updateReportText(); + if(!(m_parent_element.data()->linkType() & Element::AllReport)) + return; + + removeConnectionForReportFormula(m_report_formula); + setConnectionForReportFormula(m_report_formula); + updateReportText(); } /** - @brief DynamicElementTextItem::updateReportText - This function is only use when this text is owned by a report, and this text have for info the Label. + @brief DynamicElementTextItem::updateReportText + This function is only use when this text is owned by a report, and this text have for info the Label. */ void DynamicElementTextItem::updateReportText() { - if(!(m_parent_element.data()->linkType() & Element::AllReport)) - return; - - if (m_text_from == ElementInfo && m_info_name == "label") - { - if(m_other_report) - { - Element *elmt = m_other_report.data(); - QString label = m_report_formula; - label = autonum::AssignVariables::formulaToLabel(label, elmt->rSequenceStruct(), elmt->diagram(), elmt); - setPlainText(label); - } - else - { - setPlainText(""); - } - } - else if (m_text_from == CompositeText) { - setPlainText(reportReplacedCompositeText()); - } + if(!(m_parent_element.data()->linkType() & Element::AllReport)) + return; + + if (m_text_from == ElementInfo && m_info_name == "label") + { + if(m_other_report) + { + Element *elmt = m_other_report.data(); + QString label = m_report_formula; + label = autonum::AssignVariables::formulaToLabel(label, elmt->rSequenceStruct(), elmt->diagram(), elmt); + setPlainText(label); + } + else + { + setPlainText(""); + } + } + else if (m_text_from == CompositeText) { + setPlainText(reportReplacedCompositeText()); + } } /** - @brief DynamicElementTextItem::updateLabel - Update the displayed text, when this dynamic text is based on the label of the parent element. - This function is notably use when the label itself is based from a formula. - If this dynamic text isn't based on label, this function do nothing. + @brief DynamicElementTextItem::updateLabel + Update the displayed text, when this dynamic text is based on the label of the parent element. + This function is notably use when the label itself is based from a formula. + If this dynamic text isn't based on label, this function do nothing. */ void DynamicElementTextItem::updateLabel() { - if ((m_text_from == ElementInfo && m_info_name == "label") || - (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) - { - DiagramContext dc; - Element *element = elementUseForInfo(); - if(element) { - dc = element->elementInformations(); - } - + if ((m_text_from == ElementInfo && m_info_name == "label") || + (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) + { + DiagramContext dc; + Element *element = elementUseForInfo(); + if(element) { + dc = element->elementInformations(); + } + - if(m_text_from == ElementInfo && element) { - setPlainText(element->actualLabel()); - } - else if (m_text_from == CompositeText) { - setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, dc)); - } - } + if(m_text_from == ElementInfo && element) { + setPlainText(element->actualLabel()); + } + else if (m_text_from == CompositeText) { + setPlainText(autonum::AssignVariables::replaceVariable(m_composite_text, dc)); + } + } } /** - @brief DynamicElementTextItem::conductorWasAdded - Function only use when parent element is a folio report - @param conductor + @brief DynamicElementTextItem::conductorWasAdded + Function only use when parent element is a folio report + @param conductor */ void DynamicElementTextItem::conductorWasAdded(Conductor *conductor) { - Q_UNUSED(conductor) - setPotentialConductor(); + Q_UNUSED(conductor) + setPotentialConductor(); } /** - @brief DynamicElementTextItem::conductorWasRemoved - Function only use when parent element is a folio report - @param conductor + @brief DynamicElementTextItem::conductorWasRemoved + Function only use when parent element is a folio report + @param conductor */ void DynamicElementTextItem::conductorWasRemoved(Conductor *conductor) { - if(m_watched_conductor.data() == conductor) - { - disconnect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); - m_watched_conductor.clear(); - setPotentialConductor(); - } + if(m_watched_conductor.data() == conductor) + { + disconnect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); + m_watched_conductor.clear(); + setPotentialConductor(); + } } /** - @brief DynamicElementTextItem::setPotentialConductor - This function is only used when the parent element of this text is a report element - Get a conductor in the potential of the parent report + @brief DynamicElementTextItem::setPotentialConductor + This function is only used when the parent element of this text is a report element + Get a conductor in the potential of the parent report */ void DynamicElementTextItem::setPotentialConductor() { - if(parentElement() && (parentElement()->linkType() & Element::AllReport)) - { - if(parentElement()->terminals().isEmpty()) - return; - - /* - * #First case, if m_watched_conductor is a conductor of the parent report, everything is ok - * #Second case, if the conductors list of parent report element is not empty, - * we set one of these conductor as m_watched_conductor, even if m_watched_conductor is already set, - * because that mean the conductor is a conductor of the linked report, and we prefer to set a conductor - * owned by the parent report element of this text. - * #third case, if m_watched_conductor is null, we set a conductor of the linked report, if any. - */ - QList c_list = parentElement()->terminals().first()->conductors(); - - if(!c_list.isEmpty() && c_list.contains(m_watched_conductor.data())) - return; - else if(!c_list.isEmpty()) - { - if(!m_watched_conductor.isNull()) - disconnect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); - - m_watched_conductor = c_list.first(); - connect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); - } - else if(m_watched_conductor.isNull() && m_other_report) - { - if (!m_other_report.data()->terminals().first()->conductors().isEmpty()) - { - m_watched_conductor = m_other_report.data()->terminals().first()->conductors().first(); - connect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); - } - } - } - else //This text haven't got a parent element, then ther isn't a conductor in the potential - { - if(!m_watched_conductor.isNull()) - disconnect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); - - m_watched_conductor.clear(); - } + if(parentElement() && (parentElement()->linkType() & Element::AllReport)) + { + if(parentElement()->terminals().isEmpty()) + return; + + /* + * #First case, if m_watched_conductor is a conductor of the parent report, everything is ok + * #Second case, if the conductors list of parent report element is not empty, + * we set one of these conductor as m_watched_conductor, even if m_watched_conductor is already set, + * because that mean the conductor is a conductor of the linked report, and we prefer to set a conductor + * owned by the parent report element of this text. + * #third case, if m_watched_conductor is null, we set a conductor of the linked report, if any. + */ + QList c_list = parentElement()->terminals().first()->conductors(); + + if(!c_list.isEmpty() && c_list.contains(m_watched_conductor.data())) + return; + else if(!c_list.isEmpty()) + { + if(!m_watched_conductor.isNull()) + disconnect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); + + m_watched_conductor = c_list.first(); + connect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); + } + else if(m_watched_conductor.isNull() && m_other_report) + { + if (!m_other_report.data()->terminals().first()->conductors().isEmpty()) + { + m_watched_conductor = m_other_report.data()->terminals().first()->conductors().first(); + connect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); + } + } + } + else //This text haven't got a parent element, then ther isn't a conductor in the potential + { + if(!m_watched_conductor.isNull()) + disconnect(m_watched_conductor.data(), &Conductor::propertiesChange, this, &DynamicElementTextItem::conductorPropertiesChanged); + + m_watched_conductor.clear(); + } } /** - @brief DynamicElementTextItem::conductorPropertiesChanged - This function is only used when the parent element of this text is a report element + @brief DynamicElementTextItem::conductorPropertiesChanged + This function is only used when the parent element of this text is a report element */ void DynamicElementTextItem::conductorPropertiesChanged() { - if(m_parent_element && (m_parent_element.data()->linkType() & Element::AllReport)) - { - if(m_text_from == ElementInfo) - { - if(m_info_name == "function") - setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_function : ""); - else if (m_info_name == "tension_protocol") - setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_tension_protocol : ""); - else if (m_info_name == "conductor_color") - setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_wire_color : ""); - else if (m_info_name == "conductor_section") - setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_wire_section : ""); - } - else if (m_text_from == CompositeText) { - setPlainText(reportReplacedCompositeText()); - } - } + if(m_parent_element && (m_parent_element.data()->linkType() & Element::AllReport)) + { + if(m_text_from == ElementInfo) + { + if(m_info_name == "function") + setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_function : ""); + else if (m_info_name == "tension_protocol") + setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_tension_protocol : ""); + else if (m_info_name == "conductor_color") + setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_wire_color : ""); + else if (m_info_name == "conductor_section") + setPlainText(m_watched_conductor? m_watched_conductor.data()->properties().m_wire_section : ""); + } + else if (m_text_from == CompositeText) { + setPlainText(reportReplacedCompositeText()); + } + } } /** - @brief DynamicElementTextItem::reportReplacedCompositeText - This function is only used when the parent element of this text is a report element - @return the composite text with the variable replaced by the real value. - If the parent element of this text is not a folio report, return a default QString. + @brief DynamicElementTextItem::reportReplacedCompositeText + This function is only used when the parent element of this text is a report element + @return the composite text with the variable replaced by the real value. + If the parent element of this text is not a folio report, return a default QString. */ QString DynamicElementTextItem::reportReplacedCompositeText() const { - QString string; - - if(m_parent_element.data()->linkType() & Element::AllReport) - { - string = m_composite_text; - - if (string.contains("%{label}") && m_other_report) - { - Element *elmt = m_other_report.data(); - QString label = m_report_formula; - label = autonum::AssignVariables::formulaToLabel(label, elmt->rSequenceStruct(), elmt->diagram(), elmt); - string.replace("%{label}", label); - } - if (m_watched_conductor) - { - if(string.contains("%{function}")) - string.replace("%{function}", m_watched_conductor.data()->properties().m_function); - if(string.contains("%{tension_protocol}")) - string.replace("%{tension_protocol}", m_watched_conductor.data()->properties().m_tension_protocol); - if(string.contains("%{conductor_color}")) - string.replace("%{conductor_color}", m_watched_conductor.data()->properties().m_wire_color); - if(string.contains("%{conductor_section}")) - string.replace("%{conductor_section}", m_watched_conductor.data()->properties().m_wire_section); - } - } - - return string; + QString string; + + if(m_parent_element.data()->linkType() & Element::AllReport) + { + string = m_composite_text; + + if (string.contains("%{label}") && m_other_report) + { + Element *elmt = m_other_report.data(); + QString label = m_report_formula; + label = autonum::AssignVariables::formulaToLabel(label, elmt->rSequenceStruct(), elmt->diagram(), elmt); + string.replace("%{label}", label); + } + if (m_watched_conductor) + { + if(string.contains("%{function}")) + string.replace("%{function}", m_watched_conductor.data()->properties().m_function); + if(string.contains("%{tension_protocol}")) + string.replace("%{tension_protocol}", m_watched_conductor.data()->properties().m_tension_protocol); + if(string.contains("%{conductor_color}")) + string.replace("%{conductor_color}", m_watched_conductor.data()->properties().m_wire_color); + if(string.contains("%{conductor_section}")) + string.replace("%{conductor_section}", m_watched_conductor.data()->properties().m_wire_section); + } + } + + return string; } /** - @brief DynamicElementTextItem::zoomToLinkedElement - If the parent element is a folio report or a slave element, - and is linked, zoom to the linked element + @brief DynamicElementTextItem::zoomToLinkedElement + If the parent element is a folio report or a slave element, + and is linked, zoom to the linked element */ void DynamicElementTextItem::zoomToLinkedElement() { - if(!parentElement()) - return; - - Element *zoomed_element = nullptr; - - if(parentElement()->linkType() == Element::Slave && m_master_element) - { - if ((m_text_from == ElementInfo && m_info_name == "label") || - (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) - zoomed_element = m_master_element.data(); - } - if((parentElement()->linkType() & Element::AllReport) && m_other_report) - { - if((m_text_from == ElementInfo && m_info_name == "label") || - (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) - zoomed_element = m_other_report.data(); - } - - if(zoomed_element) - { - //Unselect and ungrab mouse to prevent unwanted - //move when linked element is in the same scene of this. - setSelected(false); - ungrabMouse(); - - if(scene() != zoomed_element->scene()) - zoomed_element->diagram()->showMe(); - zoomed_element->setSelected(true); - - //Zoom to the element - for(QGraphicsView *view : zoomed_element->scene()->views()) - { - QRectF fit = zoomed_element->sceneBoundingRect(); - fit.adjust(-200, -200, 200, 200); - view->fitInView(fit, Qt::KeepAspectRatioByExpanding); - } - } + if(!parentElement()) + return; + + Element *zoomed_element = nullptr; + + if(parentElement()->linkType() == Element::Slave && m_master_element) + { + if ((m_text_from == ElementInfo && m_info_name == "label") || + (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) + zoomed_element = m_master_element.data(); + } + if((parentElement()->linkType() & Element::AllReport) && m_other_report) + { + if((m_text_from == ElementInfo && m_info_name == "label") || + (m_text_from == CompositeText && m_composite_text.contains("%{label}"))) + zoomed_element = m_other_report.data(); + } + + if(zoomed_element) + { + //Unselect and ungrab mouse to prevent unwanted + //move when linked element is in the same scene of this. + setSelected(false); + ungrabMouse(); + + if(scene() != zoomed_element->scene()) + zoomed_element->diagram()->showMe(); + zoomed_element->setSelected(true); + + //Zoom to the element + for(QGraphicsView *view : zoomed_element->scene()->views()) + { + QRectF fit = zoomed_element->sceneBoundingRect(); + fit.adjust(-200, -200, 200, 200); + view->fitInView(fit, Qt::KeepAspectRatioByExpanding); + } + } } /** - @brief DynamicElementTextItem::updateXref - Create or delete the Xref according to the current properties of the project + @brief DynamicElementTextItem::updateXref + Create or delete the Xref according to the current properties of the project */ void DynamicElementTextItem::updateXref() { - if(diagram()) - { - if(m_parent_element.data()->linkType() == Element::Master) - { - XRefProperties xrp = diagram()->project()->defaultXRefProperties(m_parent_element.data()->kindInformations()["type"].toString()); - - if(m_text_from == DynamicElementTextItem::ElementInfo && - m_info_name == "label" && - !m_parent_element.data()->linkedElements().isEmpty() && - xrp.snapTo() == XRefProperties::Label) - { - //For add a Xref, this text must not be in a group - if(!parentGroup()) - { - if(!m_Xref_item) - m_Xref_item = new CrossRefItem(m_parent_element.data(), this); - return; - } - } - } - else if (m_parent_element.data()->linkType() == Element::Slave) - { - if(m_master_element && !parentGroup() && - ( - (m_text_from == DynamicElementTextItem::ElementInfo && m_info_name == "label") || - (m_text_from == DynamicElementTextItem::CompositeText && m_composite_text.contains("%{label}")) - ) - ) - { - XRefProperties xrp = diagram()->project()->defaultXRefProperties(m_master_element.data()->kindInformations()["type"].toString()); - QString xref_label = xrp.slaveLabel(); - xref_label = autonum::AssignVariables::formulaToLabel(xref_label, m_master_element.data()->rSequenceStruct(), m_master_element.data()->diagram(), m_master_element.data()); - - if(!m_slave_Xref_item) - { - m_slave_Xref_item = new QGraphicsTextItem(xref_label, this); - m_slave_Xref_item->setFont(QETApp::diagramTextsFont(5)); - m_slave_Xref_item->installSceneEventFilter(this); - - m_update_slave_Xref_connection << connect(m_master_element.data(), &Element::xChanged, this, &DynamicElementTextItem::updateXref); - m_update_slave_Xref_connection << connect(m_master_element.data(), &Element::yChanged, this, &DynamicElementTextItem::updateXref); - m_update_slave_Xref_connection << connect(m_master_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::updateXref); - m_update_slave_Xref_connection << connect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateXref); - m_update_slave_Xref_connection << connect(diagram()->project(), &QETProject::diagramRemoved, this, &DynamicElementTextItem::updateXref); - m_update_slave_Xref_connection << connect(diagram()->project(), &QETProject::XRefPropertiesChanged, this, &DynamicElementTextItem::updateXref); - } - else - m_slave_Xref_item->setPlainText(xref_label); - setXref_item(xrp.getXrefPos()); - return; - } - } - } + if(diagram()) + { + if(m_parent_element.data()->linkType() == Element::Master) + { + XRefProperties xrp = diagram()->project()->defaultXRefProperties(m_parent_element.data()->kindInformations()["type"].toString()); + + if(m_text_from == DynamicElementTextItem::ElementInfo && + m_info_name == "label" && + !m_parent_element.data()->linkedElements().isEmpty() && + xrp.snapTo() == XRefProperties::Label) + { + //For add a Xref, this text must not be in a group + if(!parentGroup()) + { + if(!m_Xref_item) + m_Xref_item = new CrossRefItem(m_parent_element.data(), this); + return; + } + } + } + else if (m_parent_element.data()->linkType() == Element::Slave) + { + if(m_master_element && !parentGroup() && + ( + (m_text_from == DynamicElementTextItem::ElementInfo && m_info_name == "label") || + (m_text_from == DynamicElementTextItem::CompositeText && m_composite_text.contains("%{label}")) + ) + ) + { + XRefProperties xrp = diagram()->project()->defaultXRefProperties(m_master_element.data()->kindInformations()["type"].toString()); + QString xref_label = xrp.slaveLabel(); + xref_label = autonum::AssignVariables::formulaToLabel(xref_label, m_master_element.data()->rSequenceStruct(), m_master_element.data()->diagram(), m_master_element.data()); + + if(!m_slave_Xref_item) + { + m_slave_Xref_item = new QGraphicsTextItem(xref_label, this); + m_slave_Xref_item->setFont(QETApp::diagramTextsFont(5)); + m_slave_Xref_item->installSceneEventFilter(this); + + m_update_slave_Xref_connection << connect(m_master_element.data(), &Element::xChanged, this, &DynamicElementTextItem::updateXref); + m_update_slave_Xref_connection << connect(m_master_element.data(), &Element::yChanged, this, &DynamicElementTextItem::updateXref); + m_update_slave_Xref_connection << connect(m_master_element.data(), &Element::elementInfoChange, this, &DynamicElementTextItem::updateXref); + m_update_slave_Xref_connection << connect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &DynamicElementTextItem::updateXref); + m_update_slave_Xref_connection << connect(diagram()->project(), &QETProject::diagramRemoved, this, &DynamicElementTextItem::updateXref); + m_update_slave_Xref_connection << connect(diagram()->project(), &QETProject::XRefPropertiesChanged, this, &DynamicElementTextItem::updateXref); + } + else + m_slave_Xref_item->setPlainText(xref_label); + setXref_item(xrp.getXrefPos()); + return; + } + } + } - //There is no reason to have a xref, we delete it if exist - if(m_Xref_item) - { - delete m_Xref_item; - m_Xref_item = nullptr; - } - - if(m_slave_Xref_item) - { - delete m_slave_Xref_item; - m_slave_Xref_item = nullptr; - m_update_slave_Xref_connection.clear(); - } + //There is no reason to have a xref, we delete it if exist + if(m_Xref_item) + { + delete m_Xref_item; + m_Xref_item = nullptr; + } + + if(m_slave_Xref_item) + { + delete m_slave_Xref_item; + m_slave_Xref_item = nullptr; + m_update_slave_Xref_connection.clear(); + } } void DynamicElementTextItem::setPlainText(const QString &text) { - if (toPlainText() == text) - return; + if (toPlainText() == text) + return; - bool update_alignment = true; - if (diagram() && (diagram()->project()->state() == QETProject::ProjectParsingRunning)) - update_alignment = false; - if (m_parent_element.data()->state() == QET::GIBuildingFromXml || - m_parent_element.data()->state() == QET::GILoadingFromXml) - update_alignment = false; - - if (update_alignment) { - prepareAlignment(); - } - - DiagramTextItem::setPlainText(text); - - //User define a text width - if (m_text_width > 0) - { - if (document()->size().width() > m_text_width) - { - document()->setTextWidth(m_text_width); - if (document()->size().width() > m_text_width) - { - document()->setTextWidth(document()->idealWidth()); - } - } - } - - if (update_alignment) { - finishAlignment(); - } - - if (m_Xref_item) { - m_Xref_item->autoPos(); - } - else if (m_slave_Xref_item) - { + bool update_alignment = true; + if (diagram() && (diagram()->project()->state() == QETProject::ProjectParsingRunning)) + update_alignment = false; + if (m_parent_element.data()->state() == QET::GIBuildingFromXml || + m_parent_element.data()->state() == QET::GILoadingFromXml) + update_alignment = false; + + if (update_alignment) { + prepareAlignment(); + } + + DiagramTextItem::setPlainText(text); + + //User define a text width + if (m_text_width > 0) + { + if (document()->size().width() > m_text_width) + { + document()->setTextWidth(m_text_width); + if (document()->size().width() > m_text_width) + { + document()->setTextWidth(document()->idealWidth()); + } + } + } + + if (update_alignment) { + finishAlignment(); + } + + if (m_Xref_item) { + m_Xref_item->autoPos(); + } + else if (m_slave_Xref_item) + { - XRefProperties xrp = diagram()->project()->defaultXRefProperties(m_master_element.data()->kindInformations()["type"].toString()); - setXref_item(xrp.getXrefPos()); - } + XRefProperties xrp = diagram()->project()->defaultXRefProperties(m_master_element.data()->kindInformations()["type"].toString()); + setXref_item(xrp.getXrefPos()); + } } void DynamicElementTextItem::setTextWidth(qreal width) { - this->document()->setTextWidth(width); - m_text_width = width; - emit textWidthChanged(width); + this->document()->setTextWidth(width); + m_text_width = width; + emit textWidthChanged(width); } void DynamicElementTextItem::setXref_item(Qt::AlignmentFlag m_exHrefPos) { - QRectF r = boundingRect(); - QPointF pos; - //QPointF pos(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.top()); - if (m_exHrefPos == Qt::AlignBottom) - { - pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.bottom()); - } - else if (m_exHrefPos == Qt::AlignTop) - { - pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.top() - m_slave_Xref_item->boundingRect().height()); - } - else if (m_exHrefPos == Qt::AlignLeft) // - { - pos = QPointF(r.left() - m_slave_Xref_item->boundingRect().width(),r.center().y() - m_slave_Xref_item->boundingRect().height()/2); - } - else if (m_exHrefPos == Qt::AlignRight) // - { - pos = QPointF(r.right() ,r.center().y() - m_slave_Xref_item->boundingRect().height()/2); - } - else if (m_exHrefPos == Qt::AlignBaseline) // - { - if(this->alignment() &Qt::AlignBottom) - { - pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.bottom()); - } - else if(this->alignment() &Qt::AlignTop) - { - pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.top() - m_slave_Xref_item->boundingRect().height()); - } - else if(this->alignment() &Qt::AlignLeft) - { - pos = QPointF(r.left() - m_slave_Xref_item->boundingRect().width(),r.center().y() - m_slave_Xref_item->boundingRect().height()/2); - } - else if(this->alignment() &Qt::AlignRight) - { - pos = QPointF(r.right() ,r.center().y() - m_slave_Xref_item->boundingRect().height()/2); - } - } - m_slave_Xref_item->setPos(pos); + QRectF r = boundingRect(); + QPointF pos; + //QPointF pos(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.top()); + if (m_exHrefPos == Qt::AlignBottom) + { + pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.bottom()); + } + else if (m_exHrefPos == Qt::AlignTop) + { + pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.top() - m_slave_Xref_item->boundingRect().height()); + } + else if (m_exHrefPos == Qt::AlignLeft) // + { + pos = QPointF(r.left() - m_slave_Xref_item->boundingRect().width(),r.center().y() - m_slave_Xref_item->boundingRect().height()/2); + } + else if (m_exHrefPos == Qt::AlignRight) // + { + pos = QPointF(r.right() ,r.center().y() - m_slave_Xref_item->boundingRect().height()/2); + } + else if (m_exHrefPos == Qt::AlignBaseline) // + { + if(this->alignment() &Qt::AlignBottom) + { + pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.bottom()); + } + else if(this->alignment() &Qt::AlignTop) + { + pos = QPointF(r.center().x() - m_slave_Xref_item->boundingRect().width()/2,r.top() - m_slave_Xref_item->boundingRect().height()); + } + else if(this->alignment() &Qt::AlignLeft) + { + pos = QPointF(r.left() - m_slave_Xref_item->boundingRect().width(),r.center().y() - m_slave_Xref_item->boundingRect().height()/2); + } + else if(this->alignment() &Qt::AlignRight) + { + pos = QPointF(r.right() ,r.center().y() - m_slave_Xref_item->boundingRect().height()/2); + } + } + m_slave_Xref_item->setPos(pos); - return; + return; } diff --git a/sources/qetgraphicsitem/dynamicelementtextitem.h b/sources/qetgraphicsitem/dynamicelementtextitem.h index 60c6a45c8..b7864af9a 100644 --- a/sources/qetgraphicsitem/dynamicelementtextitem.h +++ b/sources/qetgraphicsitem/dynamicelementtextitem.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef DYNAMICELEMENTTEXTITEM_H #define DYNAMICELEMENTTEXTITEM_H @@ -30,136 +30,136 @@ class ElementTextItemGroup; class CrossRefItem; /** - @brief The DynamicElementTextItem class - This class provide a simple text field of element who can be added or removed directly from the diagram editor. - This text is created to compensate a big lack of the ElementTextItem : ElementTextItem can't be added or removed directly in the diagram editor - + @brief The DynamicElementTextItem class + This class provide a simple text field of element who can be added or removed directly from the diagram editor. + This text is created to compensate a big lack of the ElementTextItem : ElementTextItem can't be added or removed directly in the diagram editor + */ class DynamicElementTextItem : public DiagramTextItem { - friend class DynamicTextItemDelegate; - friend class CompositeTextEditDialog; - friend class Element; + friend class DynamicTextItemDelegate; + friend class CompositeTextEditDialog; + friend class Element; - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) - Q_PROPERTY(TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged) - Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged) - Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged) - Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged) - Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged) + Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) + Q_PROPERTY(TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged) + Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged) + Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged) + Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged) + Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged) - public: + public: - enum TextFrom { - UserText, - ElementInfo, - CompositeText - }; - Q_ENUM (TextFrom) - enum {Type = UserType + 1010}; - int type() const override {return Type;} + enum TextFrom { + UserText, + ElementInfo, + CompositeText + }; + Q_ENUM (TextFrom) + enum {Type = UserType + 1010}; + int type() const override {return Type;} - signals: - void textChanged(QString text); - void textFromChanged(DynamicElementTextItem::TextFrom text_from); - void infoNameChanged(QString info); - void compositeTextChanged(QString text); - void frameChanged(bool frame); - void plainTextChanged(); - void textWidthChanged(qreal width); + signals: + void textChanged(QString text); + void textFromChanged(DynamicElementTextItem::TextFrom text_from); + void infoNameChanged(QString info); + void compositeTextChanged(QString text); + void frameChanged(bool frame); + void plainTextChanged(); + void textWidthChanged(qreal width); - public: - DynamicElementTextItem(Element *parent_element); - ~DynamicElementTextItem() override; - static QMetaEnum textFromMetaEnum(); - private: - DynamicElementTextItem (); - DynamicElementTextItem(const DynamicElementTextItem &); - - public: - QDomElement toXml(QDomDocument &dom_doc) const override; - void fromXml(const QDomElement &dom_elmt) override; + public: + DynamicElementTextItem(Element *parent_element); + ~DynamicElementTextItem() override; + static QMetaEnum textFromMetaEnum(); + private: + DynamicElementTextItem (); + DynamicElementTextItem(const DynamicElementTextItem &); + + public: + QDomElement toXml(QDomDocument &dom_doc) const override; + void fromXml(const QDomElement &dom_elmt) override; - Element *parentElement() const; - ElementTextItemGroup *parentGroup() const; - Element *elementUseForInfo() const; - void refreshLabelConnection(); + Element *parentElement() const; + ElementTextItemGroup *parentGroup() const; + Element *elementUseForInfo() const; + void refreshLabelConnection(); - DynamicElementTextItem::TextFrom textFrom() const; - void setTextFrom (DynamicElementTextItem::TextFrom text_from); - QString text() const; - void setText(const QString &text); - static QString xmlTagName() {return QString("dynamic_elmt_text");} - void setInfoName(const QString &info_name); - QString infoName() const; - void setCompositeText(const QString &text); - QString compositeText() const; - void setFrame(const bool frame); - bool frame() const; - QUuid uuid() const; - void updateXref(); - void setPlainText(const QString &text); - void setTextWidth(qreal width); - void setXref_item(Qt::AlignmentFlag m_exHrefPos); + DynamicElementTextItem::TextFrom textFrom() const; + void setTextFrom (DynamicElementTextItem::TextFrom text_from); + QString text() const; + void setText(const QString &text); + static QString xmlTagName() {return QString("dynamic_elmt_text");} + void setInfoName(const QString &info_name); + QString infoName() const; + void setCompositeText(const QString &text); + QString compositeText() const; + void setFrame(const bool frame); + bool frame() const; + QUuid uuid() const; + void updateXref(); + void setPlainText(const QString &text); + void setTextWidth(qreal width); + void setXref_item(Qt::AlignmentFlag m_exHrefPos); - protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; + protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override; - private: - void elementInfoChanged(); - void masterChanged(); - void reportChanged(); - void reportFormulaChanged(); - void setConnectionForReportFormula(const QString &formula); - void removeConnectionForReportFormula(const QString &formula); - void setupFormulaConnection(); - void clearFormulaConnection(); - void updateReportFormulaConnection(); - void updateReportText(); - void updateLabel(); - void conductorWasAdded(Conductor *conductor); - void conductorWasRemoved(Conductor *conductor); - void setPotentialConductor(); - void conductorPropertiesChanged(); - QString reportReplacedCompositeText() const; - void zoomToLinkedElement(); + private: + void elementInfoChanged(); + void masterChanged(); + void reportChanged(); + void reportFormulaChanged(); + void setConnectionForReportFormula(const QString &formula); + void removeConnectionForReportFormula(const QString &formula); + void setupFormulaConnection(); + void clearFormulaConnection(); + void updateReportFormulaConnection(); + void updateReportText(); + void updateLabel(); + void conductorWasAdded(Conductor *conductor); + void conductorWasRemoved(Conductor *conductor); + void setPotentialConductor(); + void conductorPropertiesChanged(); + QString reportReplacedCompositeText() const; + void zoomToLinkedElement(); - private: - QPointer - m_parent_element, - m_master_element, - m_other_report; - QPointer m_watched_conductor; - QString - m_text, - m_info_name, - m_composite_text, - m_report_formula, - m_F_str; - DynamicElementTextItem::TextFrom m_text_from = UserText; - QUuid m_uuid; - QMetaObject::Connection m_report_formula_con; - QList - m_formula_connection, - m_update_slave_Xref_connection; - QColor m_user_color; - bool - m_frame = false, - m_first_scene_change = true; - CrossRefItem *m_Xref_item = nullptr; - QGraphicsTextItem *m_slave_Xref_item = nullptr; - qreal m_text_width = -1; - QPointF m_initial_position; + private: + QPointer + m_parent_element, + m_master_element, + m_other_report; + QPointer m_watched_conductor; + QString + m_text, + m_info_name, + m_composite_text, + m_report_formula, + m_F_str; + DynamicElementTextItem::TextFrom m_text_from = UserText; + QUuid m_uuid; + QMetaObject::Connection m_report_formula_con; + QList + m_formula_connection, + m_update_slave_Xref_connection; + QColor m_user_color; + bool + m_frame = false, + m_first_scene_change = true; + CrossRefItem *m_Xref_item = nullptr; + QGraphicsTextItem *m_slave_Xref_item = nullptr; + qreal m_text_width = -1; + QPointF m_initial_position; }; #endif // DYNAMICELEMENTTEXTITEM_H diff --git a/sources/qetgraphicsitem/element.cpp b/sources/qetgraphicsitem/element.cpp index e12132489..c794258e3 100644 --- a/sources/qetgraphicsitem/element.cpp +++ b/sources/qetgraphicsitem/element.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "element.h" #include "diagram.h" @@ -37,1773 +37,1773 @@ class ElementXmlRetroCompatibility { - friend class Element; + friend class Element; - static void loadSequential( - const QDomElement &dom_element, - const QString& seq, - QStringList* list) - { - int i = 0; - while (!dom_element.attribute(seq + - QString::number(i+1)).isEmpty()) - { - list->append(dom_element.attribute( - seq + - QString::number(i+1))); - i++; - } - } + static void loadSequential( + const QDomElement &dom_element, + const QString& seq, + QStringList* list) + { + int i = 0; + while (!dom_element.attribute(seq + + QString::number(i+1)).isEmpty()) + { + list->append(dom_element.attribute( + seq + + QString::number(i+1))); + i++; + } + } - static void loadSequential( - const QDomElement &dom_element, Element *element) - { - autonum::sequentialNumbers sn; + static void loadSequential( + const QDomElement &dom_element, Element *element) + { + autonum::sequentialNumbers sn; - loadSequential(dom_element,"sequ_",&sn.unit); - loadSequential(dom_element,"sequf_",&sn.unit_folio); - loadSequential(dom_element,"seqt_",&sn.ten); - loadSequential(dom_element,"seqtf_",&sn.ten_folio); - loadSequential(dom_element,"seqh_",&sn.hundred); - loadSequential(dom_element,"seqhf_",&sn.hundred_folio); + loadSequential(dom_element,"sequ_",&sn.unit); + loadSequential(dom_element,"sequf_",&sn.unit_folio); + loadSequential(dom_element,"seqt_",&sn.ten); + loadSequential(dom_element,"seqtf_",&sn.ten_folio); + loadSequential(dom_element,"seqh_",&sn.hundred); + loadSequential(dom_element,"seqhf_",&sn.hundred_folio); - element->rSequenceStruct() = sn; - } + element->rSequenceStruct() = sn; + } }; /** - @brief Element::Element - @param location : location of this element - @param parent : parent graphics item - @param state : state of the instanciation - @param link_type + @brief Element::Element + @param location : location of this element + @param parent : parent graphics item + @param state : state of the instanciation + @param link_type */ Element::Element( - const ElementsLocation &location, - QGraphicsItem *parent, - int *state, - kind link_type) : - QetGraphicsItem(parent), - m_link_type (link_type), - m_location (location) + const ElementsLocation &location, + QGraphicsItem *parent, + int *state, + kind link_type) : + QetGraphicsItem(parent), + m_link_type (link_type), + m_location (location) { - if(! (location.isElement() && location.exist())) - { - if (state) - { - *state = 1; - return; - } - } - int elmt_state; - buildFromXml(location.xml(), &elmt_state); - if (state) { - *state = elmt_state; - } - if (elmt_state) { - return; - } - if (state) { - *state = 0; - } + if(! (location.isElement() && location.exist())) + { + if (state) + { + *state = 1; + return; + } + } + int elmt_state; + buildFromXml(location.xml(), &elmt_state); + if (state) { + *state = elmt_state; + } + if (elmt_state) { + return; + } + if (state) { + *state = 0; + } - setPrefix(autonum::elementPrefixForLocation(location)); - m_uuid = QUuid::createUuid(); - setZValue(10); - setFlags(QGraphicsItem::ItemIsMovable - | QGraphicsItem::ItemIsSelectable); - setAcceptHoverEvents(true); + setPrefix(autonum::elementPrefixForLocation(location)); + m_uuid = QUuid::createUuid(); + setZValue(10); + setFlags(QGraphicsItem::ItemIsMovable + | QGraphicsItem::ItemIsSelectable); + setAcceptHoverEvents(true); - connect(this, &Element::rotationChanged, [this]() + connect(this, &Element::rotationChanged, [this]() { - for(QGraphicsItem *qgi : childItems()) - { - if (Terminal *t = qgraphicsitem_cast(qgi)) - t->updateConductor(); - } - }); + for(QGraphicsItem *qgi : childItems()) + { + if (Terminal *t = qgraphicsitem_cast(qgi)) + t->updateConductor(); + } + }); } /** - @brief Element::~Element + @brief Element::~Element */ Element::~Element() { - qDeleteAll (m_dynamic_text_list); - qDeleteAll (m_terminals); + qDeleteAll (m_dynamic_text_list); + qDeleteAll (m_terminals); } /** - @brief Element::terminals - @return the list of terminals of this element. + @brief Element::terminals + @return the list of terminals of this element. */ QList Element::terminals() const { - return m_terminals; + return m_terminals; } /** - @brief Element::conductors - @return The list of conductors docked to this element - the list is sorted according to the position of the terminal where the conductor is docked - from top to bottom, and left to right. + @brief Element::conductors + @return The list of conductors docked to this element + the list is sorted according to the position of the terminal where the conductor is docked + from top to bottom, and left to right. */ QList Element::conductors() const { - QList conductors; + QList conductors; - for (Terminal *t : m_terminals) { - conductors << t -> conductors(); - } + for (Terminal *t : m_terminals) { + conductors << t -> conductors(); + } - return(conductors); + return(conductors); } void Element::editProperty() { - if (diagram() && !diagram()->isReadOnly()) - { - ElementPropertiesWidget *epw = new ElementPropertiesWidget(this); - PropertiesEditorDialog dialog(epw, QApplication::activeWindow()); - connect(epw, - &ElementPropertiesWidget::findEditClicked, - &dialog, - &QDialog::reject); - //Must be windowModal, else when user do a drag and drop - //with the "text" tab of ElementPropertiesWidget, - //the ui freeze, until user press escape key - dialog.setWindowModality(Qt::WindowModal); - dialog.exec(); - } + if (diagram() && !diagram()->isReadOnly()) + { + ElementPropertiesWidget *epw = new ElementPropertiesWidget(this); + PropertiesEditorDialog dialog(epw, QApplication::activeWindow()); + connect(epw, + &ElementPropertiesWidget::findEditClicked, + &dialog, + &QDialog::reject); + //Must be windowModal, else when user do a drag and drop + //with the "text" tab of ElementPropertiesWidget, + //the ui freeze, until user press escape key + dialog.setWindowModality(Qt::WindowModal); + dialog.exec(); + } } /** - @param hl true pour mettre l'element en evidence, false sinon + @param hl true pour mettre l'element en evidence, false sinon */ void Element::setHighlighted(bool hl) { - m_must_highlight = hl; - update(); + m_must_highlight = hl; + update(); } /** - @brief Element::displayHelpLine - Display the help line of each terminal if b is true - @param b + @brief Element::displayHelpLine + Display the help line of each terminal if b is true + @param b */ void Element::displayHelpLine(bool b) { - foreach (Terminal *t, terminals()) - t->drawHelpLine(b); + foreach (Terminal *t, terminals()) + t->drawHelpLine(b); } /** - @brief Element::paint - @param painter - @param options + @brief Element::paint + @param painter + @param options */ void Element::paint( - QPainter *painter, - const QStyleOptionGraphicsItem *options, - QWidget *) + QPainter *painter, + const QStyleOptionGraphicsItem *options, + QWidget *) { - if (m_must_highlight) { - drawHighlight(painter, options); - } + if (m_must_highlight) { + drawHighlight(painter, options); + } -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - if (options && options -> levelOfDetail < 1.0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + if (options && options -> levelOfDetail < 1.0) #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0) + if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0) #endif - { - painter->drawPicture(0, 0, m_low_zoom_picture); - } else { - painter->drawPicture(0, 0, m_picture); - } + { + painter->drawPicture(0, 0, m_low_zoom_picture); + } else { + painter->drawPicture(0, 0, m_picture); + } - //Draw the selection rectangle - if ( isSelected() || m_mouse_over ) { - drawSelection(painter, options); - } + //Draw the selection rectangle + if ( isSelected() || m_mouse_over ) { + drawSelection(painter, options); + } } /** - @return Le rectangle delimitant le contour de l'element + @return Le rectangle delimitant le contour de l'element */ QRectF Element::boundingRect() const { - return(QRectF(QPointF(-hotspot_coord.x(), -hotspot_coord.y()), - dimensions)); + return(QRectF(QPointF(-hotspot_coord.x(), -hotspot_coord.y()), + dimensions)); } /** - @brief Element::setSize - Define the size of the element. - The size must be a multiple of 10. - If not, the dimensions indicated will be arrrondies to higher tens. - @param wid - @param hei + @brief Element::setSize + Define the size of the element. + The size must be a multiple of 10. + If not, the dimensions indicated will be arrrondies to higher tens. + @param wid + @param hei */ void Element::setSize(int wid, int hei) { - prepareGeometryChange(); + prepareGeometryChange(); - while (wid % 10) ++ wid; - while (hei % 10) ++ hei; - dimensions = QSize(wid, hei); + while (wid % 10) ++ wid; + while (hei % 10) ++ hei; + dimensions = QSize(wid, hei); } /** - @return la taille de l'element sur le schema + @return la taille de l'element sur le schema */ QSize Element::size() const { - return(dimensions); + return(dimensions); } /** - Definit le hotspot de l'element par rapport au coin superieur gauche de son rectangle delimitant. - Necessite que la taille ait deja ete definie - @param hs Coordonnees du hotspot + Definit le hotspot de l'element par rapport au coin superieur gauche de son rectangle delimitant. + Necessite que la taille ait deja ete definie + @param hs Coordonnees du hotspot */ QPoint Element::setHotspot(QPoint hs) { - // la taille doit avoir ete definie - prepareGeometryChange(); - if (dimensions.isNull()) hotspot_coord = QPoint(0, 0); - else { - // les coordonnees indiquees ne doivent pas depasser les dimensions de l'element - int hsx = qMin(hs.x(), dimensions.width()); - int hsy = qMin(hs.y(), dimensions.height()); - hotspot_coord = QPoint(hsx, hsy); - } - return(hotspot_coord); + // la taille doit avoir ete definie + prepareGeometryChange(); + if (dimensions.isNull()) hotspot_coord = QPoint(0, 0); + else { + // les coordonnees indiquees ne doivent pas depasser les dimensions de l'element + int hsx = qMin(hs.x(), dimensions.width()); + int hsy = qMin(hs.y(), dimensions.height()); + hotspot_coord = QPoint(hsx, hsy); + } + return(hotspot_coord); } /** - @return Le hotspot courant de l'element + @return Le hotspot courant de l'element */ QPoint Element::hotspot() const { - return(hotspot_coord); + return(hotspot_coord); } /** - @brief Element::pixmap - @return the pixmap of this element + @brief Element::pixmap + @return the pixmap of this element */ QPixmap Element::pixmap() { - return ElementPictureFactory::instance()->pixmap(m_location); + return ElementPictureFactory::instance()->pixmap(m_location); } /*** Methodes protegees ***/ /** - Dessine un petit repere (axes x et y) relatif a l'element - @param painter Le QPainter a utiliser pour dessiner les axes - @param options Les options de style a prendre en compte + Dessine un petit repere (axes x et y) relatif a l'element + @param painter Le QPainter a utiliser pour dessiner les axes + @param options Les options de style a prendre en compte */ void Element::drawAxes( - QPainter *painter, - const QStyleOptionGraphicsItem *options) + QPainter *painter, + const QStyleOptionGraphicsItem *options) { - Q_UNUSED(options); - painter -> setPen(Qt::blue); - painter -> drawLine(0, 0, 10, 0); - painter -> drawLine(7,-3, 10, 0); - painter -> drawLine(7, 3, 10, 0); - painter -> setPen(Qt::red); - painter -> drawLine(0, 0, 0, 10); - painter -> drawLine(0, 10,-3, 7); - painter -> drawLine(0, 10, 3, 7); + Q_UNUSED(options); + painter -> setPen(Qt::blue); + painter -> drawLine(0, 0, 10, 0); + painter -> drawLine(7,-3, 10, 0); + painter -> drawLine(7, 3, 10, 0); + painter -> setPen(Qt::red); + painter -> drawLine(0, 0, 0, 10); + painter -> drawLine(0, 10,-3, 7); + painter -> drawLine(0, 10, 3, 7); } /*** Methodes privees ***/ /** - Dessine le cadre de selection de l'element de maniere systematiquement non antialiasee. - @param painter Le QPainter a utiliser pour dessiner les bornes. - @param options Les options de style a prendre en compte + Dessine le cadre de selection de l'element de maniere systematiquement non antialiasee. + @param painter Le QPainter a utiliser pour dessiner les bornes. + @param options Les options de style a prendre en compte */ void Element::drawSelection( - QPainter *painter, - const QStyleOptionGraphicsItem *options) + QPainter *painter, + const QStyleOptionGraphicsItem *options) { - Q_UNUSED(options); - painter -> save(); - // Annulation des renderhints - painter -> setRenderHint(QPainter::Antialiasing, false); - painter -> setRenderHint(QPainter::TextAntialiasing, false); - painter -> setRenderHint(QPainter::SmoothPixmapTransform, false); - // Dessin du cadre de selection en gris - QPen t; - t.setColor(Qt::gray); - t.setStyle(Qt::DashDotLine); - t.setCosmetic(true); - painter -> setPen(t); - // Le dessin se fait a partir du rectangle delimitant - painter -> drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), - 10, - 10); - painter -> restore(); + Q_UNUSED(options); + painter -> save(); + // Annulation des renderhints + painter -> setRenderHint(QPainter::Antialiasing, false); + painter -> setRenderHint(QPainter::TextAntialiasing, false); + painter -> setRenderHint(QPainter::SmoothPixmapTransform, false); + // Dessin du cadre de selection en gris + QPen t; + t.setColor(Qt::gray); + t.setStyle(Qt::DashDotLine); + t.setCosmetic(true); + painter -> setPen(t); + // Le dessin se fait a partir du rectangle delimitant + painter -> drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), + 10, + 10); + painter -> restore(); } /** - Dessine le cadre de selection de l'element de maniere systematiquement non antialiasee. - @param painter Le QPainter a utiliser pour dessiner les bornes. - @param options Les options de style a prendre en compte + Dessine le cadre de selection de l'element de maniere systematiquement non antialiasee. + @param painter Le QPainter a utiliser pour dessiner les bornes. + @param options Les options de style a prendre en compte */ void Element::drawHighlight( - QPainter *painter, - const QStyleOptionGraphicsItem *options) + QPainter *painter, + const QStyleOptionGraphicsItem *options) { - Q_UNUSED(options); - painter -> save(); + Q_UNUSED(options); + painter -> save(); - qreal gradient_radius = qMin(boundingRect().width(), - boundingRect().height()) / 2.0; - QRadialGradient gradient( - boundingRect().center(), - gradient_radius, - boundingRect().center() - ); - gradient.setColorAt(0.0, QColor::fromRgb(69, 137, 255, 255)); - gradient.setColorAt(1.0, QColor::fromRgb(69, 137, 255, 0)); - QBrush brush(gradient); + qreal gradient_radius = qMin(boundingRect().width(), + boundingRect().height()) / 2.0; + QRadialGradient gradient( + boundingRect().center(), + gradient_radius, + boundingRect().center() + ); + gradient.setColorAt(0.0, QColor::fromRgb(69, 137, 255, 255)); + gradient.setColorAt(1.0, QColor::fromRgb(69, 137, 255, 0)); + QBrush brush(gradient); - painter -> setPen(Qt::NoPen); - painter -> setBrush(brush); - // Le dessin se fait a partir du rectangle delimitant - painter -> drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), - 10, - 10); - painter -> restore(); + painter -> setPen(Qt::NoPen); + painter -> setBrush(brush); + // Le dessin se fait a partir du rectangle delimitant + painter -> drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), + 10, + 10); + painter -> restore(); } /** - @brief Element::buildFromXml - Build this element from an xml description - @param xml_def_elmt - @param state - Optional pointer which define the status of build - 0 - evreything all right - 4 - xml isn't a "definition" - 5 - attribute of the definition isn't present or valid - 6 - the definition is empty - 7 - parsing of a xml node who describe a graphical part failed. - 8 - No part of the drawing could be loaded - @return + @brief Element::buildFromXml + Build this element from an xml description + @param xml_def_elmt + @param state + Optional pointer which define the status of build + 0 - evreything all right + 4 - xml isn't a "definition" + 5 - attribute of the definition isn't present or valid + 6 - the definition is empty + 7 - parsing of a xml node who describe a graphical part failed. + 8 - No part of the drawing could be loaded + @return */ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state) { - m_state = QET::GIBuildingFromXml; + m_state = QET::GIBuildingFromXml; - if (xml_def_elmt.tagName() != "definition" - || xml_def_elmt.attribute("type") != "element") - { - if (state) *state = 4; - m_state = QET::GIOK; - return(false); - } + if (xml_def_elmt.tagName() != "definition" + || xml_def_elmt.attribute("type") != "element") + { + if (state) *state = 4; + m_state = QET::GIOK; + return(false); + } - //Check if the curent version can read the xml description - if (xml_def_elmt.hasAttribute("version")) - { - bool conv_ok; - qreal element_version = xml_def_elmt.attribute( - "version").toDouble(&conv_ok); - if (conv_ok && QET::version.toDouble() < element_version) - { - std::cerr << qPrintable( - QObject::tr("Avertissement : l'élément " - " a été enregistré avec une version" - " ultérieure de QElectroTech.") - ) << std::endl; - } - } + //Check if the curent version can read the xml description + if (xml_def_elmt.hasAttribute("version")) + { + bool conv_ok; + qreal element_version = xml_def_elmt.attribute( + "version").toDouble(&conv_ok); + if (conv_ok && QET::version.toDouble() < element_version) + { + std::cerr << qPrintable( + QObject::tr("Avertissement : l'??l??ment " + " a ??t?? enregistr?? avec une version" + " ult??rieure de QElectroTech.") + ) << std::endl; + } + } - //This attribute must be present and valid - int w, h, hot_x, hot_y; - if ( - !QET::attributeIsAnInteger(xml_def_elmt, QString("width"), &w) ||\ - !QET::attributeIsAnInteger(xml_def_elmt, QString("height"), &h) ||\ - !QET::attributeIsAnInteger(xml_def_elmt, QString("hotspot_x"), &hot_x) ||\ - !QET::attributeIsAnInteger(xml_def_elmt, QString("hotspot_y"), &hot_y) - ) { - if (state) *state = 5; - m_state = QET::GIOK; - return(false); - } + //This attribute must be present and valid + int w, h, hot_x, hot_y; + if ( + !QET::attributeIsAnInteger(xml_def_elmt, QString("width"), &w) ||\ + !QET::attributeIsAnInteger(xml_def_elmt, QString("height"), &h) ||\ + !QET::attributeIsAnInteger(xml_def_elmt, QString("hotspot_x"), &hot_x) ||\ + !QET::attributeIsAnInteger(xml_def_elmt, QString("hotspot_y"), &hot_y) + ) { + if (state) *state = 5; + m_state = QET::GIOK; + return(false); + } - setSize(w, h); - setHotspot(QPoint(hot_x, hot_y)); + setSize(w, h); + setHotspot(QPoint(hot_x, hot_y)); - //the definition must have childs - if (xml_def_elmt.firstChild().isNull()) - { - if (state) *state = 6; - m_state = QET::GIOK; - return(false); - } - //Extract the names - m_names.fromXml(xml_def_elmt); - setToolTip(name()); + //the definition must have childs + if (xml_def_elmt.firstChild().isNull()) + { + if (state) *state = 6; + m_state = QET::GIOK; + return(false); + } + //Extract the names + m_names.fromXml(xml_def_elmt); + setToolTip(name()); - //load kind informations - m_kind_informations.fromXml( - xml_def_elmt.firstChildElement("kindInformations"), - "kindInformation"); - //load element information - m_element_informations.fromXml( - xml_def_elmt.firstChildElement("elementInformations"), - "elementInformation"); + //load kind informations + m_kind_informations.fromXml( + xml_def_elmt.firstChildElement("kindInformations"), + "kindInformation"); + //load element information + m_element_informations.fromXml( + xml_def_elmt.firstChildElement("elementInformations"), + "elementInformation"); - //scroll of the Children of the Definition: Parts of the Drawing - int parsed_elements_count = 0; - for (QDomNode node = xml_def_elmt.firstChild() ; - !node.isNull() ; - node = node.nextSibling()) - { - QDomElement elmts = node.toElement(); - if (elmts.isNull()) - continue; + //scroll of the Children of the Definition: Parts of the Drawing + int parsed_elements_count = 0; + for (QDomNode node = xml_def_elmt.firstChild() ; + !node.isNull() ; + node = node.nextSibling()) + { + QDomElement elmts = node.toElement(); + if (elmts.isNull()) + continue; - if (elmts.tagName() == "description") - { - //Minor workaround to find if there is a "input" tagg as label. - //If not, we set the tagg "label" to the first "input. - QList input_field; - bool have_label = false; - for (QDomElement input_node = node.firstChildElement("input") ; - !input_node.isNull() ; - input_node = input_node.nextSiblingElement("input")) - { - if (!input_node.isNull()) - { - input_field << input_node; - if (input_node.attribute("tagg", "none") - == "label") - have_label = true; - } - } - if(!have_label && !input_field.isEmpty()) - input_field.first().setAttribute("tagg", - "label"); + if (elmts.tagName() == "description") + { + //Minor workaround to find if there is a "input" tagg as label. + //If not, we set the tagg "label" to the first "input. + QList input_field; + bool have_label = false; + for (QDomElement input_node = node.firstChildElement("input") ; + !input_node.isNull() ; + input_node = input_node.nextSiblingElement("input")) + { + if (!input_node.isNull()) + { + input_field << input_node; + if (input_node.attribute("tagg", "none") + == "label") + have_label = true; + } + } + if(!have_label && !input_field.isEmpty()) + input_field.first().setAttribute("tagg", + "label"); - //Parse the definition - for (QDomNode n = node.firstChild() ; - !n.isNull() ; - n = n.nextSibling()) - { - QDomElement qde = n.toElement(); - if (qde.isNull()) - continue; + //Parse the definition + for (QDomNode n = node.firstChild() ; + !n.isNull() ; + n = n.nextSibling()) + { + QDomElement qde = n.toElement(); + if (qde.isNull()) + continue; - if (parseElement(qde)) { - ++ parsed_elements_count; - } - else - { - if (state) - *state = 7; - m_state = QET::GIOK; - return(false); - } - } - } - } + if (parseElement(qde)) { + ++ parsed_elements_count; + } + else + { + if (state) + *state = 7; + m_state = QET::GIOK; + return(false); + } + } + } + } - ElementPictureFactory *epf = ElementPictureFactory::instance(); - epf->getPictures(m_location, - const_cast(m_picture), - const_cast(m_low_zoom_picture)); + ElementPictureFactory *epf = ElementPictureFactory::instance(); + epf->getPictures(m_location, + const_cast(m_picture), + const_cast(m_low_zoom_picture)); - if(!m_picture.isNull()) - ++ parsed_elements_count; + if(!m_picture.isNull()) + ++ parsed_elements_count; - //They must be at least one parsed graphics part - if (!parsed_elements_count) - { - if (state) - *state = 8; - m_state = QET::GIOK; - return(false); - } - else - { - if (state) - *state = 0; - m_state = QET::GIOK; - return(true); - } + //They must be at least one parsed graphics part + if (!parsed_elements_count) + { + if (state) + *state = 8; + m_state = QET::GIOK; + return(false); + } + else + { + if (state) + *state = 0; + m_state = QET::GIOK; + return(true); + } } /** - @brief Element::parseElement - Parse the element of the xml description of this element - @param dom - @return + @brief Element::parseElement + Parse the element of the xml description of this element + @param dom + @return */ bool Element::parseElement(const QDomElement &dom) { - if (dom.tagName() == "terminal") return(parseTerminal(dom)); - else if (dom.tagName() == "input") return(parseInput(dom)); - else if (dom.tagName() == "dynamic_text") return(parseDynamicText(dom)); - else return(true); + if (dom.tagName() == "terminal") return(parseTerminal(dom)); + else if (dom.tagName() == "input") return(parseInput(dom)); + else if (dom.tagName() == "dynamic_text") return(parseDynamicText(dom)); + else return(true); } /** - @brief Element::parseInput - Parse the input (old text field) - the parsed input are converted to dynamic text field, this function - is only here to keep compatibility with old text. - @param dom_element - @return + @brief Element::parseInput + Parse the input (old text field) + the parsed input are converted to dynamic text field, this function + is only here to keep compatibility with old text. + @param dom_element + @return */ bool Element::parseInput(const QDomElement &dom_element) { - qreal pos_x, pos_y; - int size; - if ( - !QET::attributeIsAReal(dom_element, "x", &pos_x) ||\ - !QET::attributeIsAReal(dom_element, "y", &pos_y) ||\ - !QET::attributeIsAnInteger(dom_element, "size", &size) - ) return(false); - else - { - DynamicElementTextItem *deti = new DynamicElementTextItem(this); - deti->setText(dom_element.attribute("text", "_")); - QFont font = deti->font(); - font.setPointSize(dom_element.attribute("size", - QString::number(9)).toInt()); - deti->setFont(font); - deti->setRotation(dom_element.attribute("rotation", - QString::number(0)).toDouble()); + qreal pos_x, pos_y; + int size; + if ( + !QET::attributeIsAReal(dom_element, "x", &pos_x) ||\ + !QET::attributeIsAReal(dom_element, "y", &pos_y) ||\ + !QET::attributeIsAnInteger(dom_element, "size", &size) + ) return(false); + else + { + DynamicElementTextItem *deti = new DynamicElementTextItem(this); + deti->setText(dom_element.attribute("text", "_")); + QFont font = deti->font(); + font.setPointSize(dom_element.attribute("size", + QString::number(9)).toInt()); + deti->setFont(font); + deti->setRotation(dom_element.attribute("rotation", + QString::number(0)).toDouble()); - if(dom_element.attribute("tagg", "none") != "none") - { - deti->setTextFrom(DynamicElementTextItem::ElementInfo); - deti->setInfoName(dom_element.attribute("tagg")); - } + if(dom_element.attribute("tagg", "none") != "none") + { + deti->setTextFrom(DynamicElementTextItem::ElementInfo); + deti->setInfoName(dom_element.attribute("tagg")); + } - //the origin transformation point of PartDynamicTextField is the top left corner, no matter the font size - //The origin transformation point of ElementTextItem is the middle of left edge, and so by definition, change with the size of the font - //We need to use a QTransform to find the pos of this text from the saved pos of text item - QTransform transform; - //First make the rotation - transform.rotate(dom_element.attribute("rotation", - "0").toDouble()); - QPointF pos = transform.map( - QPointF(0, - -deti->boundingRect().height()/2)); - transform.reset(); - //Second translate to the pos - QPointF p(dom_element.attribute("x", - QString::number(0)).toDouble(), - dom_element.attribute("y", - QString::number(0)).toDouble()); - transform.translate(p.x(), p.y()); - deti->setPos(transform.map(pos)); - m_converted_text_from_xml_description.insert(deti, p); - return true; - } + //the origin transformation point of PartDynamicTextField is the top left corner, no matter the font size + //The origin transformation point of ElementTextItem is the middle of left edge, and so by definition, change with the size of the font + //We need to use a QTransform to find the pos of this text from the saved pos of text item + QTransform transform; + //First make the rotation + transform.rotate(dom_element.attribute("rotation", + "0").toDouble()); + QPointF pos = transform.map( + QPointF(0, + -deti->boundingRect().height()/2)); + transform.reset(); + //Second translate to the pos + QPointF p(dom_element.attribute("x", + QString::number(0)).toDouble(), + dom_element.attribute("y", + QString::number(0)).toDouble()); + transform.translate(p.x(), p.y()); + deti->setPos(transform.map(pos)); + m_converted_text_from_xml_description.insert(deti, p); + return true; + } } /** - @brief Element::parseDynamicText - Create the dynamic text field describ in dom_element - @param dom_element - @return + @brief Element::parseDynamicText + Create the dynamic text field describ in dom_element + @param dom_element + @return */ DynamicElementTextItem *Element::parseDynamicText( - const QDomElement &dom_element) + const QDomElement &dom_element) { - DynamicElementTextItem *deti = new DynamicElementTextItem(this); - //Because the xml description of a .elmt file is the same as how a dynamic text field is save to xml in a .qet file - //wa call fromXml, we just change the tagg name (.elmt = dynamic_text, .qet = dynamic_elmt_text) - //and the uuid (because the uuid, is the uuid of the descritpion and not the uuid of instantiated dynamic text field) + DynamicElementTextItem *deti = new DynamicElementTextItem(this); + //Because the xml description of a .elmt file is the same as how a dynamic text field is save to xml in a .qet file + //wa call fromXml, we just change the tagg name (.elmt = dynamic_text, .qet = dynamic_elmt_text) + //and the uuid (because the uuid, is the uuid of the descritpion and not the uuid of instantiated dynamic text field) - QDomElement dom(dom_element.cloneNode(true).toElement()); - dom.setTagName(DynamicElementTextItem::xmlTagName()); - deti->fromXml(dom); - deti->m_uuid = QUuid::createUuid(); - this->addDynamicTextItem(deti); - return deti; + QDomElement dom(dom_element.cloneNode(true).toElement()); + dom.setTagName(DynamicElementTextItem::xmlTagName()); + deti->fromXml(dom); + deti->m_uuid = QUuid::createUuid(); + this->addDynamicTextItem(deti); + return deti; } /*! - \brief Element::parseTerminal - Parse partTerminal from xml structure - \param dom_element - \return + \brief Element::parseTerminal + Parse partTerminal from xml structure + \param dom_element + \return */ Terminal *Element::parseTerminal(const QDomElement &dom_element) { - TerminalData* data = new TerminalData(); - if (!data->fromXml(dom_element)) { - delete data; - return nullptr; - } + TerminalData* data = new TerminalData(); + if (!data->fromXml(dom_element)) { + delete data; + return nullptr; + } - Terminal *new_terminal = new Terminal(data, this); - m_terminals << new_terminal; + Terminal *new_terminal = new Terminal(data, this); + m_terminals << new_terminal; - //Sort from top to bottom and left to rigth - std::sort(m_terminals.begin(), - m_terminals.end(), - [](Terminal *a, - Terminal *b) - { - if(a->dockConductor().y() == b->dockConductor().y()) - return (a->dockConductor().x() < b->dockConductor().x()); - else - return (a->dockConductor().y() < b->dockConductor().y()); - }); + //Sort from top to bottom and left to rigth + std::sort(m_terminals.begin(), + m_terminals.end(), + [](Terminal *a, + Terminal *b) + { + if(a->dockConductor().y() == b->dockConductor().y()) + return (a->dockConductor().x() < b->dockConductor().x()); + else + return (a->dockConductor().y() < b->dockConductor().y()); + }); - return(new_terminal); + return(new_terminal); } /** - Permet de savoir si un element XML (QDomElement) represente bien un element - @param e Le QDomElement a valide - @return true si l'element XML est un Element, false sinon + Permet de savoir si un element XML (QDomElement) represente bien un element + @param e Le QDomElement a valide + @return true si l'element XML est un Element, false sinon */ bool Element::valideXml(QDomElement &e) { - // verifie le nom du tag - if (e.tagName() != "element") return(false); + // verifie le nom du tag + if (e.tagName() != "element") return(false); - // verifie la presence des attributs minimaux - if (!e.hasAttribute("type")) return(false); - if (!e.hasAttribute("x")) return(false); - if (!e.hasAttribute("y")) return(false); + // verifie la presence des attributs minimaux + if (!e.hasAttribute("type")) return(false); + if (!e.hasAttribute("x")) return(false); + if (!e.hasAttribute("y")) return(false); - bool conv_ok; - // parse l'abscisse - e.attribute("x").toDouble(&conv_ok); - if (!conv_ok) return(false); + bool conv_ok; + // parse l'abscisse + e.attribute("x").toDouble(&conv_ok); + if (!conv_ok) return(false); - // parse l'ordonnee - e.attribute("y").toDouble(&conv_ok); - if (!conv_ok) return(false); - return(true); + // parse l'ordonnee + e.attribute("y").toDouble(&conv_ok); + if (!conv_ok) return(false); + return(true); } /** - @brief Element::fromXml - Import the parameters of this element from a xml document. - When call this function ensure this element is already in a scene, because - the dynamic text item and element text item group (in the xml file) are created in this function - and need a diagram for create their Xref, when this element is linked to another. - If not the Xref can be not displayed, until the next call of update Xref of the group or text item. - @param e : the dom element where the parameter is stored - @param table_id_adr : Reference to the mapping table between IDs of the XML file - and the addresses in memory. If the import succeeds, it must be add the right couples (id, address). - @return + @brief Element::fromXml + Import the parameters of this element from a xml document. + When call this function ensure this element is already in a scene, because + the dynamic text item and element text item group (in the xml file) are created in this function + and need a diagram for create their Xref, when this element is linked to another. + If not the Xref can be not displayed, until the next call of update Xref of the group or text item. + @param e : the dom element where the parameter is stored + @param table_id_adr : Reference to the mapping table between IDs of the XML file + and the addresses in memory. If the import succeeds, it must be add the right couples (id, address). + @return */ bool Element::fromXml( - QDomElement &e, - QHash &table_id_adr) + QDomElement &e, + QHash &table_id_adr) { - m_state = QET::GILoadingFromXml; - /* - les bornes vont maintenant etre recensees pour associer leurs id a leur adresse reelle - ce recensement servira lors de la mise en place des fils - */ - QList liste_terminals; - foreach(QDomElement qde, - QET::findInDomElement(e, "terminals", "terminal")) { - if (Terminal::valideXml(qde)) liste_terminals << qde; - } + m_state = QET::GILoadingFromXml; + /* + les bornes vont maintenant etre recensees pour associer leurs id a leur adresse reelle + ce recensement servira lors de la mise en place des fils + */ + QList liste_terminals; + foreach(QDomElement qde, + QET::findInDomElement(e, "terminals", "terminal")) { + if (Terminal::valideXml(qde)) liste_terminals << qde; + } - QHash priv_id_adr; - int terminals_non_trouvees = 0; - foreach(QGraphicsItem *qgi, childItems()) { - if (Terminal *p = qgraphicsitem_cast(qgi)) { - bool terminal_trouvee = false; - foreach(QDomElement qde, liste_terminals) { - if (p -> fromXml(qde)) { - priv_id_adr.insert( - qde.attribute( - "id").toInt(), - p); - terminal_trouvee = true; - // We used to break here, because we did not expect - // several terminals to share the same position. - // Of course, it finally happened. - } - } - if (!terminal_trouvee) ++ terminals_non_trouvees; - } - } + QHash priv_id_adr; + int terminals_non_trouvees = 0; + foreach(QGraphicsItem *qgi, childItems()) { + if (Terminal *p = qgraphicsitem_cast(qgi)) { + bool terminal_trouvee = false; + foreach(QDomElement qde, liste_terminals) { + if (p -> fromXml(qde)) { + priv_id_adr.insert( + qde.attribute( + "id").toInt(), + p); + terminal_trouvee = true; + // We used to break here, because we did not expect + // several terminals to share the same position. + // Of course, it finally happened. + } + } + if (!terminal_trouvee) ++ terminals_non_trouvees; + } + } - if (terminals_non_trouvees > 0) - { - m_state = QET::GIOK; - return(false); - } - else - { - // verifie que les associations id / adr n'entrent pas en conflit avec table_id_adr - foreach(int id_trouve, priv_id_adr.keys()) - { - if (table_id_adr.contains(id_trouve)) - { - // cet element possede un id qui est deja reference (= conflit) - m_state = QET::GIOK; - return(false); - } - } - // copie des associations id / adr - foreach(int id_trouve, priv_id_adr.keys()) { - table_id_adr.insert(id_trouve, - priv_id_adr.value(id_trouve)); - } - } + if (terminals_non_trouvees > 0) + { + m_state = QET::GIOK; + return(false); + } + else + { + // verifie que les associations id / adr n'entrent pas en conflit avec table_id_adr + foreach(int id_trouve, priv_id_adr.keys()) + { + if (table_id_adr.contains(id_trouve)) + { + // cet element possede un id qui est deja reference (= conflit) + m_state = QET::GIOK; + return(false); + } + } + // copie des associations id / adr + foreach(int id_trouve, priv_id_adr.keys()) { + table_id_adr.insert(id_trouve, + priv_id_adr.value(id_trouve)); + } + } - //load uuid of connected elements - QList uuid_list = QET::findInDomElement(e, - "links_uuids", - "link_uuid"); - foreach (QDomElement qdo, uuid_list) -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - tmp_uuids_link << qdo.attribute("uuid"); + //load uuid of connected elements + QList uuid_list = QET::findInDomElement(e, + "links_uuids", + "link_uuid"); + foreach (QDomElement qdo, uuid_list) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + tmp_uuids_link << qdo.attribute("uuid"); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - qDebug()<<"Help code for QT 6 or later"; + qDebug()<<"Help code for QT 6 or later"; #endif - //uuid of this element - m_uuid= QUuid(e.attribute("uuid", QUuid::createUuid().toString())); + //uuid of this element + m_uuid= QUuid(e.attribute("uuid", QUuid::createUuid().toString())); - //load prefix - m_prefix = e.attribute("prefix"); + //load prefix + m_prefix = e.attribute("prefix"); - QString fl = e.attribute("freezeLabel", "false"); - m_freeze_label = fl == "false"? false : true; + QString fl = e.attribute("freezeLabel", "false"); + m_freeze_label = fl == "false"? false : true; - //Load Sequential Values - if (e.hasAttribute("sequ_1") - || e.hasAttribute("sequf_1") - || e.hasAttribute("seqt_1") - || e.hasAttribute("seqtf_1") - || e.hasAttribute("seqh_1") - || e.hasAttribute("sequf_1")) - ElementXmlRetroCompatibility::loadSequential(e, this); - else - m_autoNum_seq.fromXml(e.firstChildElement("sequentialNumbers")); + //Load Sequential Values + if (e.hasAttribute("sequ_1") + || e.hasAttribute("sequf_1") + || e.hasAttribute("seqt_1") + || e.hasAttribute("seqtf_1") + || e.hasAttribute("seqh_1") + || e.hasAttribute("sequf_1")) + ElementXmlRetroCompatibility::loadSequential(e, this); + else + m_autoNum_seq.fromXml(e.firstChildElement("sequentialNumbers")); - //Position and selection. - //We directly call setPos from QGraphicsObject, because QetGraphicsItem will snap to grid - QGraphicsObject::setPos(e.attribute("x").toDouble(), - e.attribute("y").toDouble()); - setZValue(e.attribute("z", QString::number(this->zValue())).toDouble()); - setFlags(QGraphicsItem::ItemIsMovable - | QGraphicsItem::ItemIsSelectable); + //Position and selection. + //We directly call setPos from QGraphicsObject, because QetGraphicsItem will snap to grid + QGraphicsObject::setPos(e.attribute("x").toDouble(), + e.attribute("y").toDouble()); + setZValue(e.attribute("z", QString::number(this->zValue())).toDouble()); + setFlags(QGraphicsItem::ItemIsMovable + | QGraphicsItem::ItemIsSelectable); - // orientation - bool conv_ok; - int read_ori = e.attribute("orientation").toInt(&conv_ok); - if (!conv_ok || read_ori < 0 || read_ori > 3) { - read_ori = 0; - } - setRotation(90*read_ori); + // orientation + bool conv_ok; + int read_ori = e.attribute("orientation").toInt(&conv_ok); + if (!conv_ok || read_ori < 0 || read_ori > 3) { + read_ori = 0; + } + setRotation(90*read_ori); - //Befor load the dynamic text field, - //we remove the dynamic text field created from the description of this element, to avoid doublons. - for(DynamicElementTextItem *deti : m_dynamic_text_list) - delete deti; - m_dynamic_text_list.clear(); + //Befor load the dynamic text field, + //we remove the dynamic text field created from the description of this element, to avoid doublons. + for(DynamicElementTextItem *deti : m_dynamic_text_list) + delete deti; + m_dynamic_text_list.clear(); - //************************// - //***Dynamic texts item***// - //************************// - for (const QDomElement& qde : QET::findInDomElement( - e, - "dynamic_texts", - DynamicElementTextItem::xmlTagName())) - { - DynamicElementTextItem *deti = new DynamicElementTextItem(this); - addDynamicTextItem(deti); - deti->fromXml(qde); - } + //************************// + //***Dynamic texts item***// + //************************// + for (const QDomElement& qde : QET::findInDomElement( + e, + "dynamic_texts", + DynamicElementTextItem::xmlTagName())) + { + DynamicElementTextItem *deti = new DynamicElementTextItem(this); + addDynamicTextItem(deti); + deti->fromXml(qde); + } - //************************// - //***Element texts item***// - //************************// - QList inputs = QET::findInDomElement(e, "inputs", "input"); + //************************// + //***Element texts item***// + //************************// + QList inputs = QET::findInDomElement(e, "inputs", "input"); - //First case, we check for the text item converted to dynamic text item - const QList conv_deti_list = - m_converted_text_from_xml_description.keys(); - QList successfully_converted; - const QList dom_inputs = inputs; + //First case, we check for the text item converted to dynamic text item + const QList conv_deti_list = + m_converted_text_from_xml_description.keys(); + QList successfully_converted; + const QList dom_inputs = inputs; - for (DynamicElementTextItem *deti : conv_deti_list) - { - for(const QDomElement& dom_input : dom_inputs) - { - //we use the same method used in ElementTextItem::fromXml - //to compar and know if the input dom element is for one of the text stored. - //The comparaison is made from the text position : - //if the position of the text is the same as the position stored in 'input' dom element - //that mean this is the good text - if (qFuzzyCompare(qreal(dom_input.attribute("x").toDouble()), - m_converted_text_from_xml_description.value(deti).x()) && - qFuzzyCompare(qreal(dom_input.attribute("y").toDouble()), - m_converted_text_from_xml_description.value(deti).y())) - { - //Once again this 'if', is only for retrocompatibility with old old old project - //when element text with tagg "label" is not null, but the element information "label" is. - if((deti->textFrom() == DynamicElementTextItem::ElementInfo) - && (deti->infoName() == "label")) - m_element_informations.addValue( - "label", - dom_input.attribute("text")); + for (DynamicElementTextItem *deti : conv_deti_list) + { + for(const QDomElement& dom_input : dom_inputs) + { + //we use the same method used in ElementTextItem::fromXml + //to compar and know if the input dom element is for one of the text stored. + //The comparaison is made from the text position : + //if the position of the text is the same as the position stored in 'input' dom element + //that mean this is the good text + if (qFuzzyCompare(qreal(dom_input.attribute("x").toDouble()), + m_converted_text_from_xml_description.value(deti).x()) && + qFuzzyCompare(qreal(dom_input.attribute("y").toDouble()), + m_converted_text_from_xml_description.value(deti).y())) + { + //Once again this 'if', is only for retrocompatibility with old old old project + //when element text with tagg "label" is not null, but the element information "label" is. + if((deti->textFrom() == DynamicElementTextItem::ElementInfo) + && (deti->infoName() == "label")) + m_element_informations.addValue( + "label", + dom_input.attribute("text")); - deti->setText(dom_input.attribute("text")); + deti->setText(dom_input.attribute("text")); - qreal rotation = deti->rotation(); - QPointF xml_pos = m_converted_text_from_xml_description.value(deti); + qreal rotation = deti->rotation(); + QPointF xml_pos = m_converted_text_from_xml_description.value(deti); - if (dom_input.attribute("userrotation").toDouble()) - rotation = dom_input.attribute("userrotation").toDouble(); + if (dom_input.attribute("userrotation").toDouble()) + rotation = dom_input.attribute("userrotation").toDouble(); - if (dom_input.hasAttribute("userx")) - xml_pos.setX(dom_input.attribute("userx").toDouble()); - if(dom_input.hasAttribute("usery")) - xml_pos.setY(dom_input.attribute("usery", "0").toDouble()); + if (dom_input.hasAttribute("userx")) + xml_pos.setX(dom_input.attribute("userx").toDouble()); + if(dom_input.hasAttribute("usery")) + xml_pos.setY(dom_input.attribute("usery", "0").toDouble()); - //the origin transformation point of PartDynamicTextField - //is the top left corner, no matter the font size - //The origin transformation point of PartTextField - //is the middle of left edge, and so by definition, - //change with the size of the font - //We need to use a QTransform to find the pos of - //this text from the saved pos of text item + //the origin transformation point of PartDynamicTextField + //is the top left corner, no matter the font size + //The origin transformation point of PartTextField + //is the middle of left edge, and so by definition, + //change with the size of the font + //We need to use a QTransform to find the pos of + //this text from the saved pos of text item - deti->setPos(xml_pos); - deti->setRotation(rotation); + deti->setPos(xml_pos); + deti->setRotation(rotation); - QTransform transform; - //First make the rotation - transform.rotate(rotation); - QPointF pos = transform.map( - QPointF(0, - -deti->boundingRect().height()/2)); - transform.reset(); - //Second translate to the pos - transform.translate(xml_pos.x(), xml_pos.y()); - deti->setPos(transform.map(pos)); + QTransform transform; + //First make the rotation + transform.rotate(rotation); + QPointF pos = transform.map( + QPointF(0, + -deti->boundingRect().height()/2)); + transform.reset(); + //Second translate to the pos + transform.translate(xml_pos.x(), xml_pos.y()); + deti->setPos(transform.map(pos)); - //dom_input and deti matched we remove - //the dom_input from inputs list, - //to avoid unnecessary checking made below - //we also move deti from the - //m_converted_text_from_xml_description to m_dynamic_text_list - inputs.removeAll(dom_input); - m_dynamic_text_list.append(deti); - m_converted_text_from_xml_description.remove(deti); - successfully_converted << deti; - } - } - } + //dom_input and deti matched we remove + //the dom_input from inputs list, + //to avoid unnecessary checking made below + //we also move deti from the + //m_converted_text_from_xml_description to m_dynamic_text_list + inputs.removeAll(dom_input); + m_dynamic_text_list.append(deti); + m_converted_text_from_xml_description.remove(deti); + successfully_converted << deti; + } + } + } - //###Firts case : if this is the first time the user open the project since text item are converted to dynamic text, - //in the previous opening of the project, every texts field present in the element description was created. - //At save time, the values of each of them was save in the 'input' dom element. - //The loop upper is made for the first case, to import the values in 'input' to the new converted dynamic texts field. - //###Second case : this is not the first time the user open the project since text item are converted to dynamic text. - //That mean, in a previous opening of the project, the text item was already converted and save as a dynamic text field. - //So there isn't 'input' dom element in the project, and every dynamic text item present in m_converted_text_from_xml_description - //need to be deleted (because already exist in m_dynamic_text_list, from a previous save) - for (DynamicElementTextItem *deti : m_converted_text_from_xml_description.keys()) - delete deti; - m_converted_text_from_xml_description.clear(); + //###Firts case : if this is the first time the user open the project since text item are converted to dynamic text, + //in the previous opening of the project, every texts field present in the element description was created. + //At save time, the values of each of them was save in the 'input' dom element. + //The loop upper is made for the first case, to import the values in 'input' to the new converted dynamic texts field. + //###Second case : this is not the first time the user open the project since text item are converted to dynamic text. + //That mean, in a previous opening of the project, the text item was already converted and save as a dynamic text field. + //So there isn't 'input' dom element in the project, and every dynamic text item present in m_converted_text_from_xml_description + //need to be deleted (because already exist in m_dynamic_text_list, from a previous save) + for (DynamicElementTextItem *deti : m_converted_text_from_xml_description.keys()) + delete deti; + m_converted_text_from_xml_description.clear(); - for (QDomElement qde : QET::findInDomElement( - e, - "texts_groups", - ElementTextItemGroup::xmlTaggName())) - { - ElementTextItemGroup *group = - addTextGroup("loaded_from_xml_group"); - group->fromXml(qde); - } + for (QDomElement qde : QET::findInDomElement( + e, + "texts_groups", + ElementTextItemGroup::xmlTaggName())) + { + ElementTextItemGroup *group = + addTextGroup("loaded_from_xml_group"); + group->fromXml(qde); + } - //load informations - DiagramContext dc; - dc.fromXml(e.firstChildElement("elementInformations"), - "elementInformation"); - /* - * Since the commit 4791, the value used as "label" and "formula" - * is stored in differents keys (instead of the same key, - * "label" in previous version), so, if "label" contain "%" - * (Use variable value), and "formula" does not exist, - * this mean the label was made before commit 4791 (0.51 dev). - * So we swap the value stored in "label" to "formula" as expected. - * @TODO remove this code at version 0.7 or more (probably useless). - */ + //load informations + DiagramContext dc; + dc.fromXml(e.firstChildElement("elementInformations"), + "elementInformation"); + /* + * Since the commit 4791, the value used as "label" and "formula" + * is stored in differents keys (instead of the same key, + * "label" in previous version), so, if "label" contain "%" + * (Use variable value), and "formula" does not exist, + * this mean the label was made before commit 4791 (0.51 dev). + * So we swap the value stored in "label" to "formula" as expected. + * @TODO remove this code at version 0.7 or more (probably useless). + */ #if TODO_LIST #pragma message("@TODO remove this code for qet 0.7 or later") #endif - if (dc["label"].toString().contains("%") - && dc["formula"].toString().isNull()) - { - dc.addValue("formula", dc["label"]); - } - //retrocompatibility with older version - if(dc.value("label").toString().isEmpty() && - !m_element_informations.value("label").toString().isEmpty()) - dc.addValue("label", m_element_informations.value("label")); + if (dc["label"].toString().contains("%") + && dc["formula"].toString().isNull()) + { + dc.addValue("formula", dc["label"]); + } + //retrocompatibility with older version + if(dc.value("label").toString().isEmpty() && + !m_element_informations.value("label").toString().isEmpty()) + dc.addValue("label", m_element_informations.value("label")); - //We must to block the update of the alignment when load the information - //otherwise the pos of the text will not be the same as it was at save time. - for(DynamicElementTextItem *deti : m_dynamic_text_list) - deti->m_block_alignment = true; - setElementInformations(dc); - for(DynamicElementTextItem *deti : m_dynamic_text_list) - deti->m_block_alignment = false; + //We must to block the update of the alignment when load the information + //otherwise the pos of the text will not be the same as it was at save time. + for(DynamicElementTextItem *deti : m_dynamic_text_list) + deti->m_block_alignment = true; + setElementInformations(dc); + for(DynamicElementTextItem *deti : m_dynamic_text_list) + deti->m_block_alignment = false; - /* During the devel of the version 0.7, - * the "old text" was replaced by the dynamic element text item. - * When open a project made befor the 0.7, - * we must to reproduce the same visual when - * the label are not empty and visible, - * and comment are not empty - * and visible and/or location are not empty and visible. - * we create a text group with inside the needed texts, - * label and comment and/or location. - */ - //#1 There must be old text converted to dynamic text - if(!successfully_converted.isEmpty()) - { - //#2 the element information must have label not empty and visible - //and a least comment or location not empty and visible - QString label = m_element_informations.value( - "label").toString(); - QString comment = m_element_informations.value( - "comment").toString(); - QString location = m_element_informations.value( - "location").toString(); - bool la = m_element_informations.keyMustShow("label"); - bool c = m_element_informations.keyMustShow("comment"); - bool lo = m_element_informations.keyMustShow("location"); + /* During the devel of the version 0.7, + * the "old text" was replaced by the dynamic element text item. + * When open a project made befor the 0.7, + * we must to reproduce the same visual when + * the label are not empty and visible, + * and comment are not empty + * and visible and/or location are not empty and visible. + * we create a text group with inside the needed texts, + * label and comment and/or location. + */ + //#1 There must be old text converted to dynamic text + if(!successfully_converted.isEmpty()) + { + //#2 the element information must have label not empty and visible + //and a least comment or location not empty and visible + QString label = m_element_informations.value( + "label").toString(); + QString comment = m_element_informations.value( + "comment").toString(); + QString location = m_element_informations.value( + "location").toString(); + bool la = m_element_informations.keyMustShow("label"); + bool c = m_element_informations.keyMustShow("comment"); + bool lo = m_element_informations.keyMustShow("location"); - if((m_link_type != Master) || - ((m_link_type == Master) && - (diagram()->project()->defaultXRefProperties( - m_kind_informations["type"].toString()).snapTo() - == XRefProperties::Label)) - ) - { - if(!label.isEmpty() && la && - ((!comment.isEmpty() && c) - || (!location.isEmpty() && lo))) - { - //#2 in the converted list one text must have text from = element info and info name = label - for(DynamicElementTextItem *deti - : successfully_converted) - { - if(deti->textFrom()== DynamicElementTextItem::ElementInfo - && deti->infoName() == "label") - { - qreal rotation = deti->rotation(); + if((m_link_type != Master) || + ((m_link_type == Master) && + (diagram()->project()->defaultXRefProperties( + m_kind_informations["type"].toString()).snapTo() + == XRefProperties::Label)) + ) + { + if(!label.isEmpty() && la && + ((!comment.isEmpty() && c) + || (!location.isEmpty() && lo))) + { + //#2 in the converted list one text must have text from = element info and info name = label + for(DynamicElementTextItem *deti + : successfully_converted) + { + if(deti->textFrom()== DynamicElementTextItem::ElementInfo + && deti->infoName() == "label") + { + qreal rotation = deti->rotation(); - //Create the comment item - DynamicElementTextItem *comment_text = nullptr; - if (m_link_type !=PreviousReport - || m_link_type !=NextReport) - { - m_state = QET::GIOK; - return(true); - } - if(!comment.isEmpty() && c) - { - comment_text = new DynamicElementTextItem(this); - comment_text->setTextFrom(DynamicElementTextItem::ElementInfo); - comment_text->setInfoName("comment"); - QFont font = comment_text->font(); - font.setPointSize(6); - comment_text->setFont(font); - comment_text->setFrame(true); - if(comment_text->toPlainText().count() > 17) - comment_text->setTextWidth(80); - comment_text->setPos(deti->x(), deti->y()+10); //+10 is arbitrary, comment_text must be below deti - addDynamicTextItem(comment_text); - } - //create the location item - DynamicElementTextItem *location_text = nullptr; - if (m_link_type !=PreviousReport || m_link_type !=NextReport) - { - m_state = QET::GIOK; - return(true); - } - if(!location.isEmpty() && lo) - { - location_text = new DynamicElementTextItem(this); - location_text->setTextFrom(DynamicElementTextItem::ElementInfo); - location_text->setInfoName("location"); - QFont font = location_text->font(); - font.setPointSize(6); - location_text->setFont(font); - if(location_text->toPlainText().count() > 17) - location_text->setTextWidth(80); - location_text->setPos(deti->x(), deti->y()+20); //+20 is arbitrary, location_text must be below deti and comment - addDynamicTextItem(location_text); - } + //Create the comment item + DynamicElementTextItem *comment_text = nullptr; + if (m_link_type !=PreviousReport + || m_link_type !=NextReport) + { + m_state = QET::GIOK; + return(true); + } + if(!comment.isEmpty() && c) + { + comment_text = new DynamicElementTextItem(this); + comment_text->setTextFrom(DynamicElementTextItem::ElementInfo); + comment_text->setInfoName("comment"); + QFont font = comment_text->font(); + font.setPointSize(6); + comment_text->setFont(font); + comment_text->setFrame(true); + if(comment_text->toPlainText().count() > 17) + comment_text->setTextWidth(80); + comment_text->setPos(deti->x(), deti->y()+10); //+10 is arbitrary, comment_text must be below deti + addDynamicTextItem(comment_text); + } + //create the location item + DynamicElementTextItem *location_text = nullptr; + if (m_link_type !=PreviousReport || m_link_type !=NextReport) + { + m_state = QET::GIOK; + return(true); + } + if(!location.isEmpty() && lo) + { + location_text = new DynamicElementTextItem(this); + location_text->setTextFrom(DynamicElementTextItem::ElementInfo); + location_text->setInfoName("location"); + QFont font = location_text->font(); + font.setPointSize(6); + location_text->setFont(font); + if(location_text->toPlainText().count() > 17) + location_text->setTextWidth(80); + location_text->setPos(deti->x(), deti->y()+20); //+20 is arbitrary, location_text must be below deti and comment + addDynamicTextItem(location_text); + } - QPointF pos = deti->pos(); - if (m_link_type !=PreviousReport - || m_link_type !=NextReport) - { - m_state = QET::GIOK; - return(true); - } - //Create the group - ElementTextItemGroup *group = - addTextGroup(tr("Label + commentaire")); - addTextToGroup(deti, group); - if(comment_text) - addTextToGroup(comment_text, - group); - if(location_text) - addTextToGroup(location_text, - group); - group->setAlignment(Qt::AlignVCenter); - group->setVerticalAdjustment(-4); - group->setRotation(rotation); - //Change the position of the group, - //so that the text "label" stay in the same - //position in scene coordinate - group->setPos(pos - deti->pos()); + QPointF pos = deti->pos(); + if (m_link_type !=PreviousReport + || m_link_type !=NextReport) + { + m_state = QET::GIOK; + return(true); + } + //Create the group + ElementTextItemGroup *group = + addTextGroup(tr("Label + commentaire")); + addTextToGroup(deti, group); + if(comment_text) + addTextToGroup(comment_text, + group); + if(location_text) + addTextToGroup(location_text, + group); + group->setAlignment(Qt::AlignVCenter); + group->setVerticalAdjustment(-4); + group->setRotation(rotation); + //Change the position of the group, + //so that the text "label" stay in the same + //position in scene coordinate + group->setPos(pos - deti->pos()); - break; - } - } - } - } - else - { - //This element is supposed to be a master and Xref property snap to bottom - if((!comment.isEmpty() && c) || (!location.isEmpty() && lo)) - { - //Create the comment item - DynamicElementTextItem *comment_text = nullptr; - if(!comment.isEmpty() && c) - { - comment_text = new DynamicElementTextItem(this); - comment_text - ->setTextFrom( - DynamicElementTextItem::ElementInfo); - comment_text->setInfoName("comment"); - QFont font = comment_text->font(); - font.setPointSize(6); - comment_text->setFont(font); - comment_text->setFrame(true); - comment_text->setTextWidth(80); - addDynamicTextItem(comment_text); - } - //create the location item - DynamicElementTextItem *location_text = nullptr; - if(!location.isEmpty() && lo) - { - location_text = new DynamicElementTextItem(this); - location_text - ->setTextFrom( - DynamicElementTextItem::ElementInfo); - location_text->setInfoName("location"); - QFont font = location_text->font(); - font.setPointSize(6); - location_text->setFont(font); - location_text->setTextWidth(80); - if(comment_text) - location_text->setPos( - comment_text->x(), - comment_text->y()+10); //+10 is arbitrary, location_text must be below the comment - addDynamicTextItem(location_text); - } + break; + } + } + } + } + else + { + //This element is supposed to be a master and Xref property snap to bottom + if((!comment.isEmpty() && c) || (!location.isEmpty() && lo)) + { + //Create the comment item + DynamicElementTextItem *comment_text = nullptr; + if(!comment.isEmpty() && c) + { + comment_text = new DynamicElementTextItem(this); + comment_text + ->setTextFrom( + DynamicElementTextItem::ElementInfo); + comment_text->setInfoName("comment"); + QFont font = comment_text->font(); + font.setPointSize(6); + comment_text->setFont(font); + comment_text->setFrame(true); + comment_text->setTextWidth(80); + addDynamicTextItem(comment_text); + } + //create the location item + DynamicElementTextItem *location_text = nullptr; + if(!location.isEmpty() && lo) + { + location_text = new DynamicElementTextItem(this); + location_text + ->setTextFrom( + DynamicElementTextItem::ElementInfo); + location_text->setInfoName("location"); + QFont font = location_text->font(); + font.setPointSize(6); + location_text->setFont(font); + location_text->setTextWidth(80); + if(comment_text) + location_text->setPos( + comment_text->x(), + comment_text->y()+10); //+10 is arbitrary, location_text must be below the comment + addDynamicTextItem(location_text); + } - //Create the group - ElementTextItemGroup *group = - addTextGroup(tr("Label + commentaire")); - if(comment_text) - addTextToGroup(comment_text, group); - if(location_text) - addTextToGroup(location_text, group); - group->setAlignment(Qt::AlignVCenter); - group->setVerticalAdjustment(-4); - group->setHoldToBottomPage(true); - } - } - } - m_state = QET::GIOK; - return(true); + //Create the group + ElementTextItemGroup *group = + addTextGroup(tr("Label + commentaire")); + if(comment_text) + addTextToGroup(comment_text, group); + if(location_text) + addTextToGroup(location_text, group); + group->setAlignment(Qt::AlignVCenter); + group->setVerticalAdjustment(-4); + group->setHoldToBottomPage(true); + } + } + } + m_state = QET::GIOK; + return(true); } /** - @brief Element::toXml - Allows to export the element in XML - \~French Permet d'exporter l'element en XML - \~ @param document : XML document to use - \~French Document XML a utiliser - \~ @param table_adr_id : - Correspondence table between the addresses of the terminals - and their id in the XML representation; - this table completed by this method - \~French Table de correspondance entre les adresses des bornes - et leur id dans la representation XML ; - cette table completee par cette methode - \~ @return The XML element representing this electrical element - \~French L'element XML representant cet element electrique + @brief Element::toXml + Allows to export the element in XML + \~French Permet d'exporter l'element en XML + \~ @param document : XML document to use + \~French Document XML a utiliser + \~ @param table_adr_id : + Correspondence table between the addresses of the terminals + and their id in the XML representation; + this table completed by this method + \~French Table de correspondance entre les adresses des bornes + et leur id dans la representation XML ; + cette table completee par cette methode + \~ @return The XML element representing this electrical element + \~French L'element XML representant cet element electrique */ QDomElement Element::toXml( - QDomDocument &document, - QHash &table_adr_id) const + QDomDocument &document, + QHash &table_adr_id) const { - QDomElement element = document.createElement("element"); + QDomElement element = document.createElement("element"); - // type - element.setAttribute("type", m_location.path()); + // type + element.setAttribute("type", m_location.path()); - // uuid - element.setAttribute("uuid", uuid().toString()); + // uuid + element.setAttribute("uuid", uuid().toString()); - // prefix - element.setAttribute("prefix", m_prefix); + // prefix + element.setAttribute("prefix", m_prefix); - //frozen label - element.setAttribute("freezeLabel", m_freeze_label? "true" : "false"); + //frozen label + element.setAttribute("freezeLabel", m_freeze_label? "true" : "false"); - // sequential num - QDomElement seq = m_autoNum_seq.toXml(document); - if (seq.hasChildNodes()) - element.appendChild(seq); + // sequential num + QDomElement seq = m_autoNum_seq.toXml(document); + if (seq.hasChildNodes()) + element.appendChild(seq); - // position, selection et orientation - element.setAttribute("x", QString::number(pos().x())); - element.setAttribute("y", QString::number(pos().y())); - element.setAttribute("z", QString::number(this->zValue())); - element.setAttribute("orientation", QString::number(orientation())); + // position, selection et orientation + element.setAttribute("x", QString::number(pos().x())); + element.setAttribute("y", QString::number(pos().y())); + element.setAttribute("z", QString::number(this->zValue())); + element.setAttribute("orientation", QString::number(orientation())); - /* get the first id to use for the bounds of this element - * recupere le premier id a utiliser pour les bornes de cet element */ - int id_terminal = 0; - if (!table_adr_id.isEmpty()) { - // trouve le plus grand id - int max_id_t = -1; - foreach (int id_t, table_adr_id.values()) { - if (id_t > max_id_t) max_id_t = id_t; - } - id_terminal = max_id_t + 1; - } + /* get the first id to use for the bounds of this element + * recupere le premier id a utiliser pour les bornes de cet element */ + int id_terminal = 0; + if (!table_adr_id.isEmpty()) { + // trouve le plus grand id + int max_id_t = -1; + foreach (int id_t, table_adr_id.values()) { + if (id_t > max_id_t) max_id_t = id_t; + } + id_terminal = max_id_t + 1; + } - // registration of device terminals - // enregistrement des bornes de l'appareil - QDomElement xml_terminals = document.createElement("terminals"); - // for each child of the element - // pour chaque enfant de l'element - foreach(Terminal *t, terminals()) { - // alors on enregistre la borne - QDomElement terminal = t -> toXml(document); - terminal.setAttribute("id", id_terminal); // for backward compatibility - table_adr_id.insert(t, id_terminal ++); - xml_terminals.appendChild(terminal); - } - element.appendChild(xml_terminals); + // registration of device terminals + // enregistrement des bornes de l'appareil + QDomElement xml_terminals = document.createElement("terminals"); + // for each child of the element + // pour chaque enfant de l'element + foreach(Terminal *t, terminals()) { + // alors on enregistre la borne + QDomElement terminal = t -> toXml(document); + terminal.setAttribute("id", id_terminal); // for backward compatibility + table_adr_id.insert(t, id_terminal ++); + xml_terminals.appendChild(terminal); + } + element.appendChild(xml_terminals); - // enregistrement des champ de texte de l'appareil - QDomElement inputs = document.createElement("inputs"); - element.appendChild(inputs); + // enregistrement des champ de texte de l'appareil + QDomElement inputs = document.createElement("inputs"); + element.appendChild(inputs); - //if this element is linked to other elements, - //save the uuid of each other elements - if (! isFree()) { - QDomElement links_uuids = document.createElement("links_uuids"); - foreach (Element *elmt, connected_elements) { - QDomElement link_uuid = - document.createElement("link_uuid"); - link_uuid.setAttribute("uuid", elmt->uuid().toString()); - links_uuids.appendChild(link_uuid); - } - element.appendChild(links_uuids); - } + //if this element is linked to other elements, + //save the uuid of each other elements + if (! isFree()) { + QDomElement links_uuids = document.createElement("links_uuids"); + foreach (Element *elmt, connected_elements) { + QDomElement link_uuid = + document.createElement("link_uuid"); + link_uuid.setAttribute("uuid", elmt->uuid().toString()); + links_uuids.appendChild(link_uuid); + } + element.appendChild(links_uuids); + } - //save information of this element - if (! m_element_informations.keys().isEmpty()) { - QDomElement infos = - document.createElement("elementInformations"); - m_element_informations.toXml(infos, "elementInformation"); - element.appendChild(infos); - } + //save information of this element + if (! m_element_informations.keys().isEmpty()) { + QDomElement infos = + document.createElement("elementInformations"); + m_element_informations.toXml(infos, "elementInformation"); + element.appendChild(infos); + } - //Dynamic texts - QDomElement dyn_text = document.createElement("dynamic_texts"); - for (DynamicElementTextItem *deti : m_dynamic_text_list) - dyn_text.appendChild(deti->toXml(document)); + //Dynamic texts + QDomElement dyn_text = document.createElement("dynamic_texts"); + for (DynamicElementTextItem *deti : m_dynamic_text_list) + dyn_text.appendChild(deti->toXml(document)); - QDomElement texts_group = document.createElement("texts_groups"); + QDomElement texts_group = document.createElement("texts_groups"); - //Dynamic texts owned by groups - for(ElementTextItemGroup *group : m_texts_group) - { - group->blockAlignmentUpdate(true); - //temporarily remove the texts from group to get the pos relative to element and not group. - //Set the alignment to top, because top is not used by groupand so, - //each time a text is removed from the group, the alignement is not updated - Qt::Alignment al = group->alignment(); - group->setAlignment(Qt::AlignTop); + //Dynamic texts owned by groups + for(ElementTextItemGroup *group : m_texts_group) + { + group->blockAlignmentUpdate(true); + //temporarily remove the texts from group to get the pos relative to element and not group. + //Set the alignment to top, because top is not used by groupand so, + //each time a text is removed from the group, the alignement is not updated + Qt::Alignment al = group->alignment(); + group->setAlignment(Qt::AlignTop); - //Remove the texts from group - QList deti_list = group->texts(); - for(DynamicElementTextItem *deti : deti_list) - group->removeFromGroup(deti); + //Remove the texts from group + QList deti_list = group->texts(); + for(DynamicElementTextItem *deti : deti_list) + group->removeFromGroup(deti); - //Save the texts to xml - for (DynamicElementTextItem *deti : deti_list) - dyn_text.appendChild(deti->toXml(document)); + //Save the texts to xml + for (DynamicElementTextItem *deti : deti_list) + dyn_text.appendChild(deti->toXml(document)); - //Re add texts to group - for(DynamicElementTextItem *deti : deti_list) - group->addToGroup(deti); + //Re add texts to group + for(DynamicElementTextItem *deti : deti_list) + group->addToGroup(deti); - //Restor the alignement - group->setAlignment(al); + //Restor the alignement + group->setAlignment(al); - //Save the group to xml - texts_group.appendChild(group->toXml(document)); - group->blockAlignmentUpdate(false); - } + //Save the group to xml + texts_group.appendChild(group->toXml(document)); + group->blockAlignmentUpdate(false); + } - //Append the dynamic texts to element - element.appendChild(dyn_text); - //Append the texts group to element - element.appendChild(texts_group); + //Append the dynamic texts to element + element.appendChild(dyn_text); + //Append the texts group to element + element.appendChild(texts_group); - return(element); + return(element); } /** - @brief Element::addDynamiqueTextItem - Add deti as a dynamic text item of this element, - deti is reparented to this - If deti is null, a new DynamicElementTextItem is created - and added to this element. - @param deti + @brief Element::addDynamiqueTextItem + Add deti as a dynamic text item of this element, + deti is reparented to this + If deti is null, a new DynamicElementTextItem is created + and added to this element. + @param deti */ void Element::addDynamicTextItem(DynamicElementTextItem *deti) { - if (deti && !m_dynamic_text_list.contains(deti)) - { - m_dynamic_text_list.append(deti); - deti->setParentItem(this); - emit textAdded(deti); - } - else - { - DynamicElementTextItem *text = new DynamicElementTextItem(this); - m_dynamic_text_list.append(text); - emit textAdded(text); - } + if (deti && !m_dynamic_text_list.contains(deti)) + { + m_dynamic_text_list.append(deti); + deti->setParentItem(this); + emit textAdded(deti); + } + else + { + DynamicElementTextItem *text = new DynamicElementTextItem(this); + m_dynamic_text_list.append(text); + emit textAdded(text); + } } /** - @brief Element::removeDynamicTextItem - Remove deti, no matter if is a child of this element - or a child of a group of this element. - Set he parent item of deti to 0, deti is not deleted. - @param deti + @brief Element::removeDynamicTextItem + Remove deti, no matter if is a child of this element + or a child of a group of this element. + Set he parent item of deti to 0, deti is not deleted. + @param deti */ void Element::removeDynamicTextItem(DynamicElementTextItem *deti) { - if (m_dynamic_text_list.contains(deti)) - { - m_dynamic_text_list.removeOne(deti); - deti->setParentItem(nullptr); - emit textRemoved(deti); - return; - } + if (m_dynamic_text_list.contains(deti)) + { + m_dynamic_text_list.removeOne(deti); + deti->setParentItem(nullptr); + emit textRemoved(deti); + return; + } - for(ElementTextItemGroup *group : m_texts_group) - { - if(group->texts().contains(deti)) - { - removeTextFromGroup(deti, group); - m_dynamic_text_list.removeOne(deti); - deti->setParentItem(nullptr); - emit textRemoved(deti); - return; - } - } + for(ElementTextItemGroup *group : m_texts_group) + { + if(group->texts().contains(deti)) + { + removeTextFromGroup(deti, group); + m_dynamic_text_list.removeOne(deti); + deti->setParentItem(nullptr); + emit textRemoved(deti); + return; + } + } } /** - @brief Element::dynamicTextItems - @return all dynamic text items of this element directly child of this element. - Texts in text-groups belonging to this element are not returned by this function. - @see ElementTextItemGroup::texts + @brief Element::dynamicTextItems + @return all dynamic text items of this element directly child of this element. + Texts in text-groups belonging to this element are not returned by this function. + @see ElementTextItemGroup::texts */ QList Element::dynamicTextItems() const { - return m_dynamic_text_list; + return m_dynamic_text_list; } /** - @brief Element::addTextGroup - Create and add an element text item group to this element. - If this element already have a group with the same name, - then name will renamed to name1 or name2 etc.... - @param name : the name of the group - @return the created group. + @brief Element::addTextGroup + Create and add an element text item group to this element. + If this element already have a group with the same name, + then name will renamed to name1 or name2 etc.... + @param name : the name of the group + @return the created group. */ ElementTextItemGroup *Element::addTextGroup(const QString &name) { - if(m_texts_group.isEmpty()) - { - ElementTextItemGroup *group = new ElementTextItemGroup(name, - this); - m_texts_group << group; - emit textsGroupAdded(group); - return group; - } + if(m_texts_group.isEmpty()) + { + ElementTextItemGroup *group = new ElementTextItemGroup(name, + this); + m_texts_group << group; + emit textsGroupAdded(group); + return group; + } - //Set a new name if name already exist - QString rename = name; - int i=1; - while (textGroup(rename)) - { - rename = name+QString::number(i); - i++; - } + //Set a new name if name already exist + QString rename = name; + int i=1; + while (textGroup(rename)) + { + rename = name+QString::number(i); + i++; + } - //Create the group - ElementTextItemGroup *group = new ElementTextItemGroup(rename, this); - m_texts_group << group; - emit textsGroupAdded(group); - return group; + //Create the group + ElementTextItemGroup *group = new ElementTextItemGroup(rename, this); + m_texts_group << group; + emit textsGroupAdded(group); + return group; } /** - @brief Element::addTextGroup - @param group add group to the group of this element. - the group must not be owned by an element. + @brief Element::addTextGroup + @param group add group to the group of this element. + the group must not be owned by an element. */ void Element::addTextGroup(ElementTextItemGroup *group) { - if(group->parentElement()) - return; + if(group->parentElement()) + return; - m_texts_group << group; - group->setParentItem(this); - emit textsGroupAdded(group); + m_texts_group << group; + group->setParentItem(this); + emit textsGroupAdded(group); } /** - @brief Element::removeTextGroup - Remove the text group group from this element, - and set the parent of group to 0. - group is not deleted. - All texts owned by the group will be reparented to this element - @param group + @brief Element::removeTextGroup + Remove the text group group from this element, + and set the parent of group to 0. + group is not deleted. + All texts owned by the group will be reparented to this element + @param group */ void Element::removeTextGroup(ElementTextItemGroup *group) { - if(!m_texts_group.contains(group)) - return; + if(!m_texts_group.contains(group)) + return; - const QList items_list = group->childItems(); + const QList items_list = group->childItems(); - for(QGraphicsItem *qgi : items_list) - { - if(qgi->type() == DynamicElementTextItem::Type) - { - DynamicElementTextItem *deti = - static_cast(qgi); - removeTextFromGroup(deti, group); - } - } + for(QGraphicsItem *qgi : items_list) + { + if(qgi->type() == DynamicElementTextItem::Type) + { + DynamicElementTextItem *deti = + static_cast(qgi); + removeTextFromGroup(deti, group); + } + } - emit textsGroupAboutToBeRemoved(group); - m_texts_group.removeOne(group); - group->setParentItem(nullptr); + emit textsGroupAboutToBeRemoved(group); + m_texts_group.removeOne(group); + group->setParentItem(nullptr); } /** - @brief Element::textGroup - @param name - @return the text group named name or nullptr if this element - haven't got a group with this name + @brief Element::textGroup + @param name + @return the text group named name or nullptr if this element + haven't got a group with this name */ ElementTextItemGroup *Element::textGroup(const QString &name) const { - for (ElementTextItemGroup *group : m_texts_group) - if(group->name() == name) - return group; + for (ElementTextItemGroup *group : m_texts_group) + if(group->name() == name) + return group; - return nullptr; + return nullptr; } /** - @brief Element::textGroups - @return All texts groups of this element + @brief Element::textGroups + @return All texts groups of this element */ QList Element::textGroups() const { - return m_texts_group; + return m_texts_group; } /** - @brief Element::addTextToGroup - Add the text text to the group group; - If group isn't owned by this element return false. - The text must be a text of this element. - @return : true if the text was succesfully added to the group. + @brief Element::addTextToGroup + Add the text text to the group group; + If group isn't owned by this element return false. + The text must be a text of this element. + @return : true if the text was succesfully added to the group. */ bool Element::addTextToGroup(DynamicElementTextItem *text, - ElementTextItemGroup *group) + ElementTextItemGroup *group) { - if(!m_dynamic_text_list.contains(text)) - return false; - if(!m_texts_group.contains(group)) - return false; + if(!m_dynamic_text_list.contains(text)) + return false; + if(!m_texts_group.contains(group)) + return false; - m_dynamic_text_list.removeOne(text); - emit textRemoved(text); + m_dynamic_text_list.removeOne(text); + emit textRemoved(text); - group->addToGroup(text); - emit textAddedToGroup(text, group); + group->addToGroup(text); + emit textAddedToGroup(text, group); - return true; + return true; } /** - @brief Element::removeTextFromGroup - Remove the text text from the group group, - en reparent text to this element - @return true if text was succesfully removed + @brief Element::removeTextFromGroup + Remove the text text from the group group, + en reparent text to this element + @return true if text was succesfully removed */ bool Element::removeTextFromGroup(DynamicElementTextItem *text, - ElementTextItemGroup *group) + ElementTextItemGroup *group) { - if(!m_texts_group.contains(group)) - return false; + if(!m_texts_group.contains(group)) + return false; - if(group->texts().contains(text)) - { - group->removeFromGroup(text); - emit textRemovedFromGroup(text, group); - addDynamicTextItem(text); - return true; - } + if(group->texts().contains(text)) + { + group->removeFromGroup(text); + emit textRemovedFromGroup(text, group); + addDynamicTextItem(text); + return true; + } - return false; + return false; } /** - @brief Element::AlignedFreeTerminals - @return a list of terminal (owned by this element) aligned to other terminal (from other element) - The first Terminal of QPair is a Terminal owned by this element, - this terminal haven't got any conductor docked. - The second Terminal of QPair is a Terminal owned by an other element, - which is aligned with the first Terminal. The second Terminal can have or not docked conductors. + @brief Element::AlignedFreeTerminals + @return a list of terminal (owned by this element) aligned to other terminal (from other element) + The first Terminal of QPair is a Terminal owned by this element, + this terminal haven't got any conductor docked. + The second Terminal of QPair is a Terminal owned by an other element, + which is aligned with the first Terminal. The second Terminal can have or not docked conductors. */ QList > Element::AlignedFreeTerminals() const { - QList > list; + QList > list; - foreach (Terminal *terminal, terminals()) - { - if (terminal->conductors().isEmpty()) - { - Terminal *other_terminal = - terminal -> alignedWithTerminal(); - if (other_terminal) - list << qMakePair(terminal, other_terminal); - } - } + foreach (Terminal *terminal, terminals()) + { + if (terminal->conductors().isEmpty()) + { + Terminal *other_terminal = + terminal -> alignedWithTerminal(); + if (other_terminal) + list << qMakePair(terminal, other_terminal); + } + } - return list; + return list; } /** - @brief Element::initLink - Initialise the link between this element and other elements. - This method can be call once because init the link according to - uuid store in a private list, after link, the list is clear, so - call another time do nothing. + @brief Element::initLink + Initialise the link between this element and other elements. + This method can be call once because init the link according to + uuid store in a private list, after link, the list is clear, so + call another time do nothing. - @param prj : - ownership project of this element and other element to be linked + @param prj : + ownership project of this element and other element to be linked */ void Element::initLink(QETProject *prj) { - // if nothing to link return now - if (tmp_uuids_link.isEmpty()) return; + // if nothing to link return now + if (tmp_uuids_link.isEmpty()) return; - ElementProvider ep(prj); - foreach (Element *elmt, ep.fromUuids(tmp_uuids_link)) { - elmt->linkToElement(this); - } - tmp_uuids_link.clear(); + ElementProvider ep(prj); + foreach (Element *elmt, ep.fromUuids(tmp_uuids_link)) { + elmt->linkToElement(this); + } + tmp_uuids_link.clear(); } QString Element::linkTypeToString() const { - switch (m_link_type) - { - case Simple: - return "Simple"; - case NextReport : - return "NextReport"; - case PreviousReport: - return "PreviousReport"; - case Master: - return "Master"; - case Slave: - return "Slave"; - case Terminale: - return "Terminale"; - default: - return "Unknown"; - } + switch (m_link_type) + { + case Simple: + return "Simple"; + case NextReport : + return "NextReport"; + case PreviousReport: + return "PreviousReport"; + case Master: + return "Master"; + case Slave: + return "Slave"; + case Terminale: + return "Terminale"; + default: + return "Unknown"; + } } /** - @brief Element::setElementInformations - Set new information for this element. - If new information is different of current infotmation emit elementInfoChange - @param dc + @brief Element::setElementInformations + Set new information for this element. + If new information is different of current infotmation emit elementInfoChange + @param dc */ void Element::setElementInformations(DiagramContext dc) { - if (m_element_informations == dc) { - return; - } + if (m_element_informations == dc) { + return; + } - DiagramContext old_info = m_element_informations; - m_element_informations = dc; - m_element_informations.addValue("label", actualLabel()); //Update the label if there is a formula - emit elementInfoChange(old_info, m_element_informations); + DiagramContext old_info = m_element_informations; + m_element_informations = dc; + m_element_informations.addValue("label", actualLabel()); //Update the label if there is a formula + emit elementInfoChange(old_info, m_element_informations); } /** - @brief comparPos - Compare position of the two elements. Compare 3 points: - 1 folio - 2 row - 3 line - returns a response when a comparison is found. - @return true if elmt1 is at lower position than elmt 2, else false + @brief comparPos + Compare position of the two elements. Compare 3 points: + 1 folio - 2 row - 3 line + returns a response when a comparison is found. + @return true if elmt1 is at lower position than elmt 2, else false */ bool comparPos(const Element *elmt1, const Element *elmt2) { - //Compare folio first - if (elmt1->diagram()->folioIndex() != elmt2->diagram()->folioIndex()) - return elmt1->diagram()->folioIndex() - < - elmt2->diagram()->folioIndex(); - //Compare the row(in letter pos) in second - QString a = elmt1 - ->diagram() - ->convertPosition(elmt1->scenePos()).letter(); - QString b = elmt2 - ->diagram() - ->convertPosition(elmt2->scenePos()).letter(); - if (a != b) - return apos().x() == elmt2->pos().x()) - return elmt1->y() <= elmt2->pos().y(); - return elmt1->pos().x() <= elmt2->pos().x(); + //Compare folio first + if (elmt1->diagram()->folioIndex() != elmt2->diagram()->folioIndex()) + return elmt1->diagram()->folioIndex() + < + elmt2->diagram()->folioIndex(); + //Compare the row(in letter pos) in second + QString a = elmt1 + ->diagram() + ->convertPosition(elmt1->scenePos()).letter(); + QString b = elmt2 + ->diagram() + ->convertPosition(elmt2->scenePos()).letter(); + if (a != b) + return apos().x() == elmt2->pos().x()) + return elmt1->y() <= elmt2->pos().y(); + return elmt1->pos().x() <= elmt2->pos().x(); } /** - @brief Element::mouseMoveEvent - @param event + @brief Element::mouseMoveEvent + @param event */ void Element::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - QetGraphicsItem::mouseMoveEvent(event); - foreach (Terminal *t, terminals()) - { - t -> drawHelpLine(true); - } + QetGraphicsItem::mouseMoveEvent(event); + foreach (Terminal *t, terminals()) + { + t -> drawHelpLine(true); + } } /** - @brief Element::mouseReleaseEvent - @param event + @brief Element::mouseReleaseEvent + @param event */ void Element::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - QetGraphicsItem::mouseReleaseEvent(event); - foreach (Terminal *t, terminals()) - { - t -> drawHelpLine(false); - } + QetGraphicsItem::mouseReleaseEvent(event); + foreach (Terminal *t, terminals()) + { + t -> drawHelpLine(false); + } } /** - When mouse over element - change m_mouse_over to true (used in paint() function ) - Also highlight linked elements - @param e QGraphicsSceneHoverEvent + When mouse over element + change m_mouse_over to true (used in paint() function ) + Also highlight linked elements + @param e QGraphicsSceneHoverEvent */ void Element::hoverEnterEvent(QGraphicsSceneHoverEvent *e) { - Q_UNUSED(e) + Q_UNUSED(e) - foreach (Element *elmt, linkedElements()) - elmt -> setHighlighted(true); + foreach (Element *elmt, linkedElements()) + elmt -> setHighlighted(true); - m_mouse_over = true; - setToolTip( name() ); - update(); + m_mouse_over = true; + setToolTip( name() ); + update(); } /** - When mouse over element leave the position - change m_mouse_over to false(used in paint() function ) - Also un-highlight linked elements - @param e QGraphicsSceneHoverEvent + When mouse over element leave the position + change m_mouse_over to false(used in paint() function ) + Also un-highlight linked elements + @param e QGraphicsSceneHoverEvent */ void Element::hoverLeaveEvent(QGraphicsSceneHoverEvent *e) { - Q_UNUSED(e) + Q_UNUSED(e) - foreach (Element *elmt, linkedElements()) - elmt -> setHighlighted(false); + foreach (Element *elmt, linkedElements()) + elmt -> setHighlighted(false); - m_mouse_over = false; - update(); + m_mouse_over = false; + update(); } /** - @brief Element::setUpFormula - Set up the formula used to create the label of this element - @param code_letter : Q_UNUSED(code_letter) - if true set tagged text to code letter - (ex K for coil) with condition : - formula is empty, text tagged "label" is emptty or "_"; + @brief Element::setUpFormula + Set up the formula used to create the label of this element + @param code_letter : Q_UNUSED(code_letter) + if true set tagged text to code letter + (ex K for coil) with condition : + formula is empty, text tagged "label" is emptty or "_"; */ void Element::setUpFormula(bool code_letter) { - Q_UNUSED(code_letter) + Q_UNUSED(code_letter) - if (linkType() == Element::Slave || linkType() & Element::AllReport) - return; + if (linkType() == Element::Slave || linkType() & Element::AllReport) + return; - if (diagram()) - { - QString formula = diagram() - ->project() - ->elementAutoNumCurrentFormula(); + if (diagram()) + { + QString formula = diagram() + ->project() + ->elementAutoNumCurrentFormula(); - m_element_informations.addValue("formula", formula); + m_element_informations.addValue("formula", formula); - QString element_currentAutoNum = diagram() - ->project() - ->elementCurrentAutoNum(); - NumerotationContext nc = diagram() - ->project() - ->elementAutoNum(element_currentAutoNum); - NumerotationContextCommands ncc (nc); + QString element_currentAutoNum = diagram() + ->project() + ->elementCurrentAutoNum(); + NumerotationContext nc = diagram() + ->project() + ->elementAutoNum(element_currentAutoNum); + NumerotationContextCommands ncc (nc); - m_autoNum_seq.clear(); - autonum::setSequential(formula, - m_autoNum_seq, - nc, - diagram(), - element_currentAutoNum); - diagram()->project()->addElementAutoNum(element_currentAutoNum, - ncc.next()); + m_autoNum_seq.clear(); + autonum::setSequential(formula, + m_autoNum_seq, + nc, + diagram(), + element_currentAutoNum); + diagram()->project()->addElementAutoNum(element_currentAutoNum, + ncc.next()); - if(!m_freeze_label && !formula.isEmpty()) - { - DiagramContext dc = m_element_informations; - m_element_informations.addValue("label", actualLabel()); - emit elementInfoChange(dc, m_element_informations); - } - } + if(!m_freeze_label && !formula.isEmpty()) + { + DiagramContext dc = m_element_informations; + m_element_informations.addValue("label", actualLabel()); + emit elementInfoChange(dc, m_element_informations); + } + } } /** - @brief Element::getPrefix - get Element Prefix + @brief Element::getPrefix + get Element Prefix */ QString Element::getPrefix() const { - return m_prefix; + return m_prefix; } /** - @brief Element::setPrefix - set Element Prefix + @brief Element::setPrefix + set Element Prefix */ void Element::setPrefix(QString prefix) { - m_prefix = std::move(prefix); + m_prefix = std::move(prefix); } /** - @brief Element::freezeLabel - Freeze this element label + @brief Element::freezeLabel + Freeze this element label */ void Element::freezeLabel(bool freeze) { - m_freeze_label = freeze; + m_freeze_label = freeze; } /** - @brief Element::freezeNewAddedElement - Freeze this label if needed + @brief Element::freezeNewAddedElement + Freeze this label if needed */ void Element::freezeNewAddedElement() { - if (this->diagram()->freezeNewElements() - || this->diagram()->project()->isFreezeNewElements()) { - freezeLabel(true); - } - else return; + if (this->diagram()->freezeNewElements() + || this->diagram()->project()->isFreezeNewElements()) { + freezeLabel(true); + } + else return; } /** - @brief Element::actualLabel - Always return the current label to be displayed. - This function is usefull when label is based on formula, because label can change at any time. - @return + @brief Element::actualLabel + Always return the current label to be displayed. + This function is usefull when label is based on formula, because label can change at any time. + @return */ QString Element::actualLabel() { - if (m_element_informations.value("formula").toString().isEmpty()) { - return m_element_informations.value("label").toString(); - } else { - return autonum::AssignVariables::formulaToLabel( - m_element_informations.value( - "formula").toString(), - m_autoNum_seq, - diagram(), - this); - } + if (m_element_informations.value("formula").toString().isEmpty()) { + return m_element_informations.value("label").toString(); + } else { + return autonum::AssignVariables::formulaToLabel( + m_element_informations.value( + "formula").toString(), + m_autoNum_seq, + diagram(), + this); + } } /** - @brief Element::name - @return the human name of this element + @brief Element::name + @return the human name of this element */ QString Element::name() const { - return m_names.name(m_location.baseName()); + return m_names.name(m_location.baseName()); } ElementsLocation Element::location() const { - return m_location; + return m_location; } diff --git a/sources/qetgraphicsitem/element.h b/sources/qetgraphicsitem/element.h index be31e69db..3e59dacc3 100644 --- a/sources/qetgraphicsitem/element.h +++ b/sources/qetgraphicsitem/element.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef ELEMENT_H #define ELEMENT_H @@ -36,209 +36,209 @@ class DynamicElementTextItem; class ElementTextItemGroup; /** - This is the base class for electrical elements. + This is the base class for electrical elements. */ class Element : public QetGraphicsItem { - friend class DiagramEventAddElement; + friend class DiagramEventAddElement; - Q_OBJECT - public: - /** - @brief The kind enum - Used to know the kind of this element - (master, slave, report ect...) - */ - enum kind { - Simple = 1, - NextReport = 2, - PreviousReport = 4, - AllReport = 6, - Master = 8, - Slave = 16, - Terminale = 32}; + Q_OBJECT + public: + /** + @brief The kind enum + Used to know the kind of this element + (master, slave, report ect...) + */ + enum kind { + Simple = 1, + NextReport = 2, + PreviousReport = 4, + AllReport = 6, + Master = 8, + Slave = 16, + Terminale = 32}; - Element(const ElementsLocation &location, - QGraphicsItem * = nullptr, - int *state = nullptr, - Element::kind link_type = Element::Simple); - ~Element() override; - private: - Element(const Element &); + Element(const ElementsLocation &location, + QGraphicsItem * = nullptr, + int *state = nullptr, + Element::kind link_type = Element::Simple); + ~Element() override; + private: + Element(const Element &); - // attributes - public: - /** - Enable the use of qgraphicsitem_cast - to safely cast a QGraphicsItem into an Element. - @return the QGraphicsItem type - */ - enum { Type = UserType + 1000 }; - int type() const override { return Type; } + // attributes + public: + /** + Enable the use of qgraphicsitem_cast + to safely cast a QGraphicsItem into an Element. + @return the QGraphicsItem type + */ + enum { Type = UserType + 1000 }; + int type() const override { return Type; } - signals: - void linkedElementChanged(); //This signal is emited when the linked elements with this element change - void elementInfoChange( - DiagramContext old_info, - DiagramContext new_info); - void textAdded(DynamicElementTextItem *deti); - void textRemoved(DynamicElementTextItem *deti); - void textsGroupAdded(ElementTextItemGroup *group); - void textsGroupAboutToBeRemoved(ElementTextItemGroup *group); - void textAddedToGroup( - DynamicElementTextItem *text, - ElementTextItemGroup *group); - void textRemovedFromGroup( - DynamicElementTextItem *text, - ElementTextItemGroup *group); + signals: + void linkedElementChanged(); //This signal is emited when the linked elements with this element change + void elementInfoChange( + DiagramContext old_info, + DiagramContext new_info); + void textAdded(DynamicElementTextItem *deti); + void textRemoved(DynamicElementTextItem *deti); + void textsGroupAdded(ElementTextItemGroup *group); + void textsGroupAboutToBeRemoved(ElementTextItemGroup *group); + void textAddedToGroup( + DynamicElementTextItem *text, + ElementTextItemGroup *group); + void textRemovedFromGroup( + DynamicElementTextItem *text, + ElementTextItemGroup *group); - public: - QList terminals() const; - QList conductors() const; - QList> AlignedFreeTerminals() const; + public: + QList terminals() const; + QList conductors() const; + QList> AlignedFreeTerminals() const; - //METHODS related to information - DiagramContext elementInformations()const - {return m_element_informations;} - virtual void setElementInformations(DiagramContext dc); - DiagramContext kindInformations() const - {return m_kind_informations;} - //@kind_information_ is used to store more information - //about the herited class like contactelement for know - // kind of contact (simple tempo) or number of contact show by the element. + //METHODS related to information + DiagramContext elementInformations()const + {return m_element_informations;} + virtual void setElementInformations(DiagramContext dc); + DiagramContext kindInformations() const + {return m_kind_informations;} + //@kind_information_ is used to store more information + //about the herited class like contactelement for know + // kind of contact (simple tempo) or number of contact show by the element. - autonum::sequentialNumbers sequenceStruct() const - {return m_autoNum_seq;} - autonum::sequentialNumbers& rSequenceStruct() - {return m_autoNum_seq;} - void setUpFormula(bool code_letter = true); - void setPrefix(QString); - QString getPrefix() const; - void freezeLabel(bool freeze); - bool isFreezeLabel() const {return m_freeze_label;} - void freezeNewAddedElement(); - QString actualLabel(); + autonum::sequentialNumbers sequenceStruct() const + {return m_autoNum_seq;} + autonum::sequentialNumbers& rSequenceStruct() + {return m_autoNum_seq;} + void setUpFormula(bool code_letter = true); + void setPrefix(QString); + QString getPrefix() const; + void freezeLabel(bool freeze); + bool isFreezeLabel() const {return m_freeze_label;} + void freezeNewAddedElement(); + QString actualLabel(); - QString name() const override; - ElementsLocation location() const; - virtual void setHighlighted(bool); - void displayHelpLine(bool b = true); - QSize size() const; - QPixmap pixmap(); - QPoint setHotspot(QPoint); - QPoint hotspot() const; - void editProperty() override; - static bool valideXml(QDomElement &); - virtual bool fromXml( - QDomElement &, - QHash &); - virtual QDomElement toXml( - QDomDocument &, - QHash &) const; - QUuid uuid() const; - int orientation() const; + QString name() const override; + ElementsLocation location() const; + virtual void setHighlighted(bool); + void displayHelpLine(bool b = true); + QSize size() const; + QPixmap pixmap(); + QPoint setHotspot(QPoint); + QPoint hotspot() const; + void editProperty() override; + static bool valideXml(QDomElement &); + virtual bool fromXml( + QDomElement &, + QHash &); + virtual QDomElement toXml( + QDomDocument &, + QHash &) const; + QUuid uuid() const; + int orientation() const; - //METHODS related to texts - void addDynamicTextItem(DynamicElementTextItem *deti = nullptr); - void removeDynamicTextItem(DynamicElementTextItem *deti); - QList dynamicTextItems() const; - ElementTextItemGroup *addTextGroup(const QString &name); - void addTextGroup(ElementTextItemGroup *group); - void removeTextGroup(ElementTextItemGroup *group); - ElementTextItemGroup *textGroup(const QString &name) const; - QList textGroups() const; - bool addTextToGroup( - DynamicElementTextItem *text, - ElementTextItemGroup *group); - bool removeTextFromGroup( - DynamicElementTextItem *text, - ElementTextItemGroup *group); + //METHODS related to texts + void addDynamicTextItem(DynamicElementTextItem *deti = nullptr); + void removeDynamicTextItem(DynamicElementTextItem *deti); + QList dynamicTextItems() const; + ElementTextItemGroup *addTextGroup(const QString &name); + void addTextGroup(ElementTextItemGroup *group); + void removeTextGroup(ElementTextItemGroup *group); + ElementTextItemGroup *textGroup(const QString &name) const; + QList textGroups() const; + bool addTextToGroup( + DynamicElementTextItem *text, + ElementTextItemGroup *group); + bool removeTextFromGroup( + DynamicElementTextItem *text, + ElementTextItemGroup *group); - //METHODS related to linked element - bool isFree() const; - virtual void linkToElement(Element *) {} - virtual void unlinkAllElements() {} - virtual void unlinkElement(Element *) {} - virtual void initLink(QETProject *); - QList linkedElements (); - virtual kind linkType() const {return m_link_type;} // return the linkable type - QString linkTypeToString() const; - void newUuid() {m_uuid = QUuid::createUuid();} //create new uuid for this element + //METHODS related to linked element + bool isFree() const; + virtual void linkToElement(Element *) {} + virtual void unlinkAllElements() {} + virtual void unlinkElement(Element *) {} + virtual void initLink(QETProject *); + QList linkedElements (); + virtual kind linkType() const {return m_link_type;} // return the linkable type + QString linkTypeToString() const; + void newUuid() {m_uuid = QUuid::createUuid();} //create new uuid for this element - protected: - void drawAxes(QPainter *, const QStyleOptionGraphicsItem *); - void setSize(int, int); + protected: + void drawAxes(QPainter *, const QStyleOptionGraphicsItem *); + void setSize(int, int); - private: - void drawSelection( - QPainter *, - const QStyleOptionGraphicsItem *); - void drawHighlight( - QPainter *, - const QStyleOptionGraphicsItem *); - bool buildFromXml(const QDomElement &, int * = nullptr); - bool parseElement(const QDomElement &dom); - bool parseInput(const QDomElement &dom_element); - DynamicElementTextItem *parseDynamicText( - const QDomElement &dom_element); - Terminal *parseTerminal(const QDomElement &dom_element); + private: + void drawSelection( + QPainter *, + const QStyleOptionGraphicsItem *); + void drawHighlight( + QPainter *, + const QStyleOptionGraphicsItem *); + bool buildFromXml(const QDomElement &, int * = nullptr); + bool parseElement(const QDomElement &dom); + bool parseInput(const QDomElement &dom_element); + DynamicElementTextItem *parseDynamicText( + const QDomElement &dom_element); + Terminal *parseTerminal(const QDomElement &dom_element); - //Reimplemented from QGraphicsItem - public: - void paint( - QPainter *, - const QStyleOptionGraphicsItem *, - QWidget *) override; - QRectF boundingRect() const override; - protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent( - QGraphicsSceneMouseEvent *event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override; + //Reimplemented from QGraphicsItem + public: + void paint( + QPainter *, + const QStyleOptionGraphicsItem *, + QWidget *) override; + QRectF boundingRect() const override; + protected: + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent( + QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override; - protected: - // m_converted_text_from_description, - // when a element is created from his description, - // the old element text item (tagged as 'input' in the xml) - // are converted to dynamic text field, - // the QPointF is the original position of the text item, - // because the origin transformation point of text item - // and dynamic text item are not the same, - // so we must to keep a track of this value, - // to be use in the function element::fromXml - QHash - m_converted_text_from_xml_description; + protected: + // m_converted_text_from_description, + // when a element is created from his description, + // the old element text item (tagged as 'input' in the xml) + // are converted to dynamic text field, + // the QPointF is the original position of the text item, + // because the origin transformation point of text item + // and dynamic text item are not the same, + // so we must to keep a track of this value, + // to be use in the function element::fromXml + QHash + m_converted_text_from_xml_description; - //ATTRIBUTES related to linked element - QList connected_elements; - QList tmp_uuids_link; - QUuid m_uuid; - kind m_link_type = Element::Simple; + //ATTRIBUTES related to linked element + QList connected_elements; + QList tmp_uuids_link; + QUuid m_uuid; + kind m_link_type = Element::Simple; - //ATTRIBUTES related to informations - DiagramContext m_element_informations, m_kind_informations; - autonum::sequentialNumbers m_autoNum_seq; - bool m_freeze_label = false; - QString m_F_str; + //ATTRIBUTES related to informations + DiagramContext m_element_informations, m_kind_informations; + autonum::sequentialNumbers m_autoNum_seq; + bool m_freeze_label = false; + QString m_F_str; - ElementsLocation m_location; - NamesList m_names; - QList m_terminals; - const QPicture m_picture; - const QPicture m_low_zoom_picture; + ElementsLocation m_location; + NamesList m_names; + QList m_terminals; + const QPicture m_picture; + const QPicture m_low_zoom_picture; - private: - bool m_must_highlight = false; - QSize dimensions; - QPoint hotspot_coord; - bool m_mouse_over = false; - QString m_prefix; - QList m_dynamic_text_list; - QList m_texts_group; + private: + bool m_must_highlight = false; + QSize dimensions; + QPoint hotspot_coord; + bool m_mouse_over = false; + QString m_prefix; + QList m_dynamic_text_list; + QList m_texts_group; }; @@ -246,40 +246,40 @@ bool comparPos(const Element * elmt1, const Element * elmt2); inline bool Element::isFree() const { - return (connected_elements.isEmpty()); + return (connected_elements.isEmpty()); } /** - Indicate the current orientation of this element - O = 0° - 1 = 90° - 2 = 180° - 3 = 270° - @return the current orientation of this element + Indicate the current orientation of this element + O = 0° + 1 = 90° + 2 = 180° + 3 = 270° + @return the current orientation of this element */ inline int Element::orientation() const { - return(QET::correctAngle(rotation())/90); + return(QET::correctAngle(rotation())/90); } /** - @brief Element::uuid - @return the uuid of this element + @brief Element::uuid + @return the uuid of this element */ inline QUuid Element::uuid() const {return m_uuid;} /** - @brief Element::linkedElements - @return the list of linked elements, the list is sorted by position + @brief Element::linkedElements + @return the list of linked elements, the list is sorted by position */ inline QList Element::linkedElements() { - std::sort( - connected_elements.begin(), - connected_elements.end(), - comparPos); - return connected_elements; + std::sort( + connected_elements.begin(), + connected_elements.end(), + comparPos); + return connected_elements; } #endif diff --git a/sources/qetgraphicsitem/elementtextitemgroup.cpp b/sources/qetgraphicsitem/elementtextitemgroup.cpp index aca072633..36fcab736 100644 --- a/sources/qetgraphicsitem/elementtextitemgroup.cpp +++ b/sources/qetgraphicsitem/elementtextitemgroup.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "elementtextitemgroup.h" #include "dynamicelementtextitem.h" @@ -31,840 +31,840 @@ #include /** - @brief sorting - @param qgia - @param qgib - @return + @brief sorting + @param qgia + @param qgib + @return */ bool sorting(QGraphicsItem *qgia, QGraphicsItem *qgib) { - return qgia->pos().y() < qgib->pos().y(); + return qgia->pos().y() < qgib->pos().y(); } /** - @brief ElementTextItemGroup::ElementTextItemGroup - @param name : - @param parent : + @brief ElementTextItemGroup::ElementTextItemGroup + @param name : + @param parent : */ ElementTextItemGroup::ElementTextItemGroup(const QString &name, - Element *parent) : - QGraphicsItemGroup(parent), - m_name(name), - m_parent_element(parent) + Element *parent) : + QGraphicsItemGroup(parent), + m_name(name), + m_parent_element(parent) { - setFlags(QGraphicsItem::ItemIsSelectable - | QGraphicsItem::ItemIsMovable); - connect(parent, - &Element::linkedElementChanged, - this, - &ElementTextItemGroup::updateXref); + setFlags(QGraphicsItem::ItemIsSelectable + | QGraphicsItem::ItemIsMovable); + connect(parent, + &Element::linkedElementChanged, + this, + &ElementTextItemGroup::updateXref); } ElementTextItemGroup::~ElementTextItemGroup() {} /** - @brief ElementTextItemGroup::addToGroup - @param item + @brief ElementTextItemGroup::addToGroup + @param item */ void ElementTextItemGroup::addToGroup(QGraphicsItem *item) { - if(item->type() == DynamicElementTextItem::Type) - { - //Befor add text to this group we must to set the text at the same rotation of this group - if((item->rotation() != rotation()) && !m_block_alignment_update) - item->setRotation(rotation()); - - QGraphicsItemGroup::addToGroup(item); - updateAlignment(); - - DynamicElementTextItem *deti = qgraphicsitem_cast(item); - connect(deti, &DynamicElementTextItem::fontChanged, - this, &ElementTextItemGroup::updateAlignment); - connect(deti, &DynamicElementTextItem::textChanged, - this, &ElementTextItemGroup::updateAlignment); - connect(deti, &DynamicElementTextItem::textFromChanged, - this, &ElementTextItemGroup::updateAlignment); - connect(deti, &DynamicElementTextItem::infoNameChanged, - this, &ElementTextItemGroup::updateAlignment); - connect(deti, &DynamicElementTextItem::compositeTextChanged, - this, &ElementTextItemGroup::updateAlignment); - connect(deti, &DynamicElementTextItem::plainTextChanged, - this, &ElementTextItemGroup::updateAlignment); - connect(deti, &DynamicElementTextItem::textWidthChanged, - this, &ElementTextItemGroup::updateAlignment); - - connect(deti, &DynamicElementTextItem::textFromChanged, - this, &ElementTextItemGroup::updateXref); - connect(deti, &DynamicElementTextItem::infoNameChanged, - this, &ElementTextItemGroup::updateXref); - - updateXref(); - } + if(item->type() == DynamicElementTextItem::Type) + { + //Befor add text to this group we must to set the text at the same rotation of this group + if((item->rotation() != rotation()) && !m_block_alignment_update) + item->setRotation(rotation()); + + QGraphicsItemGroup::addToGroup(item); + updateAlignment(); + + DynamicElementTextItem *deti = qgraphicsitem_cast(item); + connect(deti, &DynamicElementTextItem::fontChanged, + this, &ElementTextItemGroup::updateAlignment); + connect(deti, &DynamicElementTextItem::textChanged, + this, &ElementTextItemGroup::updateAlignment); + connect(deti, &DynamicElementTextItem::textFromChanged, + this, &ElementTextItemGroup::updateAlignment); + connect(deti, &DynamicElementTextItem::infoNameChanged, + this, &ElementTextItemGroup::updateAlignment); + connect(deti, &DynamicElementTextItem::compositeTextChanged, + this, &ElementTextItemGroup::updateAlignment); + connect(deti, &DynamicElementTextItem::plainTextChanged, + this, &ElementTextItemGroup::updateAlignment); + connect(deti, &DynamicElementTextItem::textWidthChanged, + this, &ElementTextItemGroup::updateAlignment); + + connect(deti, &DynamicElementTextItem::textFromChanged, + this, &ElementTextItemGroup::updateXref); + connect(deti, &DynamicElementTextItem::infoNameChanged, + this, &ElementTextItemGroup::updateXref); + + updateXref(); + } } /** - @brief ElementTextItemGroup::removeFromGroup - @param item + @brief ElementTextItemGroup::removeFromGroup + @param item */ void ElementTextItemGroup::removeFromGroup(QGraphicsItem *item) { - QGraphicsItemGroup::removeFromGroup(item); - //the item transformation is not reseted, we must to do it, - // because for exemple if the group rotation is 45° - //When item is removed from group, - // visually the item is unchanged (so 45°) - // but if we call item->rotation() the returned value is 0. - item->resetTransform(); - item->setRotation(this->rotation()); - item->setFlag(QGraphicsItem::ItemIsSelectable, true); - updateAlignment(); - - if(DynamicElementTextItem *deti = qgraphicsitem_cast(item)) - { - disconnect(deti, &DynamicElementTextItem::fontChanged, - this, &ElementTextItemGroup::updateAlignment); - disconnect(deti, &DynamicElementTextItem::textChanged, - this, &ElementTextItemGroup::updateAlignment); - disconnect(deti, &DynamicElementTextItem::textFromChanged, - this, &ElementTextItemGroup::updateAlignment); - disconnect(deti, &DynamicElementTextItem::infoNameChanged, - this, &ElementTextItemGroup::updateAlignment); - disconnect(deti, &DynamicElementTextItem::compositeTextChanged, - this, &ElementTextItemGroup::updateAlignment); - disconnect(deti, &DynamicElementTextItem::plainTextChanged, - this, &ElementTextItemGroup::updateAlignment); - disconnect(deti, &DynamicElementTextItem::textWidthChanged, - this, &ElementTextItemGroup::updateAlignment); - - disconnect(deti, &DynamicElementTextItem::textFromChanged, - this, &ElementTextItemGroup::updateXref); - disconnect(deti, &DynamicElementTextItem::infoNameChanged, - this, &ElementTextItemGroup::updateXref); - - updateXref(); - } + QGraphicsItemGroup::removeFromGroup(item); + //the item transformation is not reseted, we must to do it, + // because for exemple if the group rotation is 45° + //When item is removed from group, + // visually the item is unchanged (so 45°) + // but if we call item->rotation() the returned value is 0. + item->resetTransform(); + item->setRotation(this->rotation()); + item->setFlag(QGraphicsItem::ItemIsSelectable, true); + updateAlignment(); + + if(DynamicElementTextItem *deti = qgraphicsitem_cast(item)) + { + disconnect(deti, &DynamicElementTextItem::fontChanged, + this, &ElementTextItemGroup::updateAlignment); + disconnect(deti, &DynamicElementTextItem::textChanged, + this, &ElementTextItemGroup::updateAlignment); + disconnect(deti, &DynamicElementTextItem::textFromChanged, + this, &ElementTextItemGroup::updateAlignment); + disconnect(deti, &DynamicElementTextItem::infoNameChanged, + this, &ElementTextItemGroup::updateAlignment); + disconnect(deti, &DynamicElementTextItem::compositeTextChanged, + this, &ElementTextItemGroup::updateAlignment); + disconnect(deti, &DynamicElementTextItem::plainTextChanged, + this, &ElementTextItemGroup::updateAlignment); + disconnect(deti, &DynamicElementTextItem::textWidthChanged, + this, &ElementTextItemGroup::updateAlignment); + + disconnect(deti, &DynamicElementTextItem::textFromChanged, + this, &ElementTextItemGroup::updateXref); + disconnect(deti, &DynamicElementTextItem::infoNameChanged, + this, &ElementTextItemGroup::updateXref); + + updateXref(); + } } /** - @brief ElementTextItemGroup::blockAlignmentUpdate - If true, the texts in this group are never aligned, moved, rotated etc... - the texts stay as it was, until blockAlignmentUpdate is set to false. - @param block + @brief ElementTextItemGroup::blockAlignmentUpdate + If true, the texts in this group are never aligned, moved, rotated etc... + the texts stay as it was, until blockAlignmentUpdate is set to false. + @param block */ void ElementTextItemGroup::blockAlignmentUpdate(bool block) { - m_block_alignment_update = block; + m_block_alignment_update = block; } /** - @brief ElementTextItemGroup::setAlignement - Set the alignement of this group - @param alignement + @brief ElementTextItemGroup::setAlignement + Set the alignement of this group + @param alignement */ void ElementTextItemGroup::setAlignment(Qt::Alignment alignement) { - m_alignment = alignement; - updateAlignment(); - emit alignmentChanged(alignement); + m_alignment = alignement; + updateAlignment(); + emit alignmentChanged(alignement); } Qt::Alignment ElementTextItemGroup::alignment() const { - return m_alignment; + return m_alignment; } /** - @brief ElementTextItemGroup::setAlignment - Update the alignement of the items in this group, according - to the current alignement. - @param alignement + @brief ElementTextItemGroup::setAlignment + Update the alignement of the items in this group, according + to the current alignement. + @param alignement */ void ElementTextItemGroup::updateAlignment() { - if(m_block_alignment_update) - return; - - prepareGeometryChange(); - - QList texts = this->texts(); - - qreal rotation_ = rotation(); - - //Set the rotation of this group to 0° relative to the scene - qreal rot = rotation(); - QGraphicsItem *parent = parentItem(); - while (parent) { - rot += parent->rotation(); - parent = parent->parentItem(); - } - if(rot != 0) - setRotation(rotation() - rot); - - - if(texts.size() == 1) - { - prepareGeometryChange(); - - QGraphicsItem *first = texts.first(); - setPos(mapFromScene(first->mapToScene(pos()))); - first->setPos(0,0); - } - else if (texts.size() > 1) - { - qreal width = 0; - for(QGraphicsItem *item : texts) - if(item->boundingRect().width() > width) - width = item->boundingRect().width(); - - prepareGeometryChange(); - std::sort(texts.begin(), texts.end(), sorting); - - qreal y_offset = 0; - - if(m_alignment == Qt::AlignLeft) - { - QPointF ref = texts.first()->pos(); - - for(QGraphicsItem *item : texts) - { - item->setPos(0, ref.y()+y_offset); - y_offset+=item->boundingRect().height() + m_vertical_adjustment; - } - } - else if(m_alignment == Qt::AlignVCenter) - { - QPointF ref(width/2,0); - - for(QGraphicsItem *item : texts) - { - item->setPos(ref.x() - item->boundingRect().width()/2, - ref.y() + y_offset); - y_offset+=item->boundingRect().height() + m_vertical_adjustment; - } - } - else if (m_alignment == Qt::AlignRight) - { - QPointF ref(width,0); - - for(QGraphicsItem *item : texts) - { - item->setPos(ref.x() - item->boundingRect().width(), - ref.y() + y_offset); - y_offset+=item->boundingRect().height() + m_vertical_adjustment; - } - } - } - - //Restor the rotation - setRotation(rotation_); - - if(m_Xref_item) - m_Xref_item->autoPos(); - if(m_slave_Xref_item) - adjustSlaveXrefPos(); - if(m_hold_to_bottom_of_page) - autoPos(); + if(m_block_alignment_update) + return; + + prepareGeometryChange(); + + QList texts = this->texts(); + + qreal rotation_ = rotation(); + + //Set the rotation of this group to 0° relative to the scene + qreal rot = rotation(); + QGraphicsItem *parent = parentItem(); + while (parent) { + rot += parent->rotation(); + parent = parent->parentItem(); + } + if(rot != 0) + setRotation(rotation() - rot); + + + if(texts.size() == 1) + { + prepareGeometryChange(); + + QGraphicsItem *first = texts.first(); + setPos(mapFromScene(first->mapToScene(pos()))); + first->setPos(0,0); + } + else if (texts.size() > 1) + { + qreal width = 0; + for(QGraphicsItem *item : texts) + if(item->boundingRect().width() > width) + width = item->boundingRect().width(); + + prepareGeometryChange(); + std::sort(texts.begin(), texts.end(), sorting); + + qreal y_offset = 0; + + if(m_alignment == Qt::AlignLeft) + { + QPointF ref = texts.first()->pos(); + + for(QGraphicsItem *item : texts) + { + item->setPos(0, ref.y()+y_offset); + y_offset+=item->boundingRect().height() + m_vertical_adjustment; + } + } + else if(m_alignment == Qt::AlignVCenter) + { + QPointF ref(width/2,0); + + for(QGraphicsItem *item : texts) + { + item->setPos(ref.x() - item->boundingRect().width()/2, + ref.y() + y_offset); + y_offset+=item->boundingRect().height() + m_vertical_adjustment; + } + } + else if (m_alignment == Qt::AlignRight) + { + QPointF ref(width,0); + + for(QGraphicsItem *item : texts) + { + item->setPos(ref.x() - item->boundingRect().width(), + ref.y() + y_offset); + y_offset+=item->boundingRect().height() + m_vertical_adjustment; + } + } + } + + //Restor the rotation + setRotation(rotation_); + + if(m_Xref_item) + m_Xref_item->autoPos(); + if(m_slave_Xref_item) + adjustSlaveXrefPos(); + if(m_hold_to_bottom_of_page) + autoPos(); } /** - @brief ElementTextItemGroup::setVerticalAdjustment - Set the value of the vertical adjustment to v. - The vertical adjutment is use to adjust - the space between the texts of this group. - @param v + @brief ElementTextItemGroup::setVerticalAdjustment + Set the value of the vertical adjustment to v. + The vertical adjutment is use to adjust + the space between the texts of this group. + @param v */ void ElementTextItemGroup::setVerticalAdjustment(int v) { - prepareGeometryChange(); - m_vertical_adjustment = v; - updateAlignment(); - emit verticalAdjustmentChanged(v); + prepareGeometryChange(); + m_vertical_adjustment = v; + updateAlignment(); + emit verticalAdjustmentChanged(v); } /** - @brief ElementTextItemGroup::setName - @param name Set the name of this group + @brief ElementTextItemGroup::setName + @param name Set the name of this group */ void ElementTextItemGroup::setName(QString name) { - m_name = std::move(name); - emit nameChanged(m_name); + m_name = std::move(name); + emit nameChanged(m_name); } void ElementTextItemGroup::setHoldToBottomPage(bool hold) { - if(m_hold_to_bottom_of_page == hold) - return; - - m_hold_to_bottom_of_page = hold; - if(m_hold_to_bottom_of_page) - { - setFlag(QGraphicsItem::ItemIsSelectable, false); - setFlag(QGraphicsItem::ItemIsMovable, false); - connect(m_parent_element, &Element::yChanged, this, &ElementTextItemGroup::autoPos); - connect(m_parent_element, &Element::rotationChanged, this, &ElementTextItemGroup::autoPos); - if(m_parent_element->linkType() == Element::Master) - { - //We use timer to let the time of the parent element - // xref to be updated, - // befor update the position of this group - //because the position of this group is related - // to the size of the parent element Xref - m_linked_changed_timer = connect( - m_parent_element, - &Element::linkedElementChanged, - [this]() - {QTimer::singleShot(200, - this, - &ElementTextItemGroup::autoPos);} - ); - if(m_parent_element->diagram()) - m_XrefChanged_timer = connect( - m_parent_element->diagram()->project(), - &QETProject::XRefPropertiesChanged, - [this]() - {QTimer::singleShot(200, - this, - &ElementTextItemGroup::autoPos);} - ); - } - autoPos(); - } - else - { - setFlag(QGraphicsItem::ItemIsSelectable, true); - setFlag(QGraphicsItem::ItemIsMovable, true); - disconnect(m_parent_element, &Element::yChanged, - this, &ElementTextItemGroup::autoPos); - disconnect(m_parent_element, &Element::rotationChanged, - this, &ElementTextItemGroup::autoPos); - if(m_parent_element->linkType() == Element::Master) - { - disconnect(m_linked_changed_timer); - if(m_XrefChanged_timer) - disconnect(m_XrefChanged_timer); - } - } - - emit holdToBottomPageChanged(hold); + if(m_hold_to_bottom_of_page == hold) + return; + + m_hold_to_bottom_of_page = hold; + if(m_hold_to_bottom_of_page) + { + setFlag(QGraphicsItem::ItemIsSelectable, false); + setFlag(QGraphicsItem::ItemIsMovable, false); + connect(m_parent_element, &Element::yChanged, this, &ElementTextItemGroup::autoPos); + connect(m_parent_element, &Element::rotationChanged, this, &ElementTextItemGroup::autoPos); + if(m_parent_element->linkType() == Element::Master) + { + //We use timer to let the time of the parent element + // xref to be updated, + // befor update the position of this group + //because the position of this group is related + // to the size of the parent element Xref + m_linked_changed_timer = connect( + m_parent_element, + &Element::linkedElementChanged, + [this]() + {QTimer::singleShot(200, + this, + &ElementTextItemGroup::autoPos);} + ); + if(m_parent_element->diagram()) + m_XrefChanged_timer = connect( + m_parent_element->diagram()->project(), + &QETProject::XRefPropertiesChanged, + [this]() + {QTimer::singleShot(200, + this, + &ElementTextItemGroup::autoPos);} + ); + } + autoPos(); + } + else + { + setFlag(QGraphicsItem::ItemIsSelectable, true); + setFlag(QGraphicsItem::ItemIsMovable, true); + disconnect(m_parent_element, &Element::yChanged, + this, &ElementTextItemGroup::autoPos); + disconnect(m_parent_element, &Element::rotationChanged, + this, &ElementTextItemGroup::autoPos); + if(m_parent_element->linkType() == Element::Master) + { + disconnect(m_linked_changed_timer); + if(m_XrefChanged_timer) + disconnect(m_XrefChanged_timer); + } + } + + emit holdToBottomPageChanged(hold); } void ElementTextItemGroup::setFrame(const bool frame) { - m_frame = frame; - update(); - emit frameChanged(m_frame); + m_frame = frame; + update(); + emit frameChanged(m_frame); } bool ElementTextItemGroup::frame() const { - return m_frame; + return m_frame; } /** - @brief ElementTextItemGroup::texts - @return Every texts in this group + @brief ElementTextItemGroup::texts + @return Every texts in this group */ QList ElementTextItemGroup::texts() const { - QList list; - for(QGraphicsItem *qgi : childItems()) - { - if(qgi->type() == DynamicElementTextItem::Type) - list << static_cast(qgi); - } - return list; + QList list; + for(QGraphicsItem *qgi : childItems()) + { + if(qgi->type() == DynamicElementTextItem::Type) + list << static_cast(qgi); + } + return list; } /** - @brief ElementTextItemGroup::diagram - @return The diagram of this group, or nullptr if this group is not in a diagram + @brief ElementTextItemGroup::diagram + @return The diagram of this group, or nullptr if this group is not in a diagram */ Diagram *ElementTextItemGroup::diagram() const { - if(scene()) - return static_cast(scene()); - else - return nullptr; + if(scene()) + return static_cast(scene()); + else + return nullptr; } /** - @brief ElementTextItemGroup::parentElement - @return The parent element of this group or nullptr + @brief ElementTextItemGroup::parentElement + @return The parent element of this group or nullptr */ Element *ElementTextItemGroup::parentElement() const { - if(parentItem() && parentItem()->type() == Element::Type) - return static_cast(parentItem()); - else - return nullptr; + if(parentItem() && parentItem()->type() == Element::Type) + return static_cast(parentItem()); + else + return nullptr; } /** - @brief ElementTextItemGroup::toXml - Export data of this group to xml - @param dom_document - @return + @brief ElementTextItemGroup::toXml + Export data of this group to xml + @param dom_document + @return */ QDomElement ElementTextItemGroup::toXml(QDomDocument &dom_document) const { - QDomElement dom_element = dom_document.createElement(this->xmlTaggName()); - dom_element.setAttribute("name", m_name); - - dom_element.setAttribute("x", QString::number(pos().x())); - dom_element.setAttribute("y", QString::number(pos().y())); + QDomElement dom_element = dom_document.createElement(this->xmlTaggName()); + dom_element.setAttribute("name", m_name); + + dom_element.setAttribute("x", QString::number(pos().x())); + dom_element.setAttribute("y", QString::number(pos().y())); - QMetaEnum me = QMetaEnum::fromType(); - dom_element.setAttribute("alignment", me.valueToKey(m_alignment)); - - dom_element.setAttribute("rotation", this->rotation()); - dom_element.setAttribute("vertical_adjustment", m_vertical_adjustment); - dom_element.setAttribute("frame", m_frame? "true" : "false"); - - dom_element.setAttribute("hold_to_bottom_page", - m_hold_to_bottom_of_page == true ? "true" : "false"); - - QDomElement dom_texts = dom_document.createElement("texts"); - for(DynamicElementTextItem *deti : texts()) - { - QDomElement text = dom_document.createElement("text"); - text.setAttribute("uuid", deti->uuid().toString()); - dom_texts.appendChild(text); - } - - dom_element.appendChild(dom_texts); - return dom_element; + QMetaEnum me = QMetaEnum::fromType(); + dom_element.setAttribute("alignment", me.valueToKey(m_alignment)); + + dom_element.setAttribute("rotation", this->rotation()); + dom_element.setAttribute("vertical_adjustment", m_vertical_adjustment); + dom_element.setAttribute("frame", m_frame? "true" : "false"); + + dom_element.setAttribute("hold_to_bottom_page", + m_hold_to_bottom_of_page == true ? "true" : "false"); + + QDomElement dom_texts = dom_document.createElement("texts"); + for(DynamicElementTextItem *deti : texts()) + { + QDomElement text = dom_document.createElement("text"); + text.setAttribute("uuid", deti->uuid().toString()); + dom_texts.appendChild(text); + } + + dom_element.appendChild(dom_texts); + return dom_element; } /** - @brief ElementTextItemGroup::fromXml - Import data of this group from xml - @param dom_element + @brief ElementTextItemGroup::fromXml + Import data of this group from xml + @param dom_element */ void ElementTextItemGroup::fromXml(QDomElement &dom_element) { - if (dom_element.tagName() != xmlTaggName()) { - qDebug() << "ElementTextItemGroup::fromXml : Wrong tagg name"; - return; - } - - setName(dom_element.attribute("name", "no name")); - QMetaEnum me = QMetaEnum::fromType(); - setAlignment( - Qt::Alignment( - me.keyToValue( - dom_element.attribute( - "alignment") - .toStdString() - .data() - ) - ) - ); + if (dom_element.tagName() != xmlTaggName()) { + qDebug() << "ElementTextItemGroup::fromXml : Wrong tagg name"; + return; + } + + setName(dom_element.attribute("name", "no name")); + QMetaEnum me = QMetaEnum::fromType(); + setAlignment( + Qt::Alignment( + me.keyToValue( + dom_element.attribute( + "alignment") + .toStdString() + .data() + ) + ) + ); - setPos(dom_element.attribute("x", QString::number(0)).toDouble(), - dom_element.attribute("y", QString::number(0)).toDouble()); - - setRotation(dom_element.attribute("rotation", QString::number(0)).toDouble()); - setVerticalAdjustment(dom_element.attribute("vertical_adjustment").toInt()); - setFrame(dom_element.attribute("frame", "false") == "true"? true : false); - - QString hold = dom_element.attribute("hold_to_bottom_page", "false"); - setHoldToBottomPage(hold == "true" ? true : false); - - if(parentElement()) - { - m_block_alignment_update = true; - for(const QDomElement& text : QET::findInDomElement(dom_element, "texts", "text")) - { - DynamicElementTextItem *deti = nullptr; - QUuid uuid(text.attribute("uuid")); - - for(DynamicElementTextItem *txt : parentElement()->dynamicTextItems()) - if(txt->uuid() == uuid) - deti = txt; - - if (deti) - parentElement()->addTextToGroup(deti, this); - } - m_block_alignment_update = false; - } + setPos(dom_element.attribute("x", QString::number(0)).toDouble(), + dom_element.attribute("y", QString::number(0)).toDouble()); + + setRotation(dom_element.attribute("rotation", QString::number(0)).toDouble()); + setVerticalAdjustment(dom_element.attribute("vertical_adjustment").toInt()); + setFrame(dom_element.attribute("frame", "false") == "true"? true : false); + + QString hold = dom_element.attribute("hold_to_bottom_page", "false"); + setHoldToBottomPage(hold == "true" ? true : false); + + if(parentElement()) + { + m_block_alignment_update = true; + for(const QDomElement& text : QET::findInDomElement(dom_element, "texts", "text")) + { + DynamicElementTextItem *deti = nullptr; + QUuid uuid(text.attribute("uuid")); + + for(DynamicElementTextItem *txt : parentElement()->dynamicTextItems()) + if(txt->uuid() == uuid) + deti = txt; + + if (deti) + parentElement()->addTextToGroup(deti, this); + } + m_block_alignment_update = false; + } } /** - @brief ElementTextItemGroup::paint - @param painter - @param option - @param widget + @brief ElementTextItemGroup::paint + @param painter + @param option + @param widget */ void ElementTextItemGroup::paint( - QPainter *painter, - const QStyleOptionGraphicsItem *option, - QWidget *widget) + QPainter *painter, + const QStyleOptionGraphicsItem *option, + QWidget *widget) { - Q_UNUSED(option); - Q_UNUSED(widget); - if(isSelected()) - { - painter->save(); - QPen t; - t.setColor(Qt::gray); - t.setStyle(Qt::DashDotLine); - t.setCosmetic(true); - painter->setPen(t); - painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), - 10, 10); - - painter->restore(); - } - if(m_frame) - { - qreal font_size = 1; - QRectF rect; - for(DynamicElementTextItem *deti : this->texts()) - { - font_size = std::max(font_size, deti->font().pointSizeF()); - rect = rect.united(mapFromItem(deti, deti->frameRect()).boundingRect()); - } - - //Adjust the thickness according to the font size - qreal w=0.3; - if (font_size >= 5) - { - w = font_size*0.1; - if(w > 2.5) - w = 2.5; - } - - painter->save(); - QPen pen; - pen.setWidthF(w); - painter->setPen(pen); - painter->setRenderHint(QPainter::Antialiasing); - - //Adjust the rounding of the rectangle according to the size of the font - qreal ro = font_size/3; - painter->drawRoundedRect(rect, ro, ro); - painter->restore(); - } + Q_UNUSED(option); + Q_UNUSED(widget); + if(isSelected()) + { + painter->save(); + QPen t; + t.setColor(Qt::gray); + t.setStyle(Qt::DashDotLine); + t.setCosmetic(true); + painter->setPen(t); + painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), + 10, 10); + + painter->restore(); + } + if(m_frame) + { + qreal font_size = 1; + QRectF rect; + for(DynamicElementTextItem *deti : this->texts()) + { + font_size = std::max(font_size, deti->font().pointSizeF()); + rect = rect.united(mapFromItem(deti, deti->frameRect()).boundingRect()); + } + + //Adjust the thickness according to the font size + qreal w=0.3; + if (font_size >= 5) + { + w = font_size*0.1; + if(w > 2.5) + w = 2.5; + } + + painter->save(); + QPen pen; + pen.setWidthF(w); + painter->setPen(pen); + painter->setRenderHint(QPainter::Antialiasing); + + //Adjust the rounding of the rectangle according to the size of the font + qreal ro = font_size/3; + painter->drawRoundedRect(rect, ro, ro); + painter->restore(); + } } /** - @brief ElementTextItemGroup::boundingRect - @return + @brief ElementTextItemGroup::boundingRect + @return */ QRectF ElementTextItemGroup::boundingRect() const { - //If we refer to the Qt doc, the bounding rect of a QGraphicsItemGroup, - //is the bounding of all childrens in the group - //When add an item in the group, the bounding rect is good, but - //if we move an item already in the group, the bounding rect of the group stay unchanged. - //We reimplement this function to avoid this behavior. - QRectF rect; - for(QGraphicsItem *qgi : texts()) - { - QRectF r(qgi->pos(), QSize(qgi->boundingRect().width(), - qgi->boundingRect().height())); - rect = rect.united(r); - } - return rect; + //If we refer to the Qt doc, the bounding rect of a QGraphicsItemGroup, + //is the bounding of all childrens in the group + //When add an item in the group, the bounding rect is good, but + //if we move an item already in the group, the bounding rect of the group stay unchanged. + //We reimplement this function to avoid this behavior. + QRectF rect; + for(QGraphicsItem *qgi : texts()) + { + QRectF r(qgi->pos(), QSize(qgi->boundingRect().width(), + qgi->boundingRect().height())); + rect = rect.united(r); + } + return rect; } void ElementTextItemGroup::setRotation(qreal angle) -{ - QGraphicsItemGroup::setRotation(angle); - emit rotationChanged(angle); +{ + QGraphicsItemGroup::setRotation(angle); + emit rotationChanged(angle); } void ElementTextItemGroup::setPos(const QPointF &pos) { - QPointF old_pos = this->pos(); - QGraphicsItemGroup::setPos(pos); - if (old_pos.x() != this->pos().x()) - emit xChanged(); - if (old_pos.y() != this->pos().y()) - emit yChanged(); + QPointF old_pos = this->pos(); + QGraphicsItemGroup::setPos(pos); + if (old_pos.x() != this->pos().x()) + emit xChanged(); + if (old_pos.y() != this->pos().y()) + emit yChanged(); } void ElementTextItemGroup::setPos(qreal x, qreal y) { - QPointF old_pos = this->pos(); - QGraphicsItemGroup::setPos(x,y); - if (old_pos.x() != this->pos().x()) - emit xChanged(); - if (old_pos.y() != this->pos().y()) - emit yChanged(); + QPointF old_pos = this->pos(); + QGraphicsItemGroup::setPos(x,y); + if (old_pos.x() != this->pos().x()) + emit xChanged(); + if (old_pos.y() != this->pos().y()) + emit yChanged(); } /** - @brief ElementTextItemGroup::mousePressEvent - @param event + @brief ElementTextItemGroup::mousePressEvent + @param event */ void ElementTextItemGroup::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - if(event->button() == Qt::LeftButton) - { - m_first_move = true; - if(event->modifiers() & Qt::ControlModifier) - setSelected(!isSelected()); - } - - QGraphicsItemGroup::mousePressEvent(event); +{ + if(event->button() == Qt::LeftButton) + { + m_first_move = true; + if(event->modifiers() & Qt::ControlModifier) + setSelected(!isSelected()); + } + + QGraphicsItemGroup::mousePressEvent(event); } /** - @brief ElementTextItemGroup::mouseMoveEvent - @param event + @brief ElementTextItemGroup::mouseMoveEvent + @param event */ void ElementTextItemGroup::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if((event->buttons() & Qt::LeftButton) && (flags() & ItemIsMovable)) - { - if(diagram() && m_first_move) - diagram()->elementTextsMover().beginMovement(diagram(), - this); - - if(m_first_move) - { - m_initial_position = pos(); - if(parentElement()) - parentElement()->setHighlighted(true); - } - - QPointF current_parent_pos; - QPointF button_down_parent_pos; - current_parent_pos = mapToParent(mapFromScene(event->scenePos())); - button_down_parent_pos = mapToParent(mapFromScene(event->buttonDownScenePos(Qt::LeftButton))); - - QPointF new_pos = m_initial_position + current_parent_pos - button_down_parent_pos; - event->modifiers() == Qt::ControlModifier ? setPos(new_pos) : setPos(Diagram::snapToGrid(new_pos)); - - if(diagram()) - diagram()->elementTextsMover().continueMovement(event); - } else { - event->ignore(); - } - - if(m_first_move) - m_first_move = false; + if((event->buttons() & Qt::LeftButton) && (flags() & ItemIsMovable)) + { + if(diagram() && m_first_move) + diagram()->elementTextsMover().beginMovement(diagram(), + this); + + if(m_first_move) + { + m_initial_position = pos(); + if(parentElement()) + parentElement()->setHighlighted(true); + } + + QPointF current_parent_pos; + QPointF button_down_parent_pos; + current_parent_pos = mapToParent(mapFromScene(event->scenePos())); + button_down_parent_pos = mapToParent(mapFromScene(event->buttonDownScenePos(Qt::LeftButton))); + + QPointF new_pos = m_initial_position + current_parent_pos - button_down_parent_pos; + event->modifiers() == Qt::ControlModifier ? setPos(new_pos) : setPos(Diagram::snapToGrid(new_pos)); + + if(diagram()) + diagram()->elementTextsMover().continueMovement(event); + } else { + event->ignore(); + } + + if(m_first_move) + m_first_move = false; } /** - @brief ElementTextItemGroup::mouseReleaseEvent - @param event + @brief ElementTextItemGroup::mouseReleaseEvent + @param event */ void ElementTextItemGroup::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if(diagram()) - { - diagram()->elementTextsMover().endMovement(); - if(parentElement()) - parentElement()->setHighlighted(false); - } - - if(!(event->modifiers() & Qt::ControlModifier)) - QGraphicsItemGroup::mouseReleaseEvent(event); + if(diagram()) + { + diagram()->elementTextsMover().endMovement(); + if(parentElement()) + parentElement()->setHighlighted(false); + } + + if(!(event->modifiers() & Qt::ControlModifier)) + QGraphicsItemGroup::mouseReleaseEvent(event); } void ElementTextItemGroup::mouseDoubleClickEvent( - QGraphicsSceneMouseEvent *event) + QGraphicsSceneMouseEvent *event) { - if(m_slave_Xref_item) - { - if(m_slave_Xref_item->boundingRect().contains(mapToItem(m_slave_Xref_item, event->pos()))) - { - if(parentElement()->linkType() == Element::Slave && !parentElement()->linkedElements().isEmpty()) - { - m_slave_Xref_item->setDefaultTextColor(Qt::black); - Element *elmt = parentElement()->linkedElements().first(); - - //Unselect and ungrab mouse to prevent unwanted - //move when linked element is in the same scene of this. - setSelected(false); - ungrabMouse(); - - if(scene() != elmt->scene()) - elmt->diagram()->showMe(); - elmt->setSelected(true); - - //Zoom to the element - for(QGraphicsView *view : elmt->scene()->views()) - { - QRectF fit = elmt->sceneBoundingRect(); - fit.adjust(-200, -200, 200, 200); - view->fitInView(fit, Qt::KeepAspectRatioByExpanding); - } - } - } - } + if(m_slave_Xref_item) + { + if(m_slave_Xref_item->boundingRect().contains(mapToItem(m_slave_Xref_item, event->pos()))) + { + if(parentElement()->linkType() == Element::Slave && !parentElement()->linkedElements().isEmpty()) + { + m_slave_Xref_item->setDefaultTextColor(Qt::black); + Element *elmt = parentElement()->linkedElements().first(); + + //Unselect and ungrab mouse to prevent unwanted + //move when linked element is in the same scene of this. + setSelected(false); + ungrabMouse(); + + if(scene() != elmt->scene()) + elmt->diagram()->showMe(); + elmt->setSelected(true); + + //Zoom to the element + for(QGraphicsView *view : elmt->scene()->views()) + { + QRectF fit = elmt->sceneBoundingRect(); + fit.adjust(-200, -200, 200, 200); + view->fitInView(fit, Qt::KeepAspectRatioByExpanding); + } + } + } + } } /** - @brief ElementTextItemGroup::keyPressEvent - @param event + @brief ElementTextItemGroup::keyPressEvent + @param event */ void ElementTextItemGroup::keyPressEvent(QKeyEvent *event) -{ - if(event->modifiers() == Qt::ControlModifier) - { - if(event->key() == Qt::Key_Left && m_alignment != Qt::AlignLeft) - { - if(diagram()) - diagram()->undoStack().push(new AlignmentTextsGroupCommand(this, Qt::AlignLeft)); - else - setAlignment(Qt::AlignLeft); - } - else if (event->key() == Qt::Key_Up && m_alignment != Qt::AlignVCenter) - { - if(diagram()) - diagram()->undoStack().push(new AlignmentTextsGroupCommand(this, Qt::AlignVCenter)); - else - setAlignment(Qt::AlignVCenter); - } - else if (event->key() == Qt::Key_Right && m_alignment != Qt::AlignRight) - { - if(diagram()) - diagram()->undoStack().push(new AlignmentTextsGroupCommand(this, Qt::AlignRight)); - else - setAlignment(Qt::AlignRight); - } - } - event->ignore(); +{ + if(event->modifiers() == Qt::ControlModifier) + { + if(event->key() == Qt::Key_Left && m_alignment != Qt::AlignLeft) + { + if(diagram()) + diagram()->undoStack().push(new AlignmentTextsGroupCommand(this, Qt::AlignLeft)); + else + setAlignment(Qt::AlignLeft); + } + else if (event->key() == Qt::Key_Up && m_alignment != Qt::AlignVCenter) + { + if(diagram()) + diagram()->undoStack().push(new AlignmentTextsGroupCommand(this, Qt::AlignVCenter)); + else + setAlignment(Qt::AlignVCenter); + } + else if (event->key() == Qt::Key_Right && m_alignment != Qt::AlignRight) + { + if(diagram()) + diagram()->undoStack().push(new AlignmentTextsGroupCommand(this, Qt::AlignRight)); + else + setAlignment(Qt::AlignRight); + } + } + event->ignore(); } void ElementTextItemGroup::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - //The pos of the event is not in this item coordinate, - //but in child item hovered by the mouse, so we use the scene pos. - if(m_slave_Xref_item && - m_slave_Xref_item->boundingRect().contains(m_slave_Xref_item->mapFromScene(event->scenePos()))) - m_slave_Xref_item->setDefaultTextColor(Qt::blue); - - QGraphicsItemGroup::hoverEnterEvent(event); + //The pos of the event is not in this item coordinate, + //but in child item hovered by the mouse, so we use the scene pos. + if(m_slave_Xref_item && + m_slave_Xref_item->boundingRect().contains(m_slave_Xref_item->mapFromScene(event->scenePos()))) + m_slave_Xref_item->setDefaultTextColor(Qt::blue); + + QGraphicsItemGroup::hoverEnterEvent(event); } void ElementTextItemGroup::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - if(m_slave_Xref_item) - m_slave_Xref_item->setDefaultTextColor(Qt::black); - - QGraphicsItemGroup::hoverLeaveEvent(event); + if(m_slave_Xref_item) + m_slave_Xref_item->setDefaultTextColor(Qt::black); + + QGraphicsItemGroup::hoverLeaveEvent(event); } void ElementTextItemGroup::updateXref() { - if(m_parent_element->diagram()) - { - QETProject *project = m_parent_element->diagram()->project(); - - if(m_parent_element->linkType() == Element::Master && - !m_parent_element->linkedElements().isEmpty()) - { - - XRefProperties xrp = project->defaultXRefProperties(m_parent_element->kindInformations()["type"].toString()); - - if(xrp.snapTo() == XRefProperties::Label) - { - //At least one text owned by this group must be set with - //textFrom -> element info and element info name -> label - //for display a xref - for(DynamicElementTextItem *deti : texts()) - { - if(deti->textFrom() == DynamicElementTextItem::ElementInfo && - deti->infoName() == "label") - { - if(!m_Xref_item) - m_Xref_item = new CrossRefItem(m_parent_element, this); - m_Xref_item->autoPos(); - return; - } - } - } - } - else if(m_parent_element->linkType() == Element::Slave && - !m_parent_element->linkedElements().isEmpty()) - { - Element *master_elmt = m_parent_element->linkedElements().first(); - for(DynamicElementTextItem *deti : texts()) - { - if((deti->textFrom() == DynamicElementTextItem::ElementInfo && deti->infoName() == "label") || - (deti->textFrom() == DynamicElementTextItem::CompositeText && deti->compositeText().contains("%{label"))) - { - XRefProperties xrp = project->defaultXRefProperties(master_elmt->kindInformations()["type"].toString()); - QString xref_label = xrp.slaveLabel(); - xref_label = autonum::AssignVariables::formulaToLabel(xref_label, master_elmt->rSequenceStruct(), master_elmt->diagram(), master_elmt); - - if(!m_slave_Xref_item) - { - m_slave_Xref_item = new QGraphicsTextItem(xref_label, this); - m_slave_Xref_item->setFont(QETApp::diagramTextsFont(5)); - - m_update_slave_Xref_connection << connect(master_elmt, &Element::xChanged, this, &ElementTextItemGroup::updateXref); - m_update_slave_Xref_connection << connect(master_elmt, &Element::yChanged, this, &ElementTextItemGroup::updateXref); - m_update_slave_Xref_connection << connect(master_elmt, &Element::elementInfoChange, this, &ElementTextItemGroup::updateXref); - m_update_slave_Xref_connection << connect(project, &QETProject::projectDiagramsOrderChanged, this, &ElementTextItemGroup::updateXref); - m_update_slave_Xref_connection << connect(project, &QETProject::diagramRemoved, this, &ElementTextItemGroup::updateXref); - m_update_slave_Xref_connection << connect(project, &QETProject::XRefPropertiesChanged, this, &ElementTextItemGroup::updateXref); - } - else - m_slave_Xref_item->setPlainText(xref_label); - - adjustSlaveXrefPos(); - return; - } - } - - } - } + if(m_parent_element->diagram()) + { + QETProject *project = m_parent_element->diagram()->project(); + + if(m_parent_element->linkType() == Element::Master && + !m_parent_element->linkedElements().isEmpty()) + { + + XRefProperties xrp = project->defaultXRefProperties(m_parent_element->kindInformations()["type"].toString()); + + if(xrp.snapTo() == XRefProperties::Label) + { + //At least one text owned by this group must be set with + //textFrom -> element info and element info name -> label + //for display a xref + for(DynamicElementTextItem *deti : texts()) + { + if(deti->textFrom() == DynamicElementTextItem::ElementInfo && + deti->infoName() == "label") + { + if(!m_Xref_item) + m_Xref_item = new CrossRefItem(m_parent_element, this); + m_Xref_item->autoPos(); + return; + } + } + } + } + else if(m_parent_element->linkType() == Element::Slave && + !m_parent_element->linkedElements().isEmpty()) + { + Element *master_elmt = m_parent_element->linkedElements().first(); + for(DynamicElementTextItem *deti : texts()) + { + if((deti->textFrom() == DynamicElementTextItem::ElementInfo && deti->infoName() == "label") || + (deti->textFrom() == DynamicElementTextItem::CompositeText && deti->compositeText().contains("%{label"))) + { + XRefProperties xrp = project->defaultXRefProperties(master_elmt->kindInformations()["type"].toString()); + QString xref_label = xrp.slaveLabel(); + xref_label = autonum::AssignVariables::formulaToLabel(xref_label, master_elmt->rSequenceStruct(), master_elmt->diagram(), master_elmt); + + if(!m_slave_Xref_item) + { + m_slave_Xref_item = new QGraphicsTextItem(xref_label, this); + m_slave_Xref_item->setFont(QETApp::diagramTextsFont(5)); + + m_update_slave_Xref_connection << connect(master_elmt, &Element::xChanged, this, &ElementTextItemGroup::updateXref); + m_update_slave_Xref_connection << connect(master_elmt, &Element::yChanged, this, &ElementTextItemGroup::updateXref); + m_update_slave_Xref_connection << connect(master_elmt, &Element::elementInfoChange, this, &ElementTextItemGroup::updateXref); + m_update_slave_Xref_connection << connect(project, &QETProject::projectDiagramsOrderChanged, this, &ElementTextItemGroup::updateXref); + m_update_slave_Xref_connection << connect(project, &QETProject::diagramRemoved, this, &ElementTextItemGroup::updateXref); + m_update_slave_Xref_connection << connect(project, &QETProject::XRefPropertiesChanged, this, &ElementTextItemGroup::updateXref); + } + else + m_slave_Xref_item->setPlainText(xref_label); + + adjustSlaveXrefPos(); + return; + } + } + + } + } - - //There is no reason to have a xref, we delete it if exist - if(m_Xref_item) - { - delete m_Xref_item; - m_Xref_item = nullptr; - } - if(m_slave_Xref_item) - { - delete m_slave_Xref_item; - m_slave_Xref_item = nullptr; - m_update_slave_Xref_connection.clear(); - } + + //There is no reason to have a xref, we delete it if exist + if(m_Xref_item) + { + delete m_Xref_item; + m_Xref_item = nullptr; + } + if(m_slave_Xref_item) + { + delete m_slave_Xref_item; + m_slave_Xref_item = nullptr; + m_update_slave_Xref_connection.clear(); + } } void ElementTextItemGroup::adjustSlaveXrefPos() { - QRectF r = boundingRect(); - QPointF pos(r.center().x() - m_slave_Xref_item->boundingRect().width()/2, - r.bottom()); - m_slave_Xref_item->setPos(pos); + QRectF r = boundingRect(); + QPointF pos(r.center().x() - m_slave_Xref_item->boundingRect().width()/2, + r.bottom()); + m_slave_Xref_item->setPos(pos); } void ElementTextItemGroup::autoPos() { - int offset = 5; - - if(m_parent_element->linkType() == Element::Master) - { - if(!diagram()) - return; - - MasterElement *master = static_cast(m_parent_element); - XRefProperties xrp = diagram()->project()->defaultXRefProperties(master->kindInformations()["type"].toString()); - if(xrp.snapTo() == XRefProperties::Bottom) - { - QRectF rectXref = master->XrefBoundingRect(); - offset = xrp.offset() <= 40 ? 5 : xrp.offset(); - - offset += (int)rectXref.height(); - } - } - qreal r = rotation(); - centerToBottomDiagram(this, m_parent_element, offset); - //centerToBottomDiagram change the rotation of this group if needed, - //but setRotation is not a virtual function of QGraphicsItem, and the function centerToBottomDiagram - //work with a QGraphicsItem. So we emit the signal if rotation changed - if(rotation() != r) - emit rotationChanged(rotation()); + int offset = 5; + + if(m_parent_element->linkType() == Element::Master) + { + if(!diagram()) + return; + + MasterElement *master = static_cast(m_parent_element); + XRefProperties xrp = diagram()->project()->defaultXRefProperties(master->kindInformations()["type"].toString()); + if(xrp.snapTo() == XRefProperties::Bottom) + { + QRectF rectXref = master->XrefBoundingRect(); + offset = xrp.offset() <= 40 ? 5 : xrp.offset(); + + offset += (int)rectXref.height(); + } + } + qreal r = rotation(); + centerToBottomDiagram(this, m_parent_element, offset); + //centerToBottomDiagram change the rotation of this group if needed, + //but setRotation is not a virtual function of QGraphicsItem, and the function centerToBottomDiagram + //work with a QGraphicsItem. So we emit the signal if rotation changed + if(rotation() != r) + emit rotationChanged(rotation()); } diff --git a/sources/qetgraphicsitem/elementtextitemgroup.h b/sources/qetgraphicsitem/elementtextitemgroup.h index 373ab7161..ae01c165d 100644 --- a/sources/qetgraphicsitem/elementtextitemgroup.h +++ b/sources/qetgraphicsitem/elementtextitemgroup.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef ELEMENTTEXTITEMGROUP_H #define ELEMENTTEXTITEMGROUP_H @@ -28,98 +28,98 @@ class Diagram; class CrossRefItem; /** - @brief The ElementTextItemGroup class - This class represent a group of element text - Texts in the group can be aligned left / center /right + @brief The ElementTextItemGroup class + This class represent a group of element text + Texts in the group can be aligned left / center /right */ class ElementTextItemGroup : public QObject, public QGraphicsItemGroup { - Q_OBJECT - - Q_PROPERTY(QPointF pos READ pos WRITE setPos) - Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged) - Q_PROPERTY(int verticalAdjustment READ verticalAdjustment WRITE setVerticalAdjustment NOTIFY verticalAdjustmentChanged) - Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) - Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) - Q_PROPERTY(bool holdToBottomPage READ holdToBottomPage WRITE setHoldToBottomPage NOTIFY holdToBottomPageChanged) - Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged) - - public: - signals: - void rotationChanged(qreal); - void verticalAdjustmentChanged(int); - void alignmentChanged(Qt::Alignment); - void nameChanged(QString); - void holdToBottomPageChanged(bool); - void xChanged(); - void yChanged(); - void frameChanged(bool frame); - - public: - ElementTextItemGroup(const QString &name, Element *parent); - ~ElementTextItemGroup() override; - void addToGroup(QGraphicsItem *item); - void removeFromGroup(QGraphicsItem *item); - void blockAlignmentUpdate(bool block); - - void setAlignment(Qt::Alignment alignement); - Qt::Alignment alignment() const; - void updateAlignment(); - int verticalAdjustment() const {return m_vertical_adjustment;} - void setVerticalAdjustment(int v); - void setName(QString name); - QString name() const {return m_name;} - void setHoldToBottomPage(bool hold); - bool holdToBottomPage() const {return m_hold_to_bottom_of_page;} - void setFrame(const bool frame); - bool frame() const; - QList texts() const; - Diagram *diagram() const; - Element *parentElement() const; - - QDomElement toXml(QDomDocument &dom_document) const; - void fromXml(QDomElement &dom_element); - static QString xmlTaggName() {return QString("texts_group");} - - void paint(QPainter *painter, - const QStyleOptionGraphicsItem *option, - QWidget *widget) override; - QRectF boundingRect() const override; - void setRotation(qreal angle); - void setPos(const QPointF &pos); - void setPos(qreal x, qreal y); - - protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent( - QGraphicsSceneMouseEvent *event) override; - void mouseDoubleClickEvent( - QGraphicsSceneMouseEvent *event) override; - void keyPressEvent(QKeyEvent *event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - - private: - void updateXref(); - void adjustSlaveXrefPos(); - void autoPos(); + Q_OBJECT + + Q_PROPERTY(QPointF pos READ pos WRITE setPos) + Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged) + Q_PROPERTY(int verticalAdjustment READ verticalAdjustment WRITE setVerticalAdjustment NOTIFY verticalAdjustmentChanged) + Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) + Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) + Q_PROPERTY(bool holdToBottomPage READ holdToBottomPage WRITE setHoldToBottomPage NOTIFY holdToBottomPageChanged) + Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged) + + public: + signals: + void rotationChanged(qreal); + void verticalAdjustmentChanged(int); + void alignmentChanged(Qt::Alignment); + void nameChanged(QString); + void holdToBottomPageChanged(bool); + void xChanged(); + void yChanged(); + void frameChanged(bool frame); + + public: + ElementTextItemGroup(const QString &name, Element *parent); + ~ElementTextItemGroup() override; + void addToGroup(QGraphicsItem *item); + void removeFromGroup(QGraphicsItem *item); + void blockAlignmentUpdate(bool block); + + void setAlignment(Qt::Alignment alignement); + Qt::Alignment alignment() const; + void updateAlignment(); + int verticalAdjustment() const {return m_vertical_adjustment;} + void setVerticalAdjustment(int v); + void setName(QString name); + QString name() const {return m_name;} + void setHoldToBottomPage(bool hold); + bool holdToBottomPage() const {return m_hold_to_bottom_of_page;} + void setFrame(const bool frame); + bool frame() const; + QList texts() const; + Diagram *diagram() const; + Element *parentElement() const; + + QDomElement toXml(QDomDocument &dom_document) const; + void fromXml(QDomElement &dom_element); + static QString xmlTaggName() {return QString("texts_group");} + + void paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, + QWidget *widget) override; + QRectF boundingRect() const override; + void setRotation(qreal angle); + void setPos(const QPointF &pos); + void setPos(qreal x, qreal y); + + protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent( + QGraphicsSceneMouseEvent *event) override; + void mouseDoubleClickEvent( + QGraphicsSceneMouseEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + + private: + void updateXref(); + void adjustSlaveXrefPos(); + void autoPos(); - private: - Qt::Alignment m_alignment = Qt::AlignJustify; - QString m_name; - bool m_first_move = true, - m_hold_to_bottom_of_page = false, - m_block_alignment_update = false, - m_frame = false; - QPointF m_initial_position; - int m_vertical_adjustment = 0; - CrossRefItem *m_Xref_item = nullptr; - Element *m_parent_element = nullptr; - QList m_update_slave_Xref_connection; - QGraphicsTextItem *m_slave_Xref_item = nullptr; - QMetaObject::Connection m_XrefChanged_timer, - m_linked_changed_timer; + private: + Qt::Alignment m_alignment = Qt::AlignJustify; + QString m_name; + bool m_first_move = true, + m_hold_to_bottom_of_page = false, + m_block_alignment_update = false, + m_frame = false; + QPointF m_initial_position; + int m_vertical_adjustment = 0; + CrossRefItem *m_Xref_item = nullptr; + Element *m_parent_element = nullptr; + QList m_update_slave_Xref_connection; + QGraphicsTextItem *m_slave_Xref_item = nullptr; + QMetaObject::Connection m_XrefChanged_timer, + m_linked_changed_timer; }; #endif // ELEMENTTEXTITEMGROUP_H diff --git a/sources/qetgraphicsitem/independenttextitem.cpp b/sources/qetgraphicsitem/independenttextitem.cpp index 7868f543c..9f93a8166 100644 --- a/sources/qetgraphicsitem/independenttextitem.cpp +++ b/sources/qetgraphicsitem/independenttextitem.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "independenttextitem.h" #include "qet.h" @@ -25,24 +25,24 @@ #include /** - Constructeur - @param parent_diagram Le schema auquel est rattache le champ de texte + Constructeur + @param parent_diagram Le schema auquel est rattache le champ de texte */ IndependentTextItem::IndependentTextItem() : - DiagramTextItem(nullptr) + DiagramTextItem(nullptr) { - setFont(QETApp::indiTextsItemFont()); - QSettings settings; - setRotation(settings.value("diagrameditor/independent_text_rotation", 0).toInt()); + setFont(QETApp::indiTextsItemFont()); + QSettings settings; + setRotation(settings.value("diagrameditor/independent_text_rotation", 0).toInt()); } /** - @brief IndependentTextItem::IndependentTextItem - Constructeur - @param text Le texte affiche par le champ de texte + @brief IndependentTextItem::IndependentTextItem + Constructeur + @param text Le texte affiche par le champ de texte */ IndependentTextItem::IndependentTextItem(const QString &text) : - DiagramTextItem(text, nullptr) + DiagramTextItem(text, nullptr) {} /// Destructeur @@ -51,43 +51,43 @@ IndependentTextItem::~IndependentTextItem() } /** - Permet de lire le texte a mettre dans le champ a partir d'un element XML. - Cette methode se base sur la position du champ pour assigner ou non la - valeur a ce champ. - @param e L'element XML representant le champ de texte + Permet de lire le texte a mettre dans le champ a partir d'un element XML. + Cette methode se base sur la position du champ pour assigner ou non la + valeur a ce champ. + @param e L'element XML representant le champ de texte */ void IndependentTextItem::fromXml(const QDomElement &e) { - setPos(e.attribute("x").toDouble(), e.attribute("y").toDouble()); - setHtml(e.attribute("text")); - setRotation(e.attribute("rotation").toDouble()); - if (e.hasAttribute("font")) - { - QFont font; - font.fromString(e.attribute("font")); - setFont(font); - } + setPos(e.attribute("x").toDouble(), e.attribute("y").toDouble()); + setHtml(e.attribute("text")); + setRotation(e.attribute("rotation").toDouble()); + if (e.hasAttribute("font")) + { + QFont font; + font.fromString(e.attribute("font")); + setFont(font); + } } /** - @param document Le document XML a utiliser - @return L'element XML representant ce champ de texte + @param document Le document XML a utiliser + @return L'element XML representant ce champ de texte */ QDomElement IndependentTextItem::toXml(QDomDocument &document) const { - QDomElement result = document.createElement("input"); - result.setAttribute("x", QString("%1").arg(pos().x())); - result.setAttribute("y", QString("%1").arg(pos().y())); - result.setAttribute("text", toHtml()); - result.setAttribute("rotation", QString::number(QET::correctAngle(rotation()))); - result.setAttribute("font", font().toString()); - - return(result); + QDomElement result = document.createElement("input"); + result.setAttribute("x", QString("%1").arg(pos().x())); + result.setAttribute("y", QString("%1").arg(pos().y())); + result.setAttribute("text", toHtml()); + result.setAttribute("rotation", QString::number(QET::correctAngle(rotation()))); + result.setAttribute("font", font().toString()); + + return(result); } void IndependentTextItem::focusOutEvent(QFocusEvent *event) { - DiagramTextItem::focusOutEvent(event); - if (diagram() && (m_previous_html_text != this->toHtml())) { - diagram()->undoStack().push(new ChangeDiagramTextCommand(this, m_previous_html_text, this->toHtml())); - } + DiagramTextItem::focusOutEvent(event); + if (diagram() && (m_previous_html_text != this->toHtml())) { + diagram()->undoStack().push(new ChangeDiagramTextCommand(this, m_previous_html_text, this->toHtml())); + } } diff --git a/sources/qetgraphicsitem/qetgraphicsitem.cpp b/sources/qetgraphicsitem/qetgraphicsitem.cpp index 059182e20..8c892d53c 100644 --- a/sources/qetgraphicsitem/qetgraphicsitem.cpp +++ b/sources/qetgraphicsitem/qetgraphicsitem.cpp @@ -1,156 +1,156 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "qetgraphicsitem.h" #include "diagram.h" /** - @brief QetGraphicsItem::QetGraphicsItem - Default constructor - @param parent : Parent Item + @brief QetGraphicsItem::QetGraphicsItem + Default constructor + @param parent : Parent Item */ QetGraphicsItem::QetGraphicsItem(QGraphicsItem *parent): - QGraphicsObject(parent), - is_movable_(true), - m_first_move(true), - snap_to_grid_(true) + QGraphicsObject(parent), + is_movable_(true), + m_first_move(true), + snap_to_grid_(true) {} QetGraphicsItem::~QetGraphicsItem() {} /** - @brief QetGraphicsItem::diagram + @brief QetGraphicsItem::diagram *return the diagram of this item */ Diagram* QetGraphicsItem::diagram() const{ - return(qobject_cast(scene())); + return(qobject_cast(scene())); } /** - @brief QetGraphicsItem::setPos + @brief QetGraphicsItem::setPos *set the position of the item to p - @param p the new position of item + @param p the new position of item */ void QetGraphicsItem::setPos(const QPointF &p) { - QPointF pp = Diagram::snapToGrid(p); - if (pp == pos() || !is_movable_) - return; - QGraphicsItem::setPos(pp); + QPointF pp = Diagram::snapToGrid(p); + if (pp == pos() || !is_movable_) + return; + QGraphicsItem::setPos(pp); } /** - @brief QetGraphicsItem::setPos + @brief QetGraphicsItem::setPos *set the position of the item - @param x new abscisse of item - @param y new ordonne of item + @param x new abscisse of item + @param y new ordonne of item */ void QetGraphicsItem::setPos(qreal x, qreal y) { - setPos(QPointF(x, y)); + setPos(QPointF(x, y)); } /** - @brief QetGraphicsItem::state - @return the current state of this item + @brief QetGraphicsItem::state + @return the current state of this item */ QET::GraphicsItemState QetGraphicsItem::state() const { - return m_state; + return m_state; } /** - @brief QetGraphicsItem::mousePressEvent + @brief QetGraphicsItem::mousePressEvent *handle the mouse click - @param event + @param event */ void QetGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) - { - m_first_move = true; - if (event->modifiers() & Qt::ControlModifier) { - setSelected(!isSelected()); - } - } + if (event->button() == Qt::LeftButton) + { + m_first_move = true; + if (event->modifiers() & Qt::ControlModifier) { + setSelected(!isSelected()); + } + } - QGraphicsItem::mousePressEvent(event); + QGraphicsItem::mousePressEvent(event); } /** - @brief QetGraphicsItem::mouseDoubleClickEvent + @brief QetGraphicsItem::mouseDoubleClickEvent *handle the mouse double click - @param event + @param event */ void QetGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { - editProperty(); - event->accept(); + editProperty(); + event->accept(); } /** - @brief QetGraphicsItem::mouseMoveEvent + @brief QetGraphicsItem::mouseMoveEvent *handle mouse movement - @param event + @param event */ void QetGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (isSelected() && event->buttons() & Qt::LeftButton) - { - //Item is moving - if(diagram() && m_first_move) { - //It's the first movement, we signal it to parent diagram - diagram()->elementsMover().beginMovement(diagram(), this); - } + if (isSelected() && event->buttons() & Qt::LeftButton) + { + //Item is moving + if(diagram() && m_first_move) { + //It's the first movement, we signal it to parent diagram + diagram()->elementsMover().beginMovement(diagram(), this); + } - //we apply the mouse movement - QPointF old_pos = pos(); - if (m_first_move) { - m_mouse_to_origin_movement = old_pos - event -> buttonDownScenePos(Qt::LeftButton); - } - QPointF expected_pos = event->scenePos() + m_mouse_to_origin_movement; - setPos(expected_pos); // setPos() will snap the expected position to the grid + //we apply the mouse movement + QPointF old_pos = pos(); + if (m_first_move) { + m_mouse_to_origin_movement = old_pos - event -> buttonDownScenePos(Qt::LeftButton); + } + QPointF expected_pos = event->scenePos() + m_mouse_to_origin_movement; + setPos(expected_pos); // setPos() will snap the expected position to the grid - //we calcul the real movement apply by setPos() - QPointF effective_movement = pos() - old_pos; - if (diagram()) { - //we signal the real movement apply to diagram, - //who he apply to other selected item - diagram()->elementsMover().continueMovement(effective_movement); - } - event->accept(); - } - else { - event->ignore(); - } + //we calcul the real movement apply by setPos() + QPointF effective_movement = pos() - old_pos; + if (diagram()) { + //we signal the real movement apply to diagram, + //who he apply to other selected item + diagram()->elementsMover().continueMovement(effective_movement); + } + event->accept(); + } + else { + event->ignore(); + } - if (m_first_move) { - m_first_move = false; - } + if (m_first_move) { + m_first_move = false; + } } /** - @brief QetGraphicsItem::mouseReleaseEvent - handle mouse release click - @param event + @brief QetGraphicsItem::mouseReleaseEvent + handle mouse release click + @param event */ void QetGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (diagram()) { - diagram()->elementsMover().endMovement(); - event->accept(); - } + if (diagram()) { + diagram()->elementsMover().endMovement(); + event->accept(); + } } diff --git a/sources/qetgraphicsitem/qetgraphicsitem.h b/sources/qetgraphicsitem/qetgraphicsitem.h index eba811c35..b77d795bf 100644 --- a/sources/qetgraphicsitem/qetgraphicsitem.h +++ b/sources/qetgraphicsitem/qetgraphicsitem.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef QETGRAPHICSITEM_H #define QETGRAPHICSITEM_H @@ -25,41 +25,41 @@ class Diagram; class QetGraphicsItem : public QGraphicsObject { - Q_OBJECT + Q_OBJECT - public: - //constructor destructor - QetGraphicsItem(QGraphicsItem *parent = nullptr); - ~QetGraphicsItem() override = 0; + public: + //constructor destructor + QetGraphicsItem(QGraphicsItem *parent = nullptr); + ~QetGraphicsItem() override = 0; - //public methode - Diagram *diagram () const; - virtual void setPos (const QPointF &p); - virtual void setPos (qreal x, qreal y); + //public methode + Diagram *diagram () const; + virtual void setPos (const QPointF &p); + virtual void setPos (qreal x, qreal y); - virtual bool isMovable () const + virtual bool isMovable () const {return is_movable_;} - virtual void setMovable (bool movable) { is_movable_ = movable;} + virtual void setMovable (bool movable) { is_movable_ = movable;} - virtual void editProperty () {} - virtual QString name ()const + virtual void editProperty () {} + virtual QString name ()const {return QString("");} - - QET::GraphicsItemState state() const; + + QET::GraphicsItemState state() const; - //protected method - protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; - void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + //protected method + protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - protected: - bool is_movable_; - bool m_first_move; - bool snap_to_grid_; - QPointF m_mouse_to_origin_movement; - QET::GraphicsItemState m_state = QET:: GIOK; + protected: + bool is_movable_; + bool m_first_move; + bool snap_to_grid_; + QPointF m_mouse_to_origin_movement; + QET::GraphicsItemState m_state = QET:: GIOK; }; diff --git a/sources/qetgraphicsitem/qetshapeitem.cpp b/sources/qetgraphicsitem/qetshapeitem.cpp index b7a79f9e8..2d727b10e 100644 --- a/sources/qetgraphicsitem/qetshapeitem.cpp +++ b/sources/qetgraphicsitem/qetshapeitem.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "qetshapeitem.h" #include "createdxf.h" @@ -28,994 +28,994 @@ #include "qeticons.h" /** - @brief QetShapeItem::QetShapeItem - Constructor of shape item. point 1 and 2 must be in scene coordinate - @param p1 first point - @param p2 second point - @param type type of item (line, rectangle, ellipse) - @param parent parent item + @brief QetShapeItem::QetShapeItem + Constructor of shape item. point 1 and 2 must be in scene coordinate + @param p1 first point + @param p2 second point + @param type type of item (line, rectangle, ellipse) + @param parent parent item */ QetShapeItem::QetShapeItem(QPointF p1, QPointF p2, ShapeType type, QGraphicsItem *parent) : - QetGraphicsItem(parent), - m_shapeType(type), - m_P1 (p1), - m_P2 (p2), - m_hovered(false) + QetGraphicsItem(parent), + m_shapeType(type), + m_P1 (p1), + m_P2 (p2), + m_hovered(false) { - if (type == Polygon) m_polygon << m_P1 << m_P2; - setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsGeometryChanges); - setAcceptHoverEvents(true); - m_pen.setStyle(Qt::SolidLine); - //ensure handlers are always above this item - connect(this, &QetShapeItem::zChanged, [this]() - { - for(QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setZValue(this->zValue()+1); - }); + if (type == Polygon) m_polygon << m_P1 << m_P2; + setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsGeometryChanges); + setAcceptHoverEvents(true); + m_pen.setStyle(Qt::SolidLine); + //ensure handlers are always above this item + connect(this, &QetShapeItem::zChanged, [this]() + { + for(QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setZValue(this->zValue()+1); + }); - m_insert_point = new QAction(tr("Ajouter un point"), this); - m_insert_point->setIcon(QET::Icons::Add); - connect(m_insert_point, &QAction::triggered, this, &QetShapeItem::insertPoint); - m_remove_point = new QAction(tr("Supprimer ce point"), this); - m_remove_point->setIcon(QET::Icons::Remove); - connect(m_remove_point, &QAction::triggered, this, &QetShapeItem::removePoint); + m_insert_point = new QAction(tr("Ajouter un point"), this); + m_insert_point->setIcon(QET::Icons::Add); + connect(m_insert_point, &QAction::triggered, this, &QetShapeItem::insertPoint); + m_remove_point = new QAction(tr("Supprimer ce point"), this); + m_remove_point->setIcon(QET::Icons::Remove); + connect(m_remove_point, &QAction::triggered, this, &QetShapeItem::removePoint); } QetShapeItem::~QetShapeItem() { - if(!m_handler_vector.isEmpty()) - qDeleteAll(m_handler_vector); + if(!m_handler_vector.isEmpty()) + qDeleteAll(m_handler_vector); } /** - @brief QetShapeItem::setPen - Set the pen to use for draw the shape - @param pen + @brief QetShapeItem::setPen + Set the pen to use for draw the shape + @param pen */ void QetShapeItem::setPen(const QPen &pen) { - if (m_pen == pen) return; - m_pen = pen; - update(); - emit penChanged(); + if (m_pen == pen) return; + m_pen = pen; + update(); + emit penChanged(); } /** - @brief QetShapeItem::setBrush - Set the brush to use for the fill the shape - @param brush + @brief QetShapeItem::setBrush + Set the brush to use for the fill the shape + @param brush */ void QetShapeItem::setBrush(const QBrush &brush) { - if (m_brush == brush) return; - m_brush = brush; - update(); - emit brushChanged(); + if (m_brush == brush) return; + m_brush = brush; + update(); + emit brushChanged(); } /** - @brief QetShapeItem::setP2 - Set the second point of this item. - If this item is a polyline, - the last point of the polyline is replaced by P2. - @param P2 + @brief QetShapeItem::setP2 + Set the second point of this item. + If this item is a polyline, + the last point of the polyline is replaced by P2. + @param P2 */ void QetShapeItem::setP2(const QPointF &P2) { - if (m_shapeType == Polygon && m_polygon.last() != P2) - { - prepareGeometryChange(); - m_polygon.replace(m_polygon.size()-1, P2); - } - else if (P2 != m_P2) - { - prepareGeometryChange(); - m_P2 = P2; - } + if (m_shapeType == Polygon && m_polygon.last() != P2) + { + prepareGeometryChange(); + m_polygon.replace(m_polygon.size()-1, P2); + } + else if (P2 != m_P2) + { + prepareGeometryChange(); + m_P2 = P2; + } } /** - @brief QetShapeItem::setLine - Set item geometry to line (only available for line shape) - @param line - @return : true when shape is a Line, else false + @brief QetShapeItem::setLine + Set item geometry to line (only available for line shape) + @param line + @return : true when shape is a Line, else false */ bool QetShapeItem::setLine(const QLineF &line) { - if (Q_UNLIKELY(m_shapeType != Line)) return false; - prepareGeometryChange(); - m_P1 = line.p1(); - m_P2 = line.p2(); - adjusteHandlerPos(); - return true; + if (Q_UNLIKELY(m_shapeType != Line)) return false; + prepareGeometryChange(); + m_P1 = line.p1(); + m_P2 = line.p2(); + adjusteHandlerPos(); + return true; } /** - @brief QetShapeItem::setRect - Set this item geometry to rect (only available if shape is a rectangle or an ellipse) - @param rect : new rect - @return : true when shape is rectangle or ellipse, else false + @brief QetShapeItem::setRect + Set this item geometry to rect (only available if shape is a rectangle or an ellipse) + @param rect : new rect + @return : true when shape is rectangle or ellipse, else false */ bool QetShapeItem::setRect(const QRectF &rect) { - if (Q_LIKELY(m_shapeType == Rectangle || m_shapeType == Ellipse)) - { - prepareGeometryChange(); - m_P1 = rect.topLeft(); - m_P2 = rect.bottomRight(); - adjusteHandlerPos(); - return true; - } + if (Q_LIKELY(m_shapeType == Rectangle || m_shapeType == Ellipse)) + { + prepareGeometryChange(); + m_P1 = rect.topLeft(); + m_P2 = rect.bottomRight(); + adjusteHandlerPos(); + return true; + } - return false; + return false; } /** - @brief QetShapeItem::setPolygon - Set this item geometry to polygon (only available if shape is a polyline) - @param polygon : new polygon - @return true if item is polygon, else false + @brief QetShapeItem::setPolygon + Set this item geometry to polygon (only available if shape is a polyline) + @param polygon : new polygon + @return true if item is polygon, else false */ bool QetShapeItem::setPolygon(const QPolygonF &polygon) { - if (Q_UNLIKELY(m_shapeType != Polygon)) { - return false; - } - prepareGeometryChange(); - m_polygon = polygon; - adjusteHandlerPos(); - return true; + if (Q_UNLIKELY(m_shapeType != Polygon)) { + return false; + } + prepareGeometryChange(); + m_polygon = polygon; + adjusteHandlerPos(); + return true; } /** - @brief QetShapeItem::setClosed - Close this item, have effect only if this item is a polygon. - @param close + @brief QetShapeItem::setClosed + Close this item, have effect only if this item is a polygon. + @param close */ void QetShapeItem::setClosed(bool close) { - if (m_shapeType == Polygon && close != m_closed) - { - prepareGeometryChange(); - m_closed = close; - emit closeChanged(); - } + if (m_shapeType == Polygon && close != m_closed) + { + prepareGeometryChange(); + m_closed = close; + emit closeChanged(); + } } void QetShapeItem::setXRadius(qreal X) { - m_xRadius = X; - update(); - adjusteHandlerPos(); - emit XRadiusChanged(); + m_xRadius = X; + update(); + adjusteHandlerPos(); + emit XRadiusChanged(); } void QetShapeItem::setYRadius(qreal Y) { - m_yRadius = Y; - update(); - adjusteHandlerPos(); - emit YRadiusChanged(); + m_yRadius = Y; + update(); + adjusteHandlerPos(); + emit YRadiusChanged(); } /** - @brief QetShapeItem::pointCount - @return the number of point in the polygon + @brief QetShapeItem::pointCount + @return the number of point in the polygon */ int QetShapeItem::pointsCount() const { - return m_polygon.size(); + return m_polygon.size(); } /** - @brief QetShapeItem::setNextPoint - Add a new point to the curent polygon - @param P the new point. + @brief QetShapeItem::setNextPoint + Add a new point to the curent polygon + @param P the new point. */ void QetShapeItem::setNextPoint(QPointF P) { - prepareGeometryChange(); - m_polygon.append(Diagram::snapToGrid(P)); + prepareGeometryChange(); + m_polygon.append(Diagram::snapToGrid(P)); } /** - @brief QetShapeItem::removePoints - Number of point to remove on the polygon - If number is superior to number of polygon points-2, - all points of polygon will be removed except - the first two (minimum point for the polygon); + @brief QetShapeItem::removePoints + Number of point to remove on the polygon + If number is superior to number of polygon points-2, + all points of polygon will be removed except + the first two (minimum point for the polygon); */ void QetShapeItem::removePoints(int number) { - if (pointsCount() == 2 || number < 1) return; - if ((pointsCount()-2) < number) - number = pointsCount() - 2; + if (pointsCount() == 2 || number < 1) return; + if ((pointsCount()-2) < number) + number = pointsCount() - 2; - int i = 0; - do - { - i++; - prepareGeometryChange(); - m_polygon.pop_back(); - setTransformOriginPoint(boundingRect().center()); + int i = 0; + do + { + i++; + prepareGeometryChange(); + m_polygon.pop_back(); + setTransformOriginPoint(boundingRect().center()); - } while (i < number); + } while (i < number); } /** - @brief QetShapeItem::boundingRect - @return the bounding rect of this item + @brief QetShapeItem::boundingRect + @return the bounding rect of this item */ QRectF QetShapeItem::boundingRect() const { - return shape().boundingRect().adjusted(-6, -6, 6, 6); + return shape().boundingRect().adjusted(-6, -6, 6, 6); } /** - @brief QetShapeItem::shape - @return the shape of this item + @brief QetShapeItem::shape + @return the shape of this item */ QPainterPath QetShapeItem::shape() const { - QPainterPath path; + QPainterPath path; - switch (m_shapeType) - { - case Line: - path.moveTo(m_P1); - path.lineTo(m_P2); - break; - case Rectangle: - path.addRoundedRect( - QRectF(m_P1, m_P2), - m_xRadius, - m_yRadius); - break; - case Ellipse: - path.addEllipse(QRectF(m_P1, m_P2)); - break; - case Polygon: - path.addPolygon(m_polygon); - if (m_closed) { - path.closeSubpath(); - } - break; - } + switch (m_shapeType) + { + case Line: + path.moveTo(m_P1); + path.lineTo(m_P2); + break; + case Rectangle: + path.addRoundedRect( + QRectF(m_P1, m_P2), + m_xRadius, + m_yRadius); + break; + case Ellipse: + path.addEllipse(QRectF(m_P1, m_P2)); + break; + case Polygon: + path.addPolygon(m_polygon); + if (m_closed) { + path.closeSubpath(); + } + break; + } - QPainterPathStroker pps; - pps.setWidth(m_hovered? m_pen.widthF()+10 : m_pen.widthF()); - pps.setJoinStyle(Qt::RoundJoin); - path = pps.createStroke(path); + QPainterPathStroker pps; + pps.setWidth(m_hovered? m_pen.widthF()+10 : m_pen.widthF()); + pps.setJoinStyle(Qt::RoundJoin); + path = pps.createStroke(path); - return (path); + return (path); } /** - @brief QetShapeItem::paint - Paint this item - @param painter - @param option - @param widget + @brief QetShapeItem::paint + Paint this item + @param painter + @param option + @param widget */ void QetShapeItem::paint( - QPainter *painter, - const QStyleOptionGraphicsItem *option, - QWidget *widget) + QPainter *painter, + const QStyleOptionGraphicsItem *option, + QWidget *widget) { - Q_UNUSED(option) - Q_UNUSED(widget) + Q_UNUSED(option) + Q_UNUSED(widget) - painter->save(); - painter->setRenderHint(QPainter::Antialiasing, true); - painter->setPen(m_pen); - painter->setBrush(m_brush); + painter->save(); + painter->setRenderHint(QPainter::Antialiasing, true); + painter->setPen(m_pen); + painter->setBrush(m_brush); - //Draw hovered shadow - if (m_hovered) - { - painter->save(); - QColor color(Qt::darkBlue); - color.setAlpha(50); - painter -> setBrush (QBrush (color)); - painter -> setPen (Qt::NoPen); - painter -> drawPath (shape()); - painter -> restore (); - } + //Draw hovered shadow + if (m_hovered) + { + painter->save(); + QColor color(Qt::darkBlue); + color.setAlpha(50); + painter -> setBrush (QBrush (color)); + painter -> setPen (Qt::NoPen); + painter -> drawPath (shape()); + painter -> restore (); + } - switch (m_shapeType) - { - case Line: painter->drawLine(QLineF(m_P1, m_P2)); break; - case Rectangle: painter->drawRoundedRect(QRectF(m_P1, m_P2), - m_xRadius, - m_yRadius); break; - case Ellipse: painter->drawEllipse(QRectF(m_P1, m_P2)); break; - case Polygon: m_closed ? painter->drawPolygon(m_polygon) - : painter->drawPolyline(m_polygon); break; - } + switch (m_shapeType) + { + case Line: painter->drawLine(QLineF(m_P1, m_P2)); break; + case Rectangle: painter->drawRoundedRect(QRectF(m_P1, m_P2), + m_xRadius, + m_yRadius); break; + case Ellipse: painter->drawEllipse(QRectF(m_P1, m_P2)); break; + case Polygon: m_closed ? painter->drawPolygon(m_polygon) + : painter->drawPolyline(m_polygon); break; + } - painter->restore(); + painter->restore(); } /** - @brief QetShapeItem::hoverEnterEvent - Handle hover enter event - @param event + @brief QetShapeItem::hoverEnterEvent + Handle hover enter event + @param event */ void QetShapeItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - m_hovered = true; - QetGraphicsItem::hoverEnterEvent(event); + m_hovered = true; + QetGraphicsItem::hoverEnterEvent(event); } /** - @brief QetShapeItem::hoverLeaveEvent - Handle hover leave event - @param event + @brief QetShapeItem::hoverLeaveEvent + Handle hover leave event + @param event */ void QetShapeItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - m_hovered = false; - QetGraphicsItem::hoverLeaveEvent(event); + m_hovered = false; + QetGraphicsItem::hoverLeaveEvent(event); } void QetShapeItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - event->ignore(); - QetGraphicsItem::mousePressEvent(event); + event->ignore(); + QetGraphicsItem::mousePressEvent(event); - if (event->button() == Qt::LeftButton) { - switchResizeMode(); - event->accept(); - } + if (event->button() == Qt::LeftButton) { + switchResizeMode(); + event->accept(); + } } /** - @brief QetShapeItem::itemChange - @param change - @param value - @return + @brief QetShapeItem::itemChange + @param change + @param value + @return */ QVariant QetShapeItem::itemChange(QGraphicsItem::GraphicsItemChange change, - const QVariant &value) + const QVariant &value) { - if (change == ItemSelectedHasChanged) - { - if (value.toBool() == true) { - //If this is selected, wa add handlers. - addHandler(); - } - else //Else this is deselected, we remove handlers - { - if(!m_handler_vector.isEmpty()) - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - } - m_resize_mode = 1; - } - } - else if (change == ItemPositionHasChanged) { - adjusteHandlerPos(); - } - else if (change == ItemSceneHasChanged) - { - if (!scene()) //This is removed from scene, then we deselect this, and so, the handlers is also removed. - { - setSelected(false); - } - } + if (change == ItemSelectedHasChanged) + { + if (value.toBool() == true) { + //If this is selected, wa add handlers. + addHandler(); + } + else //Else this is deselected, we remove handlers + { + if(!m_handler_vector.isEmpty()) + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + } + m_resize_mode = 1; + } + } + else if (change == ItemPositionHasChanged) { + adjusteHandlerPos(); + } + else if (change == ItemSceneHasChanged) + { + if (!scene()) //This is removed from scene, then we deselect this, and so, the handlers is also removed. + { + setSelected(false); + } + } - return QGraphicsItem::itemChange(change, value); + return QGraphicsItem::itemChange(change, value); } /** - @brief QetShapeItem::sceneEventFilter - @param watched - @param event - @return + @brief QetShapeItem::sceneEventFilter + @param watched + @param event + @return */ bool QetShapeItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - //Watched must be an handler - if(watched->type() == QetGraphicsHandlerItem::Type) - { - QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); + //Watched must be an handler + if(watched->type() == QetGraphicsHandlerItem::Type) + { + QetGraphicsHandlerItem *qghi = qgraphicsitem_cast(watched); - if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize - { - m_vector_index = m_handler_vector.indexOf(qghi); - if (m_vector_index != -1) - { - if(event->type() == QEvent::GraphicsSceneMousePress) //Click - { - handlerMousePressEvent(); - return true; - } - else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move - { - handlerMouseMoveEvent(static_cast(event)); - return true; - } - else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release - { - handlerMouseReleaseEvent(); - return true; - } - } - } - } + if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize + { + m_vector_index = m_handler_vector.indexOf(qghi); + if (m_vector_index != -1) + { + if(event->type() == QEvent::GraphicsSceneMousePress) //Click + { + handlerMousePressEvent(); + return true; + } + else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move + { + handlerMouseMoveEvent(static_cast(event)); + return true; + } + else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release + { + handlerMouseReleaseEvent(); + return true; + } + } + } + } - return false; + return false; } /** - @brief QetShapeItem::contextMenuEvent - @param event + @brief QetShapeItem::contextMenuEvent + @param event */ void QetShapeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { - m_context_menu_pos = event->pos(); + m_context_menu_pos = event->pos(); - if (m_shapeType == QetShapeItem::Polygon) - { - if (diagram()->selectedItems().isEmpty()) { - this->setSelected(true); - } + if (m_shapeType == QetShapeItem::Polygon) + { + if (diagram()->selectedItems().isEmpty()) { + this->setSelected(true); + } - if (isSelected() && scene()->selectedItems().size() == 1) - { - if (diagram()) - { - DiagramView *d_view = nullptr; - for (QGraphicsView *view : diagram()->views()) - { - if (view->isActiveWindow()) - { - d_view = dynamic_cast(view); - if (d_view) - continue; - } - } + if (isSelected() && scene()->selectedItems().size() == 1) + { + if (diagram()) + { + DiagramView *d_view = nullptr; + for (QGraphicsView *view : diagram()->views()) + { + if (view->isActiveWindow()) + { + d_view = dynamic_cast(view); + if (d_view) + continue; + } + } - if (d_view) - { - QScopedPointer menu(new QMenu()); - menu.data()->addAction(m_insert_point); + if (d_view) + { + QScopedPointer menu(new QMenu()); + menu.data()->addAction(m_insert_point); - if (m_handler_vector.count() > 2) - { - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - { - if (qghi->contains(qghi->mapFromScene(event->scenePos()))) - { - menu.data()->addAction(m_remove_point); - break; - } - } - } + if (m_handler_vector.count() > 2) + { + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + { + if (qghi->contains(qghi->mapFromScene(event->scenePos()))) + { + menu.data()->addAction(m_remove_point); + break; + } + } + } - menu.data()->addSeparator(); - menu.data()->addActions(d_view->contextMenuActions()); - menu.data()->exec(event->screenPos()); - event->accept(); - return; - } - } - } - } + menu.data()->addSeparator(); + menu.data()->addActions(d_view->contextMenuActions()); + menu.data()->exec(event->screenPos()); + event->accept(); + return; + } + } + } + } - QetGraphicsItem::contextMenuEvent(event); + QetGraphicsItem::contextMenuEvent(event); } /** - @brief QetShapeItem::switchResizeMode + @brief QetShapeItem::switchResizeMode */ void QetShapeItem::switchResizeMode() { - if (m_shapeType == Ellipse) - { - if (m_resize_mode == 1) - { - m_resize_mode = 2; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::darkGreen); - } - } - else - { - m_resize_mode = 1; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::blue); - } - } - } - else if (m_shapeType == Rectangle) - { - if (m_resize_mode == 1) - { - m_resize_mode = 2; - for (QetGraphicsHandlerItem *qghi : m_handler_vector) - qghi->setColor(Qt::darkGreen); - } - else if (m_resize_mode == 2) - { - m_resize_mode = 3; - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::magenta); - } - } - else if (m_resize_mode == 3) - { - m_resize_mode = 1; - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - for (QetGraphicsHandlerItem *qghi : m_handler_vector) { - qghi->setColor(Qt::blue); - } + if (m_shapeType == Ellipse) + { + if (m_resize_mode == 1) + { + m_resize_mode = 2; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::darkGreen); + } + } + else + { + m_resize_mode = 1; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::blue); + } + } + } + else if (m_shapeType == Rectangle) + { + if (m_resize_mode == 1) + { + m_resize_mode = 2; + for (QetGraphicsHandlerItem *qghi : m_handler_vector) + qghi->setColor(Qt::darkGreen); + } + else if (m_resize_mode == 2) + { + m_resize_mode = 3; + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::magenta); + } + } + else if (m_resize_mode == 3) + { + m_resize_mode = 1; + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + for (QetGraphicsHandlerItem *qghi : m_handler_vector) { + qghi->setColor(Qt::blue); + } - } - } + } + } } void QetShapeItem::addHandler() { - if (m_handler_vector.isEmpty()) - { - QVector points_vector; - switch (m_shapeType) - { - case Line: - points_vector << m_P1 << m_P2; - break; - case Rectangle: - if (m_resize_mode == 3) { - points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(QRectF(m_P1, m_P2), m_xRadius, m_yRadius); - } - else { - points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); - } - break; - case Ellipse: - points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); - break; - case Polygon: - points_vector = m_polygon; - break; - } + if (m_handler_vector.isEmpty()) + { + QVector points_vector; + switch (m_shapeType) + { + case Line: + points_vector << m_P1 << m_P2; + break; + case Rectangle: + if (m_resize_mode == 3) { + points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(QRectF(m_P1, m_P2), m_xRadius, m_yRadius); + } + else { + points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); + } + break; + case Ellipse: + points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); + break; + case Polygon: + points_vector = m_polygon; + break; + } - if(!points_vector.isEmpty() && scene()) - { - m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector)); + if(!points_vector.isEmpty() && scene()) + { + m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector)); - for(QetGraphicsHandlerItem *handler : m_handler_vector) - { - handler->setZValue(this->zValue()+1); - handler->setColor(Qt::blue); - scene()->addItem(handler); - handler->installSceneEventFilter(this); - } - } - } + for(QetGraphicsHandlerItem *handler : m_handler_vector) + { + handler->setZValue(this->zValue()+1); + handler->setColor(Qt::blue); + scene()->addItem(handler); + handler->installSceneEventFilter(this); + } + } + } } /** - @brief QetShapeItem::adjusteHandlerPos - Adjust the position of the handler item + @brief QetShapeItem::adjusteHandlerPos + Adjust the position of the handler item */ void QetShapeItem::adjusteHandlerPos() { - if (m_handler_vector.isEmpty()) { - return; - } + if (m_handler_vector.isEmpty()) { + return; + } - QVector points_vector; - switch (m_shapeType) - { - case Line: { - points_vector << m_P1 << m_P2; - break; - } - case Rectangle: { - if (m_resize_mode != 3) { - points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); - } - else { - points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(QRectF(m_P1, m_P2), m_xRadius, m_yRadius); - } - break; - } - case Ellipse: { - points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); - break; - } - case Polygon: { - points_vector = m_polygon; - break; - } - } + QVector points_vector; + switch (m_shapeType) + { + case Line: { + points_vector << m_P1 << m_P2; + break; + } + case Rectangle: { + if (m_resize_mode != 3) { + points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); + } + else { + points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(QRectF(m_P1, m_P2), m_xRadius, m_yRadius); + } + break; + } + case Ellipse: { + points_vector = QetGraphicsHandlerUtility::pointsForRect(QRectF(m_P1, m_P2)); + break; + } + case Polygon: { + points_vector = m_polygon; + break; + } + } - if (m_handler_vector.size() == points_vector.size()) - { - points_vector = mapToScene(points_vector); - for (int i = 0 ; i < points_vector.size() ; ++i) - m_handler_vector.at(i)->setPos(points_vector.at(i)); - } - else - { - qDeleteAll(m_handler_vector); - m_handler_vector.clear(); - addHandler(); - } + if (m_handler_vector.size() == points_vector.size()) + { + points_vector = mapToScene(points_vector); + for (int i = 0 ; i < points_vector.size() ; ++i) + m_handler_vector.at(i)->setPos(points_vector.at(i)); + } + else + { + qDeleteAll(m_handler_vector); + m_handler_vector.clear(); + addHandler(); + } } void QetShapeItem::insertPoint() { - if (m_shapeType == QetShapeItem::Polygon) - { - QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(this->polygon(), m_closed, Diagram::snapToGrid(m_context_menu_pos)); + if (m_shapeType == QetShapeItem::Polygon) + { + QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(this->polygon(), m_closed, Diagram::snapToGrid(m_context_menu_pos)); - if(new_polygon != m_polygon) - { - //Wrap the undo for avoid to merge the undo commands when user add several points. - QUndoCommand *undo = new QUndoCommand(tr("Ajouter un point à un polygone")); - new QPropertyUndoCommand(this, "polygon", m_polygon, new_polygon, undo); - diagram()->undoStack().push(undo); - } - } + if(new_polygon != m_polygon) + { + //Wrap the undo for avoid to merge the undo commands when user add several points. + QUndoCommand *undo = new QUndoCommand(tr("Ajouter un point ?? un polygone")); + new QPropertyUndoCommand(this, "polygon", m_polygon, new_polygon, undo); + diagram()->undoStack().push(undo); + } + } } void QetShapeItem::removePoint() { - if (m_shapeType != QetShapeItem::Polygon) { - return; - } + if (m_shapeType != QetShapeItem::Polygon) { + return; + } - if (m_handler_vector.size() == 2) { - return; - } + if (m_handler_vector.size() == 2) { + return; + } - QPointF point = mapToScene(m_context_menu_pos); - int index = -1; - for (int i=0 ; icontains(qghi->mapFromScene(point))) - { - index = i; - break; - } - } - if (index > -1 && indexpolygon(); - polygon.removeAt(index); + QPointF point = mapToScene(m_context_menu_pos); + int index = -1; + for (int i=0 ; icontains(qghi->mapFromScene(point))) + { + index = i; + break; + } + } + if (index > -1 && indexpolygon(); + polygon.removeAt(index); - //Wrap the undo for avoid to merge the undo commands when user add several points. - QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone")); - new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo); - diagram()->undoStack().push(undo); - } + //Wrap the undo for avoid to merge the undo commands when user add several points. + QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone")); + new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo); + diagram()->undoStack().push(undo); + } } /** - @brief QetShapeItem::handlerMousePressEvent - @param qghi - @param event + @brief QetShapeItem::handlerMousePressEvent + @param qghi + @param event */ void QetShapeItem::handlerMousePressEvent() { - m_old_P1 = m_P1; - m_old_P2 = m_P2; - m_old_polygon = m_polygon; - m_old_xRadius = m_xRadius; - m_old_yRadius = m_yRadius; - if(m_xRadius == 0 && m_yRadius == 0) { - m_modifie_radius_equaly = true; - } + m_old_P1 = m_P1; + m_old_P2 = m_P2; + m_old_polygon = m_polygon; + m_old_xRadius = m_xRadius; + m_old_yRadius = m_yRadius; + if(m_xRadius == 0 && m_yRadius == 0) { + m_modifie_radius_equaly = true; + } } /** - @brief QetShapeItem::handlerMouseMoveEvent - @param event + @brief QetShapeItem::handlerMouseMoveEvent + @param event */ void QetShapeItem::handlerMouseMoveEvent(QGraphicsSceneMouseEvent *event) { - QPointF new_pos = event->scenePos(); - if (event->modifiers() != Qt::ControlModifier) - new_pos = Diagram::snapToGrid(event->scenePos()); - new_pos = mapFromScene(new_pos); + QPointF new_pos = event->scenePos(); + if (event->modifiers() != Qt::ControlModifier) + new_pos = Diagram::snapToGrid(event->scenePos()); + new_pos = mapFromScene(new_pos); - switch (m_shapeType) - { - case Line: - prepareGeometryChange(); - m_vector_index == 0 ? m_P1 = new_pos : m_P2 = new_pos; - adjusteHandlerPos(); - break; + switch (m_shapeType) + { + case Line: + prepareGeometryChange(); + m_vector_index == 0 ? m_P1 = new_pos : m_P2 = new_pos; + adjusteHandlerPos(); + break; - case Rectangle: - if (m_resize_mode == 1) { - setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); - break; - } - else if (m_resize_mode == 2) { - setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); - break; - } - else { - qreal radius = QetGraphicsHandlerUtility::radiusForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index); - if(m_modifie_radius_equaly) { - setXRadius(radius); - setYRadius(radius); - } - else if(m_vector_index == 0) { - setXRadius(radius); - } - else { - setYRadius(radius); - } - adjusteHandlerPos(); - break; - } - case Ellipse: - if (m_resize_mode == 1) { - setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); - break; - } - else { - setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); - break; - } + case Rectangle: + if (m_resize_mode == 1) { + setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); + break; + } + else if (m_resize_mode == 2) { + setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); + break; + } + else { + qreal radius = QetGraphicsHandlerUtility::radiusForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index); + if(m_modifie_radius_equaly) { + setXRadius(radius); + setYRadius(radius); + } + else if(m_vector_index == 0) { + setXRadius(radius); + } + else { + setYRadius(radius); + } + adjusteHandlerPos(); + break; + } + case Ellipse: + if (m_resize_mode == 1) { + setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); + break; + } + else { + setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(QRectF(m_P1, m_P2), new_pos, m_vector_index)); + break; + } - case Polygon: - prepareGeometryChange(); - m_polygon.replace(m_vector_index, new_pos); - adjusteHandlerPos(); - break; - } //End switch + case Polygon: + prepareGeometryChange(); + m_polygon.replace(m_vector_index, new_pos); + adjusteHandlerPos(); + break; + } //End switch } /** - @brief QetShapeItem::handlerMouseReleaseEvent - @param qghi - @param event + @brief QetShapeItem::handlerMouseReleaseEvent + @param qghi + @param event */ void QetShapeItem::handlerMouseReleaseEvent() { - m_modifie_radius_equaly = false; + m_modifie_radius_equaly = false; - if (diagram()) - { - QPropertyUndoCommand *undo = nullptr; - if ((m_shapeType & (Line | Rectangle | Ellipse)) && ((m_P1 != m_old_P1 || m_P2 != m_old_P2) || - (m_old_xRadius != XRadius() || m_old_yRadius != m_yRadius)) - ) - { - switch(m_shapeType) - { - case Line: { - undo = new QPropertyUndoCommand(this, "line",QLineF(m_old_P1, m_old_P2), QLineF(m_P1, m_P2)); - break; - } - case Rectangle: { - if (m_resize_mode == 1 || m_resize_mode == 2) { - undo = new QPropertyUndoCommand(this, "rect",QRectF(m_old_P1, m_old_P2), QRectF(m_P1, m_P2).normalized()); - } - else if (m_resize_mode == 3) - { - undo = new QPropertyUndoCommand(this, "xRadius", m_old_xRadius, m_xRadius); - QPropertyUndoCommand *undo_ = new QPropertyUndoCommand(this, "yRadius", m_old_yRadius, m_yRadius, undo); - undo_->setAnimated(); - } - break; - } - case Ellipse: { - undo = new QPropertyUndoCommand(this, "rect",QRectF(m_old_P1, m_old_P2), QRectF(m_P1, m_P2).normalized()); - break; - } - case Polygon: break; - } - if (undo) { - undo->setAnimated(true, false); - } - } - else if (m_shapeType == Polygon && (m_polygon != m_old_polygon)) - undo = new QPropertyUndoCommand(this, "polygon", m_old_polygon, m_polygon); + if (diagram()) + { + QPropertyUndoCommand *undo = nullptr; + if ((m_shapeType & (Line | Rectangle | Ellipse)) && ((m_P1 != m_old_P1 || m_P2 != m_old_P2) || + (m_old_xRadius != XRadius() || m_old_yRadius != m_yRadius)) + ) + { + switch(m_shapeType) + { + case Line: { + undo = new QPropertyUndoCommand(this, "line",QLineF(m_old_P1, m_old_P2), QLineF(m_P1, m_P2)); + break; + } + case Rectangle: { + if (m_resize_mode == 1 || m_resize_mode == 2) { + undo = new QPropertyUndoCommand(this, "rect",QRectF(m_old_P1, m_old_P2), QRectF(m_P1, m_P2).normalized()); + } + else if (m_resize_mode == 3) + { + undo = new QPropertyUndoCommand(this, "xRadius", m_old_xRadius, m_xRadius); + QPropertyUndoCommand *undo_ = new QPropertyUndoCommand(this, "yRadius", m_old_yRadius, m_yRadius, undo); + undo_->setAnimated(); + } + break; + } + case Ellipse: { + undo = new QPropertyUndoCommand(this, "rect",QRectF(m_old_P1, m_old_P2), QRectF(m_P1, m_P2).normalized()); + break; + } + case Polygon: break; + } + if (undo) { + undo->setAnimated(true, false); + } + } + else if (m_shapeType == Polygon && (m_polygon != m_old_polygon)) + undo = new QPropertyUndoCommand(this, "polygon", m_old_polygon, m_polygon); - if(undo) - { - undo->setText(tr("Modifier %1").arg(name())); - diagram()->undoStack().push(undo); - } - } + if(undo) + { + undo->setText(tr("Modifier %1").arg(name())); + diagram()->undoStack().push(undo); + } + } } /** - @brief QetShapeItem::fromXml - Build this item from the xml description - @param e element where is stored this item - @return true if load success + @brief QetShapeItem::fromXml + Build this item from the xml description + @param e element where is stored this item + @return true if load success */ bool QetShapeItem::fromXml(const QDomElement &e) { - if (e.tagName() != "shape") return (false); + if (e.tagName() != "shape") return (false); - is_movable_ = (e.attribute("is_movable").toInt()); - m_closed = e.attribute("closed", "0").toInt(); - m_pen = QETXML::penFromXml(e.firstChildElement("pen")); - m_brush = QETXML::brushFromXml(e.firstChildElement("brush")); + is_movable_ = (e.attribute("is_movable").toInt()); + m_closed = e.attribute("closed", "0").toInt(); + m_pen = QETXML::penFromXml(e.firstChildElement("pen")); + m_brush = QETXML::brushFromXml(e.firstChildElement("brush")); - QString type = e.attribute("type"); + QString type = e.attribute("type"); #if TODO_LIST -#pragma message("@TODO Compatibility for version older than N°4075, shape type was stored with an int") +#pragma message("@TODO Compatibility for version older than N??4075, shape type was stored with an int") #endif - //@TODO Compatibility for version older than N°4075, shape type was stored with an int - if (type.size() == 1) - { - switch(e.attribute("type","0").toInt()) - { - case 0: m_shapeType = Line; break; - case 1: m_shapeType = Rectangle; break; - case 2: m_shapeType = Ellipse; break; - case 3: m_shapeType = Polygon; break; - } - } - //For version after N°4075, shape is stored with a string - else - { - QMetaEnum me = metaObject()->enumerator(metaObject()->indexOfEnumerator("ShapeType")); - m_shapeType = QetShapeItem::ShapeType(me.keysToValue(type.toStdString().data())); - } + //@TODO Compatibility for version older than N??4075, shape type was stored with an int + if (type.size() == 1) + { + switch(e.attribute("type","0").toInt()) + { + case 0: m_shapeType = Line; break; + case 1: m_shapeType = Rectangle; break; + case 2: m_shapeType = Ellipse; break; + case 3: m_shapeType = Polygon; break; + } + } + //For version after N??4075, shape is stored with a string + else + { + QMetaEnum me = metaObject()->enumerator(metaObject()->indexOfEnumerator("ShapeType")); + m_shapeType = QetShapeItem::ShapeType(me.keysToValue(type.toStdString().data())); + } - if (m_shapeType != Polygon) - { - m_P1.setX(e.attribute("x1", nullptr).toDouble()); - m_P1.setY(e.attribute("y1", nullptr).toDouble()); - m_P2.setX(e.attribute("x2", nullptr).toDouble()); - m_P2.setY(e.attribute("y2", nullptr).toDouble()); + if (m_shapeType != Polygon) + { + m_P1.setX(e.attribute("x1", nullptr).toDouble()); + m_P1.setY(e.attribute("y1", nullptr).toDouble()); + m_P2.setX(e.attribute("x2", nullptr).toDouble()); + m_P2.setY(e.attribute("y2", nullptr).toDouble()); - if (m_shapeType == Rectangle) - { - setXRadius(e.attribute("rx", "0").toDouble()); - setYRadius(e.attribute("ry", "0").toDouble()); - } - } - else { - for(const QDomElement& de : QET::findInDomElement(e, "points", "point")) { - m_polygon << QPointF(de.attribute("x", nullptr).toDouble(), de.attribute("y", nullptr).toDouble()); - } - } - setZValue(e.attribute("z", QString::number(this->zValue())).toDouble()); + if (m_shapeType == Rectangle) + { + setXRadius(e.attribute("rx", "0").toDouble()); + setYRadius(e.attribute("ry", "0").toDouble()); + } + } + else { + for(const QDomElement& de : QET::findInDomElement(e, "points", "point")) { + m_polygon << QPointF(de.attribute("x", nullptr).toDouble(), de.attribute("y", nullptr).toDouble()); + } + } + setZValue(e.attribute("z", QString::number(this->zValue())).toDouble()); - return (true); + return (true); } /** - @brief QetShapeItem::toXml - Save this item to xml element - @param document parent document xml - @return element xml where is write this item + @brief QetShapeItem::toXml + Save this item to xml element + @param document parent document xml + @return element xml where is write this item */ QDomElement QetShapeItem::toXml(QDomDocument &document) const { - QDomElement result = document.createElement("shape"); + QDomElement result = document.createElement("shape"); - //write some attribute - QMetaEnum me = metaObject()->enumerator(metaObject()->indexOfEnumerator("ShapeType")); - result.setAttribute("type", me.valueToKey(m_shapeType)); - result.appendChild(QETXML::penToXml(document, m_pen)); - result.appendChild(QETXML::brushToXml(document, m_brush)); - result.setAttribute("is_movable", bool(is_movable_)); - result.setAttribute("closed", bool(m_closed)); + //write some attribute + QMetaEnum me = metaObject()->enumerator(metaObject()->indexOfEnumerator("ShapeType")); + result.setAttribute("type", me.valueToKey(m_shapeType)); + result.appendChild(QETXML::penToXml(document, m_pen)); + result.appendChild(QETXML::brushToXml(document, m_brush)); + result.setAttribute("is_movable", bool(is_movable_)); + result.setAttribute("closed", bool(m_closed)); - if (m_shapeType != Polygon) - { - result.setAttribute("x1", QString::number(mapToScene(m_P1).x())); - result.setAttribute("y1", QString::number(mapToScene(m_P1).y())); - result.setAttribute("x2", QString::number(mapToScene(m_P2).x())); - result.setAttribute("y2", QString::number(mapToScene(m_P2).y())); + if (m_shapeType != Polygon) + { + result.setAttribute("x1", QString::number(mapToScene(m_P1).x())); + result.setAttribute("y1", QString::number(mapToScene(m_P1).y())); + result.setAttribute("x2", QString::number(mapToScene(m_P2).x())); + result.setAttribute("y2", QString::number(mapToScene(m_P2).y())); - if (m_shapeType == Rectangle) - { - QRectF rect(m_P1, m_P2); - rect = rect.normalized(); - qreal x = m_xRadius; - if (x > rect.width()/2) { - x = rect.width()/2; - } - qreal y = m_yRadius; - if (y > rect.height()/2) { - y = rect.height()/2; - } + if (m_shapeType == Rectangle) + { + QRectF rect(m_P1, m_P2); + rect = rect.normalized(); + qreal x = m_xRadius; + if (x > rect.width()/2) { + x = rect.width()/2; + } + qreal y = m_yRadius; + if (y > rect.height()/2) { + y = rect.height()/2; + } - result.setAttribute("rx", QString::number(m_xRadius)); - result.setAttribute("ry", QString::number(m_yRadius)); - } - } - else - { - QDomElement points = document.createElement("points"); - for (QPointF p : m_polygon) - { - QDomElement point = document.createElement("point"); - QPointF pf = mapToScene(p); - point.setAttribute("x", QString::number(pf.x())); - point.setAttribute("y", QString::number(pf.y())); - points.appendChild(point); - } - result.appendChild(points); - } - result.setAttribute("z", QString::number(this->zValue())); + result.setAttribute("rx", QString::number(m_xRadius)); + result.setAttribute("ry", QString::number(m_yRadius)); + } + } + else + { + QDomElement points = document.createElement("points"); + for (QPointF p : m_polygon) + { + QDomElement point = document.createElement("point"); + QPointF pf = mapToScene(p); + point.setAttribute("x", QString::number(pf.x())); + point.setAttribute("y", QString::number(pf.y())); + points.appendChild(point); + } + result.appendChild(points); + } + result.setAttribute("z", QString::number(this->zValue())); - return(result); + return(result); } /** - @brief QetShapeItem::toDXF - Draw this element to the dxf document - @param filepath file path of the the dxf document - @param pen - @return true if draw success + @brief QetShapeItem::toDXF + Draw this element to the dxf document + @param filepath file path of the the dxf document + @param pen + @return true if draw success */ bool QetShapeItem::toDXF(const QString &filepath,const QPen &pen) { - switch (m_shapeType) - { - case Line: - Createdxf::drawLine(filepath, - QLineF( mapToScene(m_P1), - mapToScene(m_P2)), - Createdxf::dxfColor(pen)); - return true; - case Rectangle: - Createdxf::drawRectangle(filepath, - QRectF(mapToScene(m_P1), - mapToScene(m_P2)).normalized(), - Createdxf::dxfColor(pen)); - return true; - case Ellipse: - Createdxf::drawEllipse(filepath, - QRectF(mapToScene(m_P1), - mapToScene(m_P2)).normalized(), - Createdxf::dxfColor(pen)); - return true; - case Polygon: - Createdxf::drawPolygon(filepath,m_polygon,Createdxf::dxfColor(pen)); - return true; - default: - return false; - } + switch (m_shapeType) + { + case Line: + Createdxf::drawLine(filepath, + QLineF( mapToScene(m_P1), + mapToScene(m_P2)), + Createdxf::dxfColor(pen)); + return true; + case Rectangle: + Createdxf::drawRectangle(filepath, + QRectF(mapToScene(m_P1), + mapToScene(m_P2)).normalized(), + Createdxf::dxfColor(pen)); + return true; + case Ellipse: + Createdxf::drawEllipse(filepath, + QRectF(mapToScene(m_P1), + mapToScene(m_P2)).normalized(), + Createdxf::dxfColor(pen)); + return true; + case Polygon: + Createdxf::drawPolygon(filepath,m_polygon,Createdxf::dxfColor(pen)); + return true; + default: + return false; + } } /** - @brief QetShapeItem::editProperty - Edit the property of this item + @brief QetShapeItem::editProperty + Edit the property of this item */ void QetShapeItem::editProperty() { - if (diagram() -> isReadOnly()) return; + if (diagram() -> isReadOnly()) return; - PropertiesEditorDialog ped(new ShapeGraphicsItemPropertiesWidget(this), diagram()->views().at(0)); - ped.exec(); + PropertiesEditorDialog ped(new ShapeGraphicsItemPropertiesWidget(this), diagram()->views().at(0)); + ped.exec(); } /** - @brief QetShapeItem::name - @return the name of the curent shape. + @brief QetShapeItem::name + @return the name of the curent shape. */ QString QetShapeItem::name() const { - switch (m_shapeType) { - case Line: return tr("une ligne"); - case Rectangle: return tr("un rectangle"); - case Ellipse: return tr("une éllipse"); - case Polygon: return tr("une polyligne"); - default: return tr("une shape"); - } + switch (m_shapeType) { + case Line: return tr("une ligne"); + case Rectangle: return tr("un rectangle"); + case Ellipse: return tr("une ??llipse"); + case Polygon: return tr("une polyligne"); + default: return tr("une shape"); + } } diff --git a/sources/qetgraphicsitem/slaveelement.cpp b/sources/qetgraphicsitem/slaveelement.cpp index 2289981b9..b0475f4c7 100644 --- a/sources/qetgraphicsitem/slaveelement.cpp +++ b/sources/qetgraphicsitem/slaveelement.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "slaveelement.h" #include "diagramposition.h" @@ -22,79 +22,79 @@ #include "dynamicelementtextitem.h" /** - @brief SlaveElement::SlaveElement - Default constructor - @param location location of xml definition - @param qgi parent QGraphicItem - @param state int used to know if the creation of element have error + @brief SlaveElement::SlaveElement + Default constructor + @param location location of xml definition + @param qgi parent QGraphicItem + @param state int used to know if the creation of element have error */ SlaveElement::SlaveElement(const ElementsLocation &location, - QGraphicsItem *qgi, - int *state) : - Element(location, qgi, state, Element::Slave) + QGraphicsItem *qgi, + int *state) : + Element(location, qgi, state, Element::Slave) { - m_xref_item = nullptr; + m_xref_item = nullptr; } /** - @brief SlaveElement::~SlaveElement - default destructor + @brief SlaveElement::~SlaveElement + default destructor */ SlaveElement::~SlaveElement() { - unlinkAllElements(); + unlinkAllElements(); } /** - @brief SlaveElement::linkToElement - Link this slave to another element - For this class element must be a master - @param elmt + @brief SlaveElement::linkToElement + Link this slave to another element + For this class element must be a master + @param elmt */ void SlaveElement::linkToElement(Element *elmt) { - // check if element is master and if isn't already linked - if (elmt->linkType() == Master && !connected_elements.contains(elmt)) - { - if(!isFree()) - unlinkAllElements(); + // check if element is master and if isn't already linked + if (elmt->linkType() == Master && !connected_elements.contains(elmt)) + { + if(!isFree()) + unlinkAllElements(); - connected_elements << elmt; + connected_elements << elmt; - elmt -> linkToElement(this); - emit linkedElementChanged(); - } + elmt -> linkToElement(this); + emit linkedElementChanged(); + } } /** - @brief SlaveElement::unlinkAllElements - Unlink all of the element in the QList connected_elements + @brief SlaveElement::unlinkAllElements + Unlink all of the element in the QList connected_elements */ void SlaveElement::unlinkAllElements() { - // if this element is free no need to do something - if (!isFree()) - { - foreach(Element *elmt, connected_elements) - unlinkElement(elmt); - emit linkedElementChanged(); - } + // if this element is free no need to do something + if (!isFree()) + { + foreach(Element *elmt, connected_elements) + unlinkElement(elmt); + emit linkedElementChanged(); + } } /** - @brief SlaveElement::unlinkElement - Unlink the given elmt in parametre - @param elmt + @brief SlaveElement::unlinkElement + Unlink the given elmt in parametre + @param elmt */ void SlaveElement::unlinkElement(Element *elmt) { - //Ensure elmt is linked to this element - if (connected_elements.contains(elmt)) - { - connected_elements.removeOne(elmt); + //Ensure elmt is linked to this element + if (connected_elements.contains(elmt)) + { + connected_elements.removeOne(elmt); - elmt -> unlinkElement (this) ; - elmt -> setHighlighted (false); - emit linkedElementChanged(); - } + elmt -> unlinkElement (this) ; + elmt -> setHighlighted (false); + emit linkedElementChanged(); + } } diff --git a/sources/qetgraphicsitem/slaveelement.h b/sources/qetgraphicsitem/slaveelement.h index 2aba4305c..a75e021ce 100644 --- a/sources/qetgraphicsitem/slaveelement.h +++ b/sources/qetgraphicsitem/slaveelement.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef SLAVEELEMENT_H #define SLAVEELEMENT_H @@ -23,19 +23,19 @@ class SlaveElement : public Element { - Q_OBJECT - public: - explicit SlaveElement ( - const ElementsLocation &, - QGraphicsItem * = nullptr, - int * = nullptr); - ~SlaveElement() override; - void linkToElement(Element *elmt) override; - void unlinkAllElements() override; - void unlinkElement(Element *elmt) override; - - private: - QGraphicsTextItem *m_xref_item; + Q_OBJECT + public: + explicit SlaveElement ( + const ElementsLocation &, + QGraphicsItem * = nullptr, + int * = nullptr); + ~SlaveElement() override; + void linkToElement(Element *elmt) override; + void unlinkAllElements() override; + void unlinkElement(Element *elmt) override; + + private: + QGraphicsTextItem *m_xref_item; }; #endif // SLAVEELEMENT_H diff --git a/sources/qetgraphicsitem/terminal.cpp b/sources/qetgraphicsitem/terminal.cpp index a3de13335..d0d1e1f47 100644 --- a/sources/qetgraphicsitem/terminal.cpp +++ b/sources/qetgraphicsitem/terminal.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "terminal.h" @@ -34,875 +34,875 @@ const qreal Terminal::terminalSize = 4.0; const qreal Terminal::Z = 1000; /** - @brief Terminal::init - Methode privee pour initialiser la borne. - @param number of terminal - @param name of terminal - @param hiddenName + @brief Terminal::init + Methode privee pour initialiser la borne. + @param number of terminal + @param name of terminal + @param hiddenName */ void Terminal::init( - QString number, QString name, bool hiddenName) + QString number, QString name, bool hiddenName) { - hovered_color_ = Terminal::neutralColor; + hovered_color_ = Terminal::neutralColor; - // calcul de la position du point d'amarrage a l'element - dock_elmt_ = d->m_pos; - switch(d->m_orientation) { - case Qet::North: dock_elmt_ += QPointF(0, Terminal::terminalSize); break; - case Qet::East : dock_elmt_ += QPointF(-Terminal::terminalSize, 0); break; - case Qet::West : dock_elmt_ += QPointF(Terminal::terminalSize, 0); break; - case Qet::South: - default : dock_elmt_ += QPointF(0, -Terminal::terminalSize); - } - // Number of terminal - number_terminal_ = std::move(number); - // Name of terminal - name_terminal_ = std::move(name); - name_terminal_hidden = hiddenName; - // par defaut : pas de conducteur + // calcul de la position du point d'amarrage a l'element + dock_elmt_ = d->m_pos; + switch(d->m_orientation) { + case Qet::North: dock_elmt_ += QPointF(0, Terminal::terminalSize); break; + case Qet::East : dock_elmt_ += QPointF(-Terminal::terminalSize, 0); break; + case Qet::West : dock_elmt_ += QPointF(Terminal::terminalSize, 0); break; + case Qet::South: + default : dock_elmt_ += QPointF(0, -Terminal::terminalSize); + } + // Number of terminal + number_terminal_ = std::move(number); + // Name of terminal + name_terminal_ = std::move(name); + name_terminal_hidden = hiddenName; + // par defaut : pas de conducteur - // QRectF null - br_ = new QRectF(); - previous_terminal_ = nullptr; - // divers - setAcceptHoverEvents(true); - setAcceptedMouseButtons(Qt::LeftButton); - hovered_ = false; - setToolTip(QObject::tr("Borne", "tooltip")); - setZValue(Z); + // QRectF null + br_ = new QRectF(); + previous_terminal_ = nullptr; + // divers + setAcceptHoverEvents(true); + setAcceptedMouseButtons(Qt::LeftButton); + hovered_ = false; + setToolTip(QObject::tr("Borne", "tooltip")); + setZValue(Z); } /*! - \brief Terminal::init - Additionaly to the init above, this method stores position and orientation into the data class - \param pf - \param o - \param number - \param name - \param hiddenName + \brief Terminal::init + Additionaly to the init above, this method stores position and orientation into the data class + \param pf + \param o + \param number + \param name + \param hiddenName */ void Terminal::init( - QPointF pf, - Qet::Orientation o, - QString number, - QString name, - bool hiddenName) + QPointF pf, + Qet::Orientation o, + QString number, + QString name, + bool hiddenName) { - // definition du pount d'amarrage pour un conducteur - d->m_pos = pf; + // definition du pount d'amarrage pour un conducteur + d->m_pos = pf; - // definition de l'orientation de la borne (par defaut : sud) - if (o < Qet::North || o > Qet::West) d->m_orientation = Qet::South; - else d->m_orientation = o; + // definition de l'orientation de la borne (par defaut : sud) + if (o < Qet::North || o > Qet::West) d->m_orientation = Qet::South; + else d->m_orientation = o; - init(number, name, hiddenName); + init(number, name, hiddenName); } /** - initialise une borne - @param pf position du point d'amarrage pour un conducteur - @param o orientation de la borne : Qt::Horizontal ou Qt::Vertical - @param e Element auquel cette borne appartient + initialise une borne + @param pf position du point d'amarrage pour un conducteur + @param o orientation de la borne : Qt::Horizontal ou Qt::Vertical + @param e Element auquel cette borne appartient */ Terminal::Terminal(QPointF pf, Qet::Orientation o, Element *e) : - QGraphicsObject(e), - d(new TerminalData(this)), - parent_element_ (e) + QGraphicsObject(e), + d(new TerminalData(this)), + parent_element_ (e) { - init(pf, o, "_", "_", false); + init(pf, o, "_", "_", false); } /** - initialise une borne - @param pf_x Abscisse du point d'amarrage pour un conducteur - @param pf_y Ordonnee du point d'amarrage pour un conducteur - @param o orientation de la borne : Qt::Horizontal ou Qt::Vertical - @param e Element auquel cette borne appartient + initialise une borne + @param pf_x Abscisse du point d'amarrage pour un conducteur + @param pf_y Ordonnee du point d'amarrage pour un conducteur + @param o orientation de la borne : Qt::Horizontal ou Qt::Vertical + @param e Element auquel cette borne appartient */ Terminal::Terminal(qreal pf_x, qreal pf_y, Qet::Orientation o, Element *e) : - QGraphicsObject(e), - d(new TerminalData(this)), - parent_element_ (e) + QGraphicsObject(e), + d(new TerminalData(this)), + parent_element_ (e) { - init(QPointF(pf_x, pf_y), o, "_", "_", false); + init(QPointF(pf_x, pf_y), o, "_", "_", false); } /** - initialise une borne - @param pf position du point d'amarrage pour un conducteur - @param o orientation de la borne : Qt::Horizontal ou Qt::Vertical - @param num number of terminal (ex 3 - 4 for NO) - @param name of terminal - @param hiddenName hide or show the name - @param e Element auquel cette borne appartient + initialise une borne + @param pf position du point d'amarrage pour un conducteur + @param o orientation de la borne : Qt::Horizontal ou Qt::Vertical + @param num number of terminal (ex 3 - 4 for NO) + @param name of terminal + @param hiddenName hide or show the name + @param e Element auquel cette borne appartient */ Terminal::Terminal( - QPointF pf, - Qet::Orientation o, - QString num, - QString name, - bool hiddenName, - Element *e) : - QGraphicsObject (e), - d(new TerminalData(this)), - parent_element_ (e) + QPointF pf, + Qet::Orientation o, + QString num, + QString name, + bool hiddenName, + Element *e) : + QGraphicsObject (e), + d(new TerminalData(this)), + parent_element_ (e) { - init(pf, o, std::move(num), std::move(name), hiddenName); + init(pf, o, std::move(num), std::move(name), hiddenName); } Terminal::Terminal(TerminalData* data, Element* e) : - QGraphicsObject(e), - d(data), - parent_element_(e) + QGraphicsObject(e), + d(data), + parent_element_(e) { #if TODO_LIST #pragma message("@TODO what is when multiple parents exist. So the other relation is lost.") #endif - // TODO: what is when multiple parents exist. So the other relation is lost. - d->setParent(this); - init("_", "_", false); + // TODO: what is when multiple parents exist. So the other relation is lost. + d->setParent(this); + init("_", "_", false); } /** - Destructeur - La destruction de la borne entraine la destruction des conducteurs - associes. + Destructeur + La destruction de la borne entraine la destruction des conducteurs + associes. */ Terminal::~Terminal() { - foreach(Conductor *c, conductors_) delete c; - delete br_; + foreach(Conductor *c, conductors_) delete c; + delete br_; } /** - Permet de connaitre l'orientation de la borne. Si le parent de la borne - est bien un Element, cette fonction renvoie l'orientation par rapport a - la scene de la borne, en tenant compte du fait que l'element ait pu etre - pivote. Sinon elle renvoie son sens normal. - @return L'orientation actuelle de la Terminal. + Permet de connaitre l'orientation de la borne. Si le parent de la borne + est bien un Element, cette fonction renvoie l'orientation par rapport a + la scene de la borne, en tenant compte du fait que l'element ait pu etre + pivote. Sinon elle renvoie son sens normal. + @return L'orientation actuelle de la Terminal. */ Qet::Orientation Terminal::orientation() const { - if (Element *elt = qgraphicsitem_cast(parentItem())) { - // orientations actuelle et par defaut de l'element - int ori_cur = elt -> orientation(); - if (ori_cur == 0) return(d->m_orientation); - else { - // calcul l'angle de rotation implique par l'orientation de l'element parent - // angle de rotation de la borne sur la scene, divise par 90 - int angle = ori_cur + d->m_orientation; - while (angle >= 4) angle -= 4; - return((Qet::Orientation)angle); - } - } else return(d->m_orientation); + if (Element *elt = qgraphicsitem_cast(parentItem())) { + // orientations actuelle et par defaut de l'element + int ori_cur = elt -> orientation(); + if (ori_cur == 0) return(d->m_orientation); + else { + // calcul l'angle de rotation implique par l'orientation de l'element parent + // angle de rotation de la borne sur la scene, divise par 90 + int angle = ori_cur + d->m_orientation; + while (angle >= 4) angle -= 4; + return((Qet::Orientation)angle); + } + } else return(d->m_orientation); } /** - @brief Terminal::setNumber - @param number + @brief Terminal::setNumber + @param number */ void Terminal::setNumber(QString number) { - number_terminal_ = std::move(number); + number_terminal_ = std::move(number); } /** - @brief Terminal::setName - @param name : QString - @param hiddenName : bool + @brief Terminal::setName + @param name : QString + @param hiddenName : bool */ void Terminal::setName(QString name, bool hiddenName) { - name_terminal_ = std::move(name); - name_terminal_hidden = hiddenName; + name_terminal_ = std::move(name); + name_terminal_hidden = hiddenName; } /** - @brief Terminal::addConductor - Add a conductor to this terminal - @param conductor : the conductor to add. - @return true if the conductor was successfully added + @brief Terminal::addConductor + Add a conductor to this terminal + @param conductor : the conductor to add. + @return true if the conductor was successfully added */ bool Terminal::addConductor(Conductor *conductor) { - if (!conductor) return(false); + if (!conductor) return(false); - Q_ASSERT_X(((conductor -> terminal1 == this) ^ (conductor -> terminal2 == this)), - "Terminal::addConductor", - "The conductor must be linked exactly once to this terminal"); + Q_ASSERT_X(((conductor -> terminal1 == this) ^ (conductor -> terminal2 == this)), + "Terminal::addConductor", + "The conductor must be linked exactly once to this terminal"); - //Get the other terminal where the conductor must be linked - Terminal *other_terminal = (conductor -> terminal1 == this) - ? conductor->terminal2 : conductor->terminal1; + //Get the other terminal where the conductor must be linked + Terminal *other_terminal = (conductor -> terminal1 == this) + ? conductor->terminal2 : conductor->terminal1; - //Check if this terminal isn't already linked with other_terminal - foreach (Conductor* cond, conductors_) - if (cond -> terminal1 == other_terminal || cond -> terminal2 == other_terminal) - return false; //They already a conductor linked to this and other_terminal + //Check if this terminal isn't already linked with other_terminal + foreach (Conductor* cond, conductors_) + if (cond -> terminal1 == other_terminal || cond -> terminal2 == other_terminal) + return false; //They already a conductor linked to this and other_terminal - conductors_.append(conductor); - emit conductorWasAdded(conductor); - return(true); + conductors_.append(conductor); + emit conductorWasAdded(conductor); + return(true); } /** - @brief Terminal::removeConductor - Remove a conductor from this terminal - @param conductor : conductor to remove + @brief Terminal::removeConductor + Remove a conductor from this terminal + @param conductor : conductor to remove */ void Terminal::removeConductor(Conductor *conductor) { - int index = conductors_.indexOf(conductor); - if (index == -1) return; - conductors_.removeAt(index); - emit conductorWasRemoved(conductor); + int index = conductors_.indexOf(conductor); + if (index == -1) return; + conductors_.removeAt(index); + emit conductorWasRemoved(conductor); } /** - @brief Terminal::paint - Fonction de dessin des bornes - @param painter Le QPainter a utiliser - @param options Les options de dessin + @brief Terminal::paint + Fonction de dessin des bornes + @param painter Le QPainter a utiliser + @param options Les options de dessin */ void Terminal::paint( - QPainter *painter, - const QStyleOptionGraphicsItem *options, - QWidget *) + QPainter *painter, + const QStyleOptionGraphicsItem *options, + QWidget *) { - // en dessous d'un certain zoom, les bornes ne sont plus dessinees -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - if (options && options -> levelOfDetail < 0.5) return; + // en dessous d'un certain zoom, les bornes ne sont plus dessinees +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + if (options && options -> levelOfDetail < 0.5) return; #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 0.5) - return; + if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 0.5) + return; #endif - painter -> save(); + painter -> save(); - //annulation des renderhints - painter -> setRenderHint(QPainter::Antialiasing, false); - painter -> setRenderHint(QPainter::TextAntialiasing, false); - painter -> setRenderHint(QPainter::SmoothPixmapTransform, false); + //annulation des renderhints + painter -> setRenderHint(QPainter::Antialiasing, false); + painter -> setRenderHint(QPainter::TextAntialiasing, false); + painter -> setRenderHint(QPainter::SmoothPixmapTransform, false); - // on travaille avec les coordonnees de l'element parent - QPointF c = mapFromParent(d->m_pos); - QPointF e = mapFromParent(dock_elmt_); + // on travaille avec les coordonnees de l'element parent + QPointF c = mapFromParent(d->m_pos); + QPointF e = mapFromParent(dock_elmt_); - QPen t; - t.setWidthF(1.0); + QPen t; + t.setWidthF(1.0); -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - if (options && options -> levelOfDetail < 1.0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + if (options && options -> levelOfDetail < 1.0) #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0) + if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0) #endif - { - t.setCosmetic(true); - } + { + t.setCosmetic(true); + } - // dessin de la borne en rouge - t.setColor(Qt::red); - painter -> setPen(t); - painter -> drawLine(c, e); + // dessin de la borne en rouge + t.setColor(Qt::red); + painter -> setPen(t); + painter -> drawLine(c, e); - // dessin du point d'amarrage au conducteur en bleu - t.setColor(hovered_color_); - painter -> setPen(t); - painter -> setBrush(hovered_color_); - if (hovered_) { - painter -> setRenderHint(QPainter::Antialiasing, true); - painter -> drawEllipse(QRectF(c.x() - 2.5, c.y() - 2.5, 5.0, 5.0)); - } else painter -> drawPoint(c); + // dessin du point d'amarrage au conducteur en bleu + t.setColor(hovered_color_); + painter -> setPen(t); + painter -> setBrush(hovered_color_); + if (hovered_) { + painter -> setRenderHint(QPainter::Antialiasing, true); + painter -> drawEllipse(QRectF(c.x() - 2.5, c.y() - 2.5, 5.0, 5.0)); + } else painter -> drawPoint(c); - //Draw help line if needed, - if (diagram() && m_draw_help_line) - { - //Draw the help line with same orientation of terminal - //Only if there isn't docked conductor - if (conductors().isEmpty()) - { - if (!m_help_line) - m_help_line = new QGraphicsLineItem(this); - QPen pen; - pen.setColor(Qt::darkBlue); + //Draw help line if needed, + if (diagram() && m_draw_help_line) + { + //Draw the help line with same orientation of terminal + //Only if there isn't docked conductor + if (conductors().isEmpty()) + { + if (!m_help_line) + m_help_line = new QGraphicsLineItem(this); + QPen pen; + pen.setColor(Qt::darkBlue); - QLineF line(HelpLine()); + QLineF line(HelpLine()); - if (diagram() -> project() -> autoConductor()) - { - Terminal *t = alignedWithTerminal(); - if (t) - { - line.setP2(t -> dockConductor()); - pen.setColor(Qt::darkGreen); - } - } + if (diagram() -> project() -> autoConductor()) + { + Terminal *t = alignedWithTerminal(); + if (t) + { + line.setP2(t -> dockConductor()); + pen.setColor(Qt::darkGreen); + } + } - //Map the line (in scene coordinate) to m_help_line coordinate - line.setP1(m_help_line -> mapFromScene(line.p1())); - line.setP2(m_help_line -> mapFromScene(line.p2())); - m_help_line -> setPen(pen); - m_help_line -> setLine(line); - } + //Map the line (in scene coordinate) to m_help_line coordinate + line.setP1(m_help_line -> mapFromScene(line.p1())); + line.setP2(m_help_line -> mapFromScene(line.p2())); + m_help_line -> setPen(pen); + m_help_line -> setLine(line); + } - //Draw the help line perpendicular to the terminal - if (!m_help_line_a) - { - m_help_line_a = new QGraphicsLineItem(this); - QPen pen; - pen.setColor(Diagram::background_color == Qt::darkGray ? Qt::lightGray : Qt::darkGray); - m_help_line_a -> setPen(pen); - } + //Draw the help line perpendicular to the terminal + if (!m_help_line_a) + { + m_help_line_a = new QGraphicsLineItem(this); + QPen pen; + pen.setColor(Diagram::background_color == Qt::darkGray ? Qt::lightGray : Qt::darkGray); + m_help_line_a -> setPen(pen); + } - QRectF rect = diagram() -> border_and_titleblock.insideBorderRect(); - QLineF line; + QRectF rect = diagram() -> border_and_titleblock.insideBorderRect(); + QLineF line; - if (Qet::isHorizontal(orientation())) - { - line.setP1(QPointF(dockConductor().x(), rect.topLeft().y())); - line.setP2(QPointF(dockConductor().x(), rect.bottomLeft().y())); - } - else - { - line.setP1(QPointF(rect.topLeft().x(), dockConductor().y())); - line.setP2(QPointF(rect.topRight().x(), dockConductor().y())); - } + if (Qet::isHorizontal(orientation())) + { + line.setP1(QPointF(dockConductor().x(), rect.topLeft().y())); + line.setP2(QPointF(dockConductor().x(), rect.bottomLeft().y())); + } + else + { + line.setP1(QPointF(rect.topLeft().x(), dockConductor().y())); + line.setP2(QPointF(rect.topRight().x(), dockConductor().y())); + } - //Map the line (in scene coordinate) to m_help_line_a coordinate - line.setP1(m_help_line_a -> mapFromScene(line.p1())); - line.setP2(m_help_line_a -> mapFromScene(line.p2())); - m_help_line_a -> setLine(line); - } + //Map the line (in scene coordinate) to m_help_line_a coordinate + line.setP1(m_help_line_a -> mapFromScene(line.p1())); + line.setP2(m_help_line_a -> mapFromScene(line.p2())); + m_help_line_a -> setLine(line); + } - painter -> restore(); + painter -> restore(); } /** - @brief Terminal::drawHelpLine - @param draw : true, display the help line - false, hide it. + @brief Terminal::drawHelpLine + @param draw : true, display the help line + false, hide it. */ void Terminal::drawHelpLine(bool draw) { - if (m_draw_help_line == draw) return; + if (m_draw_help_line == draw) return; - m_draw_help_line = draw; + m_draw_help_line = draw; - if (!draw) - { - if (m_help_line) - { - delete m_help_line; - m_help_line = nullptr; - } - if (m_help_line_a) - { - delete m_help_line_a; - m_help_line_a = nullptr; - } - } + if (!draw) + { + if (m_help_line) + { + delete m_help_line; + m_help_line = nullptr; + } + if (m_help_line_a) + { + delete m_help_line_a; + m_help_line_a = nullptr; + } + } } /** - @brief Terminal::HelpLine - @return a line with coordinate P1 the dock point of conductor - and P2 the border of diagram, according to the orientation of terminal - The line is in scene coordinate; + @brief Terminal::HelpLine + @return a line with coordinate P1 the dock point of conductor + and P2 the border of diagram, according to the orientation of terminal + The line is in scene coordinate; */ QLineF Terminal::HelpLine() const { - QPointF scene_dock = dockConductor(); - QRectF rect = diagram() -> border_and_titleblock.insideBorderRect(); + QPointF scene_dock = dockConductor(); + QRectF rect = diagram() -> border_and_titleblock.insideBorderRect(); - QLineF line(scene_dock , QPointF()); + QLineF line(scene_dock , QPointF()); - //Set te second point of line to the edge of diagram, - //according with the orientation of this terminal - switch (orientation()) - { - case Qet::North: - line.setP2(QPointF(scene_dock.x(), rect.top())); - break; - case Qet::East: - line.setP2(QPointF(rect.right() , scene_dock.y())); - break; - case Qet::South: - line.setP2(QPointF(scene_dock.x(), rect.bottom())); - break; - case Qet::West: - line.setP2(QPointF(rect.left(), scene_dock.y())); - break; - } + //Set te second point of line to the edge of diagram, + //according with the orientation of this terminal + switch (orientation()) + { + case Qet::North: + line.setP2(QPointF(scene_dock.x(), rect.top())); + break; + case Qet::East: + line.setP2(QPointF(rect.right() , scene_dock.y())); + break; + case Qet::South: + line.setP2(QPointF(scene_dock.x(), rect.bottom())); + break; + case Qet::West: + line.setP2(QPointF(rect.left(), scene_dock.y())); + break; + } - return line; + return line; } /** - @brief Terminal::boundingRect - @return Le rectangle (en precision flottante) delimitant la borne et ses alentours. + @brief Terminal::boundingRect + @return Le rectangle (en precision flottante) delimitant la borne et ses alentours. */ QRectF Terminal::boundingRect() const { - if (br_ -> isNull()) - { - qreal dcx = d->m_pos.x(); - qreal dcy = d->m_pos.y(); - qreal dex = dock_elmt_.x(); - qreal dey = dock_elmt_.y(); - QPointF origin = (dcx <= dex && dcy <= dey ? d->m_pos : dock_elmt_); - origin += QPointF(-3.0, -3.0); - qreal w = qAbs((int)(dcx - dex)) + 7; - qreal h = qAbs((int)(dcy - dey)) + 7; - *br_ = QRectF(origin, QSizeF(w, h)); - } - return(*br_); + if (br_ -> isNull()) + { + qreal dcx = d->m_pos.x(); + qreal dcy = d->m_pos.y(); + qreal dex = dock_elmt_.x(); + qreal dey = dock_elmt_.y(); + QPointF origin = (dcx <= dex && dcy <= dey ? d->m_pos : dock_elmt_); + origin += QPointF(-3.0, -3.0); + qreal w = qAbs((int)(dcx - dex)) + 7; + qreal h = qAbs((int)(dcy - dey)) + 7; + *br_ = QRectF(origin, QSizeF(w, h)); + } + return(*br_); } /** - @brief Terminal::alignedWithTerminal - If this terminal is aligned with an other terminal - and is orientation is opposed return the other terminal - else return nullptr - @return + @brief Terminal::alignedWithTerminal + If this terminal is aligned with an other terminal + and is orientation is opposed return the other terminal + else return nullptr + @return */ Terminal* Terminal::alignedWithTerminal() const { - QLineF line(HelpLine()); + QLineF line(HelpLine()); - QPainterPath path; - path.moveTo(line.p1()); - path.lineTo(line.p2()); + QPainterPath path; + path.moveTo(line.p1()); + path.lineTo(line.p2()); - //Get all QGraphicsItem in the alignement of this terminal - QList qgi_list = diagram() -> items(path); + //Get all QGraphicsItem in the alignement of this terminal + QList qgi_list = diagram() -> items(path); - //Remove all terminals of the parent element - foreach (Terminal *t, parent_element_ -> terminals()) - qgi_list.removeAll(t); + //Remove all terminals of the parent element + foreach (Terminal *t, parent_element_ -> terminals()) + qgi_list.removeAll(t); - if (qgi_list.isEmpty()) return nullptr; + if (qgi_list.isEmpty()) return nullptr; - //Get terminals only if orientation is opposed with this terminal - QList available_terminals; - foreach (QGraphicsItem *qgi, qgi_list) - { - if (Terminal *tt = qgraphicsitem_cast (qgi)) - { - //Call QET::lineContainsPoint to be sure the line intersect - //the dock point and not an other part of terminal - if (Qet::isOpposed(orientation(), tt -> orientation()) && - QET::lineContainsPoint(line, tt -> dockConductor())) - { - available_terminals << tt; - } - } - } + //Get terminals only if orientation is opposed with this terminal + QList available_terminals; + foreach (QGraphicsItem *qgi, qgi_list) + { + if (Terminal *tt = qgraphicsitem_cast (qgi)) + { + //Call QET::lineContainsPoint to be sure the line intersect + //the dock point and not an other part of terminal + if (Qet::isOpposed(orientation(), tt -> orientation()) && + QET::lineContainsPoint(line, tt -> dockConductor())) + { + available_terminals << tt; + } + } + } - if (available_terminals.isEmpty()) return nullptr; - if (available_terminals.size() == 1) return (available_terminals.first()); + if (available_terminals.isEmpty()) return nullptr; + if (available_terminals.size() == 1) return (available_terminals.first()); - //Available_terminals have several terminals, we get the nearest terminal - line.setP2(available_terminals.first() -> dockConductor()); - qreal current_lenght = line.length(); - Terminal *nearest_terminal = available_terminals.takeFirst(); + //Available_terminals have several terminals, we get the nearest terminal + line.setP2(available_terminals.first() -> dockConductor()); + qreal current_lenght = line.length(); + Terminal *nearest_terminal = available_terminals.takeFirst(); - //Search the nearest terminal to this one - foreach (Terminal *terminal, available_terminals) - { - line.setP2(terminal -> dockConductor()); - if (line.length() < current_lenght) - { - current_lenght = line.length(); - nearest_terminal = terminal; - } - } + //Search the nearest terminal to this one + foreach (Terminal *terminal, available_terminals) + { + line.setP2(terminal -> dockConductor()); + if (line.length() < current_lenght) + { + current_lenght = line.length(); + nearest_terminal = terminal; + } + } - return nearest_terminal; + return nearest_terminal; } /** - @brief Terminal::hoverEnterEvent - Gere l'entree de la souris sur la zone de la Borne. + @brief Terminal::hoverEnterEvent + Gere l'entree de la souris sur la zone de la Borne. */ void Terminal::hoverEnterEvent(QGraphicsSceneHoverEvent *) { - hovered_ = true; - update(); + hovered_ = true; + update(); } /** - @brief Terminal::hoverMoveEvent - Gere les mouvements de la souris sur la zone de la Borne. + @brief Terminal::hoverMoveEvent + Gere les mouvements de la souris sur la zone de la Borne. */ void Terminal::hoverMoveEvent(QGraphicsSceneHoverEvent *) {} /** - @brief Terminal::hoverLeaveEvent - Gere le fait que la souris sorte de la zone de la Borne. + @brief Terminal::hoverLeaveEvent + Gere le fait que la souris sorte de la zone de la Borne. */ void Terminal::hoverLeaveEvent(QGraphicsSceneHoverEvent *) { - hovered_ = false; - update(); + hovered_ = false; + update(); } /** - @brief Terminal::mousePressEvent - Gere le fait qu'on enfonce un bouton de la souris sur la Borne. - @param e L'evenement souris correspondant + @brief Terminal::mousePressEvent + Gere le fait qu'on enfonce un bouton de la souris sur la Borne. + @param e L'evenement souris correspondant */ void Terminal::mousePressEvent(QGraphicsSceneMouseEvent *e) { - if (Diagram *diag = diagram()) { - diag -> setConductorStart(mapToScene(QPointF(d->m_pos))); - diag -> setConductorStop(e -> scenePos()); - diag -> setConductor(true); - //setCursor(Qt::CrossCursor); - } + if (Diagram *diag = diagram()) { + diag -> setConductorStart(mapToScene(QPointF(d->m_pos))); + diag -> setConductorStop(e -> scenePos()); + diag -> setConductor(true); + //setCursor(Qt::CrossCursor); + } } /** - @brief Terminal::mouseMoveEvent - Gere le fait qu'on bouge la souris sur la Borne. - @param e L'evenement souris correspondant + @brief Terminal::mouseMoveEvent + Gere le fait qu'on bouge la souris sur la Borne. + @param e L'evenement souris correspondant */ void Terminal::mouseMoveEvent(QGraphicsSceneMouseEvent *e) { - // pendant la pose d'un conducteur, on adopte un autre curseur - //setCursor(Qt::CrossCursor); + // pendant la pose d'un conducteur, on adopte un autre curseur + //setCursor(Qt::CrossCursor); - // d'un mouvement a l'autre, il faut retirer l'effet hover de la borne precedente - if (previous_terminal_) { - if (previous_terminal_ == this) hovered_ = true; - else previous_terminal_ -> hovered_ = false; - previous_terminal_ -> hovered_color_ = previous_terminal_ -> neutralColor; - previous_terminal_ -> update(); - } + // d'un mouvement a l'autre, il faut retirer l'effet hover de la borne precedente + if (previous_terminal_) { + if (previous_terminal_ == this) hovered_ = true; + else previous_terminal_ -> hovered_ = false; + previous_terminal_ -> hovered_color_ = previous_terminal_ -> neutralColor; + previous_terminal_ -> update(); + } - Diagram *diag = diagram(); - if (!diag) return; - // si la scene est un Diagram, on actualise le poseur de conducteur - diag -> setConductorStop(e -> scenePos()); + Diagram *diag = diagram(); + if (!diag) return; + // si la scene est un Diagram, on actualise le poseur de conducteur + diag -> setConductorStop(e -> scenePos()); - // on recupere la liste des qgi sous le pointeur - QList qgis = diag -> items(e -> scenePos()); + // on recupere la liste des qgi sous le pointeur + QList qgis = diag -> items(e -> scenePos()); - /* le qgi le plus haut - = le poseur de conductor - = le premier element de la liste - = la liste ne peut etre vide - = on prend le deuxieme element de la liste - */ - Q_ASSERT_X(!(qgis.isEmpty()), "Terminal::mouseMoveEvent", "La liste d'items ne devrait pas etre vide"); + /* le qgi le plus haut + = le poseur de conductor + = le premier element de la liste + = la liste ne peut etre vide + = on prend le deuxieme element de la liste + */ + Q_ASSERT_X(!(qgis.isEmpty()), "Terminal::mouseMoveEvent", "La liste d'items ne devrait pas etre vide"); - // s'il n'y rien d'autre que le poseur de conducteur dans la liste, on arrete la - if (qgis.size() <= 1) return; + // s'il n'y rien d'autre que le poseur de conducteur dans la liste, on arrete la + if (qgis.size() <= 1) return; - // sinon on prend le deuxieme element de la liste et on verifie s'il s'agit d'une borne - QGraphicsItem *qgi = qgis.at(1); - // si le qgi est une borne... - Terminal *other_terminal = qgraphicsitem_cast(qgi); - if (!other_terminal) return; - previous_terminal_ = other_terminal; + // sinon on prend le deuxieme element de la liste et on verifie s'il s'agit d'une borne + QGraphicsItem *qgi = qgis.at(1); + // si le qgi est une borne... + Terminal *other_terminal = qgraphicsitem_cast(qgi); + if (!other_terminal) return; + previous_terminal_ = other_terminal; - // s'il s'agit d'une borne, on lui applique l'effet hover approprie - if (!canBeLinkedTo(other_terminal)) { - other_terminal -> hovered_color_ = forbiddenColor; - } else if (other_terminal -> conductorsCount()) { - other_terminal -> hovered_color_ = warningColor; - } else { - other_terminal -> hovered_color_ = allowedColor; - } + // s'il s'agit d'une borne, on lui applique l'effet hover approprie + if (!canBeLinkedTo(other_terminal)) { + other_terminal -> hovered_color_ = forbiddenColor; + } else if (other_terminal -> conductorsCount()) { + other_terminal -> hovered_color_ = warningColor; + } else { + other_terminal -> hovered_color_ = allowedColor; + } - other_terminal -> hovered_ = true; - other_terminal -> update(); + other_terminal -> hovered_ = true; + other_terminal -> update(); } /** - @brief Terminal::mouseReleaseEvent - @param e + @brief Terminal::mouseReleaseEvent + @param e */ void Terminal::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) { - previous_terminal_ = nullptr; - hovered_color_ = neutralColor; + previous_terminal_ = nullptr; + hovered_color_ = neutralColor; - if (!diagram()) return; + if (!diagram()) return; - //Stop conductor preview - diagram() -> setConductor(false); + //Stop conductor preview + diagram() -> setConductor(false); - //Get item under cursor - QGraphicsItem *qgi = diagram() -> itemAt(e -> scenePos(), QTransform()); - if (!qgi) return; + //Get item under cursor + QGraphicsItem *qgi = diagram() -> itemAt(e -> scenePos(), QTransform()); + if (!qgi) return; - //Element must be a terminal - Terminal *other_terminal = qgraphicsitem_cast(qgi); - if (!other_terminal) return; + //Element must be a terminal + Terminal *other_terminal = qgraphicsitem_cast(qgi); + if (!other_terminal) return; - other_terminal -> hovered_color_ = neutralColor; - other_terminal -> hovered_ = false; + other_terminal -> hovered_color_ = neutralColor; + other_terminal -> hovered_ = false; - //We stop her if we can't link this terminal with other terminal - if (!canBeLinkedTo(other_terminal)) return; + //We stop her if we can't link this terminal with other terminal + if (!canBeLinkedTo(other_terminal)) return; - //Create conductor - Conductor *new_conductor = new Conductor(this, other_terminal); + //Create conductor + Conductor *new_conductor = new Conductor(this, other_terminal); - //Get all conductors at the same potential of new conductors - QSet conductors_list = new_conductor->relatedPotentialConductors(); + //Get all conductors at the same potential of new conductors + QSet conductors_list = new_conductor->relatedPotentialConductors(); - //Compare the properties of every conductors stored in conductors_list, - //if every conductors properties is equal, we use this properties for the new conductor. - ConductorProperties others_properties; - bool use_properties = false; - if (!conductors_list.isEmpty()) - { - use_properties = true; - others_properties = (*conductors_list.begin())->properties(); - foreach (Conductor *conductor, conductors_list) { - if (conductor->properties() != others_properties) - use_properties = false; - } - } + //Compare the properties of every conductors stored in conductors_list, + //if every conductors properties is equal, we use this properties for the new conductor. + ConductorProperties others_properties; + bool use_properties = false; + if (!conductors_list.isEmpty()) + { + use_properties = true; + others_properties = (*conductors_list.begin())->properties(); + foreach (Conductor *conductor, conductors_list) { + if (conductor->properties() != others_properties) + use_properties = false; + } + } - QUndoCommand *undo = new QUndoCommand(); - QUndoCommand *aic = new AddItemCommand(new_conductor, diagram(), QPointF(), undo); - undo->setText(aic->text()); + QUndoCommand *undo = new QUndoCommand(); + QUndoCommand *aic = new AddItemCommand(new_conductor, diagram(), QPointF(), undo); + undo->setText(aic->text()); - if (use_properties) - { - Conductor *other = conductors_list.values().first(); - new_conductor->rSequenceNum() = other->sequenceNum(); - new_conductor->setProperties(others_properties); - } - else - { - //Autonum it - ConductorAutoNumerotation can (new_conductor, diagram(), undo); - can.numerate(); - } - //Add undo command to the parent diagram - diagram() -> undoStack().push(undo); - if (use_properties) - { - Conductor *other = conductors_list.values().first(); - new_conductor->setProperties(other->properties()); - } + if (use_properties) + { + Conductor *other = conductors_list.values().first(); + new_conductor->rSequenceNum() = other->sequenceNum(); + new_conductor->setProperties(others_properties); + } + else + { + //Autonum it + ConductorAutoNumerotation can (new_conductor, diagram(), undo); + can.numerate(); + } + //Add undo command to the parent diagram + diagram() -> undoStack().push(undo); + if (use_properties) + { + Conductor *other = conductors_list.values().first(); + new_conductor->setProperties(other->properties()); + } } /** - @brief Terminal::updateConductor - Update the path of conductor docked to this terminal + @brief Terminal::updateConductor + Update the path of conductor docked to this terminal */ void Terminal::updateConductor() { - foreach (Conductor *conductor, conductors_) - conductor->updatePath(); + foreach (Conductor *conductor, conductors_) + conductor->updatePath(); } /** - @brief Terminal::isLinkedTo - @param other_terminal Autre borne - @return true si cette borne est reliee a other_terminal, false sion + @brief Terminal::isLinkedTo + @param other_terminal Autre borne + @return true si cette borne est reliee a other_terminal, false sion */ bool Terminal::isLinkedTo(Terminal *other_terminal) { - if (other_terminal == this) return(false); + if (other_terminal == this) return(false); - bool already_linked = false; - foreach (Conductor *c, conductors_) { - if (c -> terminal1 == other_terminal || c -> terminal2 == other_terminal) { - already_linked = true; - break; - } - } - return(already_linked); + bool already_linked = false; + foreach (Conductor *c, conductors_) { + if (c -> terminal1 == other_terminal || c -> terminal2 == other_terminal) { + already_linked = true; + break; + } + } + return(already_linked); } /** - @brief Terminal::canBeLinkedTo - Checking if the terminal can be linked to \p other_terminal or not - Reasons for not linable: - - \p other_terminal is this terminal - - this terminal is already connected to \p other_terminal - @param other_terminal - @return true if this terminal can be linked to other_terminal, - otherwise false + @brief Terminal::canBeLinkedTo + Checking if the terminal can be linked to \p other_terminal or not + Reasons for not linable: + - \p other_terminal is this terminal + - this terminal is already connected to \p other_terminal + @param other_terminal + @return true if this terminal can be linked to other_terminal, + otherwise false */ bool Terminal::canBeLinkedTo(Terminal *other_terminal) { - if (other_terminal == this || isLinkedTo(other_terminal)) - return false; + if (other_terminal == this || isLinkedTo(other_terminal)) + return false; - return true; + return true; } /** - @brief Terminal::conductors - @return La liste des conducteurs lies a cette borne + @brief Terminal::conductors + @return La liste des conducteurs lies a cette borne */ QList Terminal::conductors() const { - return(conductors_); + return(conductors_); } /** - @brief Terminal::toXml - Methode d'export en XML - @param doc Le Document XML a utiliser pour creer l'element XML - @return un QDomElement representant cette borne + @brief Terminal::toXml + Methode d'export en XML + @param doc Le Document XML a utiliser pour creer l'element XML + @return un QDomElement representant cette borne */ QDomElement Terminal::toXml(QDomDocument &doc) const { - QDomElement qdo = doc.createElement("terminal"); + QDomElement qdo = doc.createElement("terminal"); - // for backward compatibility - qdo.setAttribute("x", QString("%1").arg(dock_elmt_.x())); - qdo.setAttribute("y", QString("%1").arg(dock_elmt_.y())); - // end for backward compatibility + // for backward compatibility + qdo.setAttribute("x", QString("%1").arg(dock_elmt_.x())); + qdo.setAttribute("y", QString("%1").arg(dock_elmt_.y())); + // end for backward compatibility - qdo.setAttribute("orientation", d->m_orientation); - qdo.setAttribute("number", number_terminal_); - qdo.setAttribute("name", name_terminal_); - qdo.setAttribute("nameHidden", name_terminal_hidden); - return(qdo); + qdo.setAttribute("orientation", d->m_orientation); + qdo.setAttribute("number", number_terminal_); + qdo.setAttribute("name", name_terminal_); + qdo.setAttribute("nameHidden", name_terminal_hidden); + return(qdo); } /** - @brief Terminal::valideXml - Permet de savoir si un element XML represente une borne - @param terminal Le QDomElement a analyser - @return true si le QDomElement passe en parametre est une borne, false sinon + @brief Terminal::valideXml + Permet de savoir si un element XML represente une borne + @param terminal Le QDomElement a analyser + @return true si le QDomElement passe en parametre est une borne, false sinon */ bool Terminal::valideXml(QDomElement &terminal) { - // verifie le nom du tag - if (terminal.tagName() != "terminal") return(false); + // verifie le nom du tag + if (terminal.tagName() != "terminal") return(false); - // verifie la presence des attributs minimaux - if (!terminal.hasAttribute("x")) return(false); - if (!terminal.hasAttribute("y")) return(false); - if (!terminal.hasAttribute("orientation")) return(false); + // verifie la presence des attributs minimaux + if (!terminal.hasAttribute("x")) return(false); + if (!terminal.hasAttribute("y")) return(false); + if (!terminal.hasAttribute("orientation")) return(false); - bool conv_ok; - // parse l'abscisse - terminal.attribute("x").toDouble(&conv_ok); - if (!conv_ok) return(false); + bool conv_ok; + // parse l'abscisse + terminal.attribute("x").toDouble(&conv_ok); + if (!conv_ok) return(false); - // parse l'ordonnee - terminal.attribute("y").toDouble(&conv_ok); - if (!conv_ok) return(false); + // parse l'ordonnee + terminal.attribute("y").toDouble(&conv_ok); + if (!conv_ok) return(false); - // parse l'id - terminal.attribute("id").toInt(&conv_ok); - if (!conv_ok) return(false); + // parse l'id + terminal.attribute("id").toInt(&conv_ok); + if (!conv_ok) return(false); - // parse l'orientation - int terminal_or = terminal.attribute("orientation").toInt(&conv_ok); - if (!conv_ok) return(false); - if (terminal_or != Qet::North - && terminal_or != Qet::South - && terminal_or != Qet::East - && terminal_or != Qet::West) return(false); + // parse l'orientation + int terminal_or = terminal.attribute("orientation").toInt(&conv_ok); + if (!conv_ok) return(false); + if (terminal_or != Qet::North + && terminal_or != Qet::South + && terminal_or != Qet::East + && terminal_or != Qet::West) return(false); - // a ce stade, la borne est syntaxiquement correcte - return(true); + // a ce stade, la borne est syntaxiquement correcte + return(true); } /** - @brief Terminal::fromXml - Permet de savoir si un element XML represente cette borne. Attention, - l'element XML n'est pas verifie - @param terminal Le QDomElement a analyser - @return true si la borne "se reconnait" - (memes coordonnes, meme orientation), false sinon + @brief Terminal::fromXml + Permet de savoir si un element XML represente cette borne. Attention, + l'element XML n'est pas verifie + @param terminal Le QDomElement a analyser + @return true si la borne "se reconnait" + (memes coordonnes, meme orientation), false sinon */ bool Terminal::fromXml(QDomElement &terminal) { - number_terminal_ = terminal.attribute("number"); - name_terminal_ = terminal.attribute("name"); - name_terminal_hidden = terminal.attribute("nameHidden").toInt(); + number_terminal_ = terminal.attribute("number"); + name_terminal_ = terminal.attribute("name"); + name_terminal_hidden = terminal.attribute("nameHidden").toInt(); - return ( - qFuzzyCompare(terminal.attribute("x").toDouble(), dock_elmt_.x()) && - qFuzzyCompare(terminal.attribute("y").toDouble(), dock_elmt_.y()) && - (terminal.attribute("orientation").toInt() == d->m_orientation) - ); + return ( + qFuzzyCompare(terminal.attribute("x").toDouble(), dock_elmt_.x()) && + qFuzzyCompare(terminal.attribute("y").toDouble(), dock_elmt_.y()) && + (terminal.attribute("orientation").toInt() == d->m_orientation) + ); } /** - @brief Terminal::dockConductor - @return the position, relative to the scene, of the docking point for - conductors. + @brief Terminal::dockConductor + @return the position, relative to the scene, of the docking point for + conductors. */ QPointF Terminal::dockConductor() const { - return(mapToScene(d->m_pos)); + return(mapToScene(d->m_pos)); } /** - @brief Terminal::diagram - @return le Diagram auquel cette borne appartient, - ou 0 si cette borne est independant + @brief Terminal::diagram + @return le Diagram auquel cette borne appartient, + ou 0 si cette borne est independant */ Diagram *Terminal::diagram() const { - return(qobject_cast(scene())); + return(qobject_cast(scene())); } /** - @brief Terminal::parentElement - @return L'element auquel cette borne est rattachee + @brief Terminal::parentElement + @return L'element auquel cette borne est rattachee */ Element *Terminal::parentElement() const { - return(parent_element_); + return(parent_element_); } QUuid Terminal::uuid() const { - return d->m_uuid; + return d->m_uuid; } /** - @brief Conductor::relatedPotentialTerminal - Return terminal at the same potential from the same - parent element of terminal. - For folio report, return the terminal of linked other report. - For Terminal element, return the other terminal of terminal element. - @param terminal : to start search - @param all_diagram :if true return all related terminal, - false return only terminal in the same diagram of t - @return the list of terminal at the same potential + @brief Conductor::relatedPotentialTerminal + Return terminal at the same potential from the same + parent element of terminal. + For folio report, return the terminal of linked other report. + For Terminal element, return the other terminal of terminal element. + @param terminal : to start search + @param all_diagram :if true return all related terminal, + false return only terminal in the same diagram of t + @return the list of terminal at the same potential */ QList relatedPotentialTerminal ( - const Terminal *terminal, const bool all_diagram) + const Terminal *terminal, const bool all_diagram) { - // If terminal parent element is a folio report. - if (all_diagram && terminal -> parentElement() -> linkType() & Element::AllReport) - { - QList elmt_list = terminal -> parentElement() -> linkedElements(); - if (!elmt_list.isEmpty()) - { - return (elmt_list.first()->terminals()); - } - } - // If terminal parent element is a Terminal element. - else if (terminal -> parentElement() -> linkType() & Element::Terminale) - { - QList terminals = terminal->parentElement()->terminals(); - terminals.removeAll(const_cast(terminal)); - return terminals; - } + // If terminal parent element is a folio report. + if (all_diagram && terminal -> parentElement() -> linkType() & Element::AllReport) + { + QList elmt_list = terminal -> parentElement() -> linkedElements(); + if (!elmt_list.isEmpty()) + { + return (elmt_list.first()->terminals()); + } + } + // If terminal parent element is a Terminal element. + else if (terminal -> parentElement() -> linkType() & Element::Terminale) + { + QList terminals = terminal->parentElement()->terminals(); + terminals.removeAll(const_cast(terminal)); + return terminals; + } - return QList(); + return QList(); } diff --git a/sources/qetgraphicsitem/terminal.h b/sources/qetgraphicsitem/terminal.h index 7e0ca59f6..43bf34762 100644 --- a/sources/qetgraphicsitem/terminal.h +++ b/sources/qetgraphicsitem/terminal.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef TERMINAL_H #define TERMINAL_H @@ -26,167 +26,167 @@ class Element; class TerminalData; /** - @brief The Terminal class - This class represents a terminal of an electrical element, i.e. a possible - plug point for conductors. - This class handles all mouse events for connecting conductors + @brief The Terminal class + This class represents a terminal of an electrical element, i.e. a possible + plug point for conductors. + This class handles all mouse events for connecting conductors */ class Terminal : public QGraphicsObject { - Q_OBJECT + Q_OBJECT - signals: - void conductorWasAdded(Conductor *conductor); - void conductorWasRemoved(Conductor *conductor); + signals: + void conductorWasAdded(Conductor *conductor); + void conductorWasRemoved(Conductor *conductor); - // constructors, destructor - public: - Terminal(QPointF, Qet::Orientation, Element * = nullptr); - Terminal(qreal, qreal, Qet::Orientation, Element * = nullptr); - Terminal(TerminalData* data, Element *e = nullptr); - Terminal(QPointF, Qet::Orientation, QString number, - QString name, bool hiddenName, Element * = nullptr); - ~Terminal() override; + // constructors, destructor + public: + Terminal(QPointF, Qet::Orientation, Element * = nullptr); + Terminal(qreal, qreal, Qet::Orientation, Element * = nullptr); + Terminal(TerminalData* data, Element *e = nullptr); + Terminal(QPointF, Qet::Orientation, QString number, + QString name, bool hiddenName, Element * = nullptr); + ~Terminal() override; - private: - Terminal(const Terminal &); + private: + Terminal(const Terminal &); - // methods - public: - /** - @brief type - Enable the use of qgraphicsitem_cast to safely - cast a QGraphicsItem into a Terminal - @return the QGraphicsItem type - */ - int type() const override { return Type; } + // methods + public: + /** + @brief type + Enable the use of qgraphicsitem_cast to safely + cast a QGraphicsItem into a Terminal + @return the QGraphicsItem type + */ + int type() const override { return Type; } - void paint( - QPainter *painter, - const QStyleOptionGraphicsItem *, - QWidget *) override; - void drawHelpLine (bool draw = true); - QLineF HelpLine () const; - QRectF boundingRect () const override; + void paint( + QPainter *painter, + const QStyleOptionGraphicsItem *, + QWidget *) override; + void drawHelpLine (bool draw = true); + QLineF HelpLine () const; + QRectF boundingRect () const override; - // methods to manage conductors attached to the terminal - Terminal* alignedWithTerminal () const; - bool addConductor (Conductor *conductor); - void removeConductor (Conductor *conductor); - int conductorsCount () const; - Diagram *diagram () const; - Element *parentElement () const; - QUuid uuid () const; + // methods to manage conductors attached to the terminal + Terminal* alignedWithTerminal () const; + bool addConductor (Conductor *conductor); + void removeConductor (Conductor *conductor); + int conductorsCount () const; + Diagram *diagram () const; + Element *parentElement () const; + QUuid uuid () const; - QList conductors() const; - Qet::Orientation orientation() const; - QPointF dockConductor() const; - QString number() const; - QString name() const; - void setNumber(QString number); - void setName(QString name, bool hiddenName); - void updateConductor(); - bool isLinkedTo(Terminal *); - bool canBeLinkedTo(Terminal *); + QList conductors() const; + Qet::Orientation orientation() const; + QPointF dockConductor() const; + QString number() const; + QString name() const; + void setNumber(QString number); + void setName(QString name, bool hiddenName); + void updateConductor(); + bool isLinkedTo(Terminal *); + bool canBeLinkedTo(Terminal *); - // methods related to XML import/export - static bool valideXml(QDomElement &); - bool fromXml (QDomElement &); - QDomElement toXml (QDomDocument &) const; + // methods related to XML import/export + static bool valideXml(QDomElement &); + bool fromXml (QDomElement &); + QDomElement toXml (QDomDocument &) const; - protected: - // methods related to events management - void hoverEnterEvent (QGraphicsSceneHoverEvent *) override; - void hoverMoveEvent (QGraphicsSceneHoverEvent *) override; - void hoverLeaveEvent (QGraphicsSceneHoverEvent *) override; - void mousePressEvent (QGraphicsSceneMouseEvent *) override; - void mouseMoveEvent (QGraphicsSceneMouseEvent *) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *) override; + protected: + // methods related to events management + void hoverEnterEvent (QGraphicsSceneHoverEvent *) override; + void hoverMoveEvent (QGraphicsSceneHoverEvent *) override; + void hoverLeaveEvent (QGraphicsSceneHoverEvent *) override; + void mousePressEvent (QGraphicsSceneMouseEvent *) override; + void mouseMoveEvent (QGraphicsSceneMouseEvent *) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *) override; - // attributes - public: - enum { Type = UserType + 1002 }; + // attributes + public: + enum { Type = UserType + 1002 }; - static const qreal terminalSize; - static const qreal Z; - // Various static colors used for hover effects - /// default color - static QColor neutralColor; - /// color for legal actions - static QColor allowedColor; - /// color for allowed but fuzzy or not recommended actions - static QColor warningColor; - /// color for forbidden actions - static QColor forbiddenColor; + static const qreal terminalSize; + static const qreal Z; + // Various static colors used for hover effects + /// default color + static QColor neutralColor; + /// color for legal actions + static QColor allowedColor; + /// color for allowed but fuzzy or not recommended actions + static QColor warningColor; + /// color for forbidden actions + static QColor forbiddenColor; - private: - bool m_draw_help_line{false}; - QGraphicsLineItem *m_help_line{nullptr}; - QGraphicsLineItem *m_help_line_a{nullptr}; + private: + bool m_draw_help_line{false}; + QGraphicsLineItem *m_help_line{nullptr}; + QGraphicsLineItem *m_help_line_a{nullptr}; - TerminalData* d; + TerminalData* d; - /// Parent electrical element - Element *parent_element_{nullptr}; - public: - /// docking point for parent element - QPointF dock_elmt_; - private: - /// List of conductors attached to the terminal - QList conductors_; - /** - Pointer to a rectangle representing the terminal bounding rect; - used to calculate the bounding rect once only; - used a pointer because boundingRect() is supposed to be const. - */ - QRectF *br_{nullptr}; - /// Last terminal seen through an attached conductor - Terminal *previous_terminal_; - /// Whether the mouse pointer is hovering the terminal - bool hovered_; - /// Color used for the hover effect - QColor hovered_color_; - /// Number of Terminal - QString number_terminal_; - /// Name of Terminal - QString name_terminal_; - bool name_terminal_hidden; + /// Parent electrical element + Element *parent_element_{nullptr}; + public: + /// docking point for parent element + QPointF dock_elmt_; + private: + /// List of conductors attached to the terminal + QList conductors_; + /** + Pointer to a rectangle representing the terminal bounding rect; + used to calculate the bounding rect once only; + used a pointer because boundingRect() is supposed to be const. + */ + QRectF *br_{nullptr}; + /// Last terminal seen through an attached conductor + Terminal *previous_terminal_; + /// Whether the mouse pointer is hovering the terminal + bool hovered_; + /// Color used for the hover effect + QColor hovered_color_; + /// Number of Terminal + QString number_terminal_; + /// Name of Terminal + QString name_terminal_; + bool name_terminal_hidden; - private: - void init(QString number, QString name, bool hiddenName); - void init(QPointF pf, Qet::Orientation o, QString number, - QString name, bool hiddenName); + private: + void init(QString number, QString name, bool hiddenName); + void init(QPointF pf, Qet::Orientation o, QString number, + QString name, bool hiddenName); }; /** - @brief Terminal::conductorsCount - @return the number of conductors attached to the terminal. + @brief Terminal::conductorsCount + @return the number of conductors attached to the terminal. */ inline int Terminal::conductorsCount() const { - return(conductors_.size()); + return(conductors_.size()); } /** - @brief Terminal::number - @return the number of terminal. + @brief Terminal::number + @return the number of terminal. */ inline QString Terminal::number() const { - return(number_terminal_); + return(number_terminal_); } /** - @brief Terminal::name - @return the name of terminal. + @brief Terminal::name + @return the name of terminal. */ inline QString Terminal::name() const { - return(name_terminal_); + return(name_terminal_); } QList relatedPotentialTerminal (const Terminal *terminal, - const bool all_diagram = true); + const bool all_diagram = true); #endif diff --git a/sources/qetproject.cpp b/sources/qetproject.cpp index 493733d19..eae884a47 100644 --- a/sources/qetproject.cpp +++ b/sources/qetproject.cpp @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ @@ -43,252 +43,252 @@ static int BACKUP_INTERVAL = 120000; //interval in ms of backup = 2min /** - @brief QETProject::QETProject - Create a empty project - @param parent + @brief QETProject::QETProject + Create a empty project + @param parent */ QETProject::QETProject(QObject *parent) : - QObject (parent), - m_titleblocks_collection(this), - m_data_base(this, this) + QObject (parent), + m_titleblocks_collection(this), + m_data_base(this, this) { - setDefaultTitleBlockProperties(TitleBlockProperties::defaultProperties()); + setDefaultTitleBlockProperties(TitleBlockProperties::defaultProperties()); - m_elements_collection = new XmlElementCollection(this); - init(); + m_elements_collection = new XmlElementCollection(this); + init(); } /** - @brief QETProject::QETProject - Construct a project from a .qet file - @param path : path of the file - @param parent : parent QObject + @brief QETProject::QETProject + Construct a project from a .qet file + @param path : path of the file + @param parent : parent QObject */ QETProject::QETProject(const QString &path, QObject *parent) : - QObject (parent), - m_titleblocks_collection(this), - m_data_base(this, this) + QObject (parent), + m_titleblocks_collection(this), + m_data_base(this, this) { - QFile file(path); - m_state = openFile(&file); - if (m_state != ProjectState::Ok) { - return; - } + QFile file(path); + m_state = openFile(&file); + if (m_state != ProjectState::Ok) { + return; + } - init(); + init(); } /** - @brief QETProject::QETProject - @param backup : backup file to open, QETProject take ownership of backup. - @param parent : parent QObject + @brief QETProject::QETProject + @param backup : backup file to open, QETProject take ownership of backup. + @param parent : parent QObject */ QETProject::QETProject(KAutoSaveFile *backup, QObject *parent) : - QObject (parent), - m_titleblocks_collection(this), - m_data_base(this, this) + QObject (parent), + m_titleblocks_collection(this), + m_data_base(this, this) { - m_state = openFile(backup); - //Failed to open from the backup, try to open the crashed - if (m_state != ProjectState::Ok) - { - QFile file(backup->managedFile().path()); - m_state = openFile(&file); - if(m_state != ProjectState::Ok) - { - backup->open(QIODevice::ReadWrite); - delete backup; - return; - } - } - //Set the real path, instead of the path of the backup. - setFilePath(backup->managedFile().path()); - delete backup; + m_state = openFile(backup); + //Failed to open from the backup, try to open the crashed + if (m_state != ProjectState::Ok) + { + QFile file(backup->managedFile().path()); + m_state = openFile(&file); + if(m_state != ProjectState::Ok) + { + backup->open(QIODevice::ReadWrite); + delete backup; + return; + } + } + //Set the real path, instead of the path of the backup. + setFilePath(backup->managedFile().path()); + delete backup; - //Set the project to read only mode if the file it. - QFileInfo fi(m_file_path); - setReadOnly(!fi.isWritable()); + //Set the project to read only mode if the file it. + QFileInfo fi(m_file_path); + setReadOnly(!fi.isWritable()); - init(); + init(); } /** - @brief QETProject::~QETProject - Destructor + @brief QETProject::~QETProject + Destructor */ QETProject::~QETProject() { - for (auto diagram : m_diagrams_list) - delete diagram; + for (auto diagram : m_diagrams_list) + delete diagram; } /** - @brief QETProject::dataBase - @return The data base of this project + @brief QETProject::dataBase + @return The data base of this project */ projectDataBase *QETProject::dataBase() { - return &m_data_base; + return &m_data_base; } /** - @brief QETProject::uuid - @return the uuid of this project + @brief QETProject::uuid + @return the uuid of this project */ QUuid QETProject::uuid() const { - return m_uuid; + return m_uuid; } /** - @brief QETProject::init + @brief QETProject::init */ void QETProject::init() { - connect(&m_titleblocks_collection, &TitleBlockTemplatesCollection::changed, this, &QETProject::updateDiagramsTitleBlockTemplate); - connect(&m_titleblocks_collection, &TitleBlockTemplatesCollection::aboutToRemove, this, &QETProject::removeDiagramsTitleBlockTemplate); + connect(&m_titleblocks_collection, &TitleBlockTemplatesCollection::changed, this, &QETProject::updateDiagramsTitleBlockTemplate); + connect(&m_titleblocks_collection, &TitleBlockTemplatesCollection::aboutToRemove, this, &QETProject::removeDiagramsTitleBlockTemplate); - m_undo_stack = new QUndoStack(this); - connect(m_undo_stack, SIGNAL(cleanChanged(bool)), this, SLOT(undoStackChanged(bool))); + m_undo_stack = new QUndoStack(this); + connect(m_undo_stack, SIGNAL(cleanChanged(bool)), this, SLOT(undoStackChanged(bool))); - m_save_backup_timer.setInterval(BACKUP_INTERVAL); - connect(&m_save_backup_timer, &QTimer::timeout, this, &QETProject::writeBackup); - m_save_backup_timer.start(); - writeBackup(); + m_save_backup_timer.setInterval(BACKUP_INTERVAL); + connect(&m_save_backup_timer, &QTimer::timeout, this, &QETProject::writeBackup); + m_save_backup_timer.start(); + writeBackup(); - QSettings settings; - int autosave_interval = settings.value("diagrameditor/autosave-interval", 0).toInt(); - if(autosave_interval > 0) - { - int ms = autosave_interval*60*1000; - m_autosave_timer.setInterval(ms); - connect(&m_autosave_timer, &QTimer::timeout, [this]() - { - if(!this->m_file_path.isEmpty()) - this->write(); - }); - m_autosave_timer.start(); - } + QSettings settings; + int autosave_interval = settings.value("diagrameditor/autosave-interval", 0).toInt(); + if(autosave_interval > 0) + { + int ms = autosave_interval*60*1000; + m_autosave_timer.setInterval(ms); + connect(&m_autosave_timer, &QTimer::timeout, [this]() + { + if(!this->m_file_path.isEmpty()) + this->write(); + }); + m_autosave_timer.start(); + } } /** - @brief QETProject::openFile - @param file - @return + @brief QETProject::openFile + @param file + @return */ QETProject::ProjectState QETProject::openFile(QFile *file) { - bool opened_here = file->isOpen() ? false : true; - if (!file->isOpen() - && !file->open(QIODevice::ReadOnly - | QIODevice::Text)) { - return FileOpenFailed; - } - QFileInfo fi(*file); - setFilePath(fi.absoluteFilePath()); + bool opened_here = file->isOpen() ? false : true; + if (!file->isOpen() + && !file->open(QIODevice::ReadOnly + | QIODevice::Text)) { + return FileOpenFailed; + } + QFileInfo fi(*file); + setFilePath(fi.absoluteFilePath()); - //Extract the content of the xml - QDomDocument xml_project; - if (!xml_project.setContent(file)) - { - if(opened_here) { - file->close(); - } - return XmlParsingFailed; - } + //Extract the content of the xml + QDomDocument xml_project; + if (!xml_project.setContent(file)) + { + if(opened_here) { + file->close(); + } + return XmlParsingFailed; + } - //Build the project from the xml - readProjectXml(xml_project); + //Build the project from the xml + readProjectXml(xml_project); - if (!fi.isWritable()) { - setReadOnly(true); - } - if(opened_here) { - file->close(); - } - return ProjectState::Ok; + if (!fi.isWritable()) { + setReadOnly(true); + } + if(opened_here) { + file->close(); + } + return ProjectState::Ok; } /** - Cette methode peut etre utilisee pour tester la bonne ouverture d'un projet - @return l'etat du projet - @see ProjectState + Cette methode peut etre utilisee pour tester la bonne ouverture d'un projet + @return l'etat du projet + @see ProjectState */ QETProject::ProjectState QETProject::state() const { - return(m_state); + return(m_state); } /** - @return la liste des schemas de ce projet + @return la liste des schemas de ce projet */ QList QETProject::diagrams() const { - return(m_diagrams_list); + return(m_diagrams_list); } /** - @param diagram Pointer to a Diagram object - @return the folio number of the given diagram object within the project, - or -1 if it is not part of this project. - Note: this returns 0 for the first diagram, not 1 + @param diagram Pointer to a Diagram object + @return the folio number of the given diagram object within the project, + or -1 if it is not part of this project. + Note: this returns 0 for the first diagram, not 1 */ int QETProject::folioIndex(const Diagram *diagram) const { - // QList::indexOf returns -1 if no item matched. - return(m_diagrams_list.indexOf(const_cast(diagram))); + // QList::indexOf returns -1 if no item matched. + return(m_diagrams_list.indexOf(const_cast(diagram))); } /** - @brief QETProject::embeddedCollection - @return The embedded collection + @brief QETProject::embeddedCollection + @return The embedded collection */ XmlElementCollection *QETProject::embeddedElementCollection() const { - return m_elements_collection; + return m_elements_collection; } /** - @return the title block templates collection enbeedded within this project + @return the title block templates collection enbeedded within this project */ TitleBlockTemplatesProjectCollection *QETProject::embeddedTitleBlockTemplatesCollection() { - return(&m_titleblocks_collection); + return(&m_titleblocks_collection); } /** - @return le chemin du fichier dans lequel ce projet est enregistre + @return le chemin du fichier dans lequel ce projet est enregistre */ QString QETProject::filePath() { - return(m_file_path); + return(m_file_path); } /** - @brief QETProject::setFilePath - Set the filepath of this project file - Set a file path also create a backup file according to the path. - If a previous path was set, the previous backup file is deleted and a new one - is created according to the path. - @param filepath + @brief QETProject::setFilePath + Set the filepath of this project file + Set a file path also create a backup file according to the path. + If a previous path was set, the previous backup file is deleted and a new one + is created according to the path. + @param filepath */ void QETProject::setFilePath(const QString &filepath) { - if (filepath == m_file_path) { - return; - } + if (filepath == m_file_path) { + return; + } - if (m_backup_file.isOpen()) { - m_backup_file.close(); - } - m_backup_file.setManagedFile(QUrl::fromLocalFile(filepath)); + if (m_backup_file.isOpen()) { + m_backup_file.close(); + } + m_backup_file.setManagedFile(QUrl::fromLocalFile(filepath)); - m_file_path = filepath; + m_file_path = filepath; - QFileInfo fi(m_file_path); - if (fi.isWritable()) { - setReadOnly(false); - } + QFileInfo fi(m_file_path); + if (fi.isWritable()) { + setReadOnly(false); + } //title block variables should be updated after file save as dialog is confirmed, before file is saved. m_project_properties.addValue("saveddate", QDate::currentDate().toString("yyyy-MM-dd")); @@ -299,645 +299,645 @@ void QETProject::setFilePath(const QString &filepath) - emit(projectFilePathChanged(this, m_file_path)); - emit(projectInformationsChanged(this)); - updateDiagramsFolioData(); + emit(projectFilePathChanged(this, m_file_path)); + emit(projectInformationsChanged(this)); + updateDiagramsFolioData(); } /** - @return le dossier contenant le fichier projet si celui-ci a ete - enregistre ; dans le cas contraire, cette methode retourne l'emplacement - du bureau de l'utilisateur. + @return le dossier contenant le fichier projet si celui-ci a ete + enregistre ; dans le cas contraire, cette methode retourne l'emplacement + du bureau de l'utilisateur. */ QString QETProject::currentDir() const { - QString current_directory; - if (m_file_path.isEmpty()) { - current_directory = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); - } else { - current_directory = QFileInfo(m_file_path).absoluteDir().absolutePath(); - } - return(current_directory); + QString current_directory; + if (m_file_path.isEmpty()) { + current_directory = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); + } else { + current_directory = QFileInfo(m_file_path).absoluteDir().absolutePath(); + } + return(current_directory); } /** - @return une chaine de caractere du type "Projet titre du projet". - Si le projet n'a pas de titre, le nom du fichier est utilise. - Si le projet n'est pas associe a un fichier, cette methode retourne "Projet - sans titre". - De plus, si le projet est en lecture seule, le tag "[lecture seule]" est - ajoute. + @return une chaine de caractere du type "Projet titre du projet". + Si le projet n'a pas de titre, le nom du fichier est utilise. + Si le projet n'est pas associe a un fichier, cette methode retourne "Projet + sans titre". + De plus, si le projet est en lecture seule, le tag "[lecture seule]" est + ajoute. */ QString QETProject::pathNameTitle() const { - QString final_title; + QString final_title; - if (!project_title_.isEmpty()) { - final_title = QString( - tr( - "Projet « %1 : %2»", - "displayed title for a ProjectView - %1 is the project title, -%2 is the project path" - ) - ).arg(project_title_).arg (m_file_path); - } else if (!m_file_path.isEmpty()) { - final_title = QString( - tr( - "Projet %1", - "displayed title for a title-less project - %1 is the file name" - ) - ).arg(QFileInfo(m_file_path).completeBaseName()); - } else { - final_title = QString( - tr( - "Projet sans titre", - "displayed title for a project-less, file-less project" - ) - ); - } + if (!project_title_.isEmpty()) { + final_title = QString( + tr( + "Projet « %1 : %2»", + "displayed title for a ProjectView - %1 is the project title, -%2 is the project path" + ) + ).arg(project_title_).arg (m_file_path); + } else if (!m_file_path.isEmpty()) { + final_title = QString( + tr( + "Projet %1", + "displayed title for a title-less project - %1 is the file name" + ) + ).arg(QFileInfo(m_file_path).completeBaseName()); + } else { + final_title = QString( + tr( + "Projet sans titre", + "displayed title for a project-less, file-less project" + ) + ); + } - if (isReadOnly()) { - final_title = QString( - tr( - "%1 [lecture seule]", - "displayed title for a read-only project - %1 is a displayable title" - ) - ).arg(final_title); - } - if (m_modified) { - final_title = QString( - tr( - "%1 [modifié]", - "displayed title for a modified project - %1 is a displayable title" - ) - ).arg(final_title); - } + if (isReadOnly()) { + final_title = QString( + tr( + "%1 [lecture seule]", + "displayed title for a read-only project - %1 is a displayable title" + ) + ).arg(final_title); + } + if (m_modified) { + final_title = QString( + tr( + "%1 [modifié]", + "displayed title for a modified project - %1 is a displayable title" + ) + ).arg(final_title); + } - return(final_title); + return(final_title); } /** - @return le titre du projet + @return le titre du projet */ QString QETProject::title() const { - return(project_title_); + return(project_title_); } /** - @return la version de QElectroTech declaree dans le fichier projet lorsque - celui-ci a ete ouvert ; si ce projet n'a jamais ete enregistre / ouvert - depuis un fichier, cette methode retourne -1. + @return la version de QElectroTech declaree dans le fichier projet lorsque + celui-ci a ete ouvert ; si ce projet n'a jamais ete enregistre / ouvert + depuis un fichier, cette methode retourne -1. */ qreal QETProject::declaredQElectroTechVersion() { - return(m_project_qet_version); + return(m_project_qet_version); } /** - @param title le nouveau titre du projet + @param title le nouveau titre du projet */ void QETProject::setTitle(const QString &title) { - // ne fait rien si le projet est en lecture seule - if (isReadOnly()) return; + // ne fait rien si le projet est en lecture seule + if (isReadOnly()) return; - // ne fait rien si le titre du projet n'est pas change par l'appel de cette methode - if (project_title_ == title) return; + // ne fait rien si le titre du projet n'est pas change par l'appel de cette methode + if (project_title_ == title) return; - project_title_ = title; - emit(projectTitleChanged(this, project_title_)); - emit(projectInformationsChanged(this)); - updateDiagramsFolioData(); + project_title_ = title; + emit(projectTitleChanged(this, project_title_)); + emit(projectInformationsChanged(this)); + updateDiagramsFolioData(); } /** - @return les dimensions par defaut utilisees lors de la creation d'un - nouveau schema dans ce projet. + @return les dimensions par defaut utilisees lors de la creation d'un + nouveau schema dans ce projet. */ BorderProperties QETProject::defaultBorderProperties() const { - return(default_border_properties_); + return(default_border_properties_); } /** - Permet de specifier les dimensions par defaut utilisees lors de la creation - d'un nouveau schema dans ce projet. - @param border dimensions d'un schema + Permet de specifier les dimensions par defaut utilisees lors de la creation + d'un nouveau schema dans ce projet. + @param border dimensions d'un schema */ void QETProject::setDefaultBorderProperties(const BorderProperties &border) { - default_border_properties_ = border; + default_border_properties_ = border; } /** - @return le cartouche par defaut utilise lors de la creation d'un - nouveau schema dans ce projet. + @return le cartouche par defaut utilise lors de la creation d'un + nouveau schema dans ce projet. */ TitleBlockProperties QETProject::defaultTitleBlockProperties() const { - return(default_titleblock_properties_); + return(default_titleblock_properties_); } /** - @brief QETProject::setDefaultTitleBlockProperties - Specify the title block to be used at the creation of a new diagram for this project - @param titleblock + @brief QETProject::setDefaultTitleBlockProperties + Specify the title block to be used at the creation of a new diagram for this project + @param titleblock */ void QETProject::setDefaultTitleBlockProperties(const TitleBlockProperties &titleblock) { - default_titleblock_properties_ = titleblock; - //Integrate the title block in this project - if (!titleblock.template_name.isEmpty()) - { - TitleBlockTemplatesFilesCollection *collection = nullptr; - switch (titleblock.collection) - { - case QET::Common : - collection = QETApp::commonTitleBlockTemplatesCollection(); - break; - case QET::Custom : - collection = QETApp::customTitleBlockTemplatesCollection(); - break; - case QET::Embedded : - //Titleblock is already embedded to project - return; - } + default_titleblock_properties_ = titleblock; + //Integrate the title block in this project + if (!titleblock.template_name.isEmpty()) + { + TitleBlockTemplatesFilesCollection *collection = nullptr; + switch (titleblock.collection) + { + case QET::Common : + collection = QETApp::commonTitleBlockTemplatesCollection(); + break; + case QET::Custom : + collection = QETApp::customTitleBlockTemplatesCollection(); + break; + case QET::Embedded : + //Titleblock is already embedded to project + return; + } - IntegrationMoveTitleBlockTemplatesHandler m_; - integrateTitleBlockTemplate(collection -> location(titleblock.template_name), &m_); - } - emit defaultTitleBlockPropertiesChanged(); + IntegrationMoveTitleBlockTemplatesHandler m_; + integrateTitleBlockTemplate(collection -> location(titleblock.template_name), &m_); + } + emit defaultTitleBlockPropertiesChanged(); } /** - @return le type de conducteur par defaut utilise lors de la creation d'un - nouveau schema dans ce projet. + @return le type de conducteur par defaut utilise lors de la creation d'un + nouveau schema dans ce projet. */ ConductorProperties QETProject::defaultConductorProperties() const { - return(default_conductor_properties_); + return(default_conductor_properties_); } /** - Permet de specifier e type de conducteur par defaut utilise lors de la - creation d'un nouveau schema dans ce projet. + Permet de specifier e type de conducteur par defaut utilise lors de la + creation d'un nouveau schema dans ce projet. */ void QETProject::setDefaultConductorProperties(const ConductorProperties &conductor) { - default_conductor_properties_ = conductor; + default_conductor_properties_ = conductor; } QString QETProject::defaultReportProperties() const { - return m_default_report_properties; + return m_default_report_properties; } void QETProject::setDefaultReportProperties(const QString &properties) { - QString old = m_default_report_properties; - m_default_report_properties = properties; + QString old = m_default_report_properties; + m_default_report_properties = properties; - emit reportPropertiesChanged(old, properties); + emit reportPropertiesChanged(old, properties); } void QETProject::setDefaultXRefProperties(const QString& type, const XRefProperties &properties) { - m_default_xref_properties.insert(type, properties); - emit XRefPropertiesChanged(); + m_default_xref_properties.insert(type, properties); + emit XRefPropertiesChanged(); } void QETProject::setDefaultXRefProperties(QHash hash) { - m_default_xref_properties.swap(hash); - emit XRefPropertiesChanged(); + m_default_xref_properties.swap(hash); + emit XRefPropertiesChanged(); } /** - @brief QETProject::conductorAutoNum - @return All value of conductor autonum stored in project + @brief QETProject::conductorAutoNum + @return All value of conductor autonum stored in project */ QHash QETProject::conductorAutoNum() const { - return m_conductor_autonum; + return m_conductor_autonum; } /** - @brief QETProject::elementAutoNum - @return All value of element autonum stored in project + @brief QETProject::elementAutoNum + @return All value of element autonum stored in project */ QHash QETProject::elementAutoNum() const { - return m_element_autonum; + return m_element_autonum; } /** - @brief QETProject::elementAutoNumFormula - @param key : autonum title - @return Formula of element autonum stored in element autonum + @brief QETProject::elementAutoNumFormula + @param key : autonum title + @return Formula of element autonum stored in element autonum */ QString QETProject::elementAutoNumFormula (const QString& key) const { - if (m_element_autonum.contains(key)) { - return autonum::numerotationContextToFormula(m_element_autonum[key]); - } + if (m_element_autonum.contains(key)) { + return autonum::numerotationContextToFormula(m_element_autonum[key]); + } - return QString(); + return QString(); } /** - @brief QETProject::elementAutoNumCurrentFormula - @return current formula being used by project + @brief QETProject::elementAutoNumCurrentFormula + @return current formula being used by project */ QString QETProject::elementAutoNumCurrentFormula() const { - return elementAutoNumFormula(m_current_element_autonum); + return elementAutoNumFormula(m_current_element_autonum); } /** - @brief QETProject::elementCurrentAutoNum - @return current element autonum title + @brief QETProject::elementCurrentAutoNum + @return current element autonum title */ QString QETProject::elementCurrentAutoNum () const { - return m_current_element_autonum; + return m_current_element_autonum; } /** - @brief QETProject::setCurrrentElementAutonum - @param autoNum : set the current element autonum to autonum + @brief QETProject::setCurrrentElementAutonum + @param autoNum : set the current element autonum to autonum */ void QETProject::setCurrrentElementAutonum(QString autoNum) { - m_current_element_autonum = std::move(autoNum); + m_current_element_autonum = std::move(autoNum); } /** - @brief QETProject::conductorAutoNumFormula - @param key : autonum title - @return Formula of element autonum stored in conductor autonum + @brief QETProject::conductorAutoNumFormula + @param key : autonum title + @return Formula of element autonum stored in conductor autonum */ QString QETProject::conductorAutoNumFormula (const QString& key) const { - if (m_conductor_autonum.contains(key)) - return autonum::numerotationContextToFormula(m_conductor_autonum.value(key)); - else - return QString(); + if (m_conductor_autonum.contains(key)) + return autonum::numerotationContextToFormula(m_conductor_autonum.value(key)); + else + return QString(); } /** - @brief QETProject::conductorCurrentAutoNum - @return current conductor autonum title + @brief QETProject::conductorCurrentAutoNum + @return current conductor autonum title */ QString QETProject::conductorCurrentAutoNum () const { - return m_current_conductor_autonum; + return m_current_conductor_autonum; } /** - @brief QETProject::setCurrentConductorAutoNum - @param autoNum set the current conductor autonum to autonum + @brief QETProject::setCurrentConductorAutoNum + @param autoNum set the current conductor autonum to autonum */ void QETProject::setCurrentConductorAutoNum(QString autoNum) { - m_current_conductor_autonum = std::move(autoNum); + m_current_conductor_autonum = std::move(autoNum); } /** - @brief QETProject::folioAutoNum - @return All value of folio autonum stored in project + @brief QETProject::folioAutoNum + @return All value of folio autonum stored in project */ QHash QETProject::folioAutoNum() const { - return m_folio_autonum; + return m_folio_autonum; } /** - @brief QETProject::addConductorAutoNum - Add a new conductor numerotation context. If key already exist, - replace old context by the new context - @param key - @param context + @brief QETProject::addConductorAutoNum + Add a new conductor numerotation context. If key already exist, + replace old context by the new context + @param key + @param context */ void QETProject::addConductorAutoNum(const QString& key, const NumerotationContext& context) { - m_conductor_autonum.insert(key, context); + m_conductor_autonum.insert(key, context); } /** - @brief QETProject::addElementAutoNum - Add a new element numerotation context. If key already exist, - replace old context by the new context - @param key - @param context + @brief QETProject::addElementAutoNum + Add a new element numerotation context. If key already exist, + replace old context by the new context + @param key + @param context */ void QETProject::addElementAutoNum(const QString& key, const NumerotationContext& context) { - m_element_autonum.insert(key, context); - emit elementAutoNumAdded(key); + m_element_autonum.insert(key, context); + emit elementAutoNumAdded(key); } /** - @brief QETProject::addFolioAutoNum - Add a new folio numerotation context. If key already exist, - replace old context by the new context - @param key - @param context + @brief QETProject::addFolioAutoNum + Add a new folio numerotation context. If key already exist, + replace old context by the new context + @param key + @param context */ void QETProject::addFolioAutoNum(const QString& key, const NumerotationContext& context) { - m_folio_autonum.insert(key, context); + m_folio_autonum.insert(key, context); } /** - @brief QETProject::removeConductorAutoNum - Remove Conductor Numerotation Context stored with key - @param key + @brief QETProject::removeConductorAutoNum + Remove Conductor Numerotation Context stored with key + @param key */ void QETProject::removeConductorAutoNum(const QString& key) { - m_conductor_autonum.remove(key); + m_conductor_autonum.remove(key); } /** - @brief QETProject::removeElementAutonum - Remove Element Numerotation Context stored with key - @param key + @brief QETProject::removeElementAutonum + Remove Element Numerotation Context stored with key + @param key */ void QETProject::removeElementAutoNum(const QString& key) { - m_element_autonum.remove(key); - emit elementAutoNumRemoved(key); + m_element_autonum.remove(key); + emit elementAutoNumRemoved(key); } /** - @brief QETProject::removeFolioAutonum - Remove Folio Numerotation Context stored with key - @param key + @brief QETProject::removeFolioAutonum + Remove Folio Numerotation Context stored with key + @param key */ void QETProject::removeFolioAutoNum(const QString& key) { - m_folio_autonum.remove(key); + m_folio_autonum.remove(key); } /** - @brief QETProject::conductorAutoNum - Return conductor numerotation context stored with key. - If key is not found, return an empty numerotation context - @param key + @brief QETProject::conductorAutoNum + Return conductor numerotation context stored with key. + If key is not found, return an empty numerotation context + @param key */ NumerotationContext QETProject::conductorAutoNum (const QString &key) const { - if (m_conductor_autonum.contains(key)) return m_conductor_autonum[key]; - else return NumerotationContext(); + if (m_conductor_autonum.contains(key)) return m_conductor_autonum[key]; + else return NumerotationContext(); } /** - @brief QETProject::elementAutoNum - Return element numerotation context stored with key. - If key is not found, return an empty numerotation context - @param key + @brief QETProject::elementAutoNum + Return element numerotation context stored with key. + If key is not found, return an empty numerotation context + @param key */ NumerotationContext QETProject::elementAutoNum (const QString &key) { - if (m_element_autonum.contains(key)) return m_element_autonum[key]; - else return NumerotationContext(); + if (m_element_autonum.contains(key)) return m_element_autonum[key]; + else return NumerotationContext(); } /** - @brief QETProject::folioAutoNum - Return folio numerotation context stored with key. - If key is not found, return an empty numerotation context - @param key + @brief QETProject::folioAutoNum + Return folio numerotation context stored with key. + If key is not found, return an empty numerotation context + @param key */ NumerotationContext QETProject::folioAutoNum (const QString &key) const { - if (m_folio_autonum.contains(key)) return m_folio_autonum[key]; - else return NumerotationContext(); + if (m_folio_autonum.contains(key)) return m_folio_autonum[key]; + else return NumerotationContext(); } /** - @brief QETProject::freezeExistentConductorLabel - Freeze Existent Conductors in the selected folios - @param freeze - @param from - first folio index to apply freeze - @param to - last folio index to apply freeze + @brief QETProject::freezeExistentConductorLabel + Freeze Existent Conductors in the selected folios + @param freeze + @param from - first folio index to apply freeze + @param to - last folio index to apply freeze */ void QETProject::freezeExistentConductorLabel(bool freeze, int from, int to) { - for (int i = from; i <= to; i++) { - m_diagrams_list.at(i)->freezeConductors(freeze); - } + for (int i = from; i <= to; i++) { + m_diagrams_list.at(i)->freezeConductors(freeze); + } } /** - @brief QETProject::freezeNewConductorLabel - Freeze New Conductors in the selected folios - @param freeze - @param from - first folio index to apply freeze - @param to - last folio index to apply freeze + @brief QETProject::freezeNewConductorLabel + Freeze New Conductors in the selected folios + @param freeze + @param from - first folio index to apply freeze + @param to - last folio index to apply freeze */ void QETProject::freezeNewConductorLabel(bool freeze, int from, int to) { - for (int i = from; i <= to; i++) { - m_diagrams_list.at(i)->setFreezeNewConductors(freeze); - } + for (int i = from; i <= to; i++) { + m_diagrams_list.at(i)->setFreezeNewConductors(freeze); + } } /** - @brief QETProject::isFreezeNewConductors - @return freeze new conductors Project Wide status + @brief QETProject::isFreezeNewConductors + @return freeze new conductors Project Wide status */ bool QETProject::isFreezeNewConductors() { - return m_freeze_new_conductors; + return m_freeze_new_conductors; } /** - @brief QETProject::setfreezeNewConductors - Set Project Wide freeze new conductors + @brief QETProject::setfreezeNewConductors + Set Project Wide freeze new conductors */ void QETProject::setFreezeNewConductors(bool set) { - m_freeze_new_conductors = set; + m_freeze_new_conductors = set; } /** - @brief QETProject::freezeExistentElementLabel - Freeze Existent Elements in the selected folios - @param freeze - @param from - first folio index to apply freeze - @param to - last folio index to apply freeze + @brief QETProject::freezeExistentElementLabel + Freeze Existent Elements in the selected folios + @param freeze + @param from - first folio index to apply freeze + @param to - last folio index to apply freeze */ void QETProject::freezeExistentElementLabel(bool freeze, int from, int to) { - for (int i = from; i <= to; i++) { - m_diagrams_list.at(i)->freezeElements(freeze); - } + for (int i = from; i <= to; i++) { + m_diagrams_list.at(i)->freezeElements(freeze); + } } /** - @brief QETProject::freezeNewElementLabel - Freeze New Elements in the selected folios - @param freeze - @param from - first folio index to apply freeze - @param to - last folio index to apply freeze + @brief QETProject::freezeNewElementLabel + Freeze New Elements in the selected folios + @param freeze + @param from - first folio index to apply freeze + @param to - last folio index to apply freeze */ void QETProject::freezeNewElementLabel(bool freeze, int from, int to) { - for (int i = from; i <= to; i++) { - m_diagrams_list.at(i)->setFreezeNewElements(freeze); - } + for (int i = from; i <= to; i++) { + m_diagrams_list.at(i)->setFreezeNewElements(freeze); + } } /** - @brief QETProject::freezeNewElements - @return freeze new elements Project Wide status + @brief QETProject::freezeNewElements + @return freeze new elements Project Wide status */ bool QETProject::isFreezeNewElements() { - return m_freeze_new_elements; + return m_freeze_new_elements; } /** - @brief QETProject::setfreezeNewElements - Set Project Wide freeze new elements + @brief QETProject::setfreezeNewElements + Set Project Wide freeze new elements */ void QETProject::setFreezeNewElements(bool set) { - m_freeze_new_elements = set; + m_freeze_new_elements = set; } /** - @brief QETProject::autoConductor - @return true if use of auto conductor is authorized. - See also Q_PROPERTY autoConductor + @brief QETProject::autoConductor + @return true if use of auto conductor is authorized. + See also Q_PROPERTY autoConductor */ bool QETProject::autoConductor() const { - return m_auto_conductor; + return m_auto_conductor; } /** - @brief QETProject::setAutoConductor - @param ac - Enable the use of auto conductor if true - See also Q_PROPERTY autoConductor + @brief QETProject::setAutoConductor + @param ac + Enable the use of auto conductor if true + See also Q_PROPERTY autoConductor */ void QETProject::setAutoConductor(bool ac) { - if (ac != m_auto_conductor) - m_auto_conductor = ac; + if (ac != m_auto_conductor) + m_auto_conductor = ac; } /** - @brief QETProject::autoFolioNumberingNewFolios - emit Signal to add new Diagram with autonum - properties + @brief QETProject::autoFolioNumberingNewFolios + emit Signal to add new Diagram with autonum + properties */ void QETProject::autoFolioNumberingNewFolios() { - emit addAutoNumDiagram(); + emit addAutoNumDiagram(); } /** - @brief QETProject::autoFolioNumberingNewFolios - @param from - @param to - @param autonum : used, index from selected tabs "from" and "to" - rename folios with selected autonum + @brief QETProject::autoFolioNumberingNewFolios + @param from + @param to + @param autonum : used, index from selected tabs "from" and "to" + rename folios with selected autonum */ void QETProject::autoFolioNumberingSelectedFolios(int from, - int to, - const QString& autonum){ - int total_folio = m_diagrams_list.count(); - DiagramContext project_wide_properties = m_project_properties; - for (int i=from; i<=to; i++) { - QString title = m_diagrams_list[i] -> title(); - NumerotationContext nC = folioAutoNum(autonum); - NumerotationContextCommands nCC = NumerotationContextCommands(nC); - m_diagrams_list[i] -> border_and_titleblock.setFolio("%autonum"); - m_diagrams_list[i] -> border_and_titleblock.setFolioData( - i + 1, - total_folio, - nCC.toRepresentedString(), - project_wide_properties); - m_diagrams_list[i] -> project() -> addFolioAutoNum( - autonum,nCC.next()); - m_diagrams_list[i] -> update(); - } + int to, + const QString& autonum){ + int total_folio = m_diagrams_list.count(); + DiagramContext project_wide_properties = m_project_properties; + for (int i=from; i<=to; i++) { + QString title = m_diagrams_list[i] -> title(); + NumerotationContext nC = folioAutoNum(autonum); + NumerotationContextCommands nCC = NumerotationContextCommands(nC); + m_diagrams_list[i] -> border_and_titleblock.setFolio("%autonum"); + m_diagrams_list[i] -> border_and_titleblock.setFolioData( + i + 1, + total_folio, + nCC.toRepresentedString(), + project_wide_properties); + m_diagrams_list[i] -> project() -> addFolioAutoNum( + autonum,nCC.next()); + m_diagrams_list[i] -> update(); + } } /** - @brief QETProject::toXml - @return un document XML representant le projet + @brief QETProject::toXml + @return un document XML representant le projet */ QDomDocument QETProject::toXml() { - // racine du projet - QDomDocument xml_doc; - QDomElement project_root = xml_doc.createElement("project"); - project_root.setAttribute("version", QET::version); - project_root.setAttribute("title", project_title_); - xml_doc.appendChild(project_root); + // racine du projet + QDomDocument xml_doc; + QDomElement project_root = xml_doc.createElement("project"); + project_root.setAttribute("version", QET::version); + project_root.setAttribute("title", project_title_); + xml_doc.appendChild(project_root); - // titleblock templates, if any - if (m_titleblocks_collection.templates().count()) { - QDomElement titleblocktemplates_elmt = xml_doc.createElement("titleblocktemplates"); - foreach (QString template_name, m_titleblocks_collection.templates()) { - QDomElement e = m_titleblocks_collection.getTemplateXmlDescription(template_name); - titleblocktemplates_elmt.appendChild(xml_doc.importNode(e, true)); - } - project_root.appendChild(titleblocktemplates_elmt); - } + // titleblock templates, if any + if (m_titleblocks_collection.templates().count()) { + QDomElement titleblocktemplates_elmt = xml_doc.createElement("titleblocktemplates"); + foreach (QString template_name, m_titleblocks_collection.templates()) { + QDomElement e = m_titleblocks_collection.getTemplateXmlDescription(template_name); + titleblocktemplates_elmt.appendChild(xml_doc.importNode(e, true)); + } + project_root.appendChild(titleblocktemplates_elmt); + } - // project-wide properties - QDomElement project_properties = xml_doc.createElement("properties"); - writeProjectPropertiesXml(project_properties); - project_root.appendChild(project_properties); + // project-wide properties + QDomElement project_properties = xml_doc.createElement("properties"); + writeProjectPropertiesXml(project_properties); + project_root.appendChild(project_properties); - // Properties for news diagrams - QDomElement new_diagrams_properties = xml_doc.createElement("newdiagrams"); - writeDefaultPropertiesXml(new_diagrams_properties); - project_root.appendChild(new_diagrams_properties); + // Properties for news diagrams + QDomElement new_diagrams_properties = xml_doc.createElement("newdiagrams"); + writeDefaultPropertiesXml(new_diagrams_properties); + project_root.appendChild(new_diagrams_properties); - // schemas + // schemas - qDebug() << "Export XML de" << m_diagrams_list.count() << "schemas"; - int order_num = 1; - const QList diagrams_list = m_diagrams_list; - for(Diagram *diagram : diagrams_list) - { - qDebug() << QString("exporting diagram \"%1\"" - ).arg(diagram -> title()) - << "[" - << diagram - << "]"; - QDomElement xml_diagram = diagram->toXml().documentElement(); - QDomNode xml_node = xml_doc.importNode(xml_diagram, true); + qDebug() << "Export XML de" << m_diagrams_list.count() << "schemas"; + int order_num = 1; + const QList diagrams_list = m_diagrams_list; + for(Diagram *diagram : diagrams_list) + { + qDebug() << QString("exporting diagram \"%1\"" + ).arg(diagram -> title()) + << "[" + << diagram + << "]"; + QDomElement xml_diagram = diagram->toXml().documentElement(); + QDomNode xml_node = xml_doc.importNode(xml_diagram, true); - QDomNode appended_diagram = project_root.appendChild(xml_node); - appended_diagram.toElement().setAttribute("order", order_num ++); - } + QDomNode appended_diagram = project_root.appendChild(xml_node); + appended_diagram.toElement().setAttribute("order", order_num ++); + } - // Write the elements collection. - project_root.appendChild(m_elements_collection->root().cloneNode(true)); + // Write the elements collection. + project_root.appendChild(m_elements_collection->root().cloneNode(true)); - return(xml_doc); + return(xml_doc); } /** - Ferme le projet + Ferme le projet */ bool QETProject::close() { - return(true); + return(true); } /** - @brief QETProject::write - Save the project in a file - @see filePath() - @see setFilePath() - @return true if the project was successfully saved, else false + @brief QETProject::write + Save the project in a file + @see filePath() + @see setFilePath() + @return true if the project was successfully saved, else false */ QETResult QETProject::write() { - // this operation requires a filepath - if (m_file_path.isEmpty()) - return(QString("unable to save project to file: no filepath was specified")); + // this operation requires a filepath + if (m_file_path.isEmpty()) + return(QString("unable to save project to file: no filepath was specified")); - // if the project was opened read-only - // and the file is still non-writable, do not save the project - if (isReadOnly() && !QFileInfo(m_file_path).isWritable()) - return(QString("the file %1 was opened read-only and thus will not be written").arg(m_file_path)); + // if the project was opened read-only + // and the file is still non-writable, do not save the project + if (isReadOnly() && !QFileInfo(m_file_path).isWritable()) + return(QString("the file %1 was opened read-only and thus will not be written").arg(m_file_path)); - QDomDocument xml_project(toXml()); - QString error_message; - if (!QET::writeXmlFile(xml_project, m_file_path, &error_message)) - return(error_message); + QDomDocument xml_project(toXml()); + QString error_message; + if (!QET::writeXmlFile(xml_project, m_file_path, &error_message)) + return(error_message); //title block variables should be updated after file save dialog is confirmed, before file is saved. m_project_properties.addValue( @@ -950,891 +950,891 @@ QETResult QETProject::write() m_project_properties.addValue("savedfilename", QFileInfo(filePath()).baseName()); m_project_properties.addValue("savedfilepath", filePath()); - emit(projectInformationsChanged(this)); - updateDiagramsFolioData(); + emit(projectInformationsChanged(this)); + updateDiagramsFolioData(); - setModified(false); - return(QETResult()); + setModified(false); + return(QETResult()); } /** - @brief QETProject::isReadOnly - @return true si le projet est en mode readonly, false sinon + @brief QETProject::isReadOnly + @return true si le projet est en mode readonly, false sinon */ bool QETProject::isReadOnly() const { - return(m_read_only && read_only_file_path_ == m_file_path); + return(m_read_only && read_only_file_path_ == m_file_path); } /** - @brief QETProject::setReadOnly - Set this project to read only if read_only = true - @param read_only + @brief QETProject::setReadOnly + Set this project to read only if read_only = true + @param read_only */ void QETProject::setReadOnly(bool read_only) { - if (m_read_only != read_only) - { - //keep the file to which this project is read-only - read_only_file_path_ = m_file_path; - m_read_only = read_only; - emit(readOnlyChanged(this, read_only)); - } + if (m_read_only != read_only) + { + //keep the file to which this project is read-only + read_only_file_path_ = m_file_path; + m_read_only = read_only; + emit(readOnlyChanged(this, read_only)); + } } /** - @return true si le projet peut etre considere comme vide, c'est-a-dire : - - soit avec une collection embarquee vide - - soit avec uniquement des schemas consideres comme vides - - soit avec un titre de projet + @return true si le projet peut etre considere comme vide, c'est-a-dire : + - soit avec une collection embarquee vide + - soit avec uniquement des schemas consideres comme vides + - soit avec un titre de projet */ bool QETProject::isEmpty() const { - // si le projet a un titre, on considere qu'il n'est pas vide - if (!project_title_.isEmpty()) return(false); + // si le projet a un titre, on considere qu'il n'est pas vide + if (!project_title_.isEmpty()) return(false); #if TODO_LIST #pragma message("@TODO check if the embedded element collection is empty") #endif - //@TODO check if the embedded element collection is empty + //@TODO check if the embedded element collection is empty - // compte le nombre de schemas non vides - int pertinent_diagrams = 0; - foreach(Diagram *diagram, m_diagrams_list) { - if (!diagram -> isEmpty()) ++ pertinent_diagrams; - } + // compte le nombre de schemas non vides + int pertinent_diagrams = 0; + foreach(Diagram *diagram, m_diagrams_list) { + if (!diagram -> isEmpty()) ++ pertinent_diagrams; + } - return(pertinent_diagrams > 0); + return(pertinent_diagrams > 0); } /** - @brief QETProject::importElement - Import the element represented by location - to the embbeded collection of this project - @param location - @return the location of the imported element, location can be null. + @brief QETProject::importElement + Import the element represented by location + to the embbeded collection of this project + @param location + @return the location of the imported element, location can be null. */ ElementsLocation QETProject::importElement(ElementsLocation &location) { - //Location isn't an element or doesn't exist - if (! (location.isElement() && location.exist()) ) { - return ElementsLocation(); - } + //Location isn't an element or doesn't exist + if (! (location.isElement() && location.exist()) ) { + return ElementsLocation(); + } - //Get the path where the element must be imported - QString import_path; - if (location.isFileSystem()) { - import_path = "import/" + location.collectionPath(false); - } - else if (location.isProject()) { - if (location.project() == this) { - return location; - } + //Get the path where the element must be imported + QString import_path; + if (location.isFileSystem()) { + import_path = "import/" + location.collectionPath(false); + } + else if (location.isProject()) { + if (location.project() == this) { + return location; + } - import_path = location.collectionPath(false); - } + import_path = location.collectionPath(false); + } - //Element already exist in the embedded collection, we ask what to do to user - if (m_elements_collection->exist(import_path)) { - ElementsLocation existing_location(import_path, this); + //Element already exist in the embedded collection, we ask what to do to user + if (m_elements_collection->exist(import_path)) { + ElementsLocation existing_location(import_path, this); - //existing_location and location have the same uuid, so it is the same element - if (existing_location.uuid() == location.uuid()) { - return existing_location; - } + //existing_location and location have the same uuid, so it is the same element + if (existing_location.uuid() == location.uuid()) { + return existing_location; + } - ImportElementDialog ied; - if (ied.exec() == QDialog::Accepted) { - QET::Action action = ied.action(); + ImportElementDialog ied; + if (ied.exec() == QDialog::Accepted) { + QET::Action action = ied.action(); - //Use the exisitng element - if (action == QET::Ignore) { - return existing_location; - } - //Erase the existing element, and use the newer instead - else if (action == QET::Erase) { - ElementsLocation parent_loc = existing_location.parent(); - return m_elements_collection->copy(location, parent_loc); - } - //Add the new element with an other name. - else if (action == QET::Rename) { - int a = 0; - QString parent_path = existing_location.parent().projectCollectionPath(); - QString name_ = existing_location.fileName(); - name_.remove(".elmt"); + //Use the exisitng element + if (action == QET::Ignore) { + return existing_location; + } + //Erase the existing element, and use the newer instead + else if (action == QET::Erase) { + ElementsLocation parent_loc = existing_location.parent(); + return m_elements_collection->copy(location, parent_loc); + } + //Add the new element with an other name. + else if (action == QET::Rename) { + int a = 0; + QString parent_path = existing_location.parent().projectCollectionPath(); + QString name_ = existing_location.fileName(); + name_.remove(".elmt"); - ElementsLocation loc; - do - { - a++; - QString new_path = parent_path + "/" + name_ + QString::number(a) + ".elmt"; - loc = ElementsLocation (new_path); - } while (loc.exist()); + ElementsLocation loc; + do + { + a++; + QString new_path = parent_path + "/" + name_ + QString::number(a) + ".elmt"; + loc = ElementsLocation (new_path); + } while (loc.exist()); - ElementsLocation parent_loc = existing_location.parent(); - return m_elements_collection->copy(location, parent_loc, loc.fileName()); - } - else { - return ElementsLocation(); - } - } - else { - return ElementsLocation(); - } - } - //Element doesn't exist in the collection, we just import it - else { - ElementsLocation loc(m_elements_collection->addElement( - location), this); + ElementsLocation parent_loc = existing_location.parent(); + return m_elements_collection->copy(location, parent_loc, loc.fileName()); + } + else { + return ElementsLocation(); + } + } + else { + return ElementsLocation(); + } + } + //Element doesn't exist in the collection, we just import it + else { + ElementsLocation loc(m_elements_collection->addElement( + location), this); - if (!loc.exist()) { - qDebug() << "failed to import location. " - << location; - return ElementsLocation(); - } - else { - return loc; - } - } + if (!loc.exist()) { + qDebug() << "failed to import location. " + << location; + return ElementsLocation(); + } + else { + return loc; + } + } } /** - @brief QETProject::integrateTitleBlockTemplate - Integrate a title block template into this project. - @param src_tbt The location of the title block template - to be integrated into this project - @param handler - @return the name of the template after integration, - or an empty QString if a problem occurred. + @brief QETProject::integrateTitleBlockTemplate + Integrate a title block template into this project. + @param src_tbt The location of the title block template + to be integrated into this project + @param handler + @return the name of the template after integration, + or an empty QString if a problem occurred. */ QString QETProject::integrateTitleBlockTemplate(const TitleBlockTemplateLocation &src_tbt, MoveTitleBlockTemplatesHandler *handler) { - TitleBlockTemplateLocation dst_tbt(src_tbt.name(), &m_titleblocks_collection); + TitleBlockTemplateLocation dst_tbt(src_tbt.name(), &m_titleblocks_collection); - // check whether a TBT having the same name already exists within this project - QString target_name = dst_tbt.name(); - while (m_titleblocks_collection.templates().contains(target_name)) - { - QET::Action action = handler -> templateAlreadyExists(src_tbt, dst_tbt); - if (action == QET::Retry) { - continue; - } else if (action == QET::Erase) { - break; - } else if (action == QET::Abort || action == QET::Ignore) { - return(QString()); - } else if (action == QET::Rename) { - target_name = handler -> nameForRenamingOperation(); - } else if (action == QET::Managed) { - return(target_name); - } - } + // check whether a TBT having the same name already exists within this project + QString target_name = dst_tbt.name(); + while (m_titleblocks_collection.templates().contains(target_name)) + { + QET::Action action = handler -> templateAlreadyExists(src_tbt, dst_tbt); + if (action == QET::Retry) { + continue; + } else if (action == QET::Erase) { + break; + } else if (action == QET::Abort || action == QET::Ignore) { + return(QString()); + } else if (action == QET::Rename) { + target_name = handler -> nameForRenamingOperation(); + } else if (action == QET::Managed) { + return(target_name); + } + } - if (!m_titleblocks_collection.setTemplateXmlDescription(target_name, src_tbt.getTemplateXmlDescription())) - { - handler -> errorWithATemplate(src_tbt, tr("Une erreur s'est produite durant l'intégration du modèle.", "error message")); - target_name = QString(); - } - return(target_name); + if (!m_titleblocks_collection.setTemplateXmlDescription(target_name, src_tbt.getTemplateXmlDescription())) + { + handler -> errorWithATemplate(src_tbt, tr("Une erreur s'est produite durant l'intégration du modèle.", "error message")); + target_name = QString(); + } + return(target_name); } /** - Permet de savoir si un element est utilise dans un projet - @param location Emplacement d'un element - @return true si l'element location est utilise sur au moins un des schemas - de ce projet, false sinon + Permet de savoir si un element est utilise dans un projet + @param location Emplacement d'un element + @return true si l'element location est utilise sur au moins un des schemas + de ce projet, false sinon */ bool QETProject::usesElement(const ElementsLocation &location) const { - foreach(Diagram *diagram, diagrams()) { - if (diagram -> usesElement(location)) { - return(true); - } - } - return(false); + foreach(Diagram *diagram, diagrams()) { + if (diagram -> usesElement(location)) { + return(true); + } + } + return(false); } /** - @brief QETProject::unusedElements - @return the list of unused element (exactly her location) - An unused element, is an element present in the embedded collection but not present in a diagram of this project. - Be aware that an element can be not present in a diagram, - but managed by an undo command (delete an element), so an unused element can be used after an undo. + @brief QETProject::unusedElements + @return the list of unused element (exactly her location) + An unused element, is an element present in the embedded collection but not present in a diagram of this project. + Be aware that an element can be not present in a diagram, + but managed by an undo command (delete an element), so an unused element can be used after an undo. */ QList QETProject::unusedElements() const { - QList unused_list; + QList unused_list; - foreach(ElementsLocation location, m_elements_collection->elementsLocation()) - if (location.isElement() && !usesElement(location)) - unused_list << location; + foreach(ElementsLocation location, m_elements_collection->elementsLocation()) + if (location.isElement() && !usesElement(location)) + unused_list << location; - return unused_list; + return unused_list; } /** - @param location Location of a title block template - @return true if the provided template is used by at least one diagram - within this project, false otherwise + @param location Location of a title block template + @return true if the provided template is used by at least one diagram + within this project, false otherwise */ bool QETProject::usesTitleBlockTemplate(const TitleBlockTemplateLocation &location) { - // a diagram can only use a title block template embedded wihtin its parent project - if (location.parentProject() != this) return(false); + // a diagram can only use a title block template embedded wihtin its parent project + if (location.parentProject() != this) return(false); - foreach (Diagram *diagram, diagrams()) { - if (diagram -> usesTitleBlockTemplate(location.name())) { - return(true); - } - } - return(false); + foreach (Diagram *diagram, diagrams()) { + if (diagram -> usesTitleBlockTemplate(location.name())) { + return(true); + } + } + return(false); } /** - @brief QETProject::addNewDiagram - Add a new diagram in project at position pos. - @param pos - @return the new created diagram + @brief QETProject::addNewDiagram + Add a new diagram in project at position pos. + @param pos + @return the new created diagram */ Diagram *QETProject::addNewDiagram(int pos) { - if (isReadOnly()) { - return(nullptr); - } + if (isReadOnly()) { + return(nullptr); + } - Diagram *diagram = new Diagram(this); + Diagram *diagram = new Diagram(this); - diagram->border_and_titleblock.importBorder(defaultBorderProperties()); - diagram->border_and_titleblock.importTitleBlock(defaultTitleBlockProperties()); - diagram->defaultConductorProperties = defaultConductorProperties(); + diagram->border_and_titleblock.importBorder(defaultBorderProperties()); + diagram->border_and_titleblock.importTitleBlock(defaultTitleBlockProperties()); + diagram->defaultConductorProperties = defaultConductorProperties(); - addDiagram(diagram, pos); - emit(diagramAdded(this, diagram)); - return(diagram); + addDiagram(diagram, pos); + emit(diagramAdded(this, diagram)); + return(diagram); } /** - @brief QETProject::removeDiagram - Remove diagram from project - @param diagram + @brief QETProject::removeDiagram + Remove diagram from project + @param diagram */ void QETProject::removeDiagram(Diagram *diagram) { - if (isReadOnly() || - !diagram || !m_diagrams_list.contains(diagram)) { - return; - } + if (isReadOnly() || + !diagram || !m_diagrams_list.contains(diagram)) { + return; + } - if (m_diagrams_list.removeAll(diagram)) - { - m_data_base.removeDiagram(diagram); - emit(diagramRemoved(this, diagram)); - diagram->deleteLater(); - } + if (m_diagrams_list.removeAll(diagram)) + { + m_data_base.removeDiagram(diagram); + emit(diagramRemoved(this, diagram)); + diagram->deleteLater(); + } - updateDiagramsFolioData(); + updateDiagramsFolioData(); } /** - Gere le fait que l'ordre des schemas ait change - @param old_index ancien indice du schema deplace - @param new_index nouvel indice du schema deplace - Si l'ancien ou le nouvel index est negatif ou superieur au nombre de schemas - dans le projet, cette methode ne fait rien. - Les index vont de 0 a "nombre de schemas - 1" + Gere le fait que l'ordre des schemas ait change + @param old_index ancien indice du schema deplace + @param new_index nouvel indice du schema deplace + Si l'ancien ou le nouvel index est negatif ou superieur au nombre de schemas + dans le projet, cette methode ne fait rien. + Les index vont de 0 a "nombre de schemas - 1" */ void QETProject::diagramOrderChanged(int old_index, int new_index) { - if (old_index < 0 || new_index < 0) return; + if (old_index < 0 || new_index < 0) return; - int diagram_max_index = m_diagrams_list.size() - 1; - if (old_index > diagram_max_index || new_index > diagram_max_index) return; + int diagram_max_index = m_diagrams_list.size() - 1; + if (old_index > diagram_max_index || new_index > diagram_max_index) return; - m_diagrams_list.move(old_index, new_index); - updateDiagramsFolioData(); - setModified(true); - emit(projectDiagramsOrderChanged(this, old_index, new_index)); + m_diagrams_list.move(old_index, new_index); + updateDiagramsFolioData(); + setModified(true); + emit(projectDiagramsOrderChanged(this, old_index, new_index)); } /** - Mark this project as modified and emit the projectModified() signal. + Mark this project as modified and emit the projectModified() signal. */ void QETProject::setModified(bool modified) { - if (m_modified != modified) { - m_modified = modified; - emit(projectModified(this, m_modified)); - emit(projectInformationsChanged(this)); - } + if (m_modified != modified) { + m_modified = modified; + emit(projectModified(this, m_modified)); + emit(projectInformationsChanged(this)); + } } /** - @brief QETProject::readProjectXml - Read and make the project from an xml description - @param xml_project : the description of the project from an xml + @brief QETProject::readProjectXml + Read and make the project from an xml description + @param xml_project : the description of the project from an xml */ void QETProject::readProjectXml(QDomDocument &xml_project) { - QDomElement root_elmt = xml_project.documentElement(); - m_state = ProjectParsingRunning; + QDomElement root_elmt = xml_project.documentElement(); + m_state = ProjectParsingRunning; - //The roots of the xml document must be a "project" element - if (root_elmt.tagName() == "project") - { - //Normal opening mode - if (root_elmt.hasAttribute("version")) - { - bool conv_ok; - m_project_qet_version = root_elmt.attribute("version").toDouble(&conv_ok); + //The roots of the xml document must be a "project" element + if (root_elmt.tagName() == "project") + { + //Normal opening mode + if (root_elmt.hasAttribute("version")) + { + bool conv_ok; + m_project_qet_version = root_elmt.attribute("version").toDouble(&conv_ok); #if TODO_LIST #pragma message("@TODO use of version convert") #endif - if (conv_ok && QET::version.toDouble() < m_project_qet_version) - { - int ret = QET::QetMessageBox::warning( - nullptr, - tr("Avertissement", - "message box title"), - tr("Ce document semble avoir été enregistré avec " - "une version ultérieure de QElectroTech. Il est " - "possible que l'ouverture de tout ou partie de ce " - "document échoue.\n" - "Que désirez vous faire ?", - "message box content"), - QMessageBox::Open | QMessageBox::Cancel - ); + if (conv_ok && QET::version.toDouble() < m_project_qet_version) + { + int ret = QET::QetMessageBox::warning( + nullptr, + tr("Avertissement", + "message box title"), + tr("Ce document semble avoir été enregistré avec " + "une version ultérieure de QElectroTech. Il est " + "possible que l'ouverture de tout ou partie de ce " + "document échoue.\n" + "Que désirez vous faire ?", + "message box content"), + QMessageBox::Open | QMessageBox::Cancel + ); - if (ret == QMessageBox::Cancel) - { - m_state = FileOpenDiscard; - return; - } - } - } - setTitle(root_elmt.attribute("title")); - } - else - { - m_state = ProjectParsingFailed; - } + if (ret == QMessageBox::Cancel) + { + m_state = FileOpenDiscard; + return; + } + } + } + setTitle(root_elmt.attribute("title")); + } + else + { + m_state = ProjectParsingFailed; + } - m_data_base.blockSignals(true); - //Load the project-wide properties - readProjectPropertiesXml(xml_project); - //Load the default properties for the new diagrams - readDefaultPropertiesXml(xml_project); - //load the embedded titleblock templates - m_titleblocks_collection.fromXml(xml_project.documentElement()); - //Load the embedded elements collection - readElementsCollectionXml(xml_project); - //Load the diagrams - readDiagramsXml(xml_project); - m_data_base.blockSignals(false); - m_data_base.updateDB(); + m_data_base.blockSignals(true); + //Load the project-wide properties + readProjectPropertiesXml(xml_project); + //Load the default properties for the new diagrams + readDefaultPropertiesXml(xml_project); + //load the embedded titleblock templates + m_titleblocks_collection.fromXml(xml_project.documentElement()); + //Load the embedded elements collection + readElementsCollectionXml(xml_project); + //Load the diagrams + readDiagramsXml(xml_project); + m_data_base.blockSignals(false); + m_data_base.updateDB(); - m_state = Ok; + m_state = Ok; } /** - @brief QETProject::readDiagramsXml - Load the diagrams from the xml description of the project. - Note a project can have 0 diagram - @param xml_project + @brief QETProject::readDiagramsXml + Load the diagrams from the xml description of the project. + Note a project can have 0 diagram + @param xml_project */ void QETProject::readDiagramsXml(QDomDocument &xml_project) { #if TODO_LIST #pragma message("@TODO try to solve a weird bug (dialog is black) since port to Qt5 with the DialogWaiting") #endif - //@TODO try to solve a weird bug (dialog is black) since port to Qt5 with the DialogWaiting - //show DialogWaiting - DialogWaiting *dlgWaiting = nullptr; - if(DialogWaiting::hasInstance()) - { - dlgWaiting = DialogWaiting::instance(); - dlgWaiting -> setModal(true); - dlgWaiting -> show(); - dlgWaiting -> setTitle(tr("

" - "Ouverture du projet en cours...
" - "Création des folios" - "

")); - } + //@TODO try to solve a weird bug (dialog is black) since port to Qt5 with the DialogWaiting + //show DialogWaiting + DialogWaiting *dlgWaiting = nullptr; + if(DialogWaiting::hasInstance()) + { + dlgWaiting = DialogWaiting::instance(); + dlgWaiting -> setModal(true); + dlgWaiting -> show(); + dlgWaiting -> setTitle(tr("

" + "Ouverture du projet en cours...
" + "Création des folios" + "

")); + } - //Search the diagrams in the project - QDomNodeList diagram_nodes = xml_project.elementsByTagName("diagram"); + //Search the diagrams in the project + QDomNodeList diagram_nodes = xml_project.elementsByTagName("diagram"); - if(dlgWaiting) - dlgWaiting->setProgressBarRange(0, diagram_nodes.length()*3); + if(dlgWaiting) + dlgWaiting->setProgressBarRange(0, diagram_nodes.length()*3); - for (int i = 0 ; i < diagram_nodes.length() ; ++ i) - { - if(dlgWaiting) - dlgWaiting->setProgressBar(i+1); + for (int i = 0 ; i < diagram_nodes.length() ; ++ i) + { + if(dlgWaiting) + dlgWaiting->setProgressBar(i+1); - if (diagram_nodes.at(i).isElement()) - { - QDomElement diagram_xml_element = diagram_nodes - .at(i) - .toElement(); - Diagram *diagram = new Diagram(this); + if (diagram_nodes.at(i).isElement()) + { + QDomElement diagram_xml_element = diagram_nodes + .at(i) + .toElement(); + Diagram *diagram = new Diagram(this); - int diagram_order = -1; - if (!QET::attributeIsAnInteger(diagram_xml_element, - "order", - &diagram_order)) - diagram_order = 500000; + int diagram_order = -1; + if (!QET::attributeIsAnInteger(diagram_xml_element, + "order", + &diagram_order)) + diagram_order = 500000; - addDiagram(diagram, diagram_order-1); + addDiagram(diagram, diagram_order-1); - diagram->initFromXml(diagram_xml_element); - if(dlgWaiting) - dlgWaiting->setDetail(diagram->title()); - } - } + diagram->initFromXml(diagram_xml_element); + if(dlgWaiting) + dlgWaiting->setDetail(diagram->title()); + } + } - //Initialise links between elements in this project - //and refresh the text of conductor - if(dlgWaiting) - { - dlgWaiting->setTitle( tr("

" - "Ouverture du projet en cours...
" - "Mise en place des références croisées" - "

")); - } + //Initialise links between elements in this project + //and refresh the text of conductor + if(dlgWaiting) + { + dlgWaiting->setTitle( tr("

" + "Ouverture du projet en cours...
" + "Mise en place des références croisées" + "

")); + } - m_data_base.updateDB(); //All diagrams and items are created we need to update the database + m_data_base.updateDB(); //All diagrams and items are created we need to update the database - for(Diagram *d : diagrams()) - { - if(dlgWaiting) - { - dlgWaiting->setProgressBar(dlgWaiting->progressBarValue()+1); - dlgWaiting->setDetail(d->title()); - } - d->refreshContents(); - } + for(Diagram *d : diagrams()) + { + if(dlgWaiting) + { + dlgWaiting->setProgressBar(dlgWaiting->progressBarValue()+1); + dlgWaiting->setDetail(d->title()); + } + d->refreshContents(); + } } /** - @brief QETProject::readElementsCollectionXml - Load the diagrams from the xml description of the project - @param xml_project : the xml description of the project + @brief QETProject::readElementsCollectionXml + Load the diagrams from the xml description of the project + @param xml_project : the xml description of the project */ void QETProject::readElementsCollectionXml(QDomDocument &xml_project) { - //Get the embedded elements collection of the project - QDomNodeList collection_roots = xml_project.elementsByTagName("collection"); - QDomElement collection_root; + //Get the embedded elements collection of the project + QDomNodeList collection_roots = xml_project.elementsByTagName("collection"); + QDomElement collection_root; - if (!collection_roots.isEmpty()) - { - //Only the first found collection is take - collection_root = collection_roots.at(0).toElement(); - } - //Make an empty collection - if (collection_root.isNull()) { - m_elements_collection = new XmlElementCollection(this); - } - //Read the collection - else { - m_elements_collection = new XmlElementCollection(collection_root, this); - } + if (!collection_roots.isEmpty()) + { + //Only the first found collection is take + collection_root = collection_roots.at(0).toElement(); + } + //Make an empty collection + if (collection_root.isNull()) { + m_elements_collection = new XmlElementCollection(this); + } + //Read the collection + else { + m_elements_collection = new XmlElementCollection(collection_root, this); + } } /** - @brief QETProject::readProjectPropertiesXml - Load project properties from the XML description of the project - @param xml_project : the xml description of the project + @brief QETProject::readProjectPropertiesXml + Load project properties from the XML description of the project + @param xml_project : the xml description of the project */ void QETProject::readProjectPropertiesXml(QDomDocument &xml_project) { - foreach (QDomElement e, QET::findInDomElement(xml_project.documentElement(), "properties")) - m_project_properties.fromXml(e); + foreach (QDomElement e, QET::findInDomElement(xml_project.documentElement(), "properties")) + m_project_properties.fromXml(e); } /** - @brief QETProject::readDefaultPropertiesXml - load default properties for new diagram, found in the xml of this project - or by default find in the QElectroTech global conf - @param xml_project : the xml description of the project + @brief QETProject::readDefaultPropertiesXml + load default properties for new diagram, found in the xml of this project + or by default find in the QElectroTech global conf + @param xml_project : the xml description of the project */ void QETProject::readDefaultPropertiesXml(QDomDocument &xml_project) { - // Find xml element where is stored properties for new diagram - QDomNodeList newdiagrams_nodes = xml_project.elementsByTagName("newdiagrams"); - if (newdiagrams_nodes.isEmpty()) return; + // Find xml element where is stored properties for new diagram + QDomNodeList newdiagrams_nodes = xml_project.elementsByTagName("newdiagrams"); + if (newdiagrams_nodes.isEmpty()) return; - QDomElement newdiagrams_elmt = newdiagrams_nodes.at(0).toElement(); + QDomElement newdiagrams_elmt = newdiagrams_nodes.at(0).toElement(); - // By default, use value find in the global conf of QElectroTech - default_border_properties_ = BorderProperties:: defaultProperties(); - default_titleblock_properties_ = TitleBlockProperties::defaultProperties(); - default_conductor_properties_ = ConductorProperties:: defaultProperties(); - m_default_report_properties = ReportProperties:: defaultProperties(); - m_default_xref_properties = XRefProperties:: defaultProperties(); + // By default, use value find in the global conf of QElectroTech + default_border_properties_ = BorderProperties:: defaultProperties(); + default_titleblock_properties_ = TitleBlockProperties::defaultProperties(); + default_conductor_properties_ = ConductorProperties:: defaultProperties(); + m_default_report_properties = ReportProperties:: defaultProperties(); + m_default_xref_properties = XRefProperties:: defaultProperties(); - //Read values indicate in project - QDomElement border_elmt, titleblock_elmt, conductors_elmt, report_elmt, xref_elmt, conds_autonums, folio_autonums, element_autonums; + //Read values indicate in project + QDomElement border_elmt, titleblock_elmt, conductors_elmt, report_elmt, xref_elmt, conds_autonums, folio_autonums, element_autonums; - for (QDomNode child = newdiagrams_elmt.firstChild() ; !child.isNull() ; child = child.nextSibling()) - { - QDomElement child_elmt = child.toElement(); - if (child_elmt.isNull()) continue; + for (QDomNode child = newdiagrams_elmt.firstChild() ; !child.isNull() ; child = child.nextSibling()) + { + QDomElement child_elmt = child.toElement(); + if (child_elmt.isNull()) continue; - if (child_elmt.tagName() == "border") - border_elmt = child_elmt; - else if (child_elmt.tagName() == "inset") - titleblock_elmt = child_elmt; - else if (child_elmt.tagName() == "conductors") - conductors_elmt = child_elmt; - else if (child_elmt.tagName() == "report") - report_elmt = child_elmt; - else if (child_elmt.tagName() == "xrefs") - xref_elmt = child_elmt; - else if (child_elmt.tagName() == "conductors_autonums") - conds_autonums = child_elmt; - else if (child_elmt.tagName()== "folio_autonums") - folio_autonums = child_elmt; - else if (child_elmt.tagName()== "element_autonums") - element_autonums = child_elmt; - } + if (child_elmt.tagName() == "border") + border_elmt = child_elmt; + else if (child_elmt.tagName() == "inset") + titleblock_elmt = child_elmt; + else if (child_elmt.tagName() == "conductors") + conductors_elmt = child_elmt; + else if (child_elmt.tagName() == "report") + report_elmt = child_elmt; + else if (child_elmt.tagName() == "xrefs") + xref_elmt = child_elmt; + else if (child_elmt.tagName() == "conductors_autonums") + conds_autonums = child_elmt; + else if (child_elmt.tagName()== "folio_autonums") + folio_autonums = child_elmt; + else if (child_elmt.tagName()== "element_autonums") + element_autonums = child_elmt; + } - // size, titleblock, conductor, report, conductor autonum, folio autonum, element autonum - if (!border_elmt.isNull()) default_border_properties_.fromXml(border_elmt); - if (!titleblock_elmt.isNull()) default_titleblock_properties_.fromXml(titleblock_elmt); - if (!conductors_elmt.isNull()) default_conductor_properties_.fromXml(conductors_elmt); - if (!report_elmt.isNull()) setDefaultReportProperties(report_elmt.attribute("label")); - if (!xref_elmt.isNull()) - { - foreach(QDomElement elmt, QET::findInDomElement(xref_elmt, "xref")) - { - XRefProperties xrp; - xrp.fromXml(elmt); - m_default_xref_properties.insert(elmt.attribute("type"), xrp); - } - } - if (!conds_autonums.isNull()) - { - m_current_conductor_autonum = conds_autonums.attribute("current_autonum"); - m_freeze_new_conductors = conds_autonums.attribute("freeze_new_conductors") == "true"; - foreach (QDomElement elmt, QET::findInDomElement(conds_autonums, "conductor_autonum")) - { - NumerotationContext nc; - nc.fromXml(elmt); - m_conductor_autonum.insert(elmt.attribute("title"), nc); - } - } - if (!folio_autonums.isNull()) - { - foreach (QDomElement elmt, QET::findInDomElement(folio_autonums, "folio_autonum")) - { - NumerotationContext nc; - nc.fromXml(elmt); - m_folio_autonum.insert(elmt.attribute("title"), nc); - } - } - if (!element_autonums.isNull()) - { - m_current_element_autonum = element_autonums.attribute("current_autonum"); - m_freeze_new_elements = element_autonums.attribute("freeze_new_elements") == "true"; - foreach (QDomElement elmt, QET::findInDomElement(element_autonums, "element_autonum")) - { - NumerotationContext nc; - nc.fromXml(elmt); - m_element_autonum.insert(elmt.attribute("title"), nc); - } - } + // size, titleblock, conductor, report, conductor autonum, folio autonum, element autonum + if (!border_elmt.isNull()) default_border_properties_.fromXml(border_elmt); + if (!titleblock_elmt.isNull()) default_titleblock_properties_.fromXml(titleblock_elmt); + if (!conductors_elmt.isNull()) default_conductor_properties_.fromXml(conductors_elmt); + if (!report_elmt.isNull()) setDefaultReportProperties(report_elmt.attribute("label")); + if (!xref_elmt.isNull()) + { + foreach(QDomElement elmt, QET::findInDomElement(xref_elmt, "xref")) + { + XRefProperties xrp; + xrp.fromXml(elmt); + m_default_xref_properties.insert(elmt.attribute("type"), xrp); + } + } + if (!conds_autonums.isNull()) + { + m_current_conductor_autonum = conds_autonums.attribute("current_autonum"); + m_freeze_new_conductors = conds_autonums.attribute("freeze_new_conductors") == "true"; + foreach (QDomElement elmt, QET::findInDomElement(conds_autonums, "conductor_autonum")) + { + NumerotationContext nc; + nc.fromXml(elmt); + m_conductor_autonum.insert(elmt.attribute("title"), nc); + } + } + if (!folio_autonums.isNull()) + { + foreach (QDomElement elmt, QET::findInDomElement(folio_autonums, "folio_autonum")) + { + NumerotationContext nc; + nc.fromXml(elmt); + m_folio_autonum.insert(elmt.attribute("title"), nc); + } + } + if (!element_autonums.isNull()) + { + m_current_element_autonum = element_autonums.attribute("current_autonum"); + m_freeze_new_elements = element_autonums.attribute("freeze_new_elements") == "true"; + foreach (QDomElement elmt, QET::findInDomElement(element_autonums, "element_autonum")) + { + NumerotationContext nc; + nc.fromXml(elmt); + m_element_autonum.insert(elmt.attribute("title"), nc); + } + } } /** - Export project properties under the \a xml_element XML element. + Export project properties under the \a xml_element XML element. */ void QETProject::writeProjectPropertiesXml(QDomElement &xml_element) { - m_project_properties.toXml(xml_element); + m_project_properties.toXml(xml_element); } /** - @brief QETProject::writeDefaultPropertiesXml - Export all defaults properties used by a new diagram and his content - size of border - content of titleblock - default conductor - defaut folio report - default Xref - @param xml_element : xml element to use for store default propertie. + @brief QETProject::writeDefaultPropertiesXml + Export all defaults properties used by a new diagram and his content + size of border + content of titleblock + default conductor + defaut folio report + default Xref + @param xml_element : xml element to use for store default propertie. */ void QETProject::writeDefaultPropertiesXml(QDomElement &xml_element) { - QDomDocument xml_document = xml_element.ownerDocument(); + QDomDocument xml_document = xml_element.ownerDocument(); - // export size of border - QDomElement border_elmt = xml_document.createElement("border"); - default_border_properties_.toXml(border_elmt); - xml_element.appendChild(border_elmt); + // export size of border + QDomElement border_elmt = xml_document.createElement("border"); + default_border_properties_.toXml(border_elmt); + xml_element.appendChild(border_elmt); - // export content of titleblock - QDomElement titleblock_elmt = xml_document.createElement("inset"); - default_titleblock_properties_.toXml(titleblock_elmt); - xml_element.appendChild(titleblock_elmt); + // export content of titleblock + QDomElement titleblock_elmt = xml_document.createElement("inset"); + default_titleblock_properties_.toXml(titleblock_elmt); + xml_element.appendChild(titleblock_elmt); - // exporte default conductor - QDomElement conductor_elmt = xml_document.createElement("conductors"); - default_conductor_properties_.toXml(conductor_elmt); - xml_element.appendChild(conductor_elmt); + // exporte default conductor + QDomElement conductor_elmt = xml_document.createElement("conductors"); + default_conductor_properties_.toXml(conductor_elmt); + xml_element.appendChild(conductor_elmt); - // export default report properties - QDomElement report_elmt = xml_document.createElement("report"); - report_elmt.setAttribute("label", defaultReportProperties()); - xml_element.appendChild(report_elmt); + // export default report properties + QDomElement report_elmt = xml_document.createElement("report"); + report_elmt.setAttribute("label", defaultReportProperties()); + xml_element.appendChild(report_elmt); - // export default XRef properties - QDomElement xrefs_elmt = xml_document.createElement("xrefs"); - for (QString key : defaultXRefProperties().keys()) - { - auto xrp = defaultXRefProperties(key); - xrp.setKey(key); - auto xref_dom = xrp.toXml(xml_document); - xrefs_elmt.appendChild(xref_dom); - } - xml_element.appendChild(xrefs_elmt); + // export default XRef properties + QDomElement xrefs_elmt = xml_document.createElement("xrefs"); + for (QString key : defaultXRefProperties().keys()) + { + auto xrp = defaultXRefProperties(key); + xrp.setKey(key); + auto xref_dom = xrp.toXml(xml_document); + xrefs_elmt.appendChild(xref_dom); + } + xml_element.appendChild(xrefs_elmt); - //Export Conductor Autonums - QDomElement conductor_autonums = xml_document.createElement("conductors_autonums"); - conductor_autonums.setAttribute("current_autonum", m_current_conductor_autonum); - conductor_autonums.setAttribute("freeze_new_conductors", m_freeze_new_conductors ? "true" : "false"); - foreach (QString key, conductorAutoNum().keys()) { - QDomElement conductor_autonum = conductorAutoNum(key).toXml(xml_document, "conductor_autonum"); - if (key != "" && conductorAutoNumFormula(key) != "") { - conductor_autonum.setAttribute("title", key); - conductor_autonum.setAttribute("formula", conductorAutoNumFormula(key)); - conductor_autonums.appendChild(conductor_autonum); - } - } - xml_element.appendChild(conductor_autonums); + //Export Conductor Autonums + QDomElement conductor_autonums = xml_document.createElement("conductors_autonums"); + conductor_autonums.setAttribute("current_autonum", m_current_conductor_autonum); + conductor_autonums.setAttribute("freeze_new_conductors", m_freeze_new_conductors ? "true" : "false"); + foreach (QString key, conductorAutoNum().keys()) { + QDomElement conductor_autonum = conductorAutoNum(key).toXml(xml_document, "conductor_autonum"); + if (key != "" && conductorAutoNumFormula(key) != "") { + conductor_autonum.setAttribute("title", key); + conductor_autonum.setAttribute("formula", conductorAutoNumFormula(key)); + conductor_autonums.appendChild(conductor_autonum); + } + } + xml_element.appendChild(conductor_autonums); - //Export Folio Autonums - QDomElement folio_autonums = xml_document.createElement("folio_autonums"); - foreach (QString key, folioAutoNum().keys()) { - QDomElement folio_autonum = folioAutoNum(key).toXml(xml_document, "folio_autonum"); - folio_autonum.setAttribute("title", key); - folio_autonums.appendChild(folio_autonum); - } - xml_element.appendChild(folio_autonums); + //Export Folio Autonums + QDomElement folio_autonums = xml_document.createElement("folio_autonums"); + foreach (QString key, folioAutoNum().keys()) { + QDomElement folio_autonum = folioAutoNum(key).toXml(xml_document, "folio_autonum"); + folio_autonum.setAttribute("title", key); + folio_autonums.appendChild(folio_autonum); + } + xml_element.appendChild(folio_autonums); - //Export Element Autonums - QDomElement element_autonums = xml_document.createElement("element_autonums"); - element_autonums.setAttribute("current_autonum", m_current_element_autonum); - element_autonums.setAttribute("freeze_new_elements", m_freeze_new_elements ? "true" : "false"); - foreach (QString key, elementAutoNum().keys()) { - QDomElement element_autonum = elementAutoNum(key).toXml(xml_document, "element_autonum"); - if (key != "" && elementAutoNumFormula(key) != "") { - element_autonum.setAttribute("title", key); - element_autonum.setAttribute("formula", elementAutoNumFormula(key)); - element_autonums.appendChild(element_autonum); - } - } - xml_element.appendChild(element_autonums); + //Export Element Autonums + QDomElement element_autonums = xml_document.createElement("element_autonums"); + element_autonums.setAttribute("current_autonum", m_current_element_autonum); + element_autonums.setAttribute("freeze_new_elements", m_freeze_new_elements ? "true" : "false"); + foreach (QString key, elementAutoNum().keys()) { + QDomElement element_autonum = elementAutoNum(key).toXml(xml_document, "element_autonum"); + if (key != "" && elementAutoNumFormula(key) != "") { + element_autonum.setAttribute("title", key); + element_autonum.setAttribute("formula", elementAutoNumFormula(key)); + element_autonums.appendChild(element_autonum); + } + } + xml_element.appendChild(element_autonums); } /** - @brief QETProject::addDiagram - Add a diagram in this project - @param diagram added diagram - @param pos postion of the new diagram, by default at the end + @brief QETProject::addDiagram + Add a diagram in this project + @param diagram added diagram + @param pos postion of the new diagram, by default at the end */ void QETProject::addDiagram(Diagram *diagram, int pos) { - if (!diagram) { - return; - } + if (!diagram) { + return; + } - connect(&diagram->border_and_titleblock, - &BorderTitleBlock::needFolioData, - this, - &QETProject::updateDiagramsFolioData); - connect(diagram, &Diagram::usedTitleBlockTemplateChanged, - this, &QETProject::usedTitleBlockTemplateChanged); + connect(&diagram->border_and_titleblock, + &BorderTitleBlock::needFolioData, + this, + &QETProject::updateDiagramsFolioData); + connect(diagram, &Diagram::usedTitleBlockTemplateChanged, + this, &QETProject::usedTitleBlockTemplateChanged); - if (pos == -1) { - m_diagrams_list << diagram; - } else { - m_diagrams_list.insert(pos, diagram); - } - m_data_base.addDiagram(diagram); - updateDiagramsFolioData(); + if (pos == -1) { + m_diagrams_list << diagram; + } else { + m_diagrams_list.insert(pos, diagram); + } + m_data_base.addDiagram(diagram); + updateDiagramsFolioData(); } /** - @return La liste des noms a utiliser pour la categorie dediee aux elements - integres automatiquement dans le projet. + @return La liste des noms a utiliser pour la categorie dediee aux elements + integres automatiquement dans le projet. */ NamesList QETProject::namesListForIntegrationCategory() { - NamesList names; + NamesList names; - const QChar russian_data[24] = { 0x0418, 0x043C, 0x043F, 0x043E, 0x0440, 0x0442, 0x0438, 0x0440, 0x043E, 0x0432, 0x0430, 0x043D, 0x043D, 0x044B, 0x0435, 0x0020, 0x044D, 0x043B, 0x0435, 0x043C, 0x0435, 0x043D, 0x0442, 0x044B }; - const QChar greek_data[18] = { 0x0395, 0x03b9, 0x03c3, 0x03b7, 0x03b3, 0x03bc, 0x03ad, 0x03bd, 0x03b1, 0x0020, 0x03c3, 0x03c4, 0x03bf, 0x03b9, 0x03c7, 0x03b5, 0x03af, 0x03b1 }; + const QChar russian_data[24] = { 0x0418, 0x043C, 0x043F, 0x043E, 0x0440, 0x0442, 0x0438, 0x0440, 0x043E, 0x0432, 0x0430, 0x043D, 0x043D, 0x044B, 0x0435, 0x0020, 0x044D, 0x043B, 0x0435, 0x043C, 0x0435, 0x043D, 0x0442, 0x044B }; + const QChar greek_data[18] = { 0x0395, 0x03b9, 0x03c3, 0x03b7, 0x03b3, 0x03bc, 0x03ad, 0x03bd, 0x03b1, 0x0020, 0x03c3, 0x03c4, 0x03bf, 0x03b9, 0x03c7, 0x03b5, 0x03af, 0x03b1 }; const QChar japanese_data[10] = { 0x30A4, 0x30F3, 0x30D0, 0x30FC, 0x30C8, 0x3055, 0x308C, 0x305F, 0x8981, 0x7D20 }; - names.addName("fr", "Éléments importés"); - names.addName("en", "Imported elements"); - names.addName("de", "Importierte elemente"); - names.addName("es", "Elementos importados"); - names.addName("ru", QString(russian_data, 24)); - names.addName("cs", "Zavedené prvky"); - names.addName("pl", "Elementy importowane"); - names.addName("pt", "elementos importados"); - names.addName("it", "Elementi importati"); - names.addName("el", QString(greek_data, 18)); - names.addName("nl", "Elementen geïmporteerd"); - names.addName("hr", "Uvezeni elementi"); - names.addName("ca", "Elements importats"); - names.addName("ro", "Elemente importate"); - names.addName("ja", QString(japanese_data, 10)); + names.addName("fr", "Éléments importés"); + names.addName("en", "Imported elements"); + names.addName("de", "Importierte elemente"); + names.addName("es", "Elementos importados"); + names.addName("ru", QString(russian_data, 24)); + names.addName("cs", "Zavedené prvky"); + names.addName("pl", "Elementy importowane"); + names.addName("pt", "elementos importados"); + names.addName("it", "Elementi importati"); + names.addName("el", QString(greek_data, 18)); + names.addName("nl", "Elementen geïmporteerd"); + names.addName("hr", "Uvezeni elementi"); + names.addName("ca", "Elements importats"); + names.addName("ro", "Elemente importate"); + names.addName("ja", QString(japanese_data, 10)); - return(names); + return(names); } /** - @brief QETProject::writeBackup - Write a backup file of this project, in the case that QET crash + @brief QETProject::writeBackup + Write a backup file of this project, in the case that QET crash */ void QETProject::writeBackup() { -#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove - QDomDocument xml_project(toXml()); - QtConcurrent::run( - QET::writeToFile,xml_project,&m_backup_file,nullptr); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove + QDomDocument xml_project(toXml()); + QtConcurrent::run( + QET::writeToFile,xml_project,&m_backup_file,nullptr); #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") #endif - qDebug()<<"Help code for QT 6 or later"; + qDebug()<<"Help code for QT 6 or later"; #endif } /** - @return true if project options (title, project-wide properties, settings - for new diagrams, diagrams order...) were modified, false otherwise. + @return true if project options (title, project-wide properties, settings + for new diagrams, diagrams order...) were modified, false otherwise. */ bool QETProject::projectOptionsWereModified() { - // unlike similar methods, this method does not compare the content against - // expected values; instead, we just check whether we have been set as modified. - return(m_modified); + // unlike similar methods, this method does not compare the content against + // expected values; instead, we just check whether we have been set as modified. + return(m_modified); } /** - @return the project-wide properties made available to child diagrams. + @return the project-wide properties made available to child diagrams. */ DiagramContext QETProject::projectProperties() { - return(m_project_properties); + return(m_project_properties); } /** - Use \a context as project-wide properties made available to child diagrams. + Use \a context as project-wide properties made available to child diagrams. */ void QETProject::setProjectProperties(const DiagramContext &context) { - m_project_properties = context; - updateDiagramsFolioData(); + m_project_properties = context; + updateDiagramsFolioData(); } /** - Cette methode sert a reperer un projet vide, c-a-d un projet identique a ce - que l'on obtient en faisant Fichier > Nouveau. - @return true si les schemas, la collection embarquee ou les proprietes de ce - projet ont ete modifies. - Concretement, le projet doit avoir un titre vide et ni ses schemas ni sa - collection embarquee ne doivent avoir ete modifies. - @see diagramsWereModified(), embeddedCollectionWasModified() + Cette methode sert a reperer un projet vide, c-a-d un projet identique a ce + que l'on obtient en faisant Fichier > Nouveau. + @return true si les schemas, la collection embarquee ou les proprietes de ce + projet ont ete modifies. + Concretement, le projet doit avoir un titre vide et ni ses schemas ni sa + collection embarquee ne doivent avoir ete modifies. + @see diagramsWereModified(), embeddedCollectionWasModified() */ bool QETProject::projectWasModified() { - if ( projectOptionsWereModified() || - !m_undo_stack -> isClean() || - m_titleblocks_collection.templates().count() ) - return(true); + if ( projectOptionsWereModified() || + !m_undo_stack -> isClean() || + m_titleblocks_collection.templates().count() ) + return(true); - else - return(false); + else + return(false); } /** - Indique a chaque schema du projet quel est son numero de folio et combien de - folio le projet contient. + Indique a chaque schema du projet quel est son numero de folio et combien de + folio le projet contient. */ void QETProject::updateDiagramsFolioData() { - int total_folio = m_diagrams_list.count(); + int total_folio = m_diagrams_list.count(); - DiagramContext project_wide_properties = m_project_properties; - project_wide_properties.addValue("projecttitle", title()); - project_wide_properties.addValue("projectpath", filePath()); - project_wide_properties.addValue("projectfilename", QFileInfo(filePath()).baseName()); + DiagramContext project_wide_properties = m_project_properties; + project_wide_properties.addValue("projecttitle", title()); + project_wide_properties.addValue("projectpath", filePath()); + project_wide_properties.addValue("projectfilename", QFileInfo(filePath()).baseName()); - for (int i = 0 ; i < total_folio ; ++ i) - { - QString autopagenum = m_diagrams_list[i]->border_and_titleblock.autoPageNum(); - NumerotationContext nC = folioAutoNum(autopagenum); - NumerotationContextCommands nCC = NumerotationContextCommands(nC); + for (int i = 0 ; i < total_folio ; ++ i) + { + QString autopagenum = m_diagrams_list[i]->border_and_titleblock.autoPageNum(); + NumerotationContext nC = folioAutoNum(autopagenum); + NumerotationContextCommands nCC = NumerotationContextCommands(nC); - if ((m_diagrams_list[i]->border_and_titleblock.folio().contains("%autonum")) && - (!autopagenum.isNull())) - { - m_diagrams_list[i] -> border_and_titleblock.setFolioData(i + 1, total_folio, nCC.toRepresentedString(), project_wide_properties); - m_diagrams_list[i]->project()->addFolioAutoNum(autopagenum,nCC.next()); - } - else { - m_diagrams_list[i] -> border_and_titleblock.setFolioData(i + 1, total_folio, nullptr, project_wide_properties); - } + if ((m_diagrams_list[i]->border_and_titleblock.folio().contains("%autonum")) && + (!autopagenum.isNull())) + { + m_diagrams_list[i] -> border_and_titleblock.setFolioData(i + 1, total_folio, nCC.toRepresentedString(), project_wide_properties); + m_diagrams_list[i]->project()->addFolioAutoNum(autopagenum,nCC.next()); + } + else { + m_diagrams_list[i] -> border_and_titleblock.setFolioData(i + 1, total_folio, nullptr, project_wide_properties); + } - if (i > 0) - { - m_diagrams_list.at(i)->border_and_titleblock.setPreviousFolioNum(m_diagrams_list.at(i-1)->border_and_titleblock.finalfolio()); - m_diagrams_list.at(i-1)->border_and_titleblock.setNextFolioNum(m_diagrams_list.at(i)->border_and_titleblock.finalfolio()); + if (i > 0) + { + m_diagrams_list.at(i)->border_and_titleblock.setPreviousFolioNum(m_diagrams_list.at(i-1)->border_and_titleblock.finalfolio()); + m_diagrams_list.at(i-1)->border_and_titleblock.setNextFolioNum(m_diagrams_list.at(i)->border_and_titleblock.finalfolio()); - if (i == total_folio-1) { - m_diagrams_list.at(i)->border_and_titleblock.setNextFolioNum(QString()); - } - } - else { - m_diagrams_list.at(i)->border_and_titleblock.setPreviousFolioNum(QString()); - } - } + if (i == total_folio-1) { + m_diagrams_list.at(i)->border_and_titleblock.setNextFolioNum(QString()); + } + } + else { + m_diagrams_list.at(i)->border_and_titleblock.setPreviousFolioNum(QString()); + } + } - for (Diagram *d : m_diagrams_list) { - d->update(); - } + for (Diagram *d : m_diagrams_list) { + d->update(); + } } /** - Inform each diagram that the \a template_name title block changed. - @param collection Title block templates collection - @param template_name Name of the changed template + Inform each diagram that the \a template_name title block changed. + @param collection Title block templates collection + @param template_name Name of the changed template */ void QETProject::updateDiagramsTitleBlockTemplate(TitleBlockTemplatesCollection *collection, const QString &template_name) { - Q_UNUSED(collection) + Q_UNUSED(collection) - foreach (Diagram *diagram, m_diagrams_list) { - diagram -> titleBlockTemplateChanged(template_name); - } + foreach (Diagram *diagram, m_diagrams_list) { + diagram -> titleBlockTemplateChanged(template_name); + } } /** - Inform each diagram that the \a template_name title block is about to be removed. - @param collection Title block templates collection - @param template_name Name of the removed template + Inform each diagram that the \a template_name title block is about to be removed. + @param collection Title block templates collection + @param template_name Name of the removed template */ void QETProject::removeDiagramsTitleBlockTemplate(TitleBlockTemplatesCollection *collection, const QString &template_name) { - Q_UNUSED(collection) + Q_UNUSED(collection) - // warn diagrams that the given template is about to be removed - foreach (Diagram *diagram, m_diagrams_list) { - diagram -> titleBlockTemplateRemoved(template_name); - } + // warn diagrams that the given template is about to be removed + foreach (Diagram *diagram, m_diagrams_list) { + diagram -> titleBlockTemplateRemoved(template_name); + } } /** - Handles the fact a digram changed the title block template it used - @param template_name Name of the template + Handles the fact a digram changed the title block template it used + @param template_name Name of the template */ void QETProject::usedTitleBlockTemplateChanged(const QString &template_name) { - emit(diagramUsedTemplate(embeddedTitleBlockTemplatesCollection(), template_name)); + emit(diagramUsedTemplate(embeddedTitleBlockTemplatesCollection(), template_name)); } diff --git a/sources/titleblock/helpercell.cpp b/sources/titleblock/helpercell.cpp index eb62d6355..ee34129b6 100644 --- a/sources/titleblock/helpercell.cpp +++ b/sources/titleblock/helpercell.cpp @@ -1,157 +1,157 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "helpercell.h" /** - Constructor - @param parent Parent QGraphicsItem + Constructor + @param parent Parent QGraphicsItem */ HelperCell::HelperCell(QGraphicsItem *parent) : - QGraphicsObject(parent), - QGraphicsLayoutItem(), - background_color(Qt::white), - foreground_color(Qt::black), - label(), - orientation(Qt::Horizontal), - index(-1) + QGraphicsObject(parent), + QGraphicsLayoutItem(), + background_color(Qt::white), + foreground_color(Qt::black), + label(), + orientation(Qt::Horizontal), + index(-1) { - setGraphicsItem(this); - setFlag(QGraphicsItem::ItemIsSelectable, false); + setGraphicsItem(this); + setFlag(QGraphicsItem::ItemIsSelectable, false); } /** - Destructor + Destructor */ HelperCell::~HelperCell() { } /** - Ensure geometry changes are handled for both QGraphicsObject and - QGraphicsLayoutItem. - @param g New geometry + Ensure geometry changes are handled for both QGraphicsObject and + QGraphicsLayoutItem. + @param g New geometry */ void HelperCell::setGeometry(const QRectF &g) { - prepareGeometryChange(); - QGraphicsLayoutItem::setGeometry(g); - setPos(g.topLeft()); + prepareGeometryChange(); + QGraphicsLayoutItem::setGeometry(g); + setPos(g.topLeft()); } /** - @param which Size hint to be modified - @param constraint New value for the size hint - @return the size hint for \a which using the width or height of \a constraint + @param which Size hint to be modified + @param constraint New value for the size hint + @return the size hint for \a which using the width or height of \a constraint */ QSizeF HelperCell::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { - Q_UNUSED(which); - return(constraint); + Q_UNUSED(which); + return(constraint); } /** - @return the bounding rect of this helper cell + @return the bounding rect of this helper cell */ QRectF HelperCell::boundingRect() const { - return QRectF(QPointF(0,0), geometry().size()); + return QRectF(QPointF(0,0), geometry().size()); } /** - Handles the helper cell visual rendering - @param painter QPainter to be used for the rendering - @param option Rendering options - @param widget QWidget being painted, if any + Handles the helper cell visual rendering + @param painter QPainter to be used for the rendering + @param option Rendering options + @param widget QWidget being painted, if any */ void HelperCell::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - Q_UNUSED(option); - Q_UNUSED(widget); - - QRectF drawing_rectangle(QPointF(0, 0), geometry().size()); - - painter -> setPen(Qt::black); - painter -> setBrush(background_color); - painter -> drawRect(drawing_rectangle); - - painter -> setPen(foreground_color); - painter -> drawText(drawing_rectangle, Qt::AlignHCenter | Qt::AlignVCenter, label); + Q_UNUSED(option); + Q_UNUSED(widget); + + QRectF drawing_rectangle(QPointF(0, 0), geometry().size()); + + painter -> setPen(Qt::black); + painter -> setBrush(background_color); + painter -> drawRect(drawing_rectangle); + + painter -> setPen(foreground_color); + painter -> drawText(drawing_rectangle, Qt::AlignHCenter | Qt::AlignVCenter, label); } /** - @param type new type of this helper cell -- @see QET::TitleBlockColumnLength + @param type new type of this helper cell -- @see QET::TitleBlockColumnLength */ void HelperCell::setType(QET::TitleBlockColumnLength type) { - if (type == QET::Absolute) { - background_color = QColor("#C0FFFF"); - foreground_color = Qt::black; - } else if (type == QET::RelativeToTotalLength) { - background_color = QColor("#FFA858"); - foreground_color = Qt::black; - } else if (type == QET::RelativeToRemainingLength) { - background_color = QColor("#FFC0C0"); - foreground_color = Qt::black; - } + if (type == QET::Absolute) { + background_color = QColor("#C0FFFF"); + foreground_color = Qt::black; + } else if (type == QET::RelativeToTotalLength) { + background_color = QColor("#FFA858"); + foreground_color = Qt::black; + } else if (type == QET::RelativeToRemainingLength) { + background_color = QColor("#FFC0C0"); + foreground_color = Qt::black; + } } /** - Set the list of actions displayed by the context menu of this helper cell. + Set the list of actions displayed by the context menu of this helper cell. */ void HelperCell::setActions(const QList &actions) { - actions_ = actions; + actions_ = actions; } /** - @return the list of actions displayed by the context menu of this helper cell. + @return the list of actions displayed by the context menu of this helper cell. */ QList HelperCell::actions() const { - return actions_; + return actions_; } /** - @param text New label displayed by this helper cell - @param set_as_tooltip If true, the text is also used as tooltip. + @param text New label displayed by this helper cell + @param set_as_tooltip If true, the text is also used as tooltip. */ void HelperCell::setLabel(const QString &text, bool set_as_tooltip) { - label = text; - if (set_as_tooltip) { - setToolTip(text); - } + label = text; + if (set_as_tooltip) { + setToolTip(text); + } } /** - Handle context menu events. - @param event Context menu event. + Handle context menu events. + @param event Context menu event. */ void HelperCell::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { - if (actions_.isEmpty()) return; - - QMenu context_menu; - foreach (QAction *action, actions_) { - context_menu.addAction(action); - } - emit(contextMenuTriggered(this)); - context_menu.exec(event -> screenPos()); + if (actions_.isEmpty()) return; + + QMenu context_menu; + foreach (QAction *action, actions_) { + context_menu.addAction(action); + } + emit(contextMenuTriggered(this)); + context_menu.exec(event -> screenPos()); } /** - Handle double click events. + Handle double click events. */ void HelperCell::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) { - - emit(doubleClicked(this)); + + emit(doubleClicked(this)); } diff --git a/sources/titleblock/helpercell.h b/sources/titleblock/helpercell.h index e2b85c37a..905d12136 100644 --- a/sources/titleblock/helpercell.h +++ b/sources/titleblock/helpercell.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef TITLEBLOCK_SLASH_HELPER_CELL_H #define TITLEBLOCK_SLASH_HELPER_CELL_H @@ -21,48 +21,48 @@ #include "qet.h" /** - This class implements a helper widget for cells that indicate the length of - columns and rows. + This class implements a helper widget for cells that indicate the length of + columns and rows. */ class HelperCell : public QGraphicsObject, public QGraphicsLayoutItem { - Q_OBJECT - Q_INTERFACES(QGraphicsLayoutItem) - - // constructor, destructor - public: - HelperCell(QGraphicsItem * = nullptr); - ~HelperCell() override; - private: - HelperCell(const HelperCell &); - - // attributes - public: - QColor background_color; ///< Background color when rendering this cell - QColor foreground_color; ///< Text color when rendering this cell - QString label; ///< Label displayed in this cell - Qt::Orientation orientation; ///< Orientation of this cell - int index; ///< Index of this cell - - // methods - public: - void setGeometry(const QRectF &) override; - QSizeF sizeHint(Qt::SizeHint, const QSizeF & = QSizeF()) const override; - QRectF boundingRect() const override; - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; - virtual void setType(QET::TitleBlockColumnLength); - virtual void setActions(const QList &); - virtual QList actions() const; - virtual void setLabel(const QString &text, bool = true); - - protected: - void contextMenuEvent(QGraphicsSceneContextMenuEvent *) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override; - - signals: - void contextMenuTriggered(HelperCell *); - void doubleClicked(HelperCell *); - - private: - QList actions_; ///< List of actions displayed by the context menu + Q_OBJECT + Q_INTERFACES(QGraphicsLayoutItem) + + // constructor, destructor + public: + HelperCell(QGraphicsItem * = nullptr); + ~HelperCell() override; + private: + HelperCell(const HelperCell &); + + // attributes + public: + QColor background_color; ///< Background color when rendering this cell + QColor foreground_color; ///< Text color when rendering this cell + QString label; ///< Label displayed in this cell + Qt::Orientation orientation; ///< Orientation of this cell + int index; ///< Index of this cell + + // methods + public: + void setGeometry(const QRectF &) override; + QSizeF sizeHint(Qt::SizeHint, const QSizeF & = QSizeF()) const override; + QRectF boundingRect() const override; + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; + virtual void setType(QET::TitleBlockColumnLength); + virtual void setActions(const QList &); + virtual QList actions() const; + virtual void setLabel(const QString &text, bool = true); + + protected: + void contextMenuEvent(QGraphicsSceneContextMenuEvent *) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override; + + signals: + void contextMenuTriggered(HelperCell *); + void doubleClicked(HelperCell *); + + private: + QList actions_; ///< List of actions displayed by the context menu }; #endif diff --git a/sources/titleblock/splittedhelpercell.h b/sources/titleblock/splittedhelpercell.h index 657ac488e..29935b731 100644 --- a/sources/titleblock/splittedhelpercell.h +++ b/sources/titleblock/splittedhelpercell.h @@ -1,45 +1,45 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef TITLEBLOCK_SLASH_SPLITTED_HELPER_CELL_H #define TITLEBLOCK_SLASH_SPLITTED_HELPER_CELL_H #include "helpercell.h" /** - This class is a variant of HelperCell having the ability to display two - labels, with a split line between them. + This class is a variant of HelperCell having the ability to display two + labels, with a split line between them. */ class SplittedHelperCell : public HelperCell { - Q_OBJECT - public: - SplittedHelperCell(QGraphicsItem * = nullptr); - ~SplittedHelperCell() override; - private: - SplittedHelperCell(const SplittedHelperCell &); - - // methods - public: - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; - - // attributes - QColor split_background_color; ///< Background color on the split side - QColor split_foreground_color; ///< Text color on the split side - QString split_label; ///< Text displayed on the split side - int split_size; ///< Length of the split side + Q_OBJECT + public: + SplittedHelperCell(QGraphicsItem * = nullptr); + ~SplittedHelperCell() override; + private: + SplittedHelperCell(const SplittedHelperCell &); + + // methods + public: + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override; + + // attributes + QColor split_background_color; ///< Background color on the split side + QColor split_foreground_color; ///< Text color on the split side + QString split_label; ///< Text displayed on the split side + int split_size; ///< Length of the split side }; #endif diff --git a/sources/titleblockproperties.cpp b/sources/titleblockproperties.cpp index 9ecc4a1b2..04acd2de9 100644 --- a/sources/titleblockproperties.cpp +++ b/sources/titleblockproperties.cpp @@ -1,242 +1,242 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #include "titleblockproperties.h" #include "qet.h" #include "qetapp.h" /** - Constructeur. Initialise un objet TitleBlockProperties avec tous les champs - vides (date vide + useDate a UseDateValue). + Constructeur. Initialise un objet TitleBlockProperties avec tous les champs + vides (date vide + useDate a UseDateValue). */ TitleBlockProperties::TitleBlockProperties() : - date(), - useDate(UseDateValue), - display_at(Qt::BottomEdge), - collection (QET::QetCollection::Common) + date(), + useDate(UseDateValue), + display_at(Qt::BottomEdge), + collection (QET::QetCollection::Common) { } /** - Destructeur + Destructeur */ TitleBlockProperties::~TitleBlockProperties() { } /** - @param ip autre conteneur TitleBlockProperties - @return true si ip et ce conteneur sont identiques, false sinon + @param ip autre conteneur TitleBlockProperties + @return true si ip et ce conteneur sont identiques, false sinon */ bool TitleBlockProperties::operator==(const TitleBlockProperties &ip) { - return( - ip.title == title &&\ - ip.author == author &&\ - ip.date == date &&\ - ip.filename == filename &&\ - ip.plant == plant &&\ - ip.locmach == locmach &&\ - ip.indexrev == indexrev &&\ - ip.version == version &&\ - ip.folio == folio &&\ - ip.auto_page_num == auto_page_num &&\ - ip.template_name == template_name &&\ - ip.context == context &&\ - ip.display_at == display_at &&\ - ip.collection == collection - ); + return( + ip.title == title &&\ + ip.author == author &&\ + ip.date == date &&\ + ip.filename == filename &&\ + ip.plant == plant &&\ + ip.locmach == locmach &&\ + ip.indexrev == indexrev &&\ + ip.version == version &&\ + ip.folio == folio &&\ + ip.auto_page_num == auto_page_num &&\ + ip.template_name == template_name &&\ + ip.context == context &&\ + ip.display_at == display_at &&\ + ip.collection == collection + ); } /** - @param ip autre conteneur TitleBlockProperties - @return false si ip et ce conteneur sont identiques, true sinon + @param ip autre conteneur TitleBlockProperties + @return false si ip et ce conteneur sont identiques, true sinon */ bool TitleBlockProperties::operator!=(const TitleBlockProperties &ip) { - return(!(*this == ip)); + return(!(*this == ip)); } /** - Exporte le cartouche sous formes d'attributs XML ajoutes a l'element e. - @param e Element XML auquel seront ajoutes des attributs + Exporte le cartouche sous formes d'attributs XML ajoutes a l'element e. + @param e Element XML auquel seront ajoutes des attributs */ void TitleBlockProperties::toXml(QDomElement &e) const { - e.setAttribute("author", author); - e.setAttribute("title", title); - e.setAttribute("filename", filename); - e.setAttribute("plant", plant); - e.setAttribute("locmach", locmach); - e.setAttribute("indexrev",indexrev); - e.setAttribute("version", version); - e.setAttribute("folio", folio); - e.setAttribute("auto_page_num", auto_page_num); - e.setAttribute("date", exportDate()); - e.setAttribute("displayAt", (display_at == Qt::BottomEdge? "bottom" : "right")); - if (!template_name.isEmpty()) - { - e.setAttribute("titleblocktemplate", template_name); - e.setAttribute("titleblocktemplateCollection", QET::qetCollectionToString(collection)); - } - - if (context.keys().count()) { - QDomElement properties = e.ownerDocument().createElement("properties"); - context.toXml(properties); - e.appendChild(properties); - } + e.setAttribute("author", author); + e.setAttribute("title", title); + e.setAttribute("filename", filename); + e.setAttribute("plant", plant); + e.setAttribute("locmach", locmach); + e.setAttribute("indexrev",indexrev); + e.setAttribute("version", version); + e.setAttribute("folio", folio); + e.setAttribute("auto_page_num", auto_page_num); + e.setAttribute("date", exportDate()); + e.setAttribute("displayAt", (display_at == Qt::BottomEdge? "bottom" : "right")); + if (!template_name.isEmpty()) + { + e.setAttribute("titleblocktemplate", template_name); + e.setAttribute("titleblocktemplateCollection", QET::qetCollectionToString(collection)); + } + + if (context.keys().count()) { + QDomElement properties = e.ownerDocument().createElement("properties"); + context.toXml(properties); + e.appendChild(properties); + } } /** - Importe le cartouche a partir des attributs XML de l'element e - @param e Element XML dont les attributs seront lus + Importe le cartouche a partir des attributs XML de l'element e + @param e Element XML dont les attributs seront lus */ void TitleBlockProperties::fromXml(const QDomElement &e) { - // reads the historical fields - if (e.hasAttribute("author")) author = e.attribute("author"); - if (e.hasAttribute("title")) title = e.attribute("title"); - if (e.hasAttribute("filename")) filename = e.attribute("filename"); - if (e.hasAttribute("plant")) plant = e.attribute("plant"); - if (e.hasAttribute("locmach")) locmach = e.attribute("locmach"); - if (e.hasAttribute("indexrev")) indexrev = e.attribute("indexrev"); - if (e.hasAttribute("version")) version = e.attribute("version"); - if (e.hasAttribute("folio")) folio = e.attribute("folio"); - if (e.hasAttribute("auto_page_num")) auto_page_num = e.attribute("auto_page_num"); - if (e.hasAttribute("date")) setDateFromString(e.attribute("date")); - if (e.hasAttribute("displayAt")) display_at = (e.attribute("displayAt") == "bottom" ? Qt::BottomEdge : Qt::RightEdge); - - // reads the template used to render the title block - if (e.hasAttribute("titleblocktemplate")) - { - template_name = e.attribute("titleblocktemplate"); - collection = QET::qetCollectionFromString(e.attribute("titleblocktemplateCollection")); - } - - // reads the additional fields used to fill the title block - context.clear(); - foreach (QDomElement e, QET::findInDomElement(e, "properties")) { - context.fromXml(e); - } + // reads the historical fields + if (e.hasAttribute("author")) author = e.attribute("author"); + if (e.hasAttribute("title")) title = e.attribute("title"); + if (e.hasAttribute("filename")) filename = e.attribute("filename"); + if (e.hasAttribute("plant")) plant = e.attribute("plant"); + if (e.hasAttribute("locmach")) locmach = e.attribute("locmach"); + if (e.hasAttribute("indexrev")) indexrev = e.attribute("indexrev"); + if (e.hasAttribute("version")) version = e.attribute("version"); + if (e.hasAttribute("folio")) folio = e.attribute("folio"); + if (e.hasAttribute("auto_page_num")) auto_page_num = e.attribute("auto_page_num"); + if (e.hasAttribute("date")) setDateFromString(e.attribute("date")); + if (e.hasAttribute("displayAt")) display_at = (e.attribute("displayAt") == "bottom" ? Qt::BottomEdge : Qt::RightEdge); + + // reads the template used to render the title block + if (e.hasAttribute("titleblocktemplate")) + { + template_name = e.attribute("titleblocktemplate"); + collection = QET::qetCollectionFromString(e.attribute("titleblocktemplateCollection")); + } + + // reads the additional fields used to fill the title block + context.clear(); + foreach (QDomElement e, QET::findInDomElement(e, "properties")) { + context.fromXml(e); + } } /** - @brief TitleBlockProperties::toSettings - Export the TitleBlockProperties into a QSettings - @param settings : setting to use - @param prefix : name to use as prefix for this property + @brief TitleBlockProperties::toSettings + Export the TitleBlockProperties into a QSettings + @param settings : setting to use + @param prefix : name to use as prefix for this property */ void TitleBlockProperties::toSettings(QSettings &settings, const QString &prefix) const { - settings.setValue(prefix + "title", title); - settings.setValue(prefix + "author", author); - settings.setValue(prefix + "filename", filename); - settings.setValue(prefix + "plant", plant); - settings.setValue(prefix + "locmach", locmach); - settings.setValue(prefix + "indexrev", indexrev); - settings.setValue(prefix + "version", version); - settings.setValue(prefix + "folio", folio); - settings.setValue(prefix + "auto_page_num", auto_page_num); - settings.setValue(prefix + "date", exportDate()); - settings.setValue(prefix + "displayAt", (display_at == Qt::BottomEdge? "bottom" : "right")); - settings.setValue(prefix + "titleblocktemplate", template_name.isEmpty()? QString() : template_name); - settings.setValue(prefix + "titleblocktemplateCollection", QET::qetCollectionToString(collection)); - context.toSettings(settings, prefix + "properties"); + settings.setValue(prefix + "title", title); + settings.setValue(prefix + "author", author); + settings.setValue(prefix + "filename", filename); + settings.setValue(prefix + "plant", plant); + settings.setValue(prefix + "locmach", locmach); + settings.setValue(prefix + "indexrev", indexrev); + settings.setValue(prefix + "version", version); + settings.setValue(prefix + "folio", folio); + settings.setValue(prefix + "auto_page_num", auto_page_num); + settings.setValue(prefix + "date", exportDate()); + settings.setValue(prefix + "displayAt", (display_at == Qt::BottomEdge? "bottom" : "right")); + settings.setValue(prefix + "titleblocktemplate", template_name.isEmpty()? QString() : template_name); + settings.setValue(prefix + "titleblocktemplateCollection", QET::qetCollectionToString(collection)); + context.toSettings(settings, prefix + "properties"); } /** - Importe le cartouche depuis une configuration. - @param settings Parametres a lire - @param prefix prefixe a ajouter devant les noms des parametres + Importe le cartouche depuis une configuration. + @param settings Parametres a lire + @param prefix prefixe a ajouter devant les noms des parametres */ void TitleBlockProperties::fromSettings(QSettings &settings, const QString &prefix) { - title = settings.value(prefix + "title").toString(); - author = settings.value(prefix + "author").toString(); - filename = settings.value(prefix + "filename").toString(); - plant = settings.value(prefix + "plant").toString(); - locmach = settings.value(prefix + "locmach").toString(); - indexrev = settings.value(prefix + "indexrev").toString(); - version = settings.value(prefix + "version").toString(); - folio = settings.value(prefix + "folio", "%id/%total").toString(); - auto_page_num = settings.value(prefix + "auto_page_num").toString(); - setDateFromString(settings.value(prefix + "date").toString()); - display_at = (settings.value(prefix + "displayAt", QVariant("bottom")).toString() == "bottom" ? Qt::BottomEdge : Qt::RightEdge); - template_name = settings.value(prefix + "titleblocktemplate").toString(); - collection = QET::qetCollectionFromString(settings.value(prefix + "titleblocktemplateCollection").toString()); - context.fromSettings(settings, prefix + "properties"); + title = settings.value(prefix + "title").toString(); + author = settings.value(prefix + "author").toString(); + filename = settings.value(prefix + "filename").toString(); + plant = settings.value(prefix + "plant").toString(); + locmach = settings.value(prefix + "locmach").toString(); + indexrev = settings.value(prefix + "indexrev").toString(); + version = settings.value(prefix + "version").toString(); + folio = settings.value(prefix + "folio", "%id/%total").toString(); + auto_page_num = settings.value(prefix + "auto_page_num").toString(); + setDateFromString(settings.value(prefix + "date").toString()); + display_at = (settings.value(prefix + "displayAt", QVariant("bottom")).toString() == "bottom" ? Qt::BottomEdge : Qt::RightEdge); + template_name = settings.value(prefix + "titleblocktemplate").toString(); + collection = QET::qetCollectionFromString(settings.value(prefix + "titleblocktemplateCollection").toString()); + context.fromSettings(settings, prefix + "properties"); } /** - @brief TitleBlockProperties::defaultProperties - Return the default properties stored in the setting file + @brief TitleBlockProperties::defaultProperties + Return the default properties stored in the setting file */ TitleBlockProperties TitleBlockProperties::defaultProperties() { - QSettings settings; + QSettings settings; - TitleBlockProperties def; - def.fromSettings(settings, "diagrameditor/default"); + TitleBlockProperties def; + def.fromSettings(settings, "diagrameditor/default"); - return(def); + return(def); } /** - @return La date a utiliser + @return La date a utiliser */ QDate TitleBlockProperties::finalDate() const { - if (useDate == UseDateValue) { - return(date); - } else { - return(QDate::currentDate()); - } + if (useDate == UseDateValue) { + return(date); + } else { + return(QDate::currentDate()); + } } /** - @return une chaine de caracteres decrivant comment gerer la date dans le - cartouche : la chaine peut valoir : - * null pour ne pas afficher de date - * now pour afficher la date courante (a la creation du schema) - * une date au format yyyyMMdd pour utiliser une date fixe + @return une chaine de caracteres decrivant comment gerer la date dans le + cartouche : la chaine peut valoir : + * null pour ne pas afficher de date + * now pour afficher la date courante (a la creation du schema) + * une date au format yyyyMMdd pour utiliser une date fixe */ QString TitleBlockProperties::exportDate() const { - QString date_setting_value; - if (useDate == UseDateValue) { - if (date.isNull()) date_setting_value = "null"; - else date_setting_value = date.toString("yyyyMMdd"); - } else { - date_setting_value = "now"; - } - return(date_setting_value); + QString date_setting_value; + if (useDate == UseDateValue) { + if (date.isNull()) date_setting_value = "null"; + else date_setting_value = date.toString("yyyyMMdd"); + } else { + date_setting_value = "now"; + } + return(date_setting_value); } /** - Charge les attributs date et useDate a partir d'une chaine de caracteres. - @param date_string Chaine de caracteres a analyser - @see exportDate + Charge les attributs date et useDate a partir d'une chaine de caracteres. + @param date_string Chaine de caracteres a analyser + @see exportDate */ void TitleBlockProperties::setDateFromString(const QString &date_string) { - if (date_string == "now") { - date = QDate::currentDate(); - useDate = CurrentDate; - } else if (date_string.isEmpty() || date_string == "null") { - date = QDate(); - useDate = UseDateValue; - } else { - date = QDate::fromString(date_string, "yyyyMMdd"); - useDate = UseDateValue; - } + if (date_string == "now") { + date = QDate::currentDate(); + useDate = CurrentDate; + } else if (date_string.isEmpty() || date_string == "null") { + date = QDate(); + useDate = UseDateValue; + } else { + date = QDate::fromString(date_string, "yyyyMMdd"); + useDate = UseDateValue; + } } diff --git a/sources/titleblockproperties.h b/sources/titleblockproperties.h index 7f9ebeb0e..fbe61ff60 100644 --- a/sources/titleblockproperties.h +++ b/sources/titleblockproperties.h @@ -1,19 +1,19 @@ /* - Copyright 2006-2020 The QElectroTech Team - This file is part of QElectroTech. - - QElectroTech is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - QElectroTech is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with QElectroTech. If not, see . + Copyright 2006-2020 The QElectroTech Team + This file is part of QElectroTech. + + QElectroTech is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + QElectroTech is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with QElectroTech. If not, see . */ #ifndef TITLEBLOCK_PROPERTIES_H #define TITLEBLOCK_PROPERTIES_H @@ -22,53 +22,53 @@ #include "qet.h" /** - This class provides a container for the properties of a particular title - block, i.e. title, author, date, filename, folio, template, custom - properties, ... + This class provides a container for the properties of a particular title + block, i.e. title, author, date, filename, folio, template, custom + properties, ... */ class TitleBlockProperties { - public: - TitleBlockProperties(); - virtual ~TitleBlockProperties(); - /// Lists the various ways to handle the date - enum DateManagement { - UseDateValue, ///< use the date attribute - CurrentDate ///< use the current date - }; - - bool operator==(const TitleBlockProperties &); - bool operator!=(const TitleBlockProperties &); - - void toXml(QDomElement &) const; - void fromXml(const QDomElement &); - void toSettings(QSettings &, const QString & = QString()) const; - void fromSettings(QSettings &, const QString & = QString()); + public: + TitleBlockProperties(); + virtual ~TitleBlockProperties(); + /// Lists the various ways to handle the date + enum DateManagement { + UseDateValue, ///< use the date attribute + CurrentDate ///< use the current date + }; + + bool operator==(const TitleBlockProperties &); + bool operator!=(const TitleBlockProperties &); + + void toXml(QDomElement &) const; + void fromXml(const QDomElement &); + void toSettings(QSettings &, const QString & = QString()) const; + void fromSettings(QSettings &, const QString & = QString()); - void setAutoPageNum(QString autonum) {auto_page_num = autonum;} + void setAutoPageNum(QString autonum) {auto_page_num = autonum;} - static TitleBlockProperties defaultProperties(); - - QDate finalDate() const ; - - // attributes - QString title; ///< Folio title (displayed by the default template) - QString author; ///< Author of the diagram/folio (displayed by the default template) - QDate date; ///< Date (displayed by the default template) - QString filename; ///< Filename (displayed by the default template) - QString plant; ///< Plant (displayed by the default template) - QString locmach; ///< Location(displayed by the default template) - QString indexrev; ///< Revision Index (displayed by the default template) - QString version; ///< Version (displayed by the default template) - QString folio; ///< Folio information (displayed by the default template) - QString auto_page_num; - DateManagement useDate; ///< Wheter to use the date attribute - QString template_name; ///< Name of the template used to render the title block - an empty string means "the default template provided by the application" - DiagramContext context; ///< Container for the additional, user-defined fields - Qt::Edge display_at; ///< Edge to display the titleblock - QET::QetCollection collection; ///