Add TODO compile var + Fix doxygen issue

You can make your code warn on compile time for the TODO's
In order to do so, uncomment the following line. in pro file
DEFINES += TODO_LIST
This commit is contained in:
Simon De Backer 2020-09-24 17:01:33 +02:00
parent 65ba816859
commit 36dbe65457
40 changed files with 1147 additions and 966 deletions

View File

@ -27,7 +27,9 @@
#include <QtCore/QSharedMemory> #include <QtCore/QSharedMemory>
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // ### Qt 6: remove
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.10 or later") #pragma message("@TODO remove code for QT 5.10 or later")
#endif
#include <QRandomGenerator> #include <QRandomGenerator>
#endif #endif
#include "singleapplication.h" #include "singleapplication.h"
@ -44,21 +46,21 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda
: app_t( argc, argv ), d_ptr( new SingleApplicationPrivate( this ) ) : app_t( argc, argv ), d_ptr( new SingleApplicationPrivate( this ) )
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) #if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
// On Android and iOS since the library is not supported fallback to // On Android and iOS since the library is not supported fallback to
// standard QApplication behaviour by simply returning at this point. // standard QApplication behaviour by simply returning at this point.
qWarning() << "SingleApplication is not supported on Android and iOS systems."; qWarning() << "SingleApplication is not supported on Android and iOS systems.";
return; return;
#endif #endif
// Store the current mode of the program // Store the current mode of the program
d->options = options; d->options = options;
// Generating an application ID used for identifying the shared memory // Generating an application ID used for identifying the shared memory
// block and QLocalServer // block and QLocalServer
d->genBlockServerName(); d->genBlockServerName();
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
// By explicitly attaching it and then deleting it we make sure that the // By explicitly attaching it and then deleting it we make sure that the
// memory is deleted even after the process has crashed on Unix. // memory is deleted even after the process has crashed on Unix.
@ -68,7 +70,7 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda
#endif #endif
// Guarantee thread safe behaviour with a shared memory block. // Guarantee thread safe behaviour with a shared memory block.
d->memory = new QSharedMemory( d->blockServerName ); d->memory = new QSharedMemory( d->blockServerName );
// Create a shared memory block // Create a shared memory block
if( d->memory->create( sizeof( InstancesInfo ) ) ) { if( d->memory->create( sizeof( InstancesInfo ) ) ) {
// Initialize the shared memory block // Initialize the shared memory block
@ -84,41 +86,43 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda
::exit( EXIT_FAILURE ); ::exit( EXIT_FAILURE );
} }
} }
InstancesInfo* inst = static_cast<InstancesInfo*>( d->memory->data() ); InstancesInfo* inst = static_cast<InstancesInfo*>( d->memory->data() );
QElapsedTimer time; QElapsedTimer time;
time.start(); time.start();
// Make sure the shared memory block is initialised and in consistent state // Make sure the shared memory block is initialised and in consistent state
while( true ) { while( true ) {
d->memory->lock(); d->memory->lock();
if( d->blockChecksum() == inst->checksum ) break; if( d->blockChecksum() == inst->checksum ) break;
if( time.elapsed() > 5000 ) { if( time.elapsed() > 5000 ) {
qWarning() << "SingleApplication: Shared memory block has been in an inconsistent state from more than 5s. Assuming primary instance failure."; qWarning() << "SingleApplication: Shared memory block has been in an inconsistent state from more than 5s. Assuming primary instance failure.";
d->initializeMemoryBlock(); d->initializeMemoryBlock();
} }
d->memory->unlock(); d->memory->unlock();
// Random sleep here limits the probability of a collision between two racing apps // Random sleep here limits the probability of a collision between two racing apps
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // ### Qt 6: remove
qsrand( QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max() ); qsrand( QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max() );
QThread::sleep( 8 + static_cast <unsigned long>( static_cast <float>( qrand() ) / RAND_MAX * 10 ) ); QThread::sleep( 8 + static_cast <unsigned long>( static_cast <float>( qrand() ) / RAND_MAX * 10 ) );
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.10 or later") #pragma message("@TODO remove code for QT 5.10 or later")
#endif
quint32 value = QRandomGenerator::global()->generate(); quint32 value = QRandomGenerator::global()->generate();
QThread::sleep( 8 + static_cast <unsigned long>( static_cast <float>( value ) / RAND_MAX * 10 ) ); QThread::sleep( 8 + static_cast <unsigned long>( static_cast <float>( value ) / RAND_MAX * 10 ) );
#endif #endif
} }
if( inst->primary == false) { if( inst->primary == false) {
d->startPrimary(); d->startPrimary();
d->memory->unlock(); d->memory->unlock();
return; return;
} }
// Check if another instance can be started // Check if another instance can be started
if( allowSecondary ) { if( allowSecondary ) {
inst->secondary += 1; inst->secondary += 1;
@ -131,13 +135,13 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda
d->memory->unlock(); d->memory->unlock();
return; return;
} }
d->memory->unlock(); d->memory->unlock();
d->connectToPrimary( timeout, SingleApplicationPrivate::NewInstance ); d->connectToPrimary( timeout, SingleApplicationPrivate::NewInstance );
delete d; delete d;
::exit( EXIT_SUCCESS ); ::exit( EXIT_SUCCESS );
} }
@ -177,13 +181,13 @@ qint64 SingleApplication::primaryPid()
bool SingleApplication::sendMessage( QByteArray message, int timeout ) bool SingleApplication::sendMessage( QByteArray message, int timeout )
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
// Nobody to connect to // Nobody to connect to
if( isPrimary() ) return false; if( isPrimary() ) return false;
// Make sure the socket is connected // Make sure the socket is connected
d->connectToPrimary( timeout, SingleApplicationPrivate::Reconnect ); d->connectToPrimary( timeout, SingleApplicationPrivate::Reconnect );
d->socket->write( message ); d->socket->write( message );
bool dataWritten = d->socket->waitForBytesWritten( timeout ); bool dataWritten = d->socket->waitForBytesWritten( timeout );
d->socket->flush(); d->socket->flush();

View File

@ -4,51 +4,51 @@
# Chemins utilises pour la compilation et l'installation de QET # Chemins utilises pour la compilation et l'installation de QET
unix { unix {
# Chemins UNIX # Chemins UNIX
COMPIL_PREFIX = '/usr/local/' COMPIL_PREFIX = '/usr/local/'
INSTALL_PREFIX = '/usr/local/' INSTALL_PREFIX = '/usr/local/'
QET_BINARY_PATH = 'bin/' QET_BINARY_PATH = 'bin/'
QET_COMMON_COLLECTION_PATH = 'share/qelectrotech/elements/' QET_COMMON_COLLECTION_PATH = 'share/qelectrotech/elements/'
QET_COMMON_TBT_PATH = 'share/qelectrotech/titleblocks/' QET_COMMON_TBT_PATH = 'share/qelectrotech/titleblocks/'
QET_LANG_PATH = 'share/qelectrotech/lang/' QET_LANG_PATH = 'share/qelectrotech/lang/'
QET_EXAMPLES_PATH = 'share/qelectrotech/examples/' QET_EXAMPLES_PATH = 'share/qelectrotech/examples/'
QET_LICENSE_PATH = 'doc/qelectrotech/' QET_LICENSE_PATH = 'doc/qelectrotech/'
QET_MIME_XML_PATH = '../share/mime/application/' QET_MIME_XML_PATH = '../share/mime/application/'
QET_MIME_DESKTOP_PATH = '../share/mimelnk/application/' QET_MIME_DESKTOP_PATH = '../share/mimelnk/application/'
QET_MIME_PACKAGE_PATH = '../share/mime/packages/' QET_MIME_PACKAGE_PATH = '../share/mime/packages/'
QET_DESKTOP_PATH = 'share/applications/' QET_DESKTOP_PATH = 'share/applications/'
QET_ICONS_PATH = 'share/icons/hicolor/' QET_ICONS_PATH = 'share/icons/hicolor/'
QET_MAN_PATH = 'man/' QET_MAN_PATH = 'man/'
QET_APPDATA_PATH = 'share/appdata' QET_APPDATA_PATH = 'share/appdata'
} }
win32 { win32 {
# Chemins Windows # Chemins Windows
COMPIL_PREFIX = './' COMPIL_PREFIX = './'
INSTALL_PREFIX = './' INSTALL_PREFIX = './'
QET_BINARY_PATH = './' QET_BINARY_PATH = './'
QET_COMMON_COLLECTION_PATH = 'elements/' QET_COMMON_COLLECTION_PATH = 'elements/'
QET_COMMON_TBT_PATH = 'titleblocks/' QET_COMMON_TBT_PATH = 'titleblocks/'
QET_LANG_PATH = 'lang/' QET_LANG_PATH = 'lang/'
QET_LICENSE_PATH = './' QET_LICENSE_PATH = './'
# Liste des ressources Windows # Liste des ressources Windows
#RC_FILE = qelectrotech.rc #RC_FILE = qelectrotech.rc
} }
macx { macx {
# Chemins MacOS X # Chemins MacOS X
COMPIL_PREFIX = './' COMPIL_PREFIX = './'
INSTALL_PREFIX = '/usr/local/' INSTALL_PREFIX = '/usr/local/'
QET_BINARY_PATH = 'bin/' QET_BINARY_PATH = 'bin/'
QET_COMMON_COLLECTION_PATH = '../Resources/elements/' QET_COMMON_COLLECTION_PATH = '../Resources/elements/'
QET_COMMON_TBT_PATH = '../Resources/titleblocks/' QET_COMMON_TBT_PATH = '../Resources/titleblocks/'
QET_LANG_PATH = '../Resources/lang/' QET_LANG_PATH = '../Resources/lang/'
QET_EXAMPLES_PATH = 'share/qelectrotech/examples/' QET_EXAMPLES_PATH = 'share/qelectrotech/examples/'
QET_LICENSE_PATH = 'doc/qelectrotech/' QET_LICENSE_PATH = 'doc/qelectrotech/'
QET_MIME_XML_PATH = '../share/mime/application/' QET_MIME_XML_PATH = '../share/mime/application/'
QET_MIME_DESKTOP_PATH = '../share/mimelnk/application/' QET_MIME_DESKTOP_PATH = '../share/mimelnk/application/'
QET_DESKTOP_PATH = 'share/applications/' QET_DESKTOP_PATH = 'share/applications/'
QET_ICONS_PATH = 'share/icons/hicolor/' QET_ICONS_PATH = 'share/icons/hicolor/'
QET_MAN_PATH = 'man/' QET_MAN_PATH = 'man/'
ICON = 'ico/mac_icon/qelectrotech.icns' ICON = 'ico/mac_icon/qelectrotech.icns'
} }
@ -76,7 +76,14 @@ include(sources/QWidgetAnimation/QWidgetAnimation.pri)
DEFINES += QAPPLICATION_CLASS=QApplication DEFINES += QAPPLICATION_CLASS=QApplication
DEFINES += QT_MESSAGELOGCONTEXT DEFINES += QT_MESSAGELOGCONTEXT
DEFINES += GIT_COMMIT_SHA="\\\"$(shell git -C \""$$_PRO_FILE_PWD_"\" rev-parse --verify HEAD)\\\"" DEFINES += GIT_COMMIT_SHA="\\\"$(shell git -C \""$$_PRO_FILE_PWD_"\" rev-parse --verify HEAD)\\\""
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
# You can make your code warn on compile time for the TODO's
# In order to do so, uncomment the following line.
#DEFINES += TODO_LIST
TEMPLATE = app TEMPLATE = app
DEPENDPATH += . DEPENDPATH += .
@ -176,7 +183,7 @@ SOURCES += $$files(sources/*.cpp) \
$$files(sources/dataBase/*.cpp) \ $$files(sources/dataBase/*.cpp) \
$$files(sources/dataBase/ui/*.cpp) \ $$files(sources/dataBase/ui/*.cpp) \
$$files(sources/factory/ui/*.cpp) $$files(sources/factory/ui/*.cpp)
# Liste des fichiers qui seront incorpores au binaire en tant que ressources Qt # Liste des fichiers qui seront incorpores au binaire en tant que ressources Qt
RESOURCES += qelectrotech.qrc RESOURCES += qelectrotech.qrc
@ -268,28 +275,28 @@ man.extra = sh man/compress_man_pages.sh
INSTALLS += target elements tbt lang copyright INSTALLS += target elements tbt lang copyright
# Sous Unix, on installe egalement l'icone, un fichier .desktop, des fichiers mime et les pages de manuel # Sous Unix, on installe egalement l'icone, un fichier .desktop, des fichiers mime et les pages de manuel
unix { unix {
INSTALLS += desktop mime_xml mime_desktop mime_package icons man examples appdata INSTALLS += desktop mime_xml mime_desktop mime_package icons man examples appdata
} }
# Options de compilation communes a Unix et MacOS X # Options de compilation communes a Unix et MacOS X
unix { unix {
# Chemin des fichiers de traduction ; par defaut : lang/ dans le repertoire d'execution # Chemin des fichiers de traduction ; par defaut : lang/ dans le repertoire d'execution
DEFINES += QET_LANG_PATH=$$join(COMPIL_PREFIX,,,$${QET_LANG_PATH}) DEFINES += QET_LANG_PATH=$$join(COMPIL_PREFIX,,,$${QET_LANG_PATH})
# Chemin de la collection commune ; par defaut : elements/ dans le repertoire d'execution # Chemin de la collection commune ; par defaut : elements/ dans le repertoire d'execution
DEFINES += QET_COMMON_COLLECTION_PATH=$$join(COMPIL_PREFIX,,,$${QET_COMMON_COLLECTION_PATH}) DEFINES += QET_COMMON_COLLECTION_PATH=$$join(COMPIL_PREFIX,,,$${QET_COMMON_COLLECTION_PATH})
DEFINES += QET_COMMON_TBT_PATH=$$join(COMPIL_PREFIX,,,$${QET_COMMON_TBT_PATH}) DEFINES += QET_COMMON_TBT_PATH=$$join(COMPIL_PREFIX,,,$${QET_COMMON_TBT_PATH})
} }
# Options de compilation specifiques a MacOS X # Options de compilation specifiques a MacOS X
macx { macx {
# les chemins definis precedemment sont relatifs au dossier contenant le binaire executable # les chemins definis precedemment sont relatifs au dossier contenant le binaire executable
DEFINES += QET_LANG_PATH_RELATIVE_TO_BINARY_PATH DEFINES += QET_LANG_PATH_RELATIVE_TO_BINARY_PATH
DEFINES += QET_COMMON_COLLECTION_PATH_RELATIVE_TO_BINARY_PATH DEFINES += QET_COMMON_COLLECTION_PATH_RELATIVE_TO_BINARY_PATH
} }
# Compilers-specific options # Compilers-specific options
unix { unix {
QMAKE_COPY_DIR = 'cp -f -r --preserve=timestamps' QMAKE_COPY_DIR = 'cp -f -r --preserve=timestamps'
} }

View File

@ -55,7 +55,7 @@ ElementsCollectionWidget::ElementsCollectionWidget(QWidget *parent):
//********** //**********
//Register meta type has recommended by the message. //Register meta type has recommended by the message.
qRegisterMetaType<QVector<int>>(); qRegisterMetaType<QVector<int>>();
setUpWidget(); setUpWidget();
setUpAction(); setUpAction();
setUpConnection(); setUpConnection();
@ -125,7 +125,7 @@ void ElementsCollectionWidget::setCurrentLocation(
{ {
if (!location.exist()) if (!location.exist())
return; return;
if (m_model) if (m_model)
m_tree_view->setCurrentIndex( m_tree_view->setCurrentIndex(
m_model->indexFromLocation(location)); m_model->indexFromLocation(location));
@ -330,14 +330,14 @@ void ElementsCollectionWidget::openDir()
if (!eci) return; if (!eci) return;
if (eci->type() == FileElementCollectionItem::Type) if (eci->type() == FileElementCollectionItem::Type)
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
QDesktopServices::openUrl(static_cast<FileElementCollectionItem*>(eci)->dirPath()); QDesktopServices::openUrl(static_cast<FileElementCollectionItem*>(eci)->dirPath());
#else #else
QDesktopServices::openUrl(QUrl("file:///" + static_cast<FileElementCollectionItem*>(eci)->dirPath())); QDesktopServices::openUrl(QUrl("file:///" + static_cast<FileElementCollectionItem*>(eci)->dirPath()));
#endif #endif
else if (eci->type() == XmlProjectElementCollectionItem::Type) else if (eci->type() == XmlProjectElementCollectionItem::Type)
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
QDesktopServices::openUrl(static_cast<XmlProjectElementCollectionItem*>(eci)->project()->currentDir()); QDesktopServices::openUrl(static_cast<XmlProjectElementCollectionItem*>(eci)->project()->currentDir());
#else #else
@ -407,7 +407,7 @@ void ElementsCollectionWidget::deleteElement()
"message box title"), "message box title"),
tr("La suppression de l'élément a échoué.", tr("La suppression de l'élément a échoué.",
"message box content")); "message box content"));
} }
} }
} }
@ -744,7 +744,9 @@ void ElementsCollectionWidget::search()
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
QStringList text_list = text.split("+", QString::SkipEmptyParts); QStringList text_list = text.split("+", QString::SkipEmptyParts);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
QStringList text_list = text.split("+", Qt::SkipEmptyParts); QStringList text_list = text.split("+", Qt::SkipEmptyParts);
#endif #endif
QModelIndexList match_index; QModelIndexList match_index;

View File

@ -48,7 +48,7 @@ bool ConductorNumExport::toCsv()
// if(!name.endsWith(".csv")) { // if(!name.endsWith(".csv")) {
// name += ".csv"; // name += ".csv";
// } // }
QString filename = QFileDialog::getSaveFileName(m_parent_widget, QObject::tr("Enregister sous... "), name, QObject::tr("Fichiers csv (*.csv)")); QString filename = QFileDialog::getSaveFileName(m_parent_widget, QObject::tr("Enregister sous... "), name, QObject::tr("Fichiers csv (*.csv)"));
QFile file(filename); QFile file(filename);
if(!filename.isEmpty()) if(!filename.isEmpty())
@ -70,7 +70,9 @@ bool ConductorNumExport::toCsv()
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) // ### Qt 6: remove
stream << wiresNum() << endl; stream << wiresNum() << endl;
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.15 or later") #pragma message("@TODO remove code for QT 5.15 or later")
#endif
stream << wiresNum() << &Qt::endl(stream); stream << wiresNum() << &Qt::endl(stream);
#endif #endif
} }
@ -81,7 +83,7 @@ bool ConductorNumExport::toCsv()
else { else {
return false; return false;
} }
return true; return true;
} }
@ -92,7 +94,7 @@ bool ConductorNumExport::toCsv()
QString ConductorNumExport::wiresNum() const QString ConductorNumExport::wiresNum() const
{ {
QString csv; QString csv;
QStringList list = m_hash.keys(); QStringList list = m_hash.keys();
list.sort(); list.sort();
for (QString key : list) for (QString key : list)
@ -101,7 +103,7 @@ QString ConductorNumExport::wiresNum() const
csv.append(key + "\n"); csv.append(key + "\n");
} }
} }
return csv; return csv;
} }
@ -122,7 +124,7 @@ void ConductorNumExport::fillHash()
if (num.isEmpty() || num.contains(rx)) { if (num.isEmpty() || num.contains(rx)) {
continue; continue;
} }
//We must to define if the connected terminal is a folio report, if it is the case //We must to define if the connected terminal is a folio report, if it is the case
//we don't add the num to the hash because the terminal doesn't represent a real terminal. //we don't add the num to the hash because the terminal doesn't represent a real terminal.
if(!(c->terminal1->parentElement()->linkType() & Element::AllReport)) if(!(c->terminal1->parentElement()->linkType() & Element::AllReport))

View File

@ -368,7 +368,9 @@ void ConductorProperties::fromXml(QDomElement &e)
//Keep retrocompatible with version older than 0,4 //Keep retrocompatible with version older than 0,4
//If the propertie @type is simple (removed since QET 0,4), we set text no visible. //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 //@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") #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;
} }
@ -786,7 +788,9 @@ void ConductorProperties::readStyle(const QString &style_string) {
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
QStringList styles = style_string.split(";", QString::SkipEmptyParts); QStringList styles = style_string.split(";", QString::SkipEmptyParts);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code QString::SkipEmptyParts for QT 5.14 or later") #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 #endif

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -461,7 +461,7 @@ void Createdxf::drawArcEllipse(
{ {
// vector of parts of arc (stored as a pair of startAngle and spanAngle) for each quadrant. // vector of parts of arc (stored as a pair of startAngle and spanAngle) for each quadrant.
QVector< QPair<qreal,qreal> > arc_parts_vector; QVector< QPair<qreal,qreal> > arc_parts_vector;
if (spanAngle > 0) { if (spanAngle > 0) {
qreal start = startAngle; qreal start = startAngle;
qreal span; qreal span;
@ -503,46 +503,46 @@ void Createdxf::drawArcEllipse(
arc_parts_vector.push_back(newPart); arc_parts_vector.push_back(newPart);
} }
} }
for (int i = 0; i < arc_parts_vector.size(); i++) { for (int i = 0; i < arc_parts_vector.size(); i++) {
QPair<qreal,qreal> arc = arc_parts_vector[i]; QPair<qreal,qreal> arc = arc_parts_vector[i];
if (arc.second == 0) if (arc.second == 0)
continue; continue;
qreal arc_startAngle = arc.first * 3.142/180; qreal arc_startAngle = arc.first * 3.142/180;
qreal arc_spanAngle = arc.second * 3.142/180; qreal arc_spanAngle = arc.second * 3.142/180;
qreal a = w/2; qreal a = w/2;
qreal b = h/2; qreal b = h/2;
qreal x1 = x + w/2 + a*cos(arc_startAngle); qreal x1 = x + w/2 + a*cos(arc_startAngle);
qreal y1 = y - h/2 + b*sin(arc_startAngle); qreal y1 = y - h/2 + b*sin(arc_startAngle);
qreal x2 = x + w/2 + a*cos(arc_startAngle + arc_spanAngle); qreal x2 = x + w/2 + a*cos(arc_startAngle + arc_spanAngle);
qreal y2 = y - h/2 + b*sin(arc_startAngle + arc_spanAngle); qreal y2 = y - h/2 + b*sin(arc_startAngle + arc_spanAngle);
qreal mid_ellipse_x = x + w/2 + a*cos(arc_startAngle + arc_spanAngle/2); qreal mid_ellipse_x = x + w/2 + a*cos(arc_startAngle + arc_spanAngle/2);
qreal mid_ellipse_y = y - h/2 + b*sin(arc_startAngle + arc_spanAngle/2); qreal mid_ellipse_y = y - h/2 + b*sin(arc_startAngle + arc_spanAngle/2);
qreal mid_line_x = (x1+x2)/2; qreal mid_line_x = (x1+x2)/2;
qreal mid_line_y = (y1+y2)/2; qreal mid_line_y = (y1+y2)/2;
qreal x3 = (mid_ellipse_x + mid_line_x)/2; qreal x3 = (mid_ellipse_x + mid_line_x)/2;
qreal y3 = (mid_ellipse_y + mid_line_y)/2; qreal y3 = (mid_ellipse_y + mid_line_y)/2;
// find circumcenter of points (x1,y1), (x3,y3) and (x2,y2) // find circumcenter of points (x1,y1), (x3,y3) and (x2,y2)
qreal a1 = 2*x2 - 2*x1; qreal a1 = 2*x2 - 2*x1;
qreal b1 = 2*y2 - 2*y1; qreal b1 = 2*y2 - 2*y1;
qreal c1 = x1*x1 + y1*y1 - x2*x2 - y2*y2; qreal c1 = x1*x1 + y1*y1 - x2*x2 - y2*y2;
qreal a2 = 2*x3 - 2*x1; qreal a2 = 2*x3 - 2*x1;
qreal b2 = 2*y3 - 2*y1; qreal b2 = 2*y3 - 2*y1;
qreal c2 = x1*x1 + y1*y1 - x3*x3 - y3*y3; qreal c2 = x1*x1 + y1*y1 - x3*x3 - y3*y3;
qreal center_x = (b1*c2 - b2*c1) / (a1*b2 - a2*b1); qreal center_x = (b1*c2 - b2*c1) / (a1*b2 - a2*b1);
qreal center_y = (a1*c2 - a2*c1) / (b1*a2 - b2*a1); qreal center_y = (a1*c2 - a2*c1) / (b1*a2 - b2*a1);
qreal radius = sqrt( (x1-center_x)*(x1-center_x) + (y1-center_y)*(y1-center_y) ); qreal radius = sqrt( (x1-center_x)*(x1-center_x) + (y1-center_y)*(y1-center_y) );
if ( x1 > center_x && y1 > center_y ) if ( x1 > center_x && y1 > center_y )
arc_startAngle = asin( (y1 - center_y) / radius ); arc_startAngle = asin( (y1 - center_y) / radius );
else if ( x1 > center_x && y1 < center_y ) else if ( x1 > center_x && y1 < center_y )
@ -551,9 +551,9 @@ void Createdxf::drawArcEllipse(
arc_startAngle = 3.142 + asin( (center_y - y1) / radius ); arc_startAngle = 3.142 + asin( (center_y - y1) / radius );
else else
arc_startAngle = 3.142 - asin( (y1 - center_y) / radius ); arc_startAngle = 3.142 - asin( (y1 - center_y) / radius );
qreal arc_endAngle; qreal arc_endAngle;
if ( x2 > center_x && y2 > center_y ) if ( x2 > center_x && y2 > center_y )
arc_endAngle = asin( (y2 - center_y) / radius ); arc_endAngle = asin( (y2 - center_y) / radius );
else if ( x2 > center_x && y2 < center_y ) else if ( x2 > center_x && y2 < center_y )
@ -562,13 +562,13 @@ void Createdxf::drawArcEllipse(
arc_endAngle = 3.142 + asin( (center_y - y2) / radius ); arc_endAngle = 3.142 + asin( (center_y - y2) / radius );
else else
arc_endAngle = 3.142 - asin( (y2 - center_y) / radius ); arc_endAngle = 3.142 - asin( (y2 - center_y) / radius );
if (arc_endAngle < arc_startAngle) { if (arc_endAngle < arc_startAngle) {
qreal temp = arc_startAngle; qreal temp = arc_startAngle;
arc_startAngle = arc_endAngle; arc_startAngle = arc_endAngle;
arc_endAngle = temp; arc_endAngle = temp;
} }
QPointF transformed_point = ExportDialog::rotation_transformed( QPointF transformed_point = ExportDialog::rotation_transformed(
center_x, center_x,
center_y, center_y,
@ -581,7 +581,7 @@ void Createdxf::drawArcEllipse(
arc_startAngle *= 180/3.142; arc_startAngle *= 180/3.142;
arc_endAngle -= rotation_angle; arc_endAngle -= rotation_angle;
arc_startAngle -= rotation_angle; arc_startAngle -= rotation_angle;
drawArc( drawArc(
file_path, file_path,
center_x, center_x,
@ -687,51 +687,51 @@ void Createdxf::drawArc(
@param height @param height
@param rotation @param rotation
@param colour @param colour
@param xScale=1 @param xScaleW = 1
*/ */
void Createdxf::drawText( void Createdxf::drawText(
const QString& fileName, const QString& fileName,
const QString& text, const QString& text,
double x, double x,
double y, double y,
double height, double height,
double rotation, double rotation,
int colour, int colour,
double xScaleW) double xScaleW)
{ {
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
QFile file(fileName); QFile file(fileName);
if (!file.open(QFile::Append)) { if (!file.open(QFile::Append)) {
// error message // error message
QMessageBox errorFileOpen; QMessageBox errorFileOpen;
errorFileOpen.setText("Error: File "+fileName+" was not written correctly."); errorFileOpen.setText("Error: File "+fileName+" was not written correctly.");
errorFileOpen.setInformativeText("Close all Files and Re-Run"); errorFileOpen.setInformativeText("Close all Files and Re-Run");
errorFileOpen.exec(); errorFileOpen.exec();
} else { } else {
QTextStream To_Dxf(&file); QTextStream To_Dxf(&file);
// Draw the text // Draw the text
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "TEXT" << "\r\n"; To_Dxf << "TEXT" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
To_Dxf << 62 << "\r\n"; To_Dxf << 62 << "\r\n";
To_Dxf << colour << "\r\n"; // Colour Code To_Dxf << colour << "\r\n"; // Colour Code
To_Dxf << 10 << "\r\n"; // XYZ To_Dxf << 10 << "\r\n"; // XYZ
To_Dxf << x << "\r\n"; // X in UCS (User Coordinate System)coordinates To_Dxf << x << "\r\n"; // X in UCS (User Coordinate System)coordinates
To_Dxf << 20 << "\r\n"; To_Dxf << 20 << "\r\n";
To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates
To_Dxf << 30 << "\r\n"; To_Dxf << 30 << "\r\n";
To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates
To_Dxf << 40 << "\r\n"; To_Dxf << 40 << "\r\n";
To_Dxf << height << "\r\n"; // Text Height To_Dxf << height << "\r\n"; // Text Height
To_Dxf << 41 << "\r\n"; To_Dxf << 41 << "\r\n";
To_Dxf << xScaleW << "\r\n"; // X Scale To_Dxf << xScaleW << "\r\n"; // X Scale
To_Dxf << 1 << "\r\n"; To_Dxf << 1 << "\r\n";
To_Dxf << text << "\r\n"; // Text Value To_Dxf << text << "\r\n"; // Text Value
To_Dxf << 50 << "\r\n"; To_Dxf << 50 << "\r\n";
To_Dxf << rotation << "\r\n"; // Text Rotation To_Dxf << rotation << "\r\n"; // Text Rotation
file.close(); file.close();
} }
} }
} }
@ -749,7 +749,7 @@ void Createdxf::drawTextAligned(
int hAlign, int hAlign,
int vAlign, int vAlign,
double xAlign, double xAlign,
double xScaleW, double xScaleW,
int colour) int colour)
{ {
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
@ -778,7 +778,7 @@ void Createdxf::drawTextAligned(
To_Dxf << 40 << "\r\n"; To_Dxf << 40 << "\r\n";
To_Dxf << height << "\r\n"; // Text Height To_Dxf << height << "\r\n"; // Text Height
To_Dxf << 41 << "\r\n"; To_Dxf << 41 << "\r\n";
To_Dxf << xScaleW << "\r\n"; // X Scale To_Dxf << xScaleW << "\r\n"; // X Scale
To_Dxf << 1 << "\r\n"; To_Dxf << 1 << "\r\n";
To_Dxf << text << "\r\n"; // Text Value To_Dxf << text << "\r\n"; // Text Value
To_Dxf << 50 << "\r\n"; To_Dxf << 50 << "\r\n";
@ -802,11 +802,11 @@ void Createdxf::drawTextAligned(
#endif #endif
To_Dxf << 51 << "\r\n"; To_Dxf << 51 << "\r\n";
To_Dxf << oblique << "\r\n"; // Text Obliqueness To_Dxf << oblique << "\r\n"; // Text Obliqueness
To_Dxf << 72 << "\r\n"; To_Dxf << 72 << "\r\n";
To_Dxf << hAlign << "\r\n"; // Text Horizontal Alignment To_Dxf << hAlign << "\r\n"; // Text Horizontal Alignment
To_Dxf << 73 << "\r\n"; To_Dxf << 73 << "\r\n";
To_Dxf << vAlign << "\r\n"; // Text Vertical Alignment To_Dxf << vAlign << "\r\n"; // Text Vertical Alignment
if ((hAlign) || (vAlign)) { // Enter Second Point if ((hAlign) || (vAlign)) { // Enter Second Point
To_Dxf << 11 << "\r\n"; // XYZ To_Dxf << 11 << "\r\n"; // XYZ
To_Dxf << xAlign << "\r\n"; // X in UCS (User Coordinate System)coordinates To_Dxf << xAlign << "\r\n"; // X in UCS (User Coordinate System)coordinates
@ -819,76 +819,78 @@ void Createdxf::drawTextAligned(
} }
} }
} }
/** /**
@brief Createdxf::drawPolyline @brief Createdxf::drawPolyline
Convenience function for draw polyline Convenience function for draw polyline
@param filepath @param filepath
@param poly @param poly
@param colorcode @param colorcode
@param preScaled
*/ */
void Createdxf::drawPolyline(const QString &filepath, void Createdxf::drawPolyline(const QString &filepath,
const QPolygonF &poly, const QPolygonF &poly,
const int &colorcode, bool preScaled) const int &colorcode, bool preScaled)
{ {
qreal x,y; qreal x,y;
if (!filepath.isEmpty()) { if (!filepath.isEmpty()) {
QFile file(filepath); QFile file(filepath);
if (!file.open(QFile::Append)) { if (!file.open(QFile::Append)) {
// error message // error message
QMessageBox errorFileOpen; QMessageBox errorFileOpen;
errorFileOpen.setText("Error: File "+filepath+" was not written correctly."); errorFileOpen.setText("Error: File "+filepath+" was not written correctly.");
errorFileOpen.setInformativeText("Close all Files and Re-Run"); errorFileOpen.setInformativeText("Close all Files and Re-Run");
errorFileOpen.exec(); errorFileOpen.exec();
} else { } else {
QTextStream To_Dxf(&file); QTextStream To_Dxf(&file);
// Draw the Line // Draw the Line
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "POLYLINE" << "\r\n"; To_Dxf << "POLYLINE" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
To_Dxf << 62 << "\r\n"; To_Dxf << 62 << "\r\n";
To_Dxf << colorcode << "\r\n"; // Colour Code To_Dxf << colorcode << "\r\n"; // Colour Code
To_Dxf << 66 << "\r\n"; To_Dxf << 66 << "\r\n";
To_Dxf << 1 << "\r\n"; To_Dxf << 1 << "\r\n";
To_Dxf << 70 << "\r\n"; To_Dxf << 70 << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 10 << "\r\n"; To_Dxf << 10 << "\r\n";
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << 20 << "\r\n"; To_Dxf << 20 << "\r\n";
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << 30 << "\r\n"; To_Dxf << 30 << "\r\n";
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
foreach(QPointF p, poly) foreach(QPointF p, poly)
{ {
if(preScaled) { if(preScaled) {
x = p.x(); x = p.x();
y = p.y(); y = p.y();
} else { } else {
x = p.x() * xScale; x = p.x() * xScale;
y = sheetHeight - (p.y() * yScale); y = sheetHeight - (p.y() * yScale);
} }
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "VERTEX" << "\r\n"; To_Dxf << "VERTEX" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
To_Dxf << 70 << "\r\n"; To_Dxf << 70 << "\r\n";
To_Dxf << 32 << "\r\n"; To_Dxf << 32 << "\r\n";
To_Dxf << 10 << "\r\n"; To_Dxf << 10 << "\r\n";
To_Dxf << x << "\r\n"; // X in UCS (User Coordinate System)coordinates To_Dxf << x << "\r\n"; // X in UCS (User Coordinate System)coordinates
To_Dxf << 20 << "\r\n"; To_Dxf << 20 << "\r\n";
To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates
To_Dxf << 30 << "\r\n"; To_Dxf << 30 << "\r\n";
To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates
} }
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "SEQEND" << "\r\n"; To_Dxf << "SEQEND" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
file.close(); file.close();
} }
} }
} }
@ -899,63 +901,63 @@ void Createdxf::drawPolyline(const QString &filepath,
* ================================================ * ================================================
*/ */
/** /**
@brief Createdxf::drawCircle @brief Createdxf::drawCircle
draw circle in qt format draw circle in qt format
@param fileName @param fileName
@param center @param center
@param radius @param radius
@param colour @param colour
*/ */
void Createdxf::drawCircle( void Createdxf::drawCircle(
const QString& fileName, const QString& fileName,
QPointF centre, QPointF center,
double radius, double radius,
int colour) int colour)
{ {
qreal x = centre.x() * xScale; qreal x = center.x() * xScale;
qreal y = sheetHeight - centre.y() * yScale; qreal y = sheetHeight - center.y() * yScale;
qreal r = radius * xScale; qreal r = radius * xScale;
drawCircle(fileName,r,x,y,colour); drawCircle(fileName,r,x,y,colour);
} }
/** /**
@brief Createdxf::drawLine @brief Createdxf::drawLine
Convenience function to draw line Convenience function to draw line
@param filepath @param filepath
@param line @param line
@param colorcode @param colorcode
*/ */
void Createdxf::drawLine( void Createdxf::drawLine(
const QString &filepath, const QString &filepath,
const QLineF &line, const QLineF &line,
const int &colorcode) const int &colorcode)
{ {
drawLine(filepath, line.p1().x() * xScale, drawLine(filepath, line.p1().x() * xScale,
sheetHeight - (line.p1().y() * yScale), sheetHeight - (line.p1().y() * yScale),
line.p2().x() * xScale, line.p2().x() * xScale,
sheetHeight - (line.p2().y() * yScale), sheetHeight - (line.p2().y() * yScale),
colorcode); colorcode);
} }
/** /**
@brief Createdxf::drawEllipse @brief Createdxf::drawEllipse
Conveniance function for draw ellipse Conveniance function for draw ellipse
@param filepath @param filepath
@param rect @param rect
@param colorcode @param colorcode
*/ */
void Createdxf::drawEllipse( void Createdxf::drawEllipse(
const QString &filepath, const QString &filepath,
const QRectF &rect, const QRectF &rect,
const int &colorcode) const int &colorcode)
{ {
drawArcEllipse( drawArcEllipse(
filepath, filepath,
rect.topLeft().x() * xScale, rect.topLeft().x() * xScale,
sheetHeight - (rect.topLeft().y() * yScale), sheetHeight - (rect.topLeft().y() * yScale),
rect.width() * xScale, rect.width() * xScale,
rect.height() * yScale, rect.height() * yScale,
0, 360, 0, 0, 0, colorcode); 0, 360, 0, 0, 0, colorcode);
} }
/** /**
@ -966,9 +968,9 @@ void Createdxf::drawEllipse(
@param colorcode @param colorcode
*/ */
void Createdxf::drawRectangle( void Createdxf::drawRectangle(
const QString &filepath, const QString &filepath,
const QRectF &rect, const QRectF &rect,
const int &colorcode) { const int &colorcode) {
//QPolygonF poly(scaleRect(rect)); //QPolygonF poly(scaleRect(rect));
QPolygonF poly(rect); QPolygonF poly(rect);
drawPolyline(filepath,poly,colorcode); drawPolyline(filepath,poly,colorcode);
@ -982,49 +984,49 @@ void Createdxf::drawRectangle(
@param colorcode @param colorcode
*/ */
void Createdxf::drawPolygon( void Createdxf::drawPolygon(
const QString &filepath, const QString &filepath,
const QPolygonF &poly, const QPolygonF &poly,
const int &colorcode) const int &colorcode)
{ {
QPolygonF pg = poly; QPolygonF pg = poly;
if(!poly.isClosed()) { if(!poly.isClosed()) {
pg << poly.at(0); // Close it pg << poly.at(0); // Close it
} }
drawPolyline(filepath,pg,colorcode); drawPolyline(filepath,pg,colorcode);
} }
/** /**
@brief Createdxf::drawText @brief Createdxf::drawText
draw simple text in dxf format without any alignment specified draw simple text in dxf format without any alignment specified
@param fileName @param fileName
@param text @param text
@param point @param point
@param height @param height
@param rotation @param rotation
@param colour @param colour
@param xScaleW=1 @param xScaleW = 1
*/ */
void Createdxf::drawText( void Createdxf::drawText(
const QString& fileName, const QString& fileName,
const QString& text, const QString& text,
QPointF point, QPointF point,
double height, double height,
double rotation, double rotation,
int colour, int colour,
double xScaleW) double xScaleW)
{ {
qreal x = point.x() * xScale; qreal x = point.x() * xScale;
qreal y = sheetHeight - (point.y() * yScale); qreal y = sheetHeight - (point.y() * yScale);
drawText(fileName,text,x,y,height * yScale,rotation,colour,xScaleW); drawText(fileName,text,x,y,height * yScale,rotation,colour,xScaleW);
} }
void Createdxf::drawArcEllipse( void Createdxf::drawArcEllipse(
const QString &file_path, const QString &file_path,
QRectF rect, QRectF rect,
qreal startAngle, qreal startAngle,
qreal spanAngle, qreal spanAngle,
QPointF hotspot, QPointF hotspot,
qreal rotation_angle, qreal rotation_angle,
const int &colorcode) const int &colorcode)
{ {
qreal x = rect.x() * xScale; qreal x = rect.x() * xScale;
qreal y = sheetHeight - rect.y() * yScale; qreal y = sheetHeight - rect.y() * yScale;
@ -1041,8 +1043,8 @@ void Createdxf::drawArcEllipse(
static QRectF scaleRect(QRectF rect) static QRectF scaleRect(QRectF rect)
{ {
QRectF ro(rect.bottomLeft().x() * Createdxf::xScale, QRectF ro(rect.bottomLeft().x() * Createdxf::xScale,
Createdxf::sheetHeight - (rect.bottomLeft().y() * Createdxf::yScale), Createdxf::sheetHeight - (rect.bottomLeft().y() * Createdxf::yScale),
rect.width() * Createdxf::xScale, rect.width() * Createdxf::xScale,
rect.height() * Createdxf::yScale); rect.height() * Createdxf::yScale);
return ro; return ro;
} }

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -40,11 +40,11 @@ class Createdxf
double, double,
int); int);
static void drawCircle( static void drawCircle(
const QString& , const QString& ,
QPointF, QPointF,
double, double,
int ); int );
static void drawArc( static void drawArc(
const QString&, const QString&,
@ -69,14 +69,14 @@ class Createdxf
qreal rotation_angle, qreal rotation_angle,
const int &colorcode); const int &colorcode);
static void drawArcEllipse( static void drawArcEllipse(
const QString &file_path, const QString &file_path,
QRectF rect, QRectF rect,
qreal startAngle, qreal startAngle,
qreal spanAngle, qreal spanAngle,
QPointF hotspot, QPointF hotspot,
qreal rotation_angle, qreal rotation_angle,
const int &colorcode); const int &colorcode);
static void drawEllipse (const QString &filepath, static void drawEllipse (const QString &filepath,
const QRectF &rect, const QRectF &rect,
@ -117,16 +117,16 @@ class Createdxf
double,double, double,double,
double, double,
double, double,
int, int,
double xScale=1.0); double xScale=1.0);
static void drawText( static void drawText(
const QString&, const QString&,
const QString&, const QString&,
QPointF, QPointF,
double, double,
double, double,
int, int,
double xScale=1.0); double xScale=1.0);
static void drawTextAligned( static void drawTextAligned(
const QString& fileName, const QString& fileName,
const QString& text, const QString& text,
@ -141,19 +141,19 @@ class Createdxf
double xScale, double xScale,
int colour); int colour);
static void drawPolyline( static void drawPolyline(
const QString &filepath, const QString &filepath,
const QPolygonF &poly, const QPolygonF &poly,
const int &colorcode, const int &colorcode,
bool preScaled = false); bool preScaled = false);
static int getcolorCode ( static int getcolorCode (
const long red, const long red,
const long green, const long green,
const long blue); const long blue);
static long RGBcodeTable[]; static long RGBcodeTable[];
static int dxfColor(QColor color); static int dxfColor(QColor color);
static int dxfColor(QPen pen); static int dxfColor(QPen pen);
static const double sheetWidth; static const double sheetWidth;
static const double sheetHeight; static const double sheetHeight;

View File

@ -522,10 +522,10 @@ QHash<QString, QString> projectDataBase::elementInfoToString(Element *elmt)
} }
/** /**
* @brief projectDataBase::sqliteHandle @brief projectDataBase::sqliteHandle
* @param db @param db
* @return the sqlite3 handler class used internally by @db @return the sqlite3 handler class used internally by db
*/ */
sqlite3 *projectDataBase::sqliteHandle(QSqlDatabase *db) sqlite3 *projectDataBase::sqliteHandle(QSqlDatabase *db)
{ {
//sqlite 3 lib isn't availlable for the moment on macosx //sqlite 3 lib isn't availlable for the moment on macosx
@ -547,7 +547,7 @@ sqlite3 *projectDataBase::sqliteHandle(QSqlDatabase *db)
/** /**
* @brief projectDataBase::exportDb * @brief projectDataBase::exportDb
* Export the @db, to a file. * Export the db, to a file.
* @param db : database to export * @param db : database to export
* @param parent : parent widget of a QDialog used in this function * @param parent : parent widget of a QDialog used in this function
* @param caption : Title of the QDialog used in this function * @param caption : Title of the QDialog used in this function

View File

@ -46,7 +46,9 @@ ElementQueryWidget::ElementQueryWidget(QWidget *parent) :
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) // ### Qt 6: remove
connect(&m_button_group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), [this](int id) connect(&m_button_group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), [this](int id)
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.15 or later") #pragma message("@TODO remove code for QT 5.15 or later")
#endif
connect(&m_button_group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::idClicked), [this](int id) connect(&m_button_group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::idClicked), [this](int id)
#endif #endif
{ {
@ -306,7 +308,7 @@ QString ElementQueryWidget::queryStr() const
case 0: //No filter case 0: //No filter
break; break;
case 1: //Not empty case 1: //Not empty
filter_ += QString(" AND ") += key += " IS NOT NULL"; filter_ += QString(" AND ") += key += " IS NOT NULL";
break; break;
case 2: //empty case 2: //empty
filter_ += QString(" AND ") += key += " IS NULL"; filter_ += QString(" AND ") += key += " IS NULL";

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -131,7 +131,7 @@ Diagram::~Diagram()
if (m_event_interface) if (m_event_interface)
delete m_event_interface; delete m_event_interface;
// list removable items // list removable items
QList<QGraphicsItem *> deletable_items; QList<QGraphicsItem *> deletable_items;
for(QGraphicsItem *qgi : items()) for(QGraphicsItem *qgi : items())
@ -157,20 +157,20 @@ Diagram::~Diagram()
*/ */
void Diagram::drawBackground(QPainter *p, const QRectF &r) { void Diagram::drawBackground(QPainter *p, const QRectF &r) {
p -> save(); p -> save();
// disable all antialiasing, except for text // disable all antialiasing, except for text
// desactive tout antialiasing, sauf pour le texte // desactive tout antialiasing, sauf pour le texte
p -> setRenderHint(QPainter::Antialiasing, false); p -> setRenderHint(QPainter::Antialiasing, false);
p -> setRenderHint(QPainter::TextAntialiasing, true); p -> setRenderHint(QPainter::TextAntialiasing, true);
p -> setRenderHint(QPainter::SmoothPixmapTransform, false); p -> setRenderHint(QPainter::SmoothPixmapTransform, false);
// draw a white background // draw a white background
// dessine un fond blanc // dessine un fond blanc
p -> setPen(Qt::NoPen); p -> setPen(Qt::NoPen);
//set brush color to present background color. //set brush color to present background color.
p -> setBrush(Diagram::background_color); p -> setBrush(Diagram::background_color);
p -> drawRect(r); p -> drawRect(r);
if (draw_grid_) { if (draw_grid_) {
/* Draw the point of the grid /* Draw the point of the grid
* if background color is black, * if background color is black,
@ -201,12 +201,12 @@ void Diagram::drawBackground(QPainter *p, const QRectF &r) {
qreal limite_x = rect.x() + rect.width(); qreal limite_x = rect.x() + rect.width();
qreal limite_y = rect.y() + rect.height(); qreal limite_y = rect.y() + rect.height();
int g_x = (int)ceil(rect.x()); int g_x = (int)ceil(rect.x());
while (g_x % xGrid) ++ g_x; while (g_x % xGrid) ++ g_x;
int g_y = (int)ceil(rect.y()); int g_y = (int)ceil(rect.y());
while (g_y % yGrid) ++ g_y; while (g_y % yGrid) ++ g_y;
QPolygon points; QPolygon points;
for (int gx = g_x ; gx < limite_x ; gx += xGrid) { for (int gx = g_x ; gx < limite_x ; gx += xGrid) {
for (int gy = g_y ; gy < limite_y ; gy += yGrid) { for (int gy = g_y ; gy < limite_y ; gy += yGrid) {
@ -215,7 +215,7 @@ void Diagram::drawBackground(QPainter *p, const QRectF &r) {
} }
p -> drawPoints(points); p -> drawPoints(points);
} }
if (use_border_) border_and_titleblock.draw(p); if (use_border_) border_and_titleblock.draw(p);
p -> restore(); p -> restore();
} }
@ -228,7 +228,7 @@ void Diagram::drawBackground(QPainter *p, const QRectF &r) {
void Diagram::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) void Diagram::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{ {
event->setAccepted(false); event->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->mouseDoubleClickEvent(event); m_event_interface->mouseDoubleClickEvent(event);
if (event->isAccepted()) { if (event->isAccepted()) {
@ -247,7 +247,7 @@ void Diagram::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
void Diagram::mousePressEvent(QGraphicsSceneMouseEvent *event) void Diagram::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
event->setAccepted(false); event->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->mousePressEvent(event); m_event_interface->mousePressEvent(event);
if (event->isAccepted()) { if (event->isAccepted()) {
@ -266,7 +266,7 @@ void Diagram::mousePressEvent(QGraphicsSceneMouseEvent *event)
void Diagram::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void Diagram::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
event->setAccepted(false); event->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->mouseMoveEvent(event); m_event_interface->mouseMoveEvent(event);
if (event->isAccepted()) { if (event->isAccepted()) {
@ -285,7 +285,7 @@ void Diagram::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void Diagram::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void Diagram::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
event->setAccepted(false); event->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->mouseReleaseEvent(event); m_event_interface->mouseReleaseEvent(event);
if (event->isAccepted()) { if (event->isAccepted()) {
@ -304,7 +304,7 @@ void Diagram::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
void Diagram::wheelEvent(QGraphicsSceneWheelEvent *event) void Diagram::wheelEvent(QGraphicsSceneWheelEvent *event)
{ {
event->setAccepted(false); event->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->wheelEvent(event); m_event_interface->wheelEvent(event);
if (event->isAccepted()) { if (event->isAccepted()) {
@ -333,14 +333,14 @@ void Diagram::keyPressEvent(QKeyEvent *event)
int yKeyGridFine = settings.value("diagrameditor/key_fine_Ygrid", int yKeyGridFine = settings.value("diagrameditor/key_fine_Ygrid",
Diagram::yKeyGridFine).toInt(); Diagram::yKeyGridFine).toInt();
event->setAccepted(false); event->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->keyPressEvent(event); m_event_interface->keyPressEvent(event);
if (event->isAccepted()) { if (event->isAccepted()) {
return; return;
} }
} }
if (isReadOnly()) return; if (isReadOnly()) return;
QPointF movement; QPointF movement;
@ -354,7 +354,9 @@ void Diagram::keyPressEvent(QKeyEvent *event)
return; return;
} }
#if TODO_LIST
#pragma message("@TODO move code to new function") #pragma message("@TODO move code to new function")
#endif
//Move item with the keyboard arrow //Move item with the keyboard arrow
if(event->modifiers() == Qt::NoModifier) if(event->modifiers() == Qt::NoModifier)
{ {
@ -479,14 +481,14 @@ void Diagram::keyPressEvent(QKeyEvent *event)
void Diagram::keyReleaseEvent(QKeyEvent *e) void Diagram::keyReleaseEvent(QKeyEvent *e)
{ {
e->setAccepted(false); e->setAccepted(false);
if (m_event_interface) { if (m_event_interface) {
m_event_interface->keyReleaseEvent(e); m_event_interface->keyReleaseEvent(e);
if (e->isAccepted()) { if (e->isAccepted()) {
return; return;
} }
} }
bool transmit_event = true; bool transmit_event = true;
if (!isReadOnly()) { if (!isReadOnly()) {
/* detects the release of a direction key /* detects the release of a direction key
@ -537,7 +539,7 @@ void Diagram::setEventInterface(DiagramEventInterface *event_interface)
event_interface -> init(); event_interface -> init();
} }
m_event_interface = event_interface; m_event_interface = event_interface;
connect(m_event_interface, &DiagramEventInterface::finish, [this]() connect(m_event_interface, &DiagramEventInterface::finish, [this]()
{ {
delete this->m_event_interface; delete this->m_event_interface;
@ -601,7 +603,7 @@ bool Diagram::toPaintDevice(QPaintDevice &pix,
+ 2.0 * margin + 2.0 * margin
); );
} }
/* if the dimensions are not specified, /* if the dimensions are not specified,
* the image is exported at 1: 1 scale * the image is exported at 1: 1 scale
* si les dimensions ne sont pas precisees, * si les dimensions ne sont pas precisees,
@ -609,23 +611,23 @@ bool Diagram::toPaintDevice(QPaintDevice &pix,
*/ */
QSize image_size = (width == -1 && height == -1) QSize image_size = (width == -1 && height == -1)
? source_area.size().toSize() : QSize(width, height); ? source_area.size().toSize() : QSize(width, height);
// prepare the rendering // prepare the rendering
// prepare le rendu // prepare le rendu
QPainter p; QPainter p;
if (!p.begin(&pix)) return(false); if (!p.begin(&pix)) return(false);
// anti-aliasis rendering // anti-aliasis rendering
// rendu antialiase // rendu antialiase
p.setRenderHint(QPainter::Antialiasing, true); p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::TextAntialiasing, true); p.setRenderHint(QPainter::TextAntialiasing, true);
p.setRenderHint(QPainter::SmoothPixmapTransform, true); p.setRenderHint(QPainter::SmoothPixmapTransform, true);
// deselect all elements // deselect all elements
// deselectionne tous les elements // deselectionne tous les elements
QList<QGraphicsItem *> selected_elmts = selectedItems(); QList<QGraphicsItem *> selected_elmts = selectedItems();
foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(false); foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(false);
// renders itself // renders itself
// effectue le rendu lui-meme // effectue le rendu lui-meme
render(&p, render(&p,
@ -633,11 +635,11 @@ bool Diagram::toPaintDevice(QPaintDevice &pix,
source_area, source_area,
aspectRatioMode); aspectRatioMode);
p.end(); p.end();
// restore selected items // restore selected items
// restaure les elements selectionnes // restaure les elements selectionnes
foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(true); foreach (QGraphicsItem *qgi, selected_elmts) qgi -> setSelected(true);
return(true); return(true);
} }
@ -664,10 +666,10 @@ QSize Diagram::imageSize() const
image_height = border_and_titleblock image_height = border_and_titleblock
.borderAndTitleBlockRect().height(); .borderAndTitleBlockRect().height();
} }
image_width += 2.0 * margin; image_width += 2.0 * margin;
image_height += 2.0 * margin; image_height += 2.0 * margin;
// returns the size of the source area // returns the size of the source area
// renvoie la taille de la zone source // renvoie la taille de la zone source
return(QSizeF(image_width, image_height).toSize()); return(QSizeF(image_width, image_height).toSize());
@ -726,20 +728,20 @@ QList < QSet <Conductor *> > Diagram::potentials()
QDomDocument Diagram::toXml(bool whole_content) { QDomDocument Diagram::toXml(bool whole_content) {
// document // document
QDomDocument document; QDomDocument document;
// XML tree root // XML tree root
// racine de l'arbre XML // racine de l'arbre XML
auto dom_root = document.createElement("diagram"); auto dom_root = document.createElement("diagram");
// add the application version number // add the application version number
dom_root.setAttribute("version", QET::version); dom_root.setAttribute("version", QET::version);
// schema properties // schema properties
// proprietes du schema // proprietes du schema
if (whole_content) { if (whole_content) {
border_and_titleblock.titleBlockToXml(dom_root); border_and_titleblock.titleBlockToXml(dom_root);
border_and_titleblock.borderToXml(dom_root); border_and_titleblock.borderToXml(dom_root);
// Default conductor properties // Default conductor properties
QDomElement default_conductor = QDomElement default_conductor =
document.createElement("defaultconductor"); document.createElement("defaultconductor");
@ -854,10 +856,10 @@ QDomDocument Diagram::toXml(bool whole_content) {
dom_root.setAttribute("projectId", QETApp::projectId(m_project)); dom_root.setAttribute("projectId", QETApp::projectId(m_project));
} }
document.appendChild(dom_root); document.appendChild(dom_root);
if (items().isEmpty()) if (items().isEmpty())
return(document); return(document);
QVector<Element *> list_elements; QVector<Element *> list_elements;
QVector<Conductor *> list_conductors; QVector<Conductor *> list_conductors;
QVector<DiagramTextItem *> list_texts; QVector<DiagramTextItem *> list_texts;
@ -915,11 +917,11 @@ QDomDocument Diagram::toXml(bool whole_content) {
} }
} }
} }
// correspondence table between the addresses of the terminals and their ids // correspondence table between the addresses of the terminals and their ids
// table de correspondance entre les adresses des bornes et leurs ids // table de correspondance entre les adresses des bornes et leurs ids
QHash<Terminal *, int> table_adr_id; QHash<Terminal *, int> table_adr_id;
if (!list_elements.isEmpty()) { if (!list_elements.isEmpty()) {
auto dom_elements = document.createElement("elements"); auto dom_elements = document.createElement("elements");
for (auto elmt : list_elements) { for (auto elmt : list_elements) {
@ -928,7 +930,7 @@ QDomDocument Diagram::toXml(bool whole_content) {
} }
dom_root.appendChild(dom_elements); dom_root.appendChild(dom_elements);
} }
if (!list_conductors.isEmpty()) { if (!list_conductors.isEmpty()) {
auto dom_conductors = document.createElement("conductors"); auto dom_conductors = document.createElement("conductors");
for (auto cond : list_conductors) { for (auto cond : list_conductors) {
@ -937,7 +939,7 @@ QDomDocument Diagram::toXml(bool whole_content) {
} }
dom_root.appendChild(dom_conductors); dom_root.appendChild(dom_conductors);
} }
if (!list_texts.isEmpty()) { if (!list_texts.isEmpty()) {
auto dom_texts = document.createElement("inputs"); auto dom_texts = document.createElement("inputs");
for (auto dti : list_texts) { for (auto dti : list_texts) {
@ -1082,7 +1084,7 @@ bool Diagram::initFromXml(QDomElement &document,
position, position,
consider_informations, consider_informations,
content_ptr); content_ptr);
return(from_xml); return(from_xml);
} }
@ -1189,7 +1191,7 @@ bool Diagram::fromXml(QDomElement &document,
const QDomElement& root = document; const QDomElement& root = document;
// The first element must be a diagram // The first element must be a diagram
if (root.tagName() != "diagram") return(false); if (root.tagName() != "diagram") return(false);
// Read attributes of this diagram // Read attributes of this diagram
if (consider_informations) { if (consider_informations) {
// Version of diagram // Version of diagram
@ -1198,11 +1200,11 @@ bool Diagram::fromXml(QDomElement &document,
if (conv_ok) { if (conv_ok) {
diagram_qet_version_ = version_value; diagram_qet_version_ = version_value;
} }
// Load border and titleblock // Load border and titleblock
border_and_titleblock.titleBlockFromXml(root); border_and_titleblock.titleBlockFromXml(root);
border_and_titleblock.borderFromXml(root); border_and_titleblock.borderFromXml(root);
// Find the element "defaultconductor". // Find the element "defaultconductor".
// If found, load default conductor properties. // If found, load default conductor properties.
QDomElement default_conductor_elmt = QDomElement default_conductor_elmt =
@ -1259,7 +1261,7 @@ bool Diagram::fromXml(QDomElement &document,
if (root.firstChild().isNull()) { if (root.firstChild().isNull()) {
return(true); return(true);
} }
/* Backward compatibility: prior to version 0.3, we need to compensate, /* Backward compatibility: prior to version 0.3, we need to compensate,
* at diagram-opening time, the rotation of the element for each of its * at diagram-opening time, the rotation of the element for each of its
* textfields having the "FollowParentRotation" option disabled. * textfields having the "FollowParentRotation" option disabled.
@ -1312,7 +1314,7 @@ bool Diagram::fromXml(QDomElement &document,
QET::findInDomElement(root, "elements", "element")) QET::findInDomElement(root, "elements", "element"))
{ {
if (!Element::valideXml(element_xml)) continue; if (!Element::valideXml(element_xml)) continue;
// cree un element dont le type correspond a l'id type // cree un element dont le type correspond a l'id type
QString type_id = element_xml.attribute("type"); QString type_id = element_xml.attribute("type");
ElementsLocation element_location; ElementsLocation element_location;
@ -1322,7 +1324,7 @@ bool Diagram::fromXml(QDomElement &document,
else { else {
element_location = ElementsLocation(type_id); element_location = ElementsLocation(type_id);
} }
int state = 0; int state = 0;
Element *nvel_elmt = Element *nvel_elmt =
ElementFactory::Instance() -> createElement( ElementFactory::Instance() -> createElement(
@ -1338,7 +1340,7 @@ bool Diagram::fromXml(QDomElement &document,
delete nvel_elmt; delete nvel_elmt;
continue; continue;
} }
addItem(nvel_elmt); addItem(nvel_elmt);
//Loading fail, remove item from the diagram //Loading fail, remove item from the diagram
if (!nvel_elmt->fromXml(element_xml, if (!nvel_elmt->fromXml(element_xml,
@ -1353,7 +1355,7 @@ bool Diagram::fromXml(QDomElement &document,
added_elements << nvel_elmt; added_elements << nvel_elmt;
} }
} }
// Load text // Load text
QList<IndependentTextItem *> added_texts; QList<IndependentTextItem *> added_texts;
foreach (QDomElement text_xml, QET::findInDomElement(root, foreach (QDomElement text_xml, QET::findInDomElement(root,
@ -1455,7 +1457,7 @@ bool Diagram::fromXml(QDomElement &document,
for (auto qgi : added_items) for (auto qgi : added_items)
qgi->setPos(qgi->pos() += pos_); qgi->setPos(qgi->pos() += pos_);
} }
//Filling of falculatory lists //Filling of falculatory lists
if (content_ptr) { if (content_ptr) {
content_ptr -> m_elements = added_elements; content_ptr -> m_elements = added_elements;
@ -1465,7 +1467,9 @@ bool Diagram::fromXml(QDomElement &document,
content_ptr -> m_images = added_images.toSet(); content_ptr -> m_images = added_images.toSet();
content_ptr -> m_shapes = added_shapes.toSet(); content_ptr -> m_shapes = added_shapes.toSet();
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
content_ptr -> m_text_fields = QSet<IndependentTextItem *>( content_ptr -> m_text_fields = QSet<IndependentTextItem *>(
added_texts.begin(), added_texts.begin(),
added_texts.end()); added_texts.end());
@ -1627,7 +1631,7 @@ void Diagram::titleChanged(const QString &title) {
void Diagram::titleBlockTemplateChanged(const QString &template_name) { void Diagram::titleBlockTemplateChanged(const QString &template_name) {
if (border_and_titleblock.titleBlockTemplateName() != template_name) if (border_and_titleblock.titleBlockTemplateName() != template_name)
return; return;
border_and_titleblock.titleBlockTemplateChanged(template_name); border_and_titleblock.titleBlockTemplateChanged(template_name);
update(); update();
} }
@ -1644,7 +1648,7 @@ void Diagram::titleBlockTemplateChanged(const QString &template_name) {
void Diagram::titleBlockTemplateRemoved(const QString &template_name, void Diagram::titleBlockTemplateRemoved(const QString &template_name,
const QString &new_template) const QString &new_template)
{ {
if (border_and_titleblock.titleBlockTemplateName() != template_name) return; if (border_and_titleblock.titleBlockTemplateName() != template_name) return;
const TitleBlockTemplate *final_template = const TitleBlockTemplate *final_template =
m_project->embeddedTitleBlockTemplatesCollection() m_project->embeddedTitleBlockTemplatesCollection()
->getTemplate(new_template); ->getTemplate(new_template);
@ -1661,14 +1665,14 @@ void Diagram::titleBlockTemplateRemoved(const QString &template_name,
void Diagram::setTitleBlockTemplate(const QString &template_name) void Diagram::setTitleBlockTemplate(const QString &template_name)
{ {
if (!m_project) return; if (!m_project) return;
QString current_name = border_and_titleblock.titleBlockTemplateName(); QString current_name = border_and_titleblock.titleBlockTemplateName();
const TitleBlockTemplate *titleblock_template = const TitleBlockTemplate *titleblock_template =
m_project->embeddedTitleBlockTemplatesCollection() m_project->embeddedTitleBlockTemplatesCollection()
->getTemplate(template_name); ->getTemplate(template_name);
border_and_titleblock.titleBlockTemplateRemoved(current_name, border_and_titleblock.titleBlockTemplateRemoved(current_name,
titleblock_template); titleblock_template);
if (template_name != current_name) if (template_name != current_name)
emit(usedTitleBlockTemplateChanged(template_name)); emit(usedTitleBlockTemplateChanged(template_name));
} }
@ -1681,7 +1685,7 @@ void Diagram::setTitleBlockTemplate(const QString &template_name)
void Diagram::selectAll() void Diagram::selectAll()
{ {
if (items().isEmpty()) return; if (items().isEmpty()) return;
blockSignals(true); blockSignals(true);
foreach(QGraphicsItem *qgi, items()) qgi -> setSelected(true); foreach(QGraphicsItem *qgi, items()) qgi -> setSelected(true);
blockSignals(false); blockSignals(false);
@ -1696,7 +1700,7 @@ void Diagram::selectAll()
void Diagram::deselectAll() void Diagram::deselectAll()
{ {
if (items().isEmpty()) return; if (items().isEmpty()) return;
clearSelection(); clearSelection();
} }
@ -1708,7 +1712,7 @@ void Diagram::deselectAll()
void Diagram::invertSelection() void Diagram::invertSelection()
{ {
if (items().isEmpty()) return; if (items().isEmpty()) return;
blockSignals(true); blockSignals(true);
foreach (QGraphicsItem *item, foreach (QGraphicsItem *item,
items()) item -> setSelected(!item -> isSelected()); items()) item -> setSelected(!item -> isSelected());
@ -1800,7 +1804,7 @@ void Diagram::changeZValue(QET::DepthOption option)
QList<QGraphicsObject *> list; QList<QGraphicsObject *> list;
for(QGraphicsItem *item : l) for(QGraphicsItem *item : l)
list << item->toGraphicsObject(); list << item->toGraphicsObject();
qreal maxz=0, qreal maxz=0,
minz=0; minz=0;
for(QGraphicsItem *item : this->items()) for(QGraphicsItem *item : this->items())
@ -1809,9 +1813,9 @@ void Diagram::changeZValue(QET::DepthOption option)
if(z >= Terminal::Z-2) if(z >= Terminal::Z-2)
continue; continue;
maxz = std::max(maxz,z); maxz = std::max(maxz,z);
minz = std::min(minz,z); minz = std::min(minz,z);
} }
if(option == QET::Raise) if(option == QET::Raise)
{ {
for(QGraphicsObject *qgo : list) for(QGraphicsObject *qgo : list)
@ -1850,7 +1854,7 @@ void Diagram::changeZValue(QET::DepthOption option)
minz-1, minz-1,
undo); undo);
} }
if(undo->childCount()) if(undo->childCount())
this->undoStack().push(undo); this->undoStack().push(undo);
else else
@ -2213,7 +2217,7 @@ ExportProperties Diagram::applyProperties(
old_properties.draw_colored_conductors = drawColoredConductors(); old_properties.draw_colored_conductors = drawColoredConductors();
old_properties.exported_area = useBorder() ? QET::BorderArea old_properties.exported_area = useBorder() ? QET::BorderArea
: QET::ElementsArea; : QET::ElementsArea;
// apply the new rendering options // apply the new rendering options
// applique les nouvelles options de rendu // applique les nouvelles options de rendu
setUseBorder (new_properties.exported_area == QET::BorderArea); setUseBorder (new_properties.exported_area == QET::BorderArea);
@ -2222,7 +2226,7 @@ ExportProperties Diagram::applyProperties(
setDisplayGrid (new_properties.draw_grid); setDisplayGrid (new_properties.draw_grid);
border_and_titleblock.displayBorder(new_properties.draw_border); border_and_titleblock.displayBorder(new_properties.draw_border);
border_and_titleblock.displayTitleBlock (new_properties.draw_titleblock); border_and_titleblock.displayTitleBlock (new_properties.draw_titleblock);
// return old rendering options // return old rendering options
// retourne les anciennes options de rendu // retourne les anciennes options de rendu
return(old_properties); return(old_properties);
@ -2242,10 +2246,10 @@ DiagramPosition Diagram::convertPosition(const QPointF &pos) {
// delegue le calcul au BorderTitleBlock // delegue le calcul au BorderTitleBlock
DiagramPosition diagram_position = DiagramPosition diagram_position =
border_and_titleblock.convertPosition(pos); border_and_titleblock.convertPosition(pos);
// embarque la position cartesienne // embarque la position cartesienne
diagram_position.setPosition(pos); diagram_position.setPosition(pos);
return(diagram_position); return(diagram_position);
} }
@ -2426,11 +2430,11 @@ bool Diagram::canRotateSelection() const
qgi->type() == Element::Type || qgi->type() == Element::Type ||
qgi->type() == DynamicElementTextItem::Type) qgi->type() == DynamicElementTextItem::Type)
return true; return true;
if(qgi->type() == QGraphicsItemGroup::Type) if(qgi->type() == QGraphicsItemGroup::Type)
if(dynamic_cast<ElementTextItemGroup *>(qgi)) if(dynamic_cast<ElementTextItemGroup *>(qgi))
return true; return true;
} }
return false; return false;
} }

View File

@ -146,6 +146,9 @@ void DiagramPrintDialog::exec()
#if defined Q_OS_LINUX #if defined Q_OS_LINUX
//Due to some bug with xfwm, we display this dialog has a windows on linux os (X11) //Due to some bug with xfwm, we display this dialog has a windows on linux os (X11)
//@TODO see if we must this line with graphic server wayland //@TODO see if we must this line with graphic server wayland
#if TODO_LIST
#pragma message("@TODO see if we must this line with graphic server wayland")
#endif
QETPrintPreviewDialog preview_dialog(project_, printer_, parentWidget(), Qt::Window); QETPrintPreviewDialog preview_dialog(project_, printer_, parentWidget(), Qt::Window);
#else #else
QETPrintPreviewDialog preview_dialog(project_, printer_, parentWidget()); QETPrintPreviewDialog preview_dialog(project_, printer_, parentWidget());
@ -326,6 +329,9 @@ void DiagramPrintDialog::acceptPrintTypeDialog()
); );
} else dialog_ -> accept(); } else dialog_ -> accept();
} else { } else {
#if TODO_LIST
#pragma message("@TODO une imprimante doit avoir ete selectionnee")
#endif
// une imprimante doit avoir ete selectionnee // une imprimante doit avoir ete selectionnee
/// @todo /// @todo
dialog_ -> accept(); dialog_ -> accept();

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -41,14 +41,14 @@ ArcEditor::ArcEditor(QETElementEditor *editor, PartArc *arc, QWidget *parent) :
angle = new QSpinBox(); angle = new QSpinBox();
start_angle -> setRange(-360, 360); start_angle -> setRange(-360, 360);
angle -> setRange(-360, 360); angle -> setRange(-360, 360);
x->setRange(-5000, 5000); x->setRange(-5000, 5000);
y->setRange(-5000, 5000); y->setRange(-5000, 5000);
h->setRange(-5000, 5000); h->setRange(-5000, 5000);
v->setRange(-5000, 5000); v->setRange(-5000, 5000);
QVBoxLayout *v_layout = new QVBoxLayout(this); QVBoxLayout *v_layout = new QVBoxLayout(this);
QGridLayout *grid = new QGridLayout(); QGridLayout *grid = new QGridLayout();
grid -> addWidget(new QLabel(tr("Centre : ")), 0, 0); grid -> addWidget(new QLabel(tr("Centre : ")), 0, 0);
grid -> addWidget(new QLabel("x"), 1, 0, Qt::AlignRight); grid -> addWidget(new QLabel("x"), 1, 0, Qt::AlignRight);
@ -64,13 +64,13 @@ ArcEditor::ArcEditor(QETElementEditor *editor, PartArc *arc, QWidget *parent) :
grid -> addWidget(start_angle, 5, 1); grid -> addWidget(start_angle, 5, 1);
grid -> addWidget(new QLabel(tr("Angle :")), 6, 0); grid -> addWidget(new QLabel(tr("Angle :")), 6, 0);
grid -> addWidget(angle, 6, 1); grid -> addWidget(angle, 6, 1);
v_layout -> addWidget(style_); v_layout -> addWidget(style_);
v_layout -> addLayout(grid); v_layout -> addLayout(grid);
v_layout->addStretch(); v_layout->addStretch();
updateForm(); updateForm();
activeConnections(true); activeConnections(true);
} }
@ -83,6 +83,9 @@ void ArcEditor::setUpChangeConnections()
m_change_connections << connect(part, &PartArc::rectChanged, this, &ArcEditor::updateForm); m_change_connections << connect(part, &PartArc::rectChanged, this, &ArcEditor::updateForm);
m_change_connections << connect(part, &PartArc::spanAngleChanged, this, &ArcEditor::updateForm); m_change_connections << connect(part, &PartArc::spanAngleChanged, this, &ArcEditor::updateForm);
m_change_connections << connect(part, &PartArc::startAngleChanged, this, &ArcEditor::updateForm); m_change_connections << connect(part, &PartArc::startAngleChanged, this, &ArcEditor::updateForm);
#if TODO_LIST
#pragma message("@TODO implement position changes!")
#endif
// TODO: implement position changes! // TODO: implement position changes!
//m_change_connections << connect(part, &PartArc::) //m_change_connections << connect(part, &PartArc::)
} }
@ -90,7 +93,7 @@ void ArcEditor::setUpChangeConnections()
void ArcEditor::disconnectChangeConnections() void ArcEditor::disconnectChangeConnections()
{ {
for (QMetaObject::Connection c : m_change_connections) { for (QMetaObject::Connection c : m_change_connections) {
disconnect(c); disconnect(c);
} }
m_change_connections.clear(); m_change_connections.clear();
} }

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -307,10 +307,10 @@ ChangeZValueCommand::ChangeZValueCommand(
{ {
// retrieve all primitives but terminals // retrieve all primitives but terminals
QList<QGraphicsItem *> items_list = m_scene -> zItems(ElementScene::SortByZValue | ElementScene::SelectedOrNot); QList<QGraphicsItem *> items_list = m_scene -> zItems(ElementScene::SortByZValue | ElementScene::SelectedOrNot);
// prend un snapshot des zValues // prend un snapshot des zValues
foreach(QGraphicsItem *qgi, items_list) undo_hash.insert(qgi, qgi -> zValue()); foreach(QGraphicsItem *qgi, items_list) undo_hash.insert(qgi, qgi -> zValue());
// choisit le nom en fonction du traitement // choisit le nom en fonction du traitement
if (m_option == QET::BringForward) { if (m_option == QET::BringForward) {
setText(QObject::tr("amener au premier plan", "undo caption")); setText(QObject::tr("amener au premier plan", "undo caption"));
@ -368,14 +368,16 @@ void ChangeZValueCommand::applyBringForward(const QList<QGraphicsItem *> &items_
*/ */
void ChangeZValueCommand::applyRaise(const QList<QGraphicsItem *> &items_list) { void ChangeZValueCommand::applyRaise(const QList<QGraphicsItem *> &items_list) {
QList<QGraphicsItem *> my_items_list = items_list; QList<QGraphicsItem *> my_items_list = items_list;
for (int i = my_items_list.count() - 2 ; i >= 0 ; -- i) { for (int i = my_items_list.count() - 2 ; i >= 0 ; -- i) {
if (my_items_list[i] -> isSelected()) { if (my_items_list[i] -> isSelected()) {
if (!my_items_list[i +1] -> isSelected()) { if (!my_items_list[i +1] -> isSelected()) {
#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) // ### Qt 6: remove
my_items_list.swap(i, i + 1); my_items_list.swap(i, i + 1);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.13 or later") #pragma message("@TODO remove code for QT 5.13 or later")
#endif
my_items_list.swapItemsAt(i, i + 1); my_items_list.swapItemsAt(i, i + 1);
#endif #endif
} }
@ -391,20 +393,22 @@ void ChangeZValueCommand::applyRaise(const QList<QGraphicsItem *> &items_list) {
*/ */
void ChangeZValueCommand::applyLower(const QList<QGraphicsItem *> &items_list) { void ChangeZValueCommand::applyLower(const QList<QGraphicsItem *> &items_list) {
QList<QGraphicsItem *> my_items_list = items_list; QList<QGraphicsItem *> my_items_list = items_list;
for (int i = 1 ; i < my_items_list.count() ; ++ i) { for (int i = 1 ; i < my_items_list.count() ; ++ i) {
if (my_items_list[i] -> isSelected()) { if (my_items_list[i] -> isSelected()) {
if (!my_items_list[i - 1] -> isSelected()) { if (!my_items_list[i - 1] -> isSelected()) {
#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) // ### Qt 6: remove
my_items_list.swap(i, i - 1); my_items_list.swap(i, i - 1);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.13 or later") #pragma message("@TODO remove code for QT 5.13 or later")
#endif
my_items_list.swapItemsAt(i, i - 1); my_items_list.swapItemsAt(i, i - 1);
#endif #endif
} }
} }
} }
int z = 1; int z = 1;
foreach(QGraphicsItem *qgi, my_items_list) redo_hash.insert(qgi, z ++); foreach(QGraphicsItem *qgi, my_items_list) redo_hash.insert(qgi, z ++);
} }
@ -550,7 +554,7 @@ void ScalePartsCommand::scale(const QRectF &before, const QRectF &after) {
if (!scaled_primitives_.count()) return; if (!scaled_primitives_.count()) return;
if (before == after) return; if (before == after) return;
if (!before.width() || !before.height()) return; // cowardly flee division by zero FIXME? if (!before.width() || !before.height()) return; // cowardly flee division by zero FIXME?
foreach (CustomElementPart *part_item, scaled_primitives_) { foreach (CustomElementPart *part_item, scaled_primitives_) {
part_item -> startUserTransformation(before); part_item -> startUserTransformation(before);
part_item -> handleUserTransformation(before, after); part_item -> handleUserTransformation(before, after);

View File

@ -515,7 +515,9 @@ void CustomElementGraphicPart::stylesFromXml(const QDomElement &qde)
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
QStringList styles = qde.attribute("style").split(";", QString::SkipEmptyParts); QStringList styles = qde.attribute("style").split(";", QString::SkipEmptyParts);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #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 #endif

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -174,6 +174,9 @@ void PartDynamicTextField::fromXml(const QDomElement &dom_elmt) {
setFont(font_); setFont(font_);
} }
else { else {
#if TODO_LIST
#pragma message("@TODO remove in futur")
#endif
//Keep compatibility TODO remove in futur //Keep compatibility TODO remove in futur
setFont(QETApp::dynamicTextsItemFont(9)); setFont(QETApp::dynamicTextsItemFont(9));
} }
@ -393,7 +396,7 @@ void PartDynamicTextField::setPlainText(const QString &text) {
prepareAlignment(); prepareAlignment();
QGraphicsTextItem::setPlainText(text); QGraphicsTextItem::setPlainText(text);
//User define a text width //User define a text width
if(m_text_width > 0) { if(m_text_width > 0) {
if(document() -> size().width() > m_text_width) { if(document() -> size().width() > m_text_width) {
@ -477,8 +480,8 @@ void PartDynamicTextField::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
QVariant PartDynamicTextField::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { QVariant PartDynamicTextField::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) {
if (change == QGraphicsItem::ItemPositionHasChanged || change == QGraphicsItem::ItemSceneHasChanged) { if (change == QGraphicsItem::ItemPositionHasChanged || change == QGraphicsItem::ItemSceneHasChanged) {
updateCurrentPartEditor(); updateCurrentPartEditor();
if(change == QGraphicsItem::ItemSceneHasChanged && if(change == QGraphicsItem::ItemSceneHasChanged &&
m_first_add && m_first_add &&
elementScene() != nullptr) elementScene() != nullptr)
{ {
connect(elementScene(), &ElementScene::elementInfoChanged, connect(elementScene(), &ElementScene::elementInfoChanged,
@ -499,7 +502,7 @@ void PartDynamicTextField::paint(QPainter *painter, const QStyleOptionGraphicsIt
painter -> save(); painter -> save();
painter -> setFont(this -> font()); painter -> setFont(this -> font());
//Adjust the thickness according to the font size, //Adjust the thickness according to the font size,
qreal w=0.3; qreal w=0.3;
if(this -> font().pointSize() >= 5) { if(this -> font().pointSize() >= 5) {
w = this -> font().pointSizeF()*0.1; w = this -> font().pointSizeF()*0.1;
@ -590,6 +593,6 @@ void PartDynamicTextField::finishAlignment()
QPointF p = transform.map(QPointF(x,y)); QPointF p = transform.map(QPointF(x,y));
QPointF pa = transform.map(QPointF(xa,ya)); QPointF pa = transform.map(QPointF(xa,ya));
QPointF diff = pa-p; QPointF diff = pa-p;
setPos(this -> pos() - diff); setPos(this -> pos() - diff);
} }

View File

@ -672,6 +672,9 @@ void QETElementEditor::slot_updateInformations()
//We add the editor widget //We add the editor widget
ElementItemEditor *editor = static_cast<ElementItemEditor*>(m_editors[selection_xml_name]); ElementItemEditor *editor = static_cast<ElementItemEditor*>(m_editors[selection_xml_name]);
#if TODO_LIST
#pragma message("@TODO Check if it takes longer than setting the parts again to the editor.")
#endif
// TODO: Check if it takes longer than setting the parts again to the editor. // TODO: Check if it takes longer than setting the parts again to the editor.
bool equal = true; bool equal = true;
QList<CustomElementPart*> parts = editor -> currentParts(); QList<CustomElementPart*> parts = editor -> currentParts();
@ -710,6 +713,9 @@ void QETElementEditor::slot_updateInformations()
return; return;
} }
else if (selection_xml_name == "polygon" && cep_list.length() == 1) { else if (selection_xml_name == "polygon" && cep_list.length() == 1) {
#if TODO_LIST
#pragma message("@TODO maybe allowing multipart edit when number of points is the same?")
#endif
// multi edit for polygons makes no sense // multi edit for polygons makes no sense
// TODO: maybe allowing multipart edit when number of points is the same? // TODO: maybe allowing multipart edit when number of points is the same?
//We add the editor widget //We add the editor widget

View File

@ -1,19 +1,19 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "lineeditor.h" #include "lineeditor.h"
#include "ui_lineeditor.h" #include "ui_lineeditor.h"
@ -25,28 +25,68 @@
#include "qeticons.h" #include "qeticons.h"
/** /**
* @brief LineEditor::LineEditor @brief LineEditor::LineEditor
* @param editor : Element editor who belong this editor @param editor : Element editor who belong this editor
* @param part : part line to edit @param part : part line to edit
* @param parent : parent widget @param parent : parent widget
*/ */
LineEditor::LineEditor(QETElementEditor *editor, PartLine *part, QWidget *parent) : LineEditor::LineEditor(
ElementItemEditor(editor, parent), QETElementEditor *editor, PartLine *part, QWidget *parent) :
ui(new Ui::LineEditor) ElementItemEditor(editor, parent),ui(new Ui::LineEditor)
{ {
ui->setupUi(this); ui->setupUi(this);
ui->m_end1_cb->addItem(QET::Icons::EndLineNone, tr("Normale", "type of the 1st end of a line"), Qet::None ); ui->m_end1_cb->addItem(
ui->m_end1_cb->addItem(QET::Icons::EndLineSimple, tr("Flèche simple", "type of the 1st end of a line"), Qet::Simple ); QET::Icons::EndLineNone,
ui->m_end1_cb->addItem(QET::Icons::EndLineTriangle, tr("Flèche triangulaire", "type of the 1st end of a line"), Qet::Triangle); tr("Normale",
ui->m_end1_cb->addItem(QET::Icons::EndLineCircle, tr("Cercle", "type of the 1st end of a line"), Qet::Circle ); "type of the 1st end of a line"),
ui->m_end1_cb->addItem(QET::Icons::EndLineDiamond, tr("Carré", "type of the 1st end of a line"), Qet::Diamond ); Qet::None );
ui->m_end1_cb->addItem(
QET::Icons::EndLineSimple,
tr("Flèche simple",
"type of the 1st end of a line"),
Qet::Simple );
ui->m_end1_cb->addItem(
QET::Icons::EndLineTriangle,
tr("Flèche triangulaire",
"type of the 1st end of a line"),
Qet::Triangle);
ui->m_end1_cb->addItem(
QET::Icons::EndLineCircle,
tr("Cercle",
"type of the 1st end of a line"),
Qet::Circle );
ui->m_end1_cb->addItem(
QET::Icons::EndLineDiamond,
tr("Carré",
"type of the 1st end of a line"),
Qet::Diamond );
ui->m_end2_cb->addItem(QET::Icons::EndLineNone, tr("Normale", "type of the 1st end of a line"), Qet::None ); ui->m_end2_cb->addItem(
ui->m_end2_cb->addItem(QET::Icons::EndLineSimple, tr("Flèche simple", "type of the 1st end of a line"), Qet::Simple ); QET::Icons::EndLineNone,
ui->m_end2_cb->addItem(QET::Icons::EndLineTriangle, tr("Flèche triangulaire", "type of the 1st end of a line"), Qet::Triangle); tr("Normale",
ui->m_end2_cb->addItem(QET::Icons::EndLineCircle, tr("Cercle", "type of the 1st end of a line"), Qet::Circle ); "type of the 1st end of a line"),
ui->m_end2_cb->addItem(QET::Icons::EndLineDiamond, tr("Carré", "type of the 1st end of a line"), Qet::Diamond ); Qet::None );
ui->m_end2_cb->addItem(
QET::Icons::EndLineSimple,
tr("Flèche simple",
"type of the 1st end of a line"),
Qet::Simple );
ui->m_end2_cb->addItem(
QET::Icons::EndLineTriangle,
tr("Flèche triangulaire",
"type of the 1st end of a line"),
Qet::Triangle);
ui->m_end2_cb->addItem(
QET::Icons::EndLineCircle,
tr("Cercle",
"type of the 1st end of a line"),
Qet::Circle );
ui->m_end2_cb->addItem(
QET::Icons::EndLineDiamond,
tr("Carré",
"type of the 1st end of a line"),
Qet::Diamond );
m_style = new StyleEditor(editor); m_style = new StyleEditor(editor);
ui->m_main_layout->insertWidget(0, m_style); ui->m_main_layout->insertWidget(0, m_style);
@ -56,18 +96,19 @@ LineEditor::LineEditor(QETElementEditor *editor, PartLine *part, QWidget *parent
} }
/** /**
* @brief LineEditor::~LineEditor @brief LineEditor::~LineEditor
*/ */
LineEditor::~LineEditor() { LineEditor::~LineEditor()
delete ui; {
delete ui;
} }
/** /**
* @brief LineEditor::setPart @brief LineEditor::setPart
* Reimplemented from @ElementItemEditor Reimplemented from ElementItemEditor
* @param part : part line to edit @param part : part line to edit
* @return : true if the given part can be edited @return : true if the given part can be edited
*/ */
bool LineEditor::setPart(CustomElementPart *part) bool LineEditor::setPart(CustomElementPart *part)
{ {
if (m_part == part) { if (m_part == part) {
@ -100,7 +141,7 @@ bool LineEditor::setPart(CustomElementPart *part)
/** /**
* @brief LineEditor::setParts * @brief LineEditor::setParts
* Reimplemented from @ElementItemEditor * Reimplemented from ElementItemEditor
* @param parts : parts to edit * @param parts : parts to edit
* @return true if the parts can be edited * @return true if the parts can be edited
*/ */
@ -134,9 +175,9 @@ QList<CustomElementPart *> LineEditor::currentParts() const {
} }
/** /**
* @brief LineEditor::updateForm @brief LineEditor::updateForm
* Reimplemented from @ElementItemEditor Reimplemented from ElementItemEditor
*/ */
void LineEditor::updateForm() void LineEditor::updateForm()
{ {
if (!m_part) { if (!m_part) {

View File

@ -1,19 +1,19 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef LINEEDITOR_H #ifndef LINEEDITOR_H
#define LINEEDITOR_H #define LINEEDITOR_H
@ -29,15 +29,15 @@ class StyleEditor;
/** /**
* @brief The LineEditor class * @brief The LineEditor class
* Provide a widget editor used to edit the properties of a @PartLine * Provide a widget editor used to edit the properties of a PartLine
*/ */
class LineEditor : public ElementItemEditor class LineEditor : public ElementItemEditor
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit LineEditor(QETElementEditor *editor, PartLine *part = nullptr, QWidget *parent = nullptr); explicit LineEditor(QETElementEditor *editor, PartLine *part = nullptr, QWidget *parent = nullptr);
~LineEditor() override; ~LineEditor() override;
bool setPart(CustomElementPart *part) override; bool setPart(CustomElementPart *part) override;
bool setParts(QList <CustomElementPart *> parts) override; bool setParts(QList <CustomElementPart *> parts) override;
@ -58,7 +58,7 @@ class LineEditor : public ElementItemEditor
private: private:
PartLine *m_part = nullptr; PartLine *m_part = nullptr;
Ui::LineEditor *ui; Ui::LineEditor *ui;
StyleEditor *m_style = nullptr; StyleEditor *m_style = nullptr;
QList <QMetaObject::Connection> m_change_connections; QList <QMetaObject::Connection> m_change_connections;
bool m_locked = false; bool m_locked = false;

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -51,9 +51,14 @@ ElementsCollectionCache::ElementsCollectionCache(const QString &database_path, Q
cache_db_.exec("PRAGMA locking_mode = EXCLUSIVE"); cache_db_.exec("PRAGMA locking_mode = EXCLUSIVE");
cache_db_.exec("PRAGMA synchronous = OFF"); cache_db_.exec("PRAGMA synchronous = OFF");
#if TODO_LIST
#pragma message("@TODO This code remove old table with mtime for create table with uuid, created at version 0,5")
#endif
//TODO This code remove old table with mtime for create table with uuid, created at version 0,5 //TODO This code remove old table with mtime for create table with uuid, created at version 0,5
//see to remove this code at version 0,6 or 0,7 when all users will table with uuid. //see to remove this code at version 0,6 or 0,7 when all users will table with uuid.
#if TODO_LIST
#pragma message("@TODO remove this code for qet 0.6 or later") #pragma message("@TODO remove this code for qet 0.6 or later")
#endif
QSqlQuery table_name(cache_db_); QSqlQuery table_name(cache_db_);
if (table_name.exec("PRAGMA table_info(names)")) if (table_name.exec("PRAGMA table_info(names)"))
{ {
@ -71,7 +76,9 @@ ElementsCollectionCache::ElementsCollectionCache(const QString &database_path, Q
else else
table_name.finish(); table_name.finish();
} }
#if TODO_LIST
#pragma message("@TODO the tables could already exist, handle that case.")
#endif
//@TODO the tables could already exist, handle that case. //@TODO the tables could already exist, handle that case.
cache_db_.exec("CREATE TABLE names" cache_db_.exec("CREATE TABLE names"
"(" "("

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -37,7 +37,7 @@ ElementsMover::ElementsMover() :
m_movement_driver(nullptr), m_movement_driver(nullptr),
m_moved_content() m_moved_content()
{ {
} }
/** /**
@ -68,17 +68,17 @@ int ElementsMover::beginMovement(Diagram *diagram, QGraphicsItem *driver_item)
{ {
// They must be no movement in progress // They must be no movement in progress
if (movement_running_) return(-1); if (movement_running_) return(-1);
// Be sure we have diagram to work // Be sure we have diagram to work
if (!diagram) return(-1); if (!diagram) return(-1);
diagram_ = diagram; diagram_ = diagram;
// Take count of driver item // Take count of driver item
m_movement_driver = driver_item; m_movement_driver = driver_item;
// At the beginning of movement, move is NULL // At the beginning of movement, move is NULL
current_movement_ = QPointF(0.0, 0.0); current_movement_ = QPointF(0.0, 0.0);
m_moved_content = DiagramContent(diagram); m_moved_content = DiagramContent(diagram);
m_moved_content.removeNonMovableItems(); m_moved_content.removeNonMovableItems();
@ -98,11 +98,11 @@ int ElementsMover::beginMovement(Diagram *diagram, QGraphicsItem *driver_item)
} }
if (!m_moved_content.count()) return(-1); if (!m_moved_content.count()) return(-1);
/* At this point, we've got all info to manage movement. /* At this point, we've got all info to manage movement.
* There is now a move in progress */ * There is now a move in progress */
movement_running_ = true; movement_running_ = true;
return(m_moved_content.count()); return(m_moved_content.count());
} }
@ -125,10 +125,13 @@ void ElementsMover::continueMovement(const QPointF &movement)
continue; continue;
qgi -> setPos(qgi->pos() + movement); qgi -> setPos(qgi->pos() + movement);
} }
// Move some conductors // Move some conductors
for (Conductor *c : m_moved_content.m_conductors_to_update) for (Conductor *c : m_moved_content.m_conductors_to_update)
{ {
#if TODO_LIST
#pragma message("@TODO fix this problem correctly, probably we must to see conductor class.")
#endif
//Due to a weird behavior, we must to ensure that the position of the conductor is to (0,0). //Due to a weird behavior, we must to ensure that the position of the conductor is to (0,0).
//If not, in some unknown case the function QGraphicsScene::itemsBoundingRect() return a rectangle //If not, in some unknown case the function QGraphicsScene::itemsBoundingRect() return a rectangle
//that take in acount the pos() of the conductor, even if the bounding rect returned by the conductor is not in the pos(). //that take in acount the pos() of the conductor, even if the bounding rect returned by the conductor is not in the pos().
@ -218,7 +221,7 @@ void ElementsMover::endMovement()
diagram_ -> undoStack().push(undo_object); diagram_ -> undoStack().push(undo_object);
else else
delete undo_object; delete undo_object;
// There is no movement in progress now // There is no movement in progress now
movement_running_ = false; movement_running_ = false;
m_moved_content.clear(); m_moved_content.clear();

View File

@ -566,7 +566,9 @@ void ElementPictureFactory::setPainterStyle(const QDomElement &dom, QPainter &pa
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
const QStringList styles = dom.attribute("style").split(";", QString::SkipEmptyParts); const QStringList styles = dom.attribute("style").split(";", QString::SkipEmptyParts);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
const QStringList styles = dom.attribute("style").split(";", Qt::SkipEmptyParts); const QStringList styles = dom.attribute("style").split(";", Qt::SkipEmptyParts);
#endif #endif
QRegularExpression rx("^(?<name>[a-z-]+):(?<value>[a-z-]+)$"); QRegularExpression rx("^(?<name>[a-z-]+):(?<value>[a-z-]+)$");

View File

@ -176,8 +176,9 @@ bool QET::orthogonalProjection(const QPointF &point,
// determine le point d'intersection des deux droites = le projete orthogonal // determine le point d'intersection des deux droites = le projete orthogonal
QPointF intersection_point; QPointF intersection_point;
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #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) #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
intersect // ### Qt 6: remove intersect // ### Qt 6: remove
@ -416,7 +417,11 @@ QList<QChar> QET::forbiddenCharacters()
@param name Chaine de caractere a transformer en nom de fichier potable @param name Chaine de caractere a transformer en nom de fichier potable
@todo virer les caracteres accentues ? @todo virer les caracteres accentues ?
*/ */
QString QET::stringToFileName(const QString &name) { 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 // remplace les caracteres interdits par des tirets
@ -474,8 +479,9 @@ QString QET::joinWithSpaces(const QStringList &string_list) {
QStringList QET::splitWithSpaces(const QString &string) { QStringList QET::splitWithSpaces(const QString &string) {
// les chaines sont separees par des espaces non echappes // les chaines sont separees par des espaces non echappes
// = avec un nombre nul ou pair de backslashes devant // = avec un nombre nul ou pair de backslashes devant
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
QStringList escaped_strings = string.split(QRegularExpression("[^\\]?(?:\\\\)* "), QStringList escaped_strings = string.split(QRegularExpression("[^\\]?(?:\\\\)* "),
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
QString QString

View File

@ -1494,7 +1494,9 @@ void QETApp::useSystemPalette(bool use) {
*/ */
void QETApp::quitQET() void QETApp::quitQET()
{ {
#if TODO_LIST
#pragma message("@TODO Segmentation fault when closing program before loading elements is finished") #pragma message("@TODO Segmentation fault when closing program before loading elements is finished")
#endif
if (closeEveryEditor()) { if (closeEveryEditor()) {
qApp->quit(); qApp->quit();
} }

View File

@ -1999,6 +1999,9 @@ void QETDiagramEditor::activateDiagram(Diagram *diagram)
project_view -> showDiagram(diagram); project_view -> showDiagram(diagram);
} }
} else { } else {
#if TODO_LIST
#pragma message("@TODO gerer ce cas")
#endif
/// @todo gerer ce cas /// @todo gerer ce cas
} }
} }

View File

@ -448,7 +448,9 @@ void GraphicsTablePropertiesEditor::setUpEditConnection()
m_edit_connection << connect(m_table_button_group, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &GraphicsTablePropertiesEditor::apply); m_edit_connection << connect(m_table_button_group, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &GraphicsTablePropertiesEditor::apply);
m_edit_connection << connect(m_header_button_group, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &GraphicsTablePropertiesEditor::apply); m_edit_connection << connect(m_header_button_group, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &GraphicsTablePropertiesEditor::apply);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.15 or later") #pragma message("@TODO remove code for QT 5.15 or later")
#endif
m_edit_connection << connect(m_table_button_group, QOverload<int>::of(&QButtonGroup::idClicked), this, &GraphicsTablePropertiesEditor::apply); m_edit_connection << connect(m_table_button_group, QOverload<int>::of(&QButtonGroup::idClicked), this, &GraphicsTablePropertiesEditor::apply);
m_edit_connection << connect(m_header_button_group, QOverload<int>::of(&QButtonGroup::idClicked), this, &GraphicsTablePropertiesEditor::apply); m_edit_connection << connect(m_header_button_group, QOverload<int>::of(&QButtonGroup::idClicked), this, &GraphicsTablePropertiesEditor::apply);
#endif #endif

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -94,7 +94,7 @@ Conductor::Conductor(Terminal *p1, Terminal* p2) :
bool ajout_p2 = terminal2 -> 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 become false if the conductor can't be added to terminal (conductor already exist)
m_valid = (!ajout_p1 || !ajout_p2) ? false : true; m_valid = (!ajout_p1 || !ajout_p2) ? false : true;
//Default attribut for paint a conductor //Default attribut for paint a conductor
if (!pen_and_brush_initialized) if (!pen_and_brush_initialized)
{ {
@ -107,7 +107,7 @@ Conductor::Conductor(Terminal *p1, Terminal* p2) :
conductor_brush.setStyle(Qt::NoBrush); conductor_brush.setStyle(Qt::NoBrush);
pen_and_brush_initialized = true; pen_and_brush_initialized = true;
} }
//By default, the 4 profils are nuls -> we must to use priv_calculeConductor //By default, the 4 profils are nuls -> we must to use priv_calculeConductor
conductor_profiles.insert(Qt::TopLeftCorner, ConductorProfile()); conductor_profiles.insert(Qt::TopLeftCorner, ConductorProfile());
conductor_profiles.insert(Qt::TopRightCorner, ConductorProfile()); conductor_profiles.insert(Qt::TopRightCorner, ConductorProfile());
@ -118,7 +118,7 @@ Conductor::Conductor(Terminal *p1, Terminal* p2) :
generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation()); generateConductorPath(terminal1 -> dockConductor(), terminal1 -> orientation(), terminal2 -> dockConductor(), terminal2 -> orientation());
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsScenePositionChanges); setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsScenePositionChanges);
setAcceptHoverEvents(true); setAcceptHoverEvents(true);
// Add the text field // Add the text field
m_text_item = new ConductorTextItem(m_properties.text, this); m_text_item = new ConductorTextItem(m_properties.text, this);
connect(m_text_item, &ConductorTextItem::textEdited, this, &Conductor::displayedTextChanged); connect(m_text_item, &ConductorTextItem::textEdited, this, &Conductor::displayedTextChanged);
@ -178,10 +178,10 @@ void Conductor::updatePath(const QRectF &rect) {
void Conductor::segmentsToPath() void Conductor::segmentsToPath()
{ {
QPainterPath path; QPainterPath path;
if (segments == nullptr) if (segments == nullptr)
setPath(path); setPath(path);
//Start the path //Start the path
path.moveTo(segments -> firstPoint()); path.moveTo(segments -> firstPoint());
//Each segments //Each segments
@ -192,9 +192,9 @@ void Conductor::segmentsToPath()
} }
//Finish the path //Finish the path
path.lineTo(segment -> secondPoint()); path.lineTo(segment -> secondPoint());
setPath(path); setPath(path);
//If conductor is selected and he's not being modified //If conductor is selected and he's not being modified
//we update the position of the handlers //we update the position of the handlers
if (isSelected() && !m_moving_segment) if (isSelected() && !m_moving_segment)
@ -219,34 +219,34 @@ void Conductor::segmentsToPath()
void Conductor::updateConductorPath(const QPointF &p1, Qet::Orientation o1, const QPointF &p2, Qet::Orientation o2) { void Conductor::updateConductorPath(const QPointF &p1, Qet::Orientation o1, const QPointF &p2, Qet::Orientation o2) {
Q_UNUSED(o1); Q_UNUSED(o1);
Q_UNUSED(o2); 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.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.isNull(), "Conductor::priv_modifieConductor", "pas de profil utilisable");
// recupere les coordonnees fournies des bornes // recupere les coordonnees fournies des bornes
QPointF new_p1 = mapFromScene(p1); QPointF new_p1 = mapFromScene(p1);
QPointF new_p2 = mapFromScene(p2); QPointF new_p2 = mapFromScene(p2);
QRectF new_rect = QRectF(new_p1, new_p2); QRectF new_rect = QRectF(new_p1, new_p2);
// recupere la largeur et la hauteur du profil // recupere la largeur et la hauteur du profil
qreal profile_width = conductor_profile.width(); qreal profile_width = conductor_profile.width();
qreal profile_height = conductor_profile.height(); qreal profile_height = conductor_profile.height();
// calcule les differences verticales et horizontales a appliquer // calcule les differences verticales et horizontales a appliquer
qreal h_diff = (qAbs(new_rect.width()) - qAbs(profile_width) ) * getSign(profile_width); 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); qreal v_diff = (qAbs(new_rect.height()) - qAbs(profile_height)) * getSign(profile_height);
// applique les differences aux segments // applique les differences aux segments
QMultiHash<ConductorSegmentProfile *, qreal> segments_lengths; QMultiHash<ConductorSegmentProfile *, qreal> segments_lengths;
segments_lengths.unite(shareOffsetBetweenSegments(h_diff, conductor_profile.horizontalSegments())); segments_lengths.unite(shareOffsetBetweenSegments(h_diff, conductor_profile.horizontalSegments()));
segments_lengths.unite(shareOffsetBetweenSegments(v_diff, conductor_profile.verticalSegments())); 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) // 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 horiz_coeff = getCoeff(new_rect.width(), profile_width);
int verti_coeff = getCoeff(new_rect.height(), profile_height); int verti_coeff = getCoeff(new_rect.height(), profile_height);
// genere les nouveaux points // genere les nouveaux points
QList<QPointF> points; QList<QPointF> points;
points << new_p1; points << new_p1;
@ -254,14 +254,14 @@ void Conductor::updateConductorPath(const QPointF &p1, Qet::Orientation o1, cons
for (int i = 0 ; i < limit ; ++ i) { for (int i = 0 ; i < limit ; ++ i) {
// dernier point // dernier point
QPointF previous_point = points.last(); QPointF previous_point = points.last();
// profil de segment de conducteur en cours // profil de segment de conducteur en cours
ConductorSegmentProfile *csp = conductor_profile.segments.at(i); ConductorSegmentProfile *csp = conductor_profile.segments.at(i);
// coefficient et offset a utiliser pour ce point // coefficient et offset a utiliser pour ce point
qreal coeff = csp -> isHorizontal ? horiz_coeff : verti_coeff; qreal coeff = csp -> isHorizontal ? horiz_coeff : verti_coeff;
qreal offset_applied = segments_lengths.value(csp); qreal offset_applied = segments_lengths.value(csp);
// applique l'offset et le coeff au point // applique l'offset et le coeff au point
if (csp -> isHorizontal) { if (csp -> isHorizontal) {
points << QPointF ( points << QPointF (
@ -296,15 +296,15 @@ QHash<ConductorSegmentProfile *, qreal> Conductor::shareOffsetBetweenSegments(
foreach(ConductorSegmentProfile *csp, segments_list) { foreach(ConductorSegmentProfile *csp, segments_list) {
segments_hash.insert(csp, csp -> length); segments_hash.insert(csp, csp -> length);
} }
// memorise le signe de la longueur de chaque segement // memorise le signe de la longueur de chaque segement
QHash<ConductorSegmentProfile *, int> segments_signs; QHash<ConductorSegmentProfile *, int> segments_signs;
foreach(ConductorSegmentProfile *csp, segments_hash.keys()) { foreach(ConductorSegmentProfile *csp, segments_hash.keys()) {
segments_signs.insert(csp, getSign(csp -> length)); 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 // repartit l'offset sur les segments
qreal remaining_offset = offset; qreal remaining_offset = offset;
while (remaining_offset > precision || remaining_offset < -precision) { while (remaining_offset > precision || remaining_offset < -precision) {
@ -321,10 +321,10 @@ QHash<ConductorSegmentProfile *, qreal> Conductor::shareOffsetBetweenSegments(
// applique l'offset au segment // applique l'offset au segment
//qreal segment_old_length = segments_hash[csp]; //qreal segment_old_length = segments_hash[csp];
segments_hash[csp] += local_offset; segments_hash[csp] += local_offset;
// (la longueur du segment change de signe) <=> (le segment n'a pu absorbe tout l'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])) { if (segments_signs[csp] != getSign(segments_hash[csp])) {
// on remet le trop-plein dans la reserve d'offset // on remet le trop-plein dans la reserve d'offset
remaining_offset += qAbs(segments_hash[csp]) * getSign(local_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; //qDebug() << " trop-plein de" << qAbs(segments_hash[csp]) * getSign(local_offset) << "remaining_offset =" << remaining_offset;
@ -334,7 +334,7 @@ QHash<ConductorSegmentProfile *, qreal> Conductor::shareOffsetBetweenSegments(
} }
} }
} }
return(segments_hash); return(segments_hash);
} }
@ -348,18 +348,18 @@ QHash<ConductorSegmentProfile *, qreal> Conductor::shareOffsetBetweenSegments(
void Conductor::generateConductorPath(const QPointF &p1, Qet::Orientation o1, const QPointF &p2, Qet::Orientation o2) { void Conductor::generateConductorPath(const QPointF &p1, Qet::Orientation o1, const QPointF &p2, Qet::Orientation o2) {
QPointF sp1, sp2, depart, newp1, newp2, arrivee, depart0, arrivee0; QPointF sp1, sp2, depart, newp1, newp2, arrivee, depart0, arrivee0;
Qet::Orientation ori_depart, ori_arrivee; Qet::Orientation ori_depart, ori_arrivee;
// s'assure qu'il n'y a ni points // s'assure qu'il n'y a ni points
QList<QPointF> points; QList<QPointF> points;
// mappe les points par rapport a la scene // mappe les points par rapport a la scene
sp1 = mapFromScene(p1); sp1 = mapFromScene(p1);
sp2 = mapFromScene(p2); sp2 = mapFromScene(p2);
// prolonge les bornes // prolonge les bornes
newp1 = extendTerminal(sp1, o1); newp1 = extendTerminal(sp1, o1);
newp2 = extendTerminal(sp2, o2); newp2 = extendTerminal(sp2, o2);
// distingue le depart de l'arrivee : le trajet se fait toujours de gauche a droite (apres prolongation) // distingue le depart de l'arrivee : le trajet se fait toujours de gauche a droite (apres prolongation)
if (newp1.x() <= newp2.x()) { if (newp1.x() <= newp2.x()) {
depart = newp1; depart = newp1;
@ -376,13 +376,13 @@ void Conductor::generateConductorPath(const QPointF &p1, Qet::Orientation o1, co
ori_depart = o2; ori_depart = o2;
ori_arrivee = o1; ori_arrivee = o1;
} }
// debut du trajet // debut du trajet
points << depart0; points << depart0;
// prolongement de la borne de depart // prolongement de la borne de depart
points << depart; points << depart;
// commence le vrai trajet // commence le vrai trajet
if (depart.y() < arrivee.y()) { if (depart.y() < arrivee.y()) {
// trajet descendant // trajet descendant
@ -423,20 +423,20 @@ void Conductor::generateConductorPath(const QPointF &p1, Qet::Orientation o1, co
points << QPointF(arrivee.x(), depart.y()); // cas "1" points << QPointF(arrivee.x(), depart.y()); // cas "1"
} }
} }
// fin du vrai trajet // fin du vrai trajet
points << arrivee; points << arrivee;
// prolongement de la borne d'arrivee // prolongement de la borne d'arrivee
points << arrivee0; points << arrivee0;
// inverse eventuellement l'ordre des points afin que le trajet soit exprime de la borne 1 vers la borne 2 // 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()) { if (newp1.x() > newp2.x()) {
QList<QPointF> points2; QList<QPointF> points2;
for (int i = points.size() - 1 ; i >= 0 ; -- i) points2 << points.at(i); for (int i = points.size() - 1 ; i >= 0 ; -- i) points2 << points.at(i);
points = points2; points = points2;
} }
pointsToSegments(points); pointsToSegments(points);
segmentsToPath(); segmentsToPath();
} }
@ -472,14 +472,14 @@ QPointF Conductor::extendTerminal(const QPointF &terminal, Qet::Orientation term
Dessine le conducteur sans antialiasing. Dessine le conducteur sans antialiasing.
@param qp Le QPainter a utiliser pour dessiner le conducteur @param qp Le QPainter a utiliser pour dessiner le conducteur
@param options Les options de style pour le conducteur @param options Les options de style pour le conducteur
@param qw Le QWidget sur lequel on dessine @param qw Le QWidget sur lequel on dessine
*/ */
void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWidget *qw) void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWidget *qw)
{ {
Q_UNUSED(qw); Q_UNUSED(qw);
qp -> save(); qp -> save();
qp -> setRenderHint(QPainter::Antialiasing, false); qp -> setRenderHint(QPainter::Antialiasing, false);
// Set the color of conductor // Set the color of conductor
QColor final_conductor_color(m_properties.color); QColor final_conductor_color(m_properties.color);
if (must_highlight_ == Normal) { if (must_highlight_ == Normal) {
@ -495,26 +495,26 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
} }
} }
} }
//Draw the conductor bigger when is hovered //Draw the conductor bigger when is hovered
conductor_pen.setWidthF(m_mouse_over? (m_properties.cond_size) +4 : (m_properties.cond_size)); conductor_pen.setWidthF(m_mouse_over? (m_properties.cond_size) +4 : (m_properties.cond_size));
//Set the QPen and QBrush to the QPainter //Set the QPen and QBrush to the QPainter
qp -> setBrush(conductor_brush); qp -> setBrush(conductor_brush);
QPen final_conductor_pen = conductor_pen; QPen final_conductor_pen = conductor_pen;
//Set the conductor style //Set the conductor style
final_conductor_pen.setColor(final_conductor_color); final_conductor_pen.setColor(final_conductor_color);
final_conductor_pen.setStyle(m_properties.style); final_conductor_pen.setStyle(m_properties.style);
final_conductor_pen.setJoinStyle(Qt::SvgMiterJoin); // better rendering with dot final_conductor_pen.setJoinStyle(Qt::SvgMiterJoin); // better rendering with dot
//Use a cosmetique line, below a certain zoom //Use a cosmetique line, below a certain zoom
if (options && options -> levelOfDetail < 1.0) { if (options && options -> levelOfDetail < 1.0) {
final_conductor_pen.setCosmetic(true); final_conductor_pen.setCosmetic(true);
} }
qp -> setPen(final_conductor_pen); qp -> setPen(final_conductor_pen);
//Draw the conductor //Draw the conductor
qp -> drawPath(path()); qp -> drawPath(path());
//Draw the second color //Draw the second color
@ -530,7 +530,7 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
qp->drawPath(path()); qp->drawPath(path());
qp->restore(); qp->restore();
} }
if (m_properties.type == ConductorProperties::Single) { if (m_properties.type == ConductorProperties::Single) {
qp -> setBrush(final_conductor_color); qp -> setBrush(final_conductor_color);
m_properties.singleLineProperties.draw( m_properties.singleLineProperties.draw(
@ -540,7 +540,7 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
); );
if (isSelected()) qp -> setBrush(Qt::NoBrush); if (isSelected()) qp -> setBrush(Qt::NoBrush);
} }
//Draw the junctions //Draw the junctions
QList<QPointF> junctions_list = junctions(); QList<QPointF> junctions_list = junctions();
if (!junctions_list.isEmpty()) { if (!junctions_list.isEmpty()) {
@ -579,11 +579,11 @@ ConductorTextItem *Conductor::textItem() const
bool Conductor::valideXml(QDomElement &e){ bool Conductor::valideXml(QDomElement &e){
// verifie le nom du tag // verifie le nom du tag
if (e.tagName() != "conductor") return(false); if (e.tagName() != "conductor") return(false);
// verifie la presence des attributs minimaux // verifie la presence des attributs minimaux
if (!e.hasAttribute("terminal1")) return(false); if (!e.hasAttribute("terminal1")) return(false);
if (!e.hasAttribute("terminal2")) return(false); if (!e.hasAttribute("terminal2")) return(false);
bool conv_ok; bool conv_ok;
// parse l'abscisse // parse l'abscisse
if (e.hasAttribute("element1")) { if (e.hasAttribute("element1")) {
@ -595,7 +595,7 @@ bool Conductor::valideXml(QDomElement &e){
e.attribute("terminal1").toInt(&conv_ok); e.attribute("terminal1").toInt(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
} }
// parse l'ordonnee // parse l'ordonnee
if (e.hasAttribute("element2")) { if (e.hasAttribute("element2")) {
if (QUuid(e.attribute("element2")).isNull()) if (QUuid(e.attribute("element2")).isNull())
@ -627,7 +627,7 @@ void Conductor::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
void Conductor::mousePressEvent(QGraphicsSceneMouseEvent *event) void Conductor::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
QGraphicsObject::mousePressEvent(event); QGraphicsObject::mousePressEvent(event);
if (event->modifiers() & Qt::ControlModifier) if (event->modifiers() & Qt::ControlModifier)
setSelected(!isSelected()); setSelected(!isSelected());
} }
@ -668,7 +668,7 @@ void Conductor::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
@brief Conductor::itemChange @brief Conductor::itemChange
@param change @param change
@param value @param value
@return @return
*/ */
QVariant Conductor::itemChange(GraphicsItemChange change, const QVariant &value) QVariant Conductor::itemChange(GraphicsItemChange change, const QVariant &value)
{ {
@ -689,7 +689,7 @@ QVariant Conductor::itemChange(GraphicsItemChange change, const QVariant &value)
else if (change == QGraphicsItem::ItemSceneHasChanged) else if (change == QGraphicsItem::ItemSceneHasChanged)
{ {
calculateTextItemPosition(); calculateTextItemPosition();
if(!scene()) if(!scene())
removeHandler(); removeHandler();
else if (scene() && isSelected()) else if (scene() && isSelected())
@ -701,7 +701,7 @@ QVariant Conductor::itemChange(GraphicsItemChange change, const QVariant &value)
else if (change == QGraphicsItem::ItemPositionHasChanged && isSelected()) { else if (change == QGraphicsItem::ItemPositionHasChanged && isSelected()) {
adjusteHandlerPos(); adjusteHandlerPos();
} }
return(QGraphicsObject::itemChange(change, value)); return(QGraphicsObject::itemChange(change, value));
} }
@ -709,7 +709,7 @@ QVariant Conductor::itemChange(GraphicsItemChange change, const QVariant &value)
@brief Conductor::sceneEventFilter @brief Conductor::sceneEventFilter
@param watched @param watched
@param event @param event
@return @return
*/ */
bool Conductor::sceneEventFilter(QGraphicsItem *watched, QEvent *event) bool Conductor::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{ {
@ -717,7 +717,7 @@ bool Conductor::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@ -746,7 +746,7 @@ bool Conductor::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@ -758,7 +758,7 @@ void Conductor::adjusteHandlerPos()
{ {
if (m_handler_vector.isEmpty()) if (m_handler_vector.isEmpty())
return; return;
if (m_handler_vector.size() == handlerPoints().size()) if (m_handler_vector.size() == handlerPoints().size())
{ {
QVector <QPointF> points_vector = mapToScene(handlerPoints()); QVector <QPointF> points_vector = mapToScene(handlerPoints());
@ -775,7 +775,7 @@ void Conductor::adjusteHandlerPos()
void Conductor::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) void Conductor::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
//we get the segment corresponding to the handler //we get the segment corresponding to the handler
if (m_vector_index > -1) if (m_vector_index > -1)
{ {
@ -783,7 +783,7 @@ void Conductor::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSc
m_moving_segment = true; m_moving_segment = true;
m_moved_segment = segmentsList().at(m_vector_index+1); m_moved_segment = segmentsList().at(m_vector_index+1);
before_mov_text_pos_ = m_text_item -> pos(); before_mov_text_pos_ = m_text_item -> pos();
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
if(handler != qghi) if(handler != qghi)
handler->hide(); handler->hide();
@ -801,14 +801,14 @@ void Conductor::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSce
{ {
//Snap the mouse pos to grid //Snap the mouse pos to grid
QPointF pos_ = Diagram::snapToGrid(mapFromScene(event->scenePos())); QPointF pos_ = Diagram::snapToGrid(mapFromScene(event->scenePos()));
//Position of the last point //Position of the last point
QPointF p = m_moved_segment -> middle(); QPointF p = m_moved_segment -> middle();
//Calcul the movement //Calcul the movement
m_moved_segment -> moveX(pos_.x() - p.x()); m_moved_segment -> moveX(pos_.x() - p.x());
m_moved_segment -> moveY(pos_.y() - p.y()); m_moved_segment -> moveY(pos_.y() - p.y());
//Apply the movement //Apply the movement
modified_path = true; modified_path = true;
has_to_save_profile = true; has_to_save_profile = true;
@ -827,9 +827,9 @@ void Conductor::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphics
{ {
Q_UNUSED(event); Q_UNUSED(event);
Q_UNUSED(qghi); Q_UNUSED(qghi);
m_vector_index = -1; m_vector_index = -1;
m_moving_segment = false; m_moving_segment = false;
if (has_to_save_profile) if (has_to_save_profile)
{ {
@ -849,9 +849,9 @@ void Conductor::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphics
void Conductor::addHandler() void Conductor::addHandler()
{ {
if (m_handler_vector.isEmpty() && scene()) if (m_handler_vector.isEmpty() && scene())
{ {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(handlerPoints())); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(handlerPoints()));
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
handler->setColor(Qt::blue); handler->setColor(Qt::blue);
@ -897,7 +897,7 @@ QPainterPath Conductor::shape() const
pps.setJoinStyle(conductor_pen.joinStyle()); pps.setJoinStyle(conductor_pen.joinStyle());
QPainterPath shape_(pps.createStroke(path())); QPainterPath shape_(pps.createStroke(path()));
return shape_; return shape_;
} }
@ -936,23 +936,23 @@ QList<QPointF> Conductor::segmentsToPoints() const
{ {
// liste qui sera retournee // liste qui sera retournee
QList<QPointF> points_list; QList<QPointF> points_list;
// on retourne la liste tout de suite s'il n'y a pas de segments // on retourne la liste tout de suite s'il n'y a pas de segments
if (segments == nullptr) return(points_list); if (segments == nullptr) return(points_list);
// recupere le premier point // recupere le premier point
points_list << segments -> firstPoint(); points_list << segments -> firstPoint();
// parcourt les segments pour recuperer les autres points // parcourt les segments pour recuperer les autres points
ConductorSegment *segment = segments; ConductorSegment *segment = segments;
while(segment -> hasNextSegment()) { while(segment -> hasNextSegment()) {
points_list << segment -> secondPoint(); points_list << segment -> secondPoint();
segment = segment -> nextSegment(); segment = segment -> nextSegment();
} }
// recupere le dernier point // recupere le dernier point
points_list << segment -> secondPoint(); points_list << segment -> secondPoint();
//retourne la liste //retourne la liste
return(points_list); return(points_list);
} }
@ -964,7 +964,7 @@ QList<QPointF> Conductor::segmentsToPoints() const
void Conductor::pointsToSegments(const QList<QPointF>& points_list) { void Conductor::pointsToSegments(const QList<QPointF>& points_list) {
// supprime les segments actuels // supprime les segments actuels
deleteSegments(); deleteSegments();
// cree les segments a partir de la liste de points // cree les segments a partir de la liste de points
ConductorSegment *last_segment = nullptr; ConductorSegment *last_segment = nullptr;
for (int i = 0 ; i < points_list.size() - 1 ; ++ i) { for (int i = 0 ; i < points_list.size() - 1 ; ++ i) {
@ -1039,7 +1039,7 @@ QDomElement Conductor::toXml(QDomDocument &dom_document,
dom_element.setAttribute("terminal2", terminal2->uuid().toString()); dom_element.setAttribute("terminal2", terminal2->uuid().toString());
} }
dom_element.setAttribute("freezeLabel", m_freeze_label? "true" : "false"); dom_element.setAttribute("freezeLabel", m_freeze_label? "true" : "false");
// on n'exporte les segments du conducteur que si ceux-ci ont // on n'exporte les segments du conducteur que si ceux-ci ont
// ete modifies par l'utilisateur // ete modifies par l'utilisateur
if (modified_path) if (modified_path)
@ -1057,7 +1057,7 @@ QDomElement Conductor::toXml(QDomDocument &dom_document,
QDomElement dom_seq = m_autoNum_seq.toXml(dom_document); QDomElement dom_seq = m_autoNum_seq.toXml(dom_document);
dom_element.appendChild(dom_seq); dom_element.appendChild(dom_seq);
// Export the properties and text // Export the properties and text
m_properties. toXml(dom_element); m_properties. toXml(dom_element);
if(m_text_item->wasMovedByUser()) if(m_text_item->wasMovedByUser())
@ -1177,10 +1177,10 @@ QVector<QPointF> Conductor::handlerPoints() const
const QList<ConductorSegment *> Conductor::segmentsList() const const QList<ConductorSegment *> Conductor::segmentsList() const
{ {
if (segments == nullptr) return(QList<ConductorSegment *>()); if (segments == nullptr) return(QList<ConductorSegment *>());
QList<ConductorSegment *> segments_vector; QList<ConductorSegment *> segments_vector;
ConductorSegment *segment = segments; ConductorSegment *segment = segments;
while (segment -> hasNextSegment()) { while (segment -> hasNextSegment()) {
segments_vector << segment; segments_vector << segment;
segment = segment -> nextSegment(); segment = segment -> nextSegment();
@ -1203,12 +1203,12 @@ qreal Conductor::length() const{
ConductorSegment *Conductor::middleSegment() 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; ConductorSegment *s = segments;
qreal l = 0; qreal l = 0;
while (s -> hasNextSegment()) { while (s -> hasNextSegment()) {
l += qAbs(s -> length()); l += qAbs(s -> length());
if (l >= half_length) break; if (l >= half_length) break;
@ -1344,7 +1344,7 @@ void Conductor::calculateTextItemPosition()
rotation == Qt::Vertical ? m_text_item -> setRotation(m_properties.verti_rotate_text): rotation == Qt::Vertical ? m_text_item -> setRotation(m_properties.verti_rotate_text):
m_text_item -> setRotation(m_properties.horiz_rotate_text); m_text_item -> setRotation(m_properties.horiz_rotate_text);
} }
//Adjust the position of text if his rotation //Adjust the position of text if his rotation
//is 0° or 270°, to be exactly centered to the conductor //is 0° or 270°, to be exactly centered to the conductor
if (m_text_item -> rotation() == 0) if (m_text_item -> rotation() == 0)
@ -1359,9 +1359,9 @@ void Conductor::calculateTextItemPosition()
if(m_properties.m_vertical_alignment == Qt::AlignLeft) if(m_properties.m_vertical_alignment == Qt::AlignLeft)
text_pos.rx() -= m_text_item->boundingRect().height(); 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 //Ensure text item don't collide with this conductor
while (m_text_item->collidesWithItem(this)) while (m_text_item->collidesWithItem(this))
{ {
@ -1491,7 +1491,7 @@ void Conductor::setPath(const QPainterPath &path)
{ {
if(path == m_path) if(path == m_path)
return; return;
prepareGeometryChange(); prepareGeometryChange();
m_path = path; m_path = path;
update(); update();
@ -1694,7 +1694,9 @@ QSet<Conductor *> Conductor::relatedPotentialConductors(const bool all_diagram,
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
other_conductors += other_conductors_list_t.toSet(); other_conductors += other_conductors_list_t.toSet();
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
other_conductors += QSet<Conductor*>(other_conductors_list_t.begin(),other_conductors_list_t.end()); other_conductors += QSet<Conductor*>(other_conductors_list_t.begin(),other_conductors_list_t.end());
#endif #endif
} }
@ -1750,17 +1752,17 @@ void Conductor::setUpConnectionForFormula(QString old_formula, QString new_formu
//we must to replace %F by the real text, to check if the real text contain the variable %id //we must to replace %F by the real text, to check if the real text contain the variable %id
if (old_formula.contains("%F")) if (old_formula.contains("%F"))
old_formula.replace("%F", diagram()->border_and_titleblock.folio()); old_formula.replace("%F", diagram()->border_and_titleblock.folio());
if (old_formula.contains("%id")) if (old_formula.contains("%id"))
disconnect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText); disconnect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText);
//Label is frozen, so we don't update it. //Label is frozen, so we don't update it.
if (m_freeze_label == true) if (m_freeze_label == true)
return; return;
if (new_formula.contains("%F")) if (new_formula.contains("%F"))
new_formula.replace("%F", diagram()->border_and_titleblock.folio()); new_formula.replace("%F", diagram()->border_and_titleblock.folio());
if (new_formula.contains("%id")) if (new_formula.contains("%id"))
connect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText); connect(diagram()->project(), &QETProject::projectDiagramsOrderChanged, this, &Conductor::refreshText);
} }
@ -1785,18 +1787,18 @@ bool isContained(const QPointF &a, const QPointF &b, const QPointF &c) {
QList<QPointF> Conductor::junctions() const QList<QPointF> Conductor::junctions() const
{ {
QList<QPointF> junctions_list; QList<QPointF> junctions_list;
// pour qu'il y ait des jonctions, il doit y avoir d'autres conducteurs et des bifurcations // pour qu'il y ait des jonctions, il doit y avoir d'autres conducteurs et des bifurcations
QList<Conductor *> other_conductors = relatedConductors(this); QList<Conductor *> other_conductors = relatedConductors(this);
QList<ConductorBend> bends_list = bends(); QList<ConductorBend> bends_list = bends();
if (other_conductors.isEmpty() || bends_list.isEmpty()) { if (other_conductors.isEmpty() || bends_list.isEmpty()) {
return(junctions_list); return(junctions_list);
} }
QList<QPointF> points = segmentsToPoints(); QList<QPointF> points = segmentsToPoints();
for (int i = 1 ; i < (points.size() -1) ; ++ i) { for (int i = 1 ; i < (points.size() -1) ; ++ i) {
QPointF point = points.at(i); QPointF point = points.at(i);
// determine si le point est une bifurcation ou non // determine si le point est une bifurcation ou non
bool is_bend = false; bool is_bend = false;
Qt::Corner current_bend_type = Qt::TopLeftCorner; Qt::Corner current_bend_type = Qt::TopLeftCorner;
@ -1811,7 +1813,7 @@ QList<QPointF> Conductor::junctions() const
} }
// si le point n'est pas une bifurcation, il ne peut etre une jonction (enfin pas au niveau de ce conducteur) // 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; if (!is_bend) continue;
bool is_junction = false; bool is_junction = false;
QPointF scene_point = mapToScene(point); QPointF scene_point = mapToScene(point);
foreach(Conductor *c, other_conductors) foreach(Conductor *c, other_conductors)
@ -1857,7 +1859,7 @@ QList<ConductorBend> Conductor::bends() const
{ {
QList<ConductorBend> points; QList<ConductorBend> points;
if (!segments) return(points); if (!segments) return(points);
// recupere la liste des segments de taille non nulle // recupere la liste des segments de taille non nulle
QList<ConductorSegment *> visible_segments; QList<ConductorSegment *> visible_segments;
ConductorSegment *segment = segments; ConductorSegment *segment = segments;
@ -1866,7 +1868,7 @@ QList<ConductorBend> Conductor::bends() const
segment = segment -> nextSegment(); segment = segment -> nextSegment();
} }
if (!segment -> isPoint()) visible_segments << segment; if (!segment -> isPoint()) visible_segments << segment;
ConductorSegment *next_segment; ConductorSegment *next_segment;
for (int i = 0 ; i < visible_segments.count() -1 ; ++ i) { for (int i = 0 ; i < visible_segments.count() -1 ; ++ i) {
segment = visible_segments[i]; segment = visible_segments[i];
@ -1877,7 +1879,7 @@ QList<ConductorBend> Conductor::bends() const
Qt::Corner bend_type; Qt::Corner bend_type;
qreal sl = segment -> length(); qreal sl = segment -> length();
qreal nsl = next_segment -> length(); qreal nsl = next_segment -> length();
if (segment -> isHorizontal()) { if (segment -> isHorizontal()) {
if (sl < 0 && nsl < 0) { if (sl < 0 && nsl < 0) {
bend_type = Qt::BottomLeftCorner; bend_type = Qt::BottomLeftCorner;
@ -1974,14 +1976,14 @@ QPointF Conductor::movePointIntoPolygon(const QPointF &point, const QPainterPath
QList<QPointF> points; QList<QPointF> points;
foreach(QPolygonF polygon, polygons) { foreach(QPolygonF polygon, polygons) {
if (polygon.count() <= 1) continue; if (polygon.count() <= 1) continue;
// on recense les lignes et les points // on recense les lignes et les points
for (int i = 1 ; i < polygon.count() ; ++ i) { for (int i = 1 ; i < polygon.count() ; ++ i) {
lines << QLineF(polygon.at(i - 1), polygon.at(i)); lines << QLineF(polygon.at(i - 1), polygon.at(i));
points << polygon.at(i -1); points << polygon.at(i -1);
} }
} }
// on fait des projetes orthogonaux du point sur les differents segments du // on fait des projetes orthogonaux du point sur les differents segments du
// polygone, en les triant par longueur croissante // polygone, en les triant par longueur croissante
QMap<qreal, QPointF> intersections; QMap<qreal, QPointF> intersections;
@ -2007,7 +2009,7 @@ QPointF Conductor::movePointIntoPolygon(const QPointF &point, const QPainterPath
} }
} }
// on connait desormais le coin le plus proche du texte // 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 // 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)); return(points.at(point_index));
} }

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -105,14 +105,14 @@ Element::Element(
if (state) { if (state) {
*state = 0; *state = 0;
} }
setPrefix(autonum::elementPrefixForLocation(location)); setPrefix(autonum::elementPrefixForLocation(location));
m_uuid = QUuid::createUuid(); m_uuid = QUuid::createUuid();
setZValue(10); setZValue(10);
setFlags(QGraphicsItem::ItemIsMovable setFlags(QGraphicsItem::ItemIsMovable
| QGraphicsItem::ItemIsSelectable); | QGraphicsItem::ItemIsSelectable);
setAcceptHoverEvents(true); setAcceptHoverEvents(true);
connect(this, &Element::rotationChanged, [this]() connect(this, &Element::rotationChanged, [this]()
{ {
for(QGraphicsItem *qgi : childItems()) for(QGraphicsItem *qgi : childItems())
@ -150,11 +150,11 @@ QList<Terminal *> Element::terminals() const
QList<Conductor *> Element::conductors() const QList<Conductor *> Element::conductors() const
{ {
QList<Conductor *> conductors; QList<Conductor *> conductors;
for (Terminal *t : m_terminals) { for (Terminal *t : m_terminals) {
conductors << t -> conductors(); conductors << t -> conductors();
} }
return(conductors); return(conductors);
} }
@ -209,13 +209,13 @@ void Element::paint(
if (m_must_highlight) { if (m_must_highlight) {
drawHighlight(painter, options); drawHighlight(painter, options);
} }
if (options && options -> levelOfDetail < 1.0) { if (options && options -> levelOfDetail < 1.0) {
painter->drawPicture(0, 0, m_low_zoom_picture); painter->drawPicture(0, 0, m_low_zoom_picture);
} else { } else {
painter->drawPicture(0, 0, m_picture); painter->drawPicture(0, 0, m_picture);
} }
//Draw the selection rectangle //Draw the selection rectangle
if ( isSelected() || m_mouse_over ) { if ( isSelected() || m_mouse_over ) {
drawSelection(painter, options); drawSelection(painter, options);
@ -355,7 +355,7 @@ void Element::drawHighlight(
{ {
Q_UNUSED(options); Q_UNUSED(options);
painter -> save(); painter -> save();
qreal gradient_radius = qMin(boundingRect().width(), qreal gradient_radius = qMin(boundingRect().width(),
boundingRect().height()) / 2.0; boundingRect().height()) / 2.0;
QRadialGradient gradient( QRadialGradient gradient(
@ -366,7 +366,7 @@ void Element::drawHighlight(
gradient.setColorAt(0.0, QColor::fromRgb(69, 137, 255, 255)); gradient.setColorAt(0.0, QColor::fromRgb(69, 137, 255, 255));
gradient.setColorAt(1.0, QColor::fromRgb(69, 137, 255, 0)); gradient.setColorAt(1.0, QColor::fromRgb(69, 137, 255, 0));
QBrush brush(gradient); QBrush brush(gradient);
painter -> setPen(Qt::NoPen); painter -> setPen(Qt::NoPen);
painter -> setBrush(brush); painter -> setBrush(brush);
// Le dessin se fait a partir du rectangle delimitant // Le dessin se fait a partir du rectangle delimitant
@ -463,7 +463,7 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
QDomElement elmts = node.toElement(); QDomElement elmts = node.toElement();
if (elmts.isNull()) if (elmts.isNull())
continue; continue;
if (elmts.tagName() == "description") if (elmts.tagName() == "description")
{ {
//Minor workaround to find if there is a "input" tagg as label. //Minor workaround to find if there is a "input" tagg as label.
@ -485,7 +485,7 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
if(!have_label && !input_field.isEmpty()) if(!have_label && !input_field.isEmpty())
input_field.first().setAttribute("tagg", input_field.first().setAttribute("tagg",
"label"); "label");
//Parse the definition //Parse the definition
for (QDomNode n = node.firstChild() ; for (QDomNode n = node.firstChild() ;
!n.isNull() ; !n.isNull() ;
@ -494,7 +494,7 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
QDomElement qde = n.toElement(); QDomElement qde = n.toElement();
if (qde.isNull()) if (qde.isNull())
continue; continue;
if (parseElement(qde)) { if (parseElement(qde)) {
++ parsed_elements_count; ++ parsed_elements_count;
} }
@ -513,7 +513,7 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
epf->getPictures(m_location, epf->getPictures(m_location,
const_cast<QPicture&>(m_picture), const_cast<QPicture&>(m_picture),
const_cast<QPicture&>(m_low_zoom_picture)); const_cast<QPicture&>(m_low_zoom_picture));
if(!m_picture.isNull()) if(!m_picture.isNull())
++ parsed_elements_count; ++ parsed_elements_count;
@ -581,7 +581,7 @@ bool Element::parseInput(const QDomElement &dom_element)
deti->setTextFrom(DynamicElementTextItem::ElementInfo); deti->setTextFrom(DynamicElementTextItem::ElementInfo);
deti->setInfoName(dom_element.attribute("tagg")); 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 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 //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 //We need to use a QTransform to find the pos of this text from the saved pos of text item
@ -618,7 +618,7 @@ DynamicElementTextItem *Element::parseDynamicText(
//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 //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) //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) //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()); QDomElement dom(dom_element.cloneNode(true).toElement());
dom.setTagName(DynamicElementTextItem::xmlTagName()); dom.setTagName(DynamicElementTextItem::xmlTagName());
deti->fromXml(dom); deti->fromXml(dom);
@ -643,7 +643,7 @@ Terminal *Element::parseTerminal(const QDomElement &dom_element)
Terminal *new_terminal = new Terminal(data, this); Terminal *new_terminal = new Terminal(data, this);
m_terminals << new_terminal; m_terminals << new_terminal;
//Sort from top to bottom and left to rigth //Sort from top to bottom and left to rigth
std::sort(m_terminals.begin(), std::sort(m_terminals.begin(),
m_terminals.end(), m_terminals.end(),
@ -655,7 +655,7 @@ Terminal *Element::parseTerminal(const QDomElement &dom_element)
else else
return (a->dockConductor().y() < b->dockConductor().y()); return (a->dockConductor().y() < b->dockConductor().y());
}); });
return(new_terminal); return(new_terminal);
} }
@ -667,17 +667,17 @@ Terminal *Element::parseTerminal(const QDomElement &dom_element)
bool Element::valideXml(QDomElement &e) { bool Element::valideXml(QDomElement &e) {
// verifie le nom du tag // verifie le nom du tag
if (e.tagName() != "element") return(false); if (e.tagName() != "element") return(false);
// verifie la presence des attributs minimaux // verifie la presence des attributs minimaux
if (!e.hasAttribute("type")) return(false); if (!e.hasAttribute("type")) return(false);
if (!e.hasAttribute("x")) return(false); if (!e.hasAttribute("x")) return(false);
if (!e.hasAttribute("y")) return(false); if (!e.hasAttribute("y")) return(false);
bool conv_ok; bool conv_ok;
// parse l'abscisse // parse l'abscisse
e.attribute("x").toDouble(&conv_ok); e.attribute("x").toDouble(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
// parse l'ordonnee // parse l'ordonnee
e.attribute("y").toDouble(&conv_ok); e.attribute("y").toDouble(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
@ -713,7 +713,7 @@ bool Element::fromXml(
QET::findInDomElement(e, "terminals", "terminal")) { QET::findInDomElement(e, "terminals", "terminal")) {
if (Terminal::valideXml(qde)) liste_terminals << qde; if (Terminal::valideXml(qde)) liste_terminals << qde;
} }
QHash<int, Terminal *> priv_id_adr; QHash<int, Terminal *> priv_id_adr;
int terminals_non_trouvees = 0; int terminals_non_trouvees = 0;
foreach(QGraphicsItem *qgi, childItems()) { foreach(QGraphicsItem *qgi, childItems()) {
@ -734,12 +734,12 @@ bool Element::fromXml(
if (!terminal_trouvee) ++ terminals_non_trouvees; if (!terminal_trouvee) ++ terminals_non_trouvees;
} }
} }
if (terminals_non_trouvees > 0) if (terminals_non_trouvees > 0)
{ {
m_state = QET::GIOK; m_state = QET::GIOK;
return(false); return(false);
} }
else else
{ {
// verifie que les associations id / adr n'entrent pas en conflit avec table_id_adr // verifie que les associations id / adr n'entrent pas en conflit avec table_id_adr
@ -765,7 +765,7 @@ bool Element::fromXml(
"link_uuid"); "link_uuid");
foreach (QDomElement qdo, uuid_list) foreach (QDomElement qdo, uuid_list)
tmp_uuids_link << qdo.attribute("uuid"); tmp_uuids_link << qdo.attribute("uuid");
//uuid of this element //uuid of this element
m_uuid= QUuid(e.attribute("uuid", QUuid::createUuid().toString())); m_uuid= QUuid(e.attribute("uuid", QUuid::createUuid().toString()));
@ -793,7 +793,7 @@ bool Element::fromXml(
setZValue(e.attribute("z", QString::number(this->zValue())).toDouble()); setZValue(e.attribute("z", QString::number(this->zValue())).toDouble());
setFlags(QGraphicsItem::ItemIsMovable setFlags(QGraphicsItem::ItemIsMovable
| QGraphicsItem::ItemIsSelectable); | QGraphicsItem::ItemIsSelectable);
// orientation // orientation
bool conv_ok; bool conv_ok;
int read_ori = e.attribute("orientation").toInt(&conv_ok); int read_ori = e.attribute("orientation").toInt(&conv_ok);
@ -803,7 +803,7 @@ bool Element::fromXml(
} else { } else {
setRotation(90*read_ori); setRotation(90*read_ori);
} }
//Befor load the dynamic text field, //Befor load the dynamic text field,
//we remove the dynamic text field created from the description of this element, to avoid doublons. //we remove the dynamic text field created from the description of this element, to avoid doublons.
for(DynamicElementTextItem *deti : m_dynamic_text_list) for(DynamicElementTextItem *deti : m_dynamic_text_list)
@ -827,13 +827,13 @@ bool Element::fromXml(
//***Element texts item***// //***Element texts item***//
//************************// //************************//
QList<QDomElement> inputs = QET::findInDomElement(e, "inputs", "input"); QList<QDomElement> inputs = QET::findInDomElement(e, "inputs", "input");
//First case, we check for the text item converted to dynamic text item //First case, we check for the text item converted to dynamic text item
const QList <DynamicElementTextItem *> conv_deti_list = const QList <DynamicElementTextItem *> conv_deti_list =
m_converted_text_from_xml_description.keys(); m_converted_text_from_xml_description.keys();
QList <DynamicElementTextItem *> successfully_converted; QList <DynamicElementTextItem *> successfully_converted;
const QList <QDomElement> dom_inputs = inputs; const QList <QDomElement> dom_inputs = inputs;
for (DynamicElementTextItem *deti : conv_deti_list) for (DynamicElementTextItem *deti : conv_deti_list)
{ {
for(const QDomElement& dom_input : dom_inputs) for(const QDomElement& dom_input : dom_inputs)
@ -849,26 +849,26 @@ bool Element::fromXml(
m_converted_text_from_xml_description.value(deti).y())) m_converted_text_from_xml_description.value(deti).y()))
{ {
//Once again this 'if', is only for retrocompatibility with old old old project //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. //when element text with tagg "label" is not null, but the element information "label" is.
if((deti->textFrom() == DynamicElementTextItem::ElementInfo) if((deti->textFrom() == DynamicElementTextItem::ElementInfo)
&& (deti->infoName() == "label")) && (deti->infoName() == "label"))
m_element_informations.addValue( m_element_informations.addValue(
"label", "label",
dom_input.attribute("text")); dom_input.attribute("text"));
deti->setText(dom_input.attribute("text")); deti->setText(dom_input.attribute("text"));
qreal rotation = deti->rotation(); qreal rotation = deti->rotation();
QPointF xml_pos = m_converted_text_from_xml_description.value(deti); QPointF xml_pos = m_converted_text_from_xml_description.value(deti);
if (dom_input.attribute("userrotation").toDouble()) if (dom_input.attribute("userrotation").toDouble())
rotation = dom_input.attribute("userrotation").toDouble(); rotation = dom_input.attribute("userrotation").toDouble();
if (dom_input.hasAttribute("userx")) if (dom_input.hasAttribute("userx"))
xml_pos.setX(dom_input.attribute("userx").toDouble()); xml_pos.setX(dom_input.attribute("userx").toDouble());
if(dom_input.hasAttribute("usery")) if(dom_input.hasAttribute("usery"))
xml_pos.setY(dom_input.attribute("usery", "0").toDouble()); xml_pos.setY(dom_input.attribute("usery", "0").toDouble());
//the origin transformation point of PartDynamicTextField //the origin transformation point of PartDynamicTextField
//is the top left corner, no matter the font size //is the top left corner, no matter the font size
//The origin transformation point of PartTextField //The origin transformation point of PartTextField
@ -876,10 +876,10 @@ bool Element::fromXml(
//change with the size of the font //change with the size of the font
//We need to use a QTransform to find the pos of //We need to use a QTransform to find the pos of
//this text from the saved pos of text item //this text from the saved pos of text item
deti->setPos(xml_pos); deti->setPos(xml_pos);
deti->setRotation(rotation); deti->setRotation(rotation);
QTransform transform; QTransform transform;
//First make the rotation //First make the rotation
transform.rotate(rotation); transform.rotate(rotation);
@ -890,7 +890,7 @@ bool Element::fromXml(
//Second translate to the pos //Second translate to the pos
transform.translate(xml_pos.x(), xml_pos.y()); transform.translate(xml_pos.x(), xml_pos.y());
deti->setPos(transform.map(pos)); deti->setPos(transform.map(pos));
//dom_input and deti matched we remove //dom_input and deti matched we remove
//the dom_input from inputs list, //the dom_input from inputs list,
//to avoid unnecessary checking made below //to avoid unnecessary checking made below
@ -903,7 +903,7 @@ bool Element::fromXml(
} }
} }
} }
//###Firts case : if this is the first time the user open the project since text item are converted to dynamic text, //###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. //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. //At save time, the values of each of them was save in the 'input' dom element.
@ -915,7 +915,7 @@ bool Element::fromXml(
for (DynamicElementTextItem *deti : m_converted_text_from_xml_description.keys()) for (DynamicElementTextItem *deti : m_converted_text_from_xml_description.keys())
delete deti; delete deti;
m_converted_text_from_xml_description.clear(); m_converted_text_from_xml_description.clear();
for (QDomElement qde : QET::findInDomElement( for (QDomElement qde : QET::findInDomElement(
e, e,
"texts_groups", "texts_groups",
@ -925,7 +925,7 @@ bool Element::fromXml(
addTextGroup("loaded_from_xml_group"); addTextGroup("loaded_from_xml_group");
group->fromXml(qde); group->fromXml(qde);
} }
//load informations //load informations
DiagramContext dc; DiagramContext dc;
dc.fromXml(e.firstChildElement("elementInformations"), dc.fromXml(e.firstChildElement("elementInformations"),
@ -939,7 +939,9 @@ bool Element::fromXml(
* So we swap the value stored in "label" to "formula" as expected. * So we swap the value stored in "label" to "formula" as expected.
* @TODO remove this code at version 0.7 or more (probably useless). * @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") #pragma message("@TODO remove this code for qet 0.7 or later")
#endif
if (dc["label"].toString().contains("%") if (dc["label"].toString().contains("%")
&& dc["formula"].toString().isNull()) && dc["formula"].toString().isNull())
{ {
@ -949,7 +951,7 @@ bool Element::fromXml(
if(dc.value("label").toString().isEmpty() && if(dc.value("label").toString().isEmpty() &&
!m_element_informations.value("label").toString().isEmpty()) !m_element_informations.value("label").toString().isEmpty())
dc.addValue("label", m_element_informations.value("label")); dc.addValue("label", m_element_informations.value("label"));
//We must to block the update of the alignment when load the information //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. //otherwise the pos of the text will not be the same as it was at save time.
for(DynamicElementTextItem *deti : m_dynamic_text_list) for(DynamicElementTextItem *deti : m_dynamic_text_list)
@ -957,8 +959,8 @@ bool Element::fromXml(
setElementInformations(dc); setElementInformations(dc);
for(DynamicElementTextItem *deti : m_dynamic_text_list) for(DynamicElementTextItem *deti : m_dynamic_text_list)
deti->m_block_alignment = false; deti->m_block_alignment = false;
/* During the devel of the version 0.7, /* During the devel of the version 0.7,
* the "old text" was replaced by the dynamic element text item. * the "old text" was replaced by the dynamic element text item.
* When open a project made befor the 0.7, * When open a project made befor the 0.7,
@ -983,7 +985,7 @@ bool Element::fromXml(
bool la = m_element_informations.keyMustShow("label"); bool la = m_element_informations.keyMustShow("label");
bool c = m_element_informations.keyMustShow("comment"); bool c = m_element_informations.keyMustShow("comment");
bool lo = m_element_informations.keyMustShow("location"); bool lo = m_element_informations.keyMustShow("location");
if((m_link_type != Master) || if((m_link_type != Master) ||
((m_link_type == Master) && ((m_link_type == Master) &&
(diagram()->project()->defaultXRefProperties( (diagram()->project()->defaultXRefProperties(
@ -1003,7 +1005,7 @@ bool Element::fromXml(
&& deti->infoName() == "label") && deti->infoName() == "label")
{ {
qreal rotation = deti->rotation(); qreal rotation = deti->rotation();
//Create the comment item //Create the comment item
DynamicElementTextItem *comment_text = nullptr; DynamicElementTextItem *comment_text = nullptr;
if (m_link_type !=PreviousReport if (m_link_type !=PreviousReport
@ -1046,7 +1048,7 @@ bool Element::fromXml(
location_text->setPos(deti->x(), deti->y()+20); //+20 is arbitrary, location_text must be below deti and comment location_text->setPos(deti->x(), deti->y()+20); //+20 is arbitrary, location_text must be below deti and comment
addDynamicTextItem(location_text); addDynamicTextItem(location_text);
} }
QPointF pos = deti->pos(); QPointF pos = deti->pos();
if (m_link_type !=PreviousReport if (m_link_type !=PreviousReport
|| m_link_type !=NextReport) || m_link_type !=NextReport)
@ -1071,7 +1073,7 @@ bool Element::fromXml(
//so that the text "label" stay in the same //so that the text "label" stay in the same
//position in scene coordinate //position in scene coordinate
group->setPos(pos - deti->pos()); group->setPos(pos - deti->pos());
break; break;
} }
} }
@ -1117,7 +1119,7 @@ bool Element::fromXml(
comment_text->y()+10); //+10 is arbitrary, location_text must be below the comment comment_text->y()+10); //+10 is arbitrary, location_text must be below the comment
addDynamicTextItem(location_text); addDynamicTextItem(location_text);
} }
//Create the group //Create the group
ElementTextItemGroup *group = ElementTextItemGroup *group =
addTextGroup(tr("Label + commentaire")); addTextGroup(tr("Label + commentaire"));
@ -1142,7 +1144,7 @@ bool Element::fromXml(
\~ @param document : XML document to use \~ @param document : XML document to use
\~French Document XML a utiliser \~French Document XML a utiliser
\~ @param table_adr_id : \~ @param table_adr_id :
Correspondence table between the addresses of the terminals Correspondence table between the addresses of the terminals
and their id in the XML representation; and their id in the XML representation;
this table completed by this method this table completed by this method
\~French Table de correspondance entre les adresses des bornes \~French Table de correspondance entre les adresses des bornes
@ -1157,7 +1159,7 @@ QDomElement Element::toXml(
int> &table_adr_id) const int> &table_adr_id) const
{ {
QDomElement element = document.createElement("element"); QDomElement element = document.createElement("element");
// type // type
element.setAttribute("type", m_location.path()); element.setAttribute("type", m_location.path());
@ -1174,13 +1176,13 @@ QDomElement Element::toXml(
QDomElement seq = m_autoNum_seq.toXml(document); QDomElement seq = m_autoNum_seq.toXml(document);
if (seq.hasChildNodes()) if (seq.hasChildNodes())
element.appendChild(seq); element.appendChild(seq);
// position, selection et orientation // position, selection et orientation
element.setAttribute("x", QString::number(pos().x())); element.setAttribute("x", QString::number(pos().x()));
element.setAttribute("y", QString::number(pos().y())); element.setAttribute("y", QString::number(pos().y()));
element.setAttribute("z", QString::number(this->zValue())); element.setAttribute("z", QString::number(this->zValue()));
element.setAttribute("orientation", QString::number(orientation())); element.setAttribute("orientation", QString::number(orientation()));
/* get the first id to use for the bounds of this element /* get the first id to use for the bounds of this element
* recupere le premier id a utiliser pour les bornes de cet element */ * recupere le premier id a utiliser pour les bornes de cet element */
int id_terminal = 0; int id_terminal = 0;
@ -1192,7 +1194,7 @@ QDomElement Element::toXml(
} }
id_terminal = max_id_t + 1; id_terminal = max_id_t + 1;
} }
// registration of device terminals // registration of device terminals
// enregistrement des bornes de l'appareil // enregistrement des bornes de l'appareil
QDomElement xml_terminals = document.createElement("terminals"); QDomElement xml_terminals = document.createElement("terminals");
@ -1206,7 +1208,7 @@ QDomElement Element::toXml(
xml_terminals.appendChild(terminal); xml_terminals.appendChild(terminal);
} }
element.appendChild(xml_terminals); element.appendChild(xml_terminals);
// enregistrement des champ de texte de l'appareil // enregistrement des champ de texte de l'appareil
QDomElement inputs = document.createElement("inputs"); QDomElement inputs = document.createElement("inputs");
element.appendChild(inputs); element.appendChild(inputs);
@ -1236,9 +1238,9 @@ QDomElement Element::toXml(
QDomElement dyn_text = document.createElement("dynamic_texts"); QDomElement dyn_text = document.createElement("dynamic_texts");
for (DynamicElementTextItem *deti : m_dynamic_text_list) for (DynamicElementTextItem *deti : m_dynamic_text_list)
dyn_text.appendChild(deti->toXml(document)); 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 //Dynamic texts owned by groups
for(ElementTextItemGroup *group : m_texts_group) for(ElementTextItemGroup *group : m_texts_group)
{ {
@ -1248,28 +1250,28 @@ QDomElement Element::toXml(
//each time a text is removed from the group, the alignement is not updated //each time a text is removed from the group, the alignement is not updated
Qt::Alignment al = group->alignment(); Qt::Alignment al = group->alignment();
group->setAlignment(Qt::AlignTop); group->setAlignment(Qt::AlignTop);
//Remove the texts from group //Remove the texts from group
QList<DynamicElementTextItem *> deti_list = group->texts(); QList<DynamicElementTextItem *> deti_list = group->texts();
for(DynamicElementTextItem *deti : deti_list) for(DynamicElementTextItem *deti : deti_list)
group->removeFromGroup(deti); group->removeFromGroup(deti);
//Save the texts to xml //Save the texts to xml
for (DynamicElementTextItem *deti : deti_list) for (DynamicElementTextItem *deti : deti_list)
dyn_text.appendChild(deti->toXml(document)); dyn_text.appendChild(deti->toXml(document));
//Re add texts to group //Re add texts to group
for(DynamicElementTextItem *deti : deti_list) for(DynamicElementTextItem *deti : deti_list)
group->addToGroup(deti); group->addToGroup(deti);
//Restor the alignement //Restor the alignement
group->setAlignment(al); group->setAlignment(al);
//Save the group to xml //Save the group to xml
texts_group.appendChild(group->toXml(document)); texts_group.appendChild(group->toXml(document));
group->blockAlignmentUpdate(false); group->blockAlignmentUpdate(false);
} }
//Append the dynamic texts to element //Append the dynamic texts to element
element.appendChild(dyn_text); element.appendChild(dyn_text);
//Append the texts group to element //Append the texts group to element
@ -1318,7 +1320,7 @@ void Element::removeDynamicTextItem(DynamicElementTextItem *deti)
emit textRemoved(deti); emit textRemoved(deti);
return; return;
} }
for(ElementTextItemGroup *group : m_texts_group) for(ElementTextItemGroup *group : m_texts_group)
{ {
if(group->texts().contains(deti)) if(group->texts().contains(deti))
@ -1361,7 +1363,7 @@ ElementTextItemGroup *Element::addTextGroup(const QString &name)
emit textsGroupAdded(group); emit textsGroupAdded(group);
return group; return group;
} }
//Set a new name if name already exist //Set a new name if name already exist
QString rename = name; QString rename = name;
int i=1; int i=1;
@ -1370,7 +1372,7 @@ ElementTextItemGroup *Element::addTextGroup(const QString &name)
rename = name+QString::number(i); rename = name+QString::number(i);
i++; i++;
} }
//Create the group //Create the group
ElementTextItemGroup *group = new ElementTextItemGroup(rename, this); ElementTextItemGroup *group = new ElementTextItemGroup(rename, this);
m_texts_group << group; m_texts_group << group;
@ -1387,7 +1389,7 @@ void Element::addTextGroup(ElementTextItemGroup *group)
{ {
if(group->parentElement()) if(group->parentElement())
return; return;
m_texts_group << group; m_texts_group << group;
group->setParentItem(this); group->setParentItem(this);
emit textsGroupAdded(group); emit textsGroupAdded(group);
@ -1405,9 +1407,9 @@ void Element::removeTextGroup(ElementTextItemGroup *group)
{ {
if(!m_texts_group.contains(group)) if(!m_texts_group.contains(group))
return; return;
const QList <QGraphicsItem *> items_list = group->childItems(); const QList <QGraphicsItem *> items_list = group->childItems();
for(QGraphicsItem *qgi : items_list) for(QGraphicsItem *qgi : items_list)
{ {
if(qgi->type() == DynamicElementTextItem::Type) if(qgi->type() == DynamicElementTextItem::Type)
@ -1417,8 +1419,8 @@ void Element::removeTextGroup(ElementTextItemGroup *group)
removeTextFromGroup(deti, group); removeTextFromGroup(deti, group);
} }
} }
emit textsGroupAboutToBeRemoved(group); emit textsGroupAboutToBeRemoved(group);
m_texts_group.removeOne(group); m_texts_group.removeOne(group);
group->setParentItem(nullptr); group->setParentItem(nullptr);
@ -1435,7 +1437,7 @@ ElementTextItemGroup *Element::textGroup(const QString &name) const
for (ElementTextItemGroup *group : m_texts_group) for (ElementTextItemGroup *group : m_texts_group)
if(group->name() == name) if(group->name() == name)
return group; return group;
return nullptr; return nullptr;
} }
@ -1465,10 +1467,10 @@ bool Element::addTextToGroup(DynamicElementTextItem *text,
m_dynamic_text_list.removeOne(text); m_dynamic_text_list.removeOne(text);
emit textRemoved(text); emit textRemoved(text);
group->addToGroup(text); group->addToGroup(text);
emit textAddedToGroup(text, group); emit textAddedToGroup(text, group);
return true; return true;
} }
@ -1483,7 +1485,7 @@ bool Element::removeTextFromGroup(DynamicElementTextItem *text,
{ {
if(!m_texts_group.contains(group)) if(!m_texts_group.contains(group))
return false; return false;
if(group->texts().contains(text)) if(group->texts().contains(text))
{ {
group->removeFromGroup(text); group->removeFromGroup(text);
@ -1491,7 +1493,7 @@ bool Element::removeTextFromGroup(DynamicElementTextItem *text,
addDynamicTextItem(text); addDynamicTextItem(text);
return true; return true;
} }
return false; return false;
} }
@ -1683,7 +1685,7 @@ void Element::hoverLeaveEvent(QGraphicsSceneHoverEvent *e)
void Element::setUpFormula(bool code_letter) void Element::setUpFormula(bool code_letter)
{ {
Q_UNUSED(code_letter) Q_UNUSED(code_letter)
if (linkType() == Element::Slave || linkType() & Element::AllReport) if (linkType() == Element::Slave || linkType() & Element::AllReport)
return; return;
@ -1694,7 +1696,7 @@ void Element::setUpFormula(bool code_letter)
->elementAutoNumCurrentFormula(); ->elementAutoNumCurrentFormula();
m_element_informations.addValue("formula", formula); m_element_informations.addValue("formula", formula);
QString element_currentAutoNum = diagram() QString element_currentAutoNum = diagram()
->project() ->project()
->elementCurrentAutoNum(); ->elementCurrentAutoNum();
@ -1702,7 +1704,7 @@ void Element::setUpFormula(bool code_letter)
->project() ->project()
->elementAutoNum(element_currentAutoNum); ->elementAutoNum(element_currentAutoNum);
NumerotationContextCommands ncc (nc); NumerotationContextCommands ncc (nc);
m_autoNum_seq.clear(); m_autoNum_seq.clear();
autonum::setSequential(formula, autonum::setSequential(formula,
m_autoNum_seq, m_autoNum_seq,

View File

@ -52,7 +52,7 @@ QetShapeItem::QetShapeItem(QPointF p1, QPointF p2, ShapeType type, QGraphicsItem
for(QetGraphicsHandlerItem *qghi : m_handler_vector) for(QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setZValue(this->zValue()+1); qghi->setZValue(this->zValue()+1);
}); });
m_insert_point = new QAction(tr("Ajouter un point"), this); m_insert_point = new QAction(tr("Ajouter un point"), this);
m_insert_point->setIcon(QET::Icons::Add); m_insert_point->setIcon(QET::Icons::Add);
connect(m_insert_point, &QAction::triggered, this, &QetShapeItem::insertPoint); connect(m_insert_point, &QAction::triggered, this, &QetShapeItem::insertPoint);
@ -266,7 +266,7 @@ QPainterPath QetShapeItem::shape() const
path.moveTo(m_P1); path.moveTo(m_P1);
path.lineTo(m_P2); path.lineTo(m_P2);
break; break;
case Rectangle: case Rectangle:
path.addRoundedRect( path.addRoundedRect(
QRectF(m_P1, m_P2), QRectF(m_P1, m_P2),
m_xRadius, m_xRadius,
@ -363,7 +363,7 @@ void QetShapeItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
event->ignore(); event->ignore();
QetGraphicsItem::mousePressEvent(event); QetGraphicsItem::mousePressEvent(event);
if (event->button() == Qt::LeftButton) { if (event->button() == Qt::LeftButton) {
switchResizeMode(); switchResizeMode();
event->accept(); event->accept();
@ -374,7 +374,7 @@ void QetShapeItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
@brief QetShapeItem::itemChange @brief QetShapeItem::itemChange
@param change @param change
@param value @param value
@return @return
*/ */
QVariant QetShapeItem::itemChange(QGraphicsItem::GraphicsItemChange change, QVariant QetShapeItem::itemChange(QGraphicsItem::GraphicsItemChange change,
const QVariant &value) const QVariant &value)
@ -405,7 +405,7 @@ QVariant QetShapeItem::itemChange(QGraphicsItem::GraphicsItemChange change,
setSelected(false); setSelected(false);
} }
} }
return QGraphicsItem::itemChange(change, value); return QGraphicsItem::itemChange(change, value);
} }
@ -413,7 +413,7 @@ QVariant QetShapeItem::itemChange(QGraphicsItem::GraphicsItemChange change,
@brief QetShapeItem::sceneEventFilter @brief QetShapeItem::sceneEventFilter
@param watched @param watched
@param event @param event
@return @return
*/ */
bool QetShapeItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event) bool QetShapeItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{ {
@ -421,7 +421,7 @@ bool QetShapeItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@ -445,7 +445,7 @@ bool QetShapeItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@ -456,13 +456,13 @@ bool QetShapeItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
void QetShapeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) void QetShapeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{ {
m_context_menu_pos = event->pos(); m_context_menu_pos = event->pos();
if (m_shapeType == QetShapeItem::Polygon) if (m_shapeType == QetShapeItem::Polygon)
{ {
if (diagram()->selectedItems().isEmpty()) { if (diagram()->selectedItems().isEmpty()) {
this->setSelected(true); this->setSelected(true);
} }
if (isSelected() && scene()->selectedItems().size() == 1) if (isSelected() && scene()->selectedItems().size() == 1)
{ {
if (diagram()) if (diagram())
@ -477,12 +477,12 @@ void QetShapeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
continue; continue;
} }
} }
if (d_view) if (d_view)
{ {
QScopedPointer<QMenu> menu(new QMenu()); QScopedPointer<QMenu> menu(new QMenu());
menu.data()->addAction(m_insert_point); menu.data()->addAction(m_insert_point);
if (m_handler_vector.count() > 2) if (m_handler_vector.count() > 2)
{ {
for (QetGraphicsHandlerItem *qghi : m_handler_vector) for (QetGraphicsHandlerItem *qghi : m_handler_vector)
@ -494,7 +494,7 @@ void QetShapeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
} }
} }
} }
menu.data()->addSeparator(); menu.data()->addSeparator();
menu.data()->addActions(d_view->contextMenuActions()); menu.data()->addActions(d_view->contextMenuActions());
menu.data()->exec(event->screenPos()); menu.data()->exec(event->screenPos());
@ -504,7 +504,7 @@ void QetShapeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
} }
} }
} }
QetGraphicsItem::contextMenuEvent(event); QetGraphicsItem::contextMenuEvent(event);
} }
@ -557,7 +557,7 @@ void QetShapeItem::switchResizeMode()
for (QetGraphicsHandlerItem *qghi : m_handler_vector) { for (QetGraphicsHandlerItem *qghi : m_handler_vector) {
qghi->setColor(Qt::blue); qghi->setColor(Qt::blue);
} }
} }
} }
} }
@ -587,11 +587,11 @@ void QetShapeItem::addHandler()
points_vector = m_polygon; points_vector = m_polygon;
break; break;
} }
if(!points_vector.isEmpty() && scene()) if(!points_vector.isEmpty() && scene())
{ {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector)); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector));
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
handler->setZValue(this->zValue()+1); handler->setZValue(this->zValue()+1);
@ -612,7 +612,7 @@ void QetShapeItem::adjusteHandlerPos()
if (m_handler_vector.isEmpty()) { if (m_handler_vector.isEmpty()) {
return; return;
} }
QVector <QPointF> points_vector; QVector <QPointF> points_vector;
switch (m_shapeType) switch (m_shapeType)
{ {
@ -638,7 +638,7 @@ void QetShapeItem::adjusteHandlerPos()
break; break;
} }
} }
if (m_handler_vector.size() == points_vector.size()) if (m_handler_vector.size() == points_vector.size())
{ {
points_vector = mapToScene(points_vector); points_vector = mapToScene(points_vector);
@ -658,7 +658,7 @@ void QetShapeItem::insertPoint()
if (m_shapeType == QetShapeItem::Polygon) if (m_shapeType == QetShapeItem::Polygon)
{ {
QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(this->polygon(), m_closed, Diagram::snapToGrid(m_context_menu_pos)); QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(this->polygon(), m_closed, Diagram::snapToGrid(m_context_menu_pos));
if(new_polygon != m_polygon) if(new_polygon != m_polygon)
{ {
//Wrap the undo for avoid to merge the undo commands when user add several points. //Wrap the undo for avoid to merge the undo commands when user add several points.
@ -674,11 +674,11 @@ void QetShapeItem::removePoint()
if (m_shapeType != QetShapeItem::Polygon) { if (m_shapeType != QetShapeItem::Polygon) {
return; return;
} }
if (m_handler_vector.size() == 2) { if (m_handler_vector.size() == 2) {
return; return;
} }
QPointF point = mapToScene(m_context_menu_pos); QPointF point = mapToScene(m_context_menu_pos);
int index = -1; int index = -1;
for (int i=0 ; i<m_handler_vector.size() ; i++) for (int i=0 ; i<m_handler_vector.size() ; i++)
@ -694,7 +694,7 @@ void QetShapeItem::removePoint()
{ {
QPolygonF polygon = this->polygon(); QPolygonF polygon = this->polygon();
polygon.removeAt(index); polygon.removeAt(index);
//Wrap the undo for avoid to merge the undo commands when user add several points. //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")); QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone"));
new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo); new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo);
@ -788,7 +788,7 @@ void QetShapeItem::handlerMouseMoveEvent(QGraphicsSceneMouseEvent *event)
void QetShapeItem::handlerMouseReleaseEvent() void QetShapeItem::handlerMouseReleaseEvent()
{ {
m_modifie_radius_equaly = false; m_modifie_radius_equaly = false;
if (diagram()) if (diagram())
{ {
QPropertyUndoCommand *undo = nullptr; QPropertyUndoCommand *undo = nullptr;
@ -826,7 +826,7 @@ void QetShapeItem::handlerMouseReleaseEvent()
} }
else if (m_shapeType == Polygon && (m_polygon != m_old_polygon)) else if (m_shapeType == Polygon && (m_polygon != m_old_polygon))
undo = new QPropertyUndoCommand(this, "polygon", m_old_polygon, m_polygon); undo = new QPropertyUndoCommand(this, "polygon", m_old_polygon, m_polygon);
if(undo) if(undo)
{ {
undo->setText(tr("Modifier %1").arg(name())); undo->setText(tr("Modifier %1").arg(name()));
@ -851,6 +851,9 @@ bool QetShapeItem::fromXml(const QDomElement &e)
m_brush = QETXML::brushFromXml(e.firstChildElement("brush")); 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")
#endif
//@TODO Compatibility for version older than N°4075, shape type was stored with an int //@TODO Compatibility for version older than N°4075, shape type was stored with an int
if (type.size() == 1) if (type.size() == 1)
{ {
@ -875,7 +878,7 @@ bool QetShapeItem::fromXml(const QDomElement &e)
m_P1.setY(e.attribute("y1", nullptr).toDouble()); m_P1.setY(e.attribute("y1", nullptr).toDouble());
m_P2.setX(e.attribute("x2", nullptr).toDouble()); m_P2.setX(e.attribute("x2", nullptr).toDouble());
m_P2.setY(e.attribute("y2", nullptr).toDouble()); m_P2.setY(e.attribute("y2", nullptr).toDouble());
if (m_shapeType == Rectangle) if (m_shapeType == Rectangle)
{ {
setXRadius(e.attribute("rx", "0").toDouble()); setXRadius(e.attribute("rx", "0").toDouble());
@ -916,7 +919,7 @@ QDomElement QetShapeItem::toXml(QDomDocument &document) const
result.setAttribute("y1", QString::number(mapToScene(m_P1).y())); result.setAttribute("y1", QString::number(mapToScene(m_P1).y()));
result.setAttribute("x2", QString::number(mapToScene(m_P2).x())); result.setAttribute("x2", QString::number(mapToScene(m_P2).x()));
result.setAttribute("y2", QString::number(mapToScene(m_P2).y())); result.setAttribute("y2", QString::number(mapToScene(m_P2).y()));
if (m_shapeType == Rectangle) if (m_shapeType == Rectangle)
{ {
QRectF rect(m_P1, m_P2); QRectF rect(m_P1, m_P2);
@ -929,7 +932,7 @@ QDomElement QetShapeItem::toXml(QDomDocument &document) const
if (y > rect.height()/2) { if (y > rect.height()/2) {
y = rect.height()/2; y = rect.height()/2;
} }
result.setAttribute("rx", QString::number(m_xRadius)); result.setAttribute("rx", QString::number(m_xRadius));
result.setAttribute("ry", QString::number(m_yRadius)); result.setAttribute("ry", QString::number(m_yRadius));
} }
@ -965,28 +968,28 @@ bool QetShapeItem::toDXF(const QString &filepath,const QPen &pen)
switch (m_shapeType) switch (m_shapeType)
{ {
case Line: case Line:
Createdxf::drawLine(filepath, Createdxf::drawLine(filepath,
QLineF( mapToScene(m_P1), QLineF( mapToScene(m_P1),
mapToScene(m_P2)), mapToScene(m_P2)),
Createdxf::dxfColor(pen)); Createdxf::dxfColor(pen));
return true; return true;
case Rectangle: case Rectangle:
Createdxf::drawRectangle(filepath, Createdxf::drawRectangle(filepath,
QRectF(mapToScene(m_P1), QRectF(mapToScene(m_P1),
mapToScene(m_P2)).normalized(), mapToScene(m_P2)).normalized(),
Createdxf::dxfColor(pen)); Createdxf::dxfColor(pen));
return true; return true;
case Ellipse: case Ellipse:
Createdxf::drawEllipse(filepath, Createdxf::drawEllipse(filepath,
QRectF(mapToScene(m_P1), QRectF(mapToScene(m_P1),
mapToScene(m_P2)).normalized(), mapToScene(m_P2)).normalized(),
Createdxf::dxfColor(pen)); Createdxf::dxfColor(pen));
return true; return true;
case Polygon: case Polygon:
Createdxf::drawPolygon(filepath,m_polygon,Createdxf::dxfColor(pen)); Createdxf::drawPolygon(filepath,m_polygon,Createdxf::dxfColor(pen));
return true; return true;
default: default:
return false; return false;
} }
} }

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -155,6 +155,9 @@ Terminal::Terminal(TerminalData* data, Element* e) :
d(data), d(data),
parent_element_(e) 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. // TODO: what is when multiple parents exist. So the other relation is lost.
d->setParent(this); d->setParent(this);
init("_", "_", false); init("_", "_", false);
@ -232,7 +235,7 @@ bool Terminal::addConductor(Conductor *conductor)
//Get the other terminal where the conductor must be linked //Get the other terminal where the conductor must be linked
Terminal *other_terminal = (conductor -> terminal1 == this) Terminal *other_terminal = (conductor -> terminal1 == this)
? conductor->terminal2 : conductor->terminal1; ? conductor->terminal2 : conductor->terminal1;
//Check if this terminal isn't already linked with other_terminal //Check if this terminal isn't already linked with other_terminal
foreach (Conductor* cond, conductors_) foreach (Conductor* cond, conductors_)
if (cond -> terminal1 == other_terminal || cond -> terminal2 == other_terminal) if (cond -> terminal1 == other_terminal || cond -> terminal2 == other_terminal)
@ -556,7 +559,7 @@ void Terminal::mousePressEvent(QGraphicsSceneMouseEvent *e)
*/ */
void Terminal::mouseMoveEvent(QGraphicsSceneMouseEvent *e) void Terminal::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{ {
// pendant la pose d'un conducteur, on adopte un autre curseur // pendant la pose d'un conducteur, on adopte un autre curseur
//setCursor(Qt::CrossCursor); //setCursor(Qt::CrossCursor);
// d'un mouvement a l'autre, il faut retirer l'effet hover de la borne precedente // d'un mouvement a l'autre, il faut retirer l'effet hover de la borne precedente
@ -571,10 +574,10 @@ void Terminal::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
if (!diag) return; if (!diag) return;
// si la scene est un Diagram, on actualise le poseur de conducteur // si la scene est un Diagram, on actualise le poseur de conducteur
diag -> setConductorStop(e -> scenePos()); diag -> setConductorStop(e -> scenePos());
// on recupere la liste des qgi sous le pointeur // on recupere la liste des qgi sous le pointeur
QList<QGraphicsItem *> qgis = diag -> items(e -> scenePos()); QList<QGraphicsItem *> qgis = diag -> items(e -> scenePos());
/* le qgi le plus haut /* le qgi le plus haut
= le poseur de conductor = le poseur de conductor
= le premier element de la liste = le premier element de la liste
@ -582,17 +585,17 @@ void Terminal::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
= on prend le deuxieme element de la liste = on prend le deuxieme element de la liste
*/ */
Q_ASSERT_X(!(qgis.isEmpty()), "Terminal::mouseMoveEvent", "La liste d'items ne devrait pas etre vide"); 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 // s'il n'y rien d'autre que le poseur de conducteur dans la liste, on arrete la
if (qgis.size() <= 1) return; if (qgis.size() <= 1) return;
// sinon on prend le deuxieme element de la liste et on verifie s'il s'agit d'une borne // sinon on prend le deuxieme element de la liste et on verifie s'il s'agit d'une borne
QGraphicsItem *qgi = qgis.at(1); QGraphicsItem *qgi = qgis.at(1);
// si le qgi est une borne... // si le qgi est une borne...
Terminal *other_terminal = qgraphicsitem_cast<Terminal *>(qgi); Terminal *other_terminal = qgraphicsitem_cast<Terminal *>(qgi);
if (!other_terminal) return; if (!other_terminal) return;
previous_terminal_ = other_terminal; previous_terminal_ = other_terminal;
// s'il s'agit d'une borne, on lui applique l'effet hover approprie // s'il s'agit d'une borne, on lui applique l'effet hover approprie
if (!canBeLinkedTo(other_terminal)) { if (!canBeLinkedTo(other_terminal)) {
other_terminal -> hovered_color_ = forbiddenColor; other_terminal -> hovered_color_ = forbiddenColor;
@ -698,7 +701,7 @@ void Terminal::updateConductor()
*/ */
bool Terminal::isLinkedTo(Terminal *other_terminal) { bool Terminal::isLinkedTo(Terminal *other_terminal) {
if (other_terminal == this) return(false); if (other_terminal == this) return(false);
bool already_linked = false; bool already_linked = false;
foreach (Conductor *c, conductors_) { foreach (Conductor *c, conductors_) {
if (c -> terminal1 == other_terminal || c -> terminal2 == other_terminal) { if (c -> terminal1 == other_terminal || c -> terminal2 == other_terminal) {
@ -768,25 +771,25 @@ bool Terminal::valideXml(QDomElement &terminal)
{ {
// verifie le nom du tag // verifie le nom du tag
if (terminal.tagName() != "terminal") return(false); if (terminal.tagName() != "terminal") return(false);
// verifie la presence des attributs minimaux // verifie la presence des attributs minimaux
if (!terminal.hasAttribute("x")) return(false); if (!terminal.hasAttribute("x")) return(false);
if (!terminal.hasAttribute("y")) return(false); if (!terminal.hasAttribute("y")) return(false);
if (!terminal.hasAttribute("orientation")) return(false); if (!terminal.hasAttribute("orientation")) return(false);
bool conv_ok; bool conv_ok;
// parse l'abscisse // parse l'abscisse
terminal.attribute("x").toDouble(&conv_ok); terminal.attribute("x").toDouble(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
// parse l'ordonnee // parse l'ordonnee
terminal.attribute("y").toDouble(&conv_ok); terminal.attribute("y").toDouble(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
// parse l'id // parse l'id
terminal.attribute("id").toInt(&conv_ok); terminal.attribute("id").toInt(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
// parse l'orientation // parse l'orientation
int terminal_or = terminal.attribute("orientation").toInt(&conv_ok); int terminal_or = terminal.attribute("orientation").toInt(&conv_ok);
if (!conv_ok) return(false); if (!conv_ok) return(false);
@ -794,7 +797,7 @@ bool Terminal::valideXml(QDomElement &terminal)
&& terminal_or != Qet::South && terminal_or != Qet::South
&& terminal_or != Qet::East && terminal_or != Qet::East
&& terminal_or != Qet::West) return(false); && terminal_or != Qet::West) return(false);
// a ce stade, la borne est syntaxiquement correcte // a ce stade, la borne est syntaxiquement correcte
return(true); return(true);
} }

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -38,7 +38,7 @@ QETMainWindow::QETMainWindow(QWidget *widget, Qt::WindowFlags flags) :
{ {
initCommonActions(); initCommonActions();
initCommonMenus(); initCommonMenus();
setAcceptDrops(true); setAcceptDrops(true);
} }
@ -55,12 +55,15 @@ QETMainWindow::~QETMainWindow()
void QETMainWindow::initCommonActions() void QETMainWindow::initCommonActions()
{ {
QETApp *qet_app = QETApp::instance(); QETApp *qet_app = QETApp::instance();
configure_action_ = new QAction(QET::Icons::Configure, tr("&Configurer QElectroTech"), this); configure_action_ = new QAction(QET::Icons::Configure, tr("&Configurer QElectroTech"), this);
configure_action_ -> setStatusTip(tr("Permet de régler différents paramètres de QElectroTech", "status bar tip")); configure_action_ -> setStatusTip(tr("Permet de régler différents paramètres de QElectroTech", "status bar tip"));
connect(configure_action_, &QAction::triggered, [qet_app]() connect(configure_action_, &QAction::triggered, [qet_app]()
{ {
qet_app->configureQET(); qet_app->configureQET();
#if TODO_LIST
#pragma message("@TODO we use reloadOldElementPanel only to keep up to date the string of the folio in the old element panel. then, if user change the option "Use labels of folio instead of their ID" the string of folio in the old element panel is up to date")
#endif
//TODO we use reloadOldElementPanel only to keep up to date the string of the folio in the old element panel. //TODO we use reloadOldElementPanel only to keep up to date the string of the folio in the old element panel.
//then, if user change the option "Use labels of folio instead of their ID" the string of folio in the old element panel is up to date //then, if user change the option "Use labels of folio instead of their ID" the string of folio in the old element panel is up to date
for (QETDiagramEditor *qde : qet_app->diagramEditors()) for (QETDiagramEditor *qde : qet_app->diagramEditors())
@ -72,59 +75,59 @@ void QETMainWindow::initCommonActions()
} }
} }
}); });
fullscreen_action_ = new QAction(this); fullscreen_action_ = new QAction(this);
updateFullScreenAction(); updateFullScreenAction();
connect(fullscreen_action_, SIGNAL(triggered()), this, SLOT(toggleFullScreen())); connect(fullscreen_action_, SIGNAL(triggered()), this, SLOT(toggleFullScreen()));
whatsthis_action_ = QWhatsThis::createAction(this); whatsthis_action_ = QWhatsThis::createAction(this);
about_qet_ = new QAction(QET::Icons::QETLogo, tr("À &propos de QElectroTech"), this); about_qet_ = new QAction(QET::Icons::QETLogo, tr("À &propos de QElectroTech"), this);
about_qet_ -> setStatusTip(tr("Affiche des informations sur QElectroTech", "status bar tip")); about_qet_ -> setStatusTip(tr("Affiche des informations sur QElectroTech", "status bar tip"));
connect(about_qet_, SIGNAL(triggered()), qet_app, SLOT(aboutQET())); connect(about_qet_, SIGNAL(triggered()), qet_app, SLOT(aboutQET()));
manual_online_ = new QAction(QET::Icons::QETManual, tr("Manuel en ligne"), this); manual_online_ = new QAction(QET::Icons::QETManual, tr("Manuel en ligne"), this);
manual_online_ -> setStatusTip(tr("Lance le navigateur par défaut vers le manuel en ligne de QElectroTech", "status bar tip")); manual_online_ -> setStatusTip(tr("Lance le navigateur par défaut vers le manuel en ligne de QElectroTech", "status bar tip"));
connect(manual_online_, &QAction::triggered, [](bool) { connect(manual_online_, &QAction::triggered, [](bool) {
QString link = "https://download.tuxfamily.org/qet/manual_0.7/build/index.html"; QString link = "https://download.tuxfamily.org/qet/manual_0.7/build/index.html";
QDesktopServices::openUrl(QUrl(link)); QDesktopServices::openUrl(QUrl(link));
}); });
manual_online_ -> setShortcut(Qt::Key_F1); manual_online_ -> setShortcut(Qt::Key_F1);
youtube_ = new QAction(QET::Icons::QETVideo, tr("Chaine Youtube"), this); youtube_ = new QAction(QET::Icons::QETVideo, tr("Chaine Youtube"), this);
youtube_ -> setStatusTip(tr("Lance le navigateur par défaut vers la chaine Youtube de QElectroTech", "status bar tip")); youtube_ -> setStatusTip(tr("Lance le navigateur par défaut vers la chaine Youtube de QElectroTech", "status bar tip"));
connect(youtube_, &QAction::triggered, [](bool) { connect(youtube_, &QAction::triggered, [](bool) {
QString link = "https://www.youtube.com/user/scorpio8101/videos"; QString link = "https://www.youtube.com/user/scorpio8101/videos";
QDesktopServices::openUrl(QUrl(link)); QDesktopServices::openUrl(QUrl(link));
}); });
upgrade_ = new QAction(QET::Icons::QETDownload, tr("Télécharger une nouvelle version (dev)"), this); upgrade_ = new QAction(QET::Icons::QETDownload, tr("Télécharger une nouvelle version (dev)"), this);
upgrade_ -> setStatusTip(tr("Lance le navigateur par défaut vers le dépot Nightly en ligne de QElectroTech", "status bar tip")); upgrade_ -> setStatusTip(tr("Lance le navigateur par défaut vers le dépot Nightly en ligne de QElectroTech", "status bar tip"));
upgrade_M = new QAction(QET::Icons::QETDownload, tr("Télécharger une nouvelle version (dev)"), this); upgrade_M = new QAction(QET::Icons::QETDownload, tr("Télécharger une nouvelle version (dev)"), this);
upgrade_M -> setStatusTip(tr("Lance le navigateur par défaut vers le dépot Nightly en ligne de QElectroTech", "status bar tip")); upgrade_M -> setStatusTip(tr("Lance le navigateur par défaut vers le dépot Nightly en ligne de QElectroTech", "status bar tip"));
connect(upgrade_, &QAction::triggered, [](bool) { connect(upgrade_, &QAction::triggered, [](bool) {
QString link = "https://qelectrotech.org/download_windows_QET.html"; QString link = "https://qelectrotech.org/download_windows_QET.html";
QDesktopServices::openUrl(QUrl(link)); QDesktopServices::openUrl(QUrl(link));
}); });
connect(upgrade_M, &QAction::triggered, [](bool) { connect(upgrade_M, &QAction::triggered, [](bool) {
QString link = "https://qelectrotech.org/download_mac_QET.html"; QString link = "https://qelectrotech.org/download_mac_QET.html";
QDesktopServices::openUrl(QUrl(link)); QDesktopServices::openUrl(QUrl(link));
}); });
donate_ = new QAction(QET::Icons::QETDonate, tr("Soutenir le projet par un don"), this); donate_ = new QAction(QET::Icons::QETDonate, tr("Soutenir le projet par un don"), this);
donate_ -> setStatusTip(tr("Soutenir le projet QElectroTech par un don", "status bar tip")); donate_ -> setStatusTip(tr("Soutenir le projet QElectroTech par un don", "status bar tip"));
connect(donate_, &QAction::triggered, [](bool) { connect(donate_, &QAction::triggered, [](bool) {
QString link = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZZHC9D7C3MDPC"; QString link = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZZHC9D7C3MDPC";
QDesktopServices::openUrl(QUrl(link)); QDesktopServices::openUrl(QUrl(link));
}); });
about_qt_ = new QAction(QET::Icons::QtLogo, tr("À propos de &Qt"), this); about_qt_ = new QAction(QET::Icons::QtLogo, tr("À propos de &Qt"), this);
about_qt_ -> setStatusTip(tr("Affiche des informations sur la bibliothèque Qt", "status bar tip")); about_qt_ -> setStatusTip(tr("Affiche des informations sur la bibliothèque Qt", "status bar tip"));
connect(about_qt_, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(about_qt_, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
@ -139,8 +142,8 @@ void QETMainWindow::initCommonMenus()
settings_menu_ -> addAction(fullscreen_action_); settings_menu_ -> addAction(fullscreen_action_);
settings_menu_ -> addAction(configure_action_); settings_menu_ -> addAction(configure_action_);
connect(settings_menu_, SIGNAL(aboutToShow()), this, SLOT(checkToolbarsmenu())); connect(settings_menu_, SIGNAL(aboutToShow()), this, SLOT(checkToolbarsmenu()));
help_menu_ = new QMenu(tr("&Aide", "window menu")); help_menu_ = new QMenu(tr("&Aide", "window menu"));
help_menu_ -> addAction(whatsthis_action_); help_menu_ -> addAction(whatsthis_action_);
help_menu_ -> addSeparator(); help_menu_ -> addSeparator();
@ -151,7 +154,7 @@ void QETMainWindow::initCommonMenus()
help_menu_ -> addAction(upgrade_M); help_menu_ -> addAction(upgrade_M);
help_menu_ -> addAction(donate_); help_menu_ -> addAction(donate_);
help_menu_ -> addAction(about_qt_); help_menu_ -> addAction(about_qt_);
#ifdef Q_OS_WIN32 #ifdef Q_OS_WIN32
upgrade_ -> setVisible(true); upgrade_ -> setVisible(true);
#else #else
@ -174,11 +177,11 @@ upgrade_M -> setVisible(false);
*/ */
void QETMainWindow::insertMenu(QMenu *before, QMenu *menu, bool customize) { void QETMainWindow::insertMenu(QMenu *before, QMenu *menu, bool customize) {
if (!menu) return; if (!menu) return;
QAction *before_action = actionForMenu(before); QAction *before_action = actionForMenu(before);
QAction *menu_action = menuBar() -> insertMenu(before_action, menu); QAction *menu_action = menuBar() -> insertMenu(before_action, menu);
menu_actions_.insert(menu, menu_action); menu_actions_.insert(menu, menu_action);
if (customize) { if (customize) {
menu -> setTearOffEnabled(true); menu -> setTearOffEnabled(true);
} }

View File

@ -988,6 +988,9 @@ bool QETProject::isEmpty() const
// si le projet a un titre, on considere qu'il n'est pas vide // si le projet a un titre, on considere qu'il n'est pas vide
if (!project_title_.isEmpty()) return(false); 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 // compte le nombre de schemas non vides
@ -1273,7 +1276,9 @@ void QETProject::readProjectXml(QDomDocument &xml_project)
{ {
bool conv_ok; bool conv_ok;
m_project_qet_version = root_elmt.attribute("version").toDouble(&conv_ok); m_project_qet_version = root_elmt.attribute("version").toDouble(&conv_ok);
#if TODO_LIST
#pragma message("@TODO use of version convert") #pragma message("@TODO use of version convert")
#endif
if (conv_ok && QET::version.toDouble() < m_project_qet_version) if (conv_ok && QET::version.toDouble() < m_project_qet_version)
{ {
int ret = QET::QetMessageBox::warning( int ret = QET::QetMessageBox::warning(
@ -1328,7 +1333,9 @@ void QETProject::readProjectXml(QDomDocument &xml_project)
*/ */
void QETProject::readDiagramsXml(QDomDocument &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") #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 //@TODO try to solve a weird bug (dialog is black) since port to Qt5 with the DialogWaiting
//show DialogWaiting //show DialogWaiting
DialogWaiting *dlgWaiting = nullptr; DialogWaiting *dlgWaiting = nullptr;

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -34,7 +34,7 @@ RecentFiles::RecentFiles(const QString &identifier, int size, QObject *parent) :
{ {
mapper_ = new QSignalMapper(this); mapper_ = new QSignalMapper(this);
connect(mapper_, SIGNAL(mapped(const QString &)), this, SLOT(handleMenuRequest(const QString &))); connect(mapper_, SIGNAL(mapped(const QString &)), this, SLOT(handleMenuRequest(const QString &)));
extractFilesFromSettings(); extractFilesFromSettings();
buildMenu(); buildMenu();
} }
@ -45,6 +45,9 @@ RecentFiles::RecentFiles(const QString &identifier, int size, QObject *parent) :
*/ */
RecentFiles::~RecentFiles() RecentFiles::~RecentFiles()
{ {
#if TODO_LIST
#pragma message("@TODO determiner s'il faut detruire ou non le menu")
#endif
delete menu_; delete menu_;
} }
@ -124,7 +127,7 @@ void RecentFiles::extractFilesFromSettings()
{ {
//Forget the list of recent files //Forget the list of recent files
list_.clear(); list_.clear();
//Get the last opened file from the settings //Get the last opened file from the settings
QSettings settings; QSettings settings;
for (int i = size_ ; i >= 1 ; -- i) for (int i = size_ ; i >= 1 ; -- i)
@ -141,14 +144,14 @@ void RecentFiles::extractFilesFromSettings()
void RecentFiles::insertFile(const QString &filepath) { void RecentFiles::insertFile(const QString &filepath) {
// s'assure que le chemin soit exprime avec des separateurs conformes au systeme // s'assure que le chemin soit exprime avec des separateurs conformes au systeme
QString filepath_ns = QDir::toNativeSeparators(filepath); QString filepath_ns = QDir::toNativeSeparators(filepath);
// evite d'inserer un chemin de fichier vide ou en double // evite d'inserer un chemin de fichier vide ou en double
if (filepath_ns.isEmpty()) return; if (filepath_ns.isEmpty()) return;
list_.removeAll(filepath_ns); list_.removeAll(filepath_ns);
// insere le chemin de fichier // insere le chemin de fichier
list_.push_front(filepath_ns); list_.push_front(filepath_ns);
// s'assure que l'on ne retient pas plus de fichiers que necessaire // s'assure que l'on ne retient pas plus de fichiers que necessaire
while (list_.count() > size_) list_.removeLast(); while (list_.count() > size_) list_.removeLast();
} }
@ -178,7 +181,7 @@ void RecentFiles::buildMenu()
} else { } else {
menu_ -> clear(); menu_ -> clear();
} }
// remplit le menu // remplit le menu
foreach (QString filepath, list_) { foreach (QString filepath, list_) {
// creee une nouvelle action pour le fichier // creee une nouvelle action pour le fichier
@ -187,7 +190,7 @@ void RecentFiles::buildMenu()
action -> setIcon(files_icon_); action -> setIcon(files_icon_);
} }
menu_ -> addAction(action); menu_ -> addAction(action);
// lie l'action et le mapper // lie l'action et le mapper
mapper_ -> setMapping(action, filepath); mapper_ -> setMapping(action, filepath);
connect(action, SIGNAL(triggered()), mapper_, SLOT(map())); connect(action, SIGNAL(triggered()), mapper_, SLOT(map()));

View File

@ -183,21 +183,21 @@ class RichTextEditor : public QTextEdit
public: public:
RichTextEditor(QWidget *parent = nullptr); RichTextEditor(QWidget *parent = nullptr);
void setDefaultFont(QFont font); void setDefaultFont(QFont font);
QToolBar *createToolBar(QWidget *parent = nullptr); QToolBar *createToolBar(QWidget *parent = nullptr);
bool simplifyRichText() const { return m_simplifyRichText; } bool simplifyRichText() const { return m_simplifyRichText; }
public slots: public slots:
void setFontBold(bool b); void setFontBold(bool b);
void setFontPointSize(double); void setFontPointSize(double);
void setText(const QString &text); void setText(const QString &text);
void setSimplifyRichText(bool v); void setSimplifyRichText(bool v);
QString text(Qt::TextFormat format) const; QString text(Qt::TextFormat format) const;
signals: signals:
void stateChanged(); void stateChanged();
void simplifyRichTextChanged(bool); void simplifyRichTextChanged(bool);
private: private:
bool m_simplifyRichText; bool m_simplifyRichText;
}; };
@ -205,16 +205,16 @@ class RichTextEditor : public QTextEdit
class AddLinkDialog : public QDialog class AddLinkDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
AddLinkDialog(RichTextEditor *editor, QWidget *parent = nullptr); AddLinkDialog(RichTextEditor *editor, QWidget *parent = nullptr);
~AddLinkDialog() override; ~AddLinkDialog() override;
int showDialog(); int showDialog();
public slots: public slots:
void accept() override; void accept() override;
private: private:
RichTextEditor *m_editor; RichTextEditor *m_editor;
Ui::AddLinkDialog *m_ui; Ui::AddLinkDialog *m_ui;
@ -225,9 +225,9 @@ AddLinkDialog::AddLinkDialog(RichTextEditor *editor, QWidget *parent) :
m_ui(new Ui::AddLinkDialog) m_ui(new Ui::AddLinkDialog)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_editor = editor; m_editor = editor;
} }
@ -246,7 +246,7 @@ int AddLinkDialog::showDialog()
} else { } else {
m_ui->titleInput->setFocus(); m_ui->titleInput->setFocus();
} }
return exec(); return exec();
} }
@ -254,34 +254,34 @@ void AddLinkDialog::accept()
{ {
const QString title = m_ui->titleInput->text(); const QString title = m_ui->titleInput->text();
const QString url = m_ui->urlInput->text(); const QString url = m_ui->urlInput->text();
if (!title.isEmpty()) { if (!title.isEmpty()) {
QString html = QLatin1String("<a href=\""); QString html = QLatin1String("<a href=\"");
html += url; html += url;
html += QLatin1String("\">"); html += QLatin1String("\">");
html += title; html += title;
html += QLatin1String("</a>"); html += QLatin1String("</a>");
m_editor->insertHtml(html); m_editor->insertHtml(html);
} }
m_ui->titleInput->clear(); m_ui->titleInput->clear();
m_ui->urlInput->clear(); m_ui->urlInput->clear();
QDialog::accept(); QDialog::accept();
} }
class HtmlTextEdit : public QTextEdit class HtmlTextEdit : public QTextEdit
{ {
Q_OBJECT Q_OBJECT
public: public:
HtmlTextEdit(QWidget *parent = nullptr) HtmlTextEdit(QWidget *parent = nullptr)
: QTextEdit(parent) : QTextEdit(parent)
{} {}
void contextMenuEvent(QContextMenuEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override;
private slots: private slots:
void actionTriggered(QAction *action); void actionTriggered(QAction *action);
}; };
@ -290,12 +290,12 @@ void HtmlTextEdit::contextMenuEvent(QContextMenuEvent *event)
{ {
QMenu *menu = createStandardContextMenu(); QMenu *menu = createStandardContextMenu();
QMenu *htmlMenu = new QMenu(tr("Insert HTML entity"), menu); QMenu *htmlMenu = new QMenu(tr("Insert HTML entity"), menu);
typedef struct { typedef struct {
const char *text; const char *text;
const char *entity; const char *entity;
} Entry; } Entry;
const Entry entries[] = { const Entry entries[] = {
{ "&&amp; (&&)", "&amp;" }, { "&&amp; (&&)", "&amp;" },
{ "&&nbsp;", "&nbsp;" }, { "&&nbsp;", "&nbsp;" },
@ -304,14 +304,14 @@ void HtmlTextEdit::contextMenuEvent(QContextMenuEvent *event)
{ "&&copy; (Copyright)", "&copy;" }, { "&&copy; (Copyright)", "&copy;" },
{ "&&reg; (Trade Mark)", "&reg;" }, { "&&reg; (Trade Mark)", "&reg;" },
}; };
for (int i = 0; i < 6; ++i) { for (int i = 0; i < 6; ++i) {
QAction *entityAction = new QAction(QLatin1String(entries[i].text), QAction *entityAction = new QAction(QLatin1String(entries[i].text),
htmlMenu); htmlMenu);
entityAction->setData(QLatin1String(entries[i].entity)); entityAction->setData(QLatin1String(entries[i].entity));
htmlMenu->addAction(entityAction); htmlMenu->addAction(entityAction);
} }
menu->addMenu(htmlMenu); menu->addMenu(htmlMenu);
connect(htmlMenu, SIGNAL(triggered(QAction*)), connect(htmlMenu, SIGNAL(triggered(QAction*)),
SLOT(actionTriggered(QAction*))); SLOT(actionTriggered(QAction*)));
@ -327,19 +327,19 @@ void HtmlTextEdit::actionTriggered(QAction *action)
class ColorAction : public QAction class ColorAction : public QAction
{ {
Q_OBJECT Q_OBJECT
public: public:
ColorAction(QObject *parent); ColorAction(QObject *parent);
const QColor& color() const { return m_color; } const QColor& color() const { return m_color; }
void setColor(const QColor &color); void setColor(const QColor &color);
signals: signals:
void colorChanged(const QColor &color); void colorChanged(const QColor &color);
private slots: private slots:
void chooseColor(); void chooseColor();
private: private:
QColor m_color; QColor m_color;
}; };
@ -381,10 +381,10 @@ class RichTextEditorToolBar : public QToolBar
public: public:
RichTextEditorToolBar(RichTextEditor *editor, RichTextEditorToolBar(RichTextEditor *editor,
QWidget *parent = nullptr); QWidget *parent = nullptr);
public slots: public slots:
void updateActions(); void updateActions();
private slots: private slots:
void alignmentActionTriggered(QAction *action); void alignmentActionTriggered(QAction *action);
void sizeInputActivated(const QString &size); void sizeInputActivated(const QString &size);
@ -393,8 +393,8 @@ class RichTextEditorToolBar : public QToolBar
void setVAlignSub(bool sub); void setVAlignSub(bool sub);
void insertLink(); void insertLink();
void insertImage(); void insertImage();
private: private:
QAction *m_bold_action; QAction *m_bold_action;
QAction *m_italic_action; QAction *m_italic_action;
@ -410,7 +410,7 @@ class RichTextEditorToolBar : public QToolBar
QAction *m_simplify_richtext_action; QAction *m_simplify_richtext_action;
ColorAction *m_color_action; ColorAction *m_color_action;
QComboBox *m_font_size_input; QComboBox *m_font_size_input;
QPointer<RichTextEditor> m_editor; QPointer<RichTextEditor> m_editor;
}; };
@ -437,106 +437,106 @@ RichTextEditorToolBar::RichTextEditorToolBar(RichTextEditor *editor,
m_font_size_input(new QComboBox), m_font_size_input(new QComboBox),
m_editor(editor) m_editor(editor)
{ {
// Font size combo box // Font size combo box
m_font_size_input->setEditable(false); m_font_size_input->setEditable(false);
const QList<int> font_sizes = QFontDatabase::standardSizes(); const QList<int> font_sizes = QFontDatabase::standardSizes();
foreach (int font_size, font_sizes) foreach (int font_size, font_sizes)
m_font_size_input->addItem(QString::number(font_size)); m_font_size_input->addItem(QString::number(font_size));
connect(m_font_size_input, SIGNAL(activated(QString)), connect(m_font_size_input, SIGNAL(activated(QString)),
this, SLOT(sizeInputActivated(QString))); this, SLOT(sizeInputActivated(QString)));
addWidget(m_font_size_input); addWidget(m_font_size_input);
// Bold, italic and underline buttons // Bold, italic and underline buttons
m_bold_action = createCheckableAction( m_bold_action = createCheckableAction(
QIcon(":/ico/32x32/format-text-bold.png"), QIcon(":/ico/32x32/format-text-bold.png"),
tr("Texte en gras"), editor, SLOT(setFontBold(bool)), this); tr("Texte en gras"), editor, SLOT(setFontBold(bool)), this);
m_bold_action->setShortcut(tr("CTRL+B")); m_bold_action->setShortcut(tr("CTRL+B"));
addAction(m_bold_action); addAction(m_bold_action);
m_italic_action = createCheckableAction( m_italic_action = createCheckableAction(
QIcon(":/ico/32x32/format-text-italic.png"), QIcon(":/ico/32x32/format-text-italic.png"),
tr("Texte en italique"), editor, SLOT(setFontItalic(bool)), this); tr("Texte en italique"), editor, SLOT(setFontItalic(bool)), this);
m_italic_action->setShortcut(tr("CTRL+I")); m_italic_action->setShortcut(tr("CTRL+I"));
addAction(m_italic_action); addAction(m_italic_action);
m_underline_action = createCheckableAction( m_underline_action = createCheckableAction(
QIcon(":/ico/32x32/format-text-underline.png"), QIcon(":/ico/32x32/format-text-underline.png"),
tr("Texte souligé"), editor, SLOT(setFontUnderline(bool)), this); tr("Texte souligé"), editor, SLOT(setFontUnderline(bool)), this);
m_underline_action->setShortcut(tr("CTRL+U")); m_underline_action->setShortcut(tr("CTRL+U"));
addAction(m_underline_action); addAction(m_underline_action);
// Left, center, right and justified alignment buttons // Left, center, right and justified alignment buttons
QActionGroup *alignment_group = new QActionGroup(this); QActionGroup *alignment_group = new QActionGroup(this);
connect(alignment_group, SIGNAL(triggered(QAction*)), connect(alignment_group, SIGNAL(triggered(QAction*)),
SLOT(alignmentActionTriggered(QAction*))); SLOT(alignmentActionTriggered(QAction*)));
m_align_left_action = createCheckableAction( m_align_left_action = createCheckableAction(
QIcon(), QIcon(),
tr("Left Align"), editor, nullptr, alignment_group); tr("Left Align"), editor, nullptr, alignment_group);
addAction(m_align_left_action); addAction(m_align_left_action);
m_align_center_action = createCheckableAction( m_align_center_action = createCheckableAction(
QIcon(), QIcon(),
tr("Center"), editor, nullptr, alignment_group); tr("Center"), editor, nullptr, alignment_group);
addAction(m_align_center_action); addAction(m_align_center_action);
m_align_right_action = createCheckableAction( m_align_right_action = createCheckableAction(
QIcon(), QIcon(),
tr("Right Align"), editor, nullptr, alignment_group); tr("Right Align"), editor, nullptr, alignment_group);
addAction(m_align_right_action); addAction(m_align_right_action);
m_align_justify_action = createCheckableAction( m_align_justify_action = createCheckableAction(
QIcon(), QIcon(),
tr("Justify"), editor, nullptr, alignment_group); tr("Justify"), editor, nullptr, alignment_group);
addAction(m_align_justify_action); addAction(m_align_justify_action);
m_align_justify_action -> setVisible( false ); m_align_justify_action -> setVisible( false );
m_align_center_action -> setVisible( false ); m_align_center_action -> setVisible( false );
m_align_left_action -> setVisible( false ); m_align_left_action -> setVisible( false );
m_align_right_action -> setVisible( false ); m_align_right_action -> setVisible( false );
// Superscript and subscript buttons // Superscript and subscript buttons
m_valign_sup_action = createCheckableAction( m_valign_sup_action = createCheckableAction(
QIcon(":/ico/22x22/format-text-superscript.png"), QIcon(":/ico/22x22/format-text-superscript.png"),
tr("Superscript"), tr("Superscript"),
this, SLOT(setVAlignSuper(bool)), this); this, SLOT(setVAlignSuper(bool)), this);
addAction(m_valign_sup_action); addAction(m_valign_sup_action);
m_valign_sub_action = createCheckableAction( m_valign_sub_action = createCheckableAction(
QIcon(":/ico/22x22/format-text-subscript.png"), QIcon(":/ico/22x22/format-text-subscript.png"),
tr("Subscript"), tr("Subscript"),
this, SLOT(setVAlignSub(bool)), this); this, SLOT(setVAlignSub(bool)), this);
addAction(m_valign_sub_action); addAction(m_valign_sub_action);
m_valign_sup_action -> setVisible( true ); m_valign_sup_action -> setVisible( true );
m_valign_sub_action -> setVisible( true ); m_valign_sub_action -> setVisible( true );
// Insert hyperlink and image buttons // Insert hyperlink and image buttons
m_link_action->setText(tr("Insérer un lien")); m_link_action->setText(tr("Insérer un lien"));
connect(m_link_action, SIGNAL(triggered()), SLOT(insertLink())); connect(m_link_action, SIGNAL(triggered()), SLOT(insertLink()));
addAction(m_link_action); addAction(m_link_action);
m_image_action->setText(tr("Insert &Image")); m_image_action->setText(tr("Insert &Image"));
connect(m_image_action, SIGNAL(triggered()), SLOT(insertImage())); connect(m_image_action, SIGNAL(triggered()), SLOT(insertImage()));
addAction(m_image_action); addAction(m_image_action);
m_image_action -> setVisible( false ); m_image_action -> setVisible( false );
addSeparator(); addSeparator();
// Text color button // Text color button
connect(m_color_action, SIGNAL(colorChanged(QColor)), connect(m_color_action, SIGNAL(colorChanged(QColor)),
this, SLOT(colorChanged(QColor))); this, SLOT(colorChanged(QColor)));
addAction(m_color_action); addAction(m_color_action);
// Simplify rich text // Simplify rich text
m_simplify_richtext_action = createCheckableAction( m_simplify_richtext_action = createCheckableAction(
QIcon(":/ico/32x32/simplifyrichtext.png"), QIcon(":/ico/32x32/simplifyrichtext.png"),
@ -545,17 +545,17 @@ RichTextEditorToolBar::RichTextEditorToolBar(RichTextEditor *editor,
connect(m_editor, SIGNAL(simplifyRichTextChanged(bool)), connect(m_editor, SIGNAL(simplifyRichTextChanged(bool)),
m_simplify_richtext_action, SLOT(setChecked(bool))); m_simplify_richtext_action, SLOT(setChecked(bool)));
addAction(m_simplify_richtext_action); addAction(m_simplify_richtext_action);
connect(editor, SIGNAL(textChanged()), this, SLOT(updateActions())); connect(editor, SIGNAL(textChanged()), this, SLOT(updateActions()));
connect(editor, SIGNAL(stateChanged()), this, SLOT(updateActions())); connect(editor, SIGNAL(stateChanged()), this, SLOT(updateActions()));
updateActions(); updateActions();
} }
void RichTextEditorToolBar::alignmentActionTriggered(QAction *action) void RichTextEditorToolBar::alignmentActionTriggered(QAction *action)
{ {
Qt::Alignment new_alignment; Qt::Alignment new_alignment;
if (action == m_align_left_action) { if (action == m_align_left_action) {
new_alignment = Qt::AlignLeft; new_alignment = Qt::AlignLeft;
} else if (action == m_align_center_action) { } else if (action == m_align_center_action) {
@ -565,7 +565,7 @@ void RichTextEditorToolBar::alignmentActionTriggered(QAction *action)
} else { } else {
new_alignment = Qt::AlignJustify; new_alignment = Qt::AlignJustify;
} }
m_editor->setAlignment(new_alignment); m_editor->setAlignment(new_alignment);
} }
@ -583,7 +583,7 @@ void RichTextEditorToolBar::sizeInputActivated(const QString &size)
int i = size.toInt(&ok); int i = size.toInt(&ok);
if (!ok) if (!ok)
return; return;
m_editor->setFontPointSize(i); m_editor->setFontPointSize(i);
m_editor->setFocus(); m_editor->setFocus();
} }
@ -592,11 +592,11 @@ void RichTextEditorToolBar::setVAlignSuper(bool super)
{ {
const QTextCharFormat::VerticalAlignment align = super ? const QTextCharFormat::VerticalAlignment align = super ?
QTextCharFormat::AlignSuperScript : QTextCharFormat::AlignNormal; QTextCharFormat::AlignSuperScript : QTextCharFormat::AlignNormal;
QTextCharFormat charFormat = m_editor->currentCharFormat(); QTextCharFormat charFormat = m_editor->currentCharFormat();
charFormat.setVerticalAlignment(align); charFormat.setVerticalAlignment(align);
m_editor->setCurrentCharFormat(charFormat); m_editor->setCurrentCharFormat(charFormat);
m_valign_sub_action->setChecked(false); m_valign_sub_action->setChecked(false);
} }
@ -604,11 +604,11 @@ void RichTextEditorToolBar::setVAlignSub(bool sub)
{ {
const QTextCharFormat::VerticalAlignment align = sub ? const QTextCharFormat::VerticalAlignment align = sub ?
QTextCharFormat::AlignSubScript : QTextCharFormat::AlignNormal; QTextCharFormat::AlignSubScript : QTextCharFormat::AlignNormal;
QTextCharFormat charFormat = m_editor->currentCharFormat(); QTextCharFormat charFormat = m_editor->currentCharFormat();
charFormat.setVerticalAlignment(align); charFormat.setVerticalAlignment(align);
m_editor->setCurrentCharFormat(charFormat); m_editor->setCurrentCharFormat(charFormat);
m_valign_sup_action->setChecked(false); m_valign_sup_action->setChecked(false);
} }
@ -634,7 +634,7 @@ void RichTextEditorToolBar::updateActions()
setEnabled(false); setEnabled(false);
return; return;
} }
const Qt::Alignment alignment = m_editor->alignment(); const Qt::Alignment alignment = m_editor->alignment();
const QTextCursor cursor = m_editor->textCursor(); const QTextCursor cursor = m_editor->textCursor();
const QTextCharFormat charFormat = cursor.charFormat(); const QTextCharFormat charFormat = cursor.charFormat();
@ -643,7 +643,7 @@ void RichTextEditorToolBar::updateActions()
charFormat.verticalAlignment(); charFormat.verticalAlignment();
const bool superScript = valign == QTextCharFormat::AlignSuperScript; const bool superScript = valign == QTextCharFormat::AlignSuperScript;
const bool subScript = valign == QTextCharFormat::AlignSubScript; const bool subScript = valign == QTextCharFormat::AlignSubScript;
if (alignment & Qt::AlignLeft) { if (alignment & Qt::AlignLeft) {
m_align_left_action->setChecked(true); m_align_left_action->setChecked(true);
} else if (alignment & Qt::AlignRight) { } else if (alignment & Qt::AlignRight) {
@ -653,18 +653,18 @@ void RichTextEditorToolBar::updateActions()
} else { } else {
m_align_justify_action->setChecked(true); m_align_justify_action->setChecked(true);
} }
m_bold_action->setChecked(font.bold()); m_bold_action->setChecked(font.bold());
m_italic_action->setChecked(font.italic()); m_italic_action->setChecked(font.italic());
m_underline_action->setChecked(font.underline()); m_underline_action->setChecked(font.underline());
m_valign_sup_action->setChecked(superScript); m_valign_sup_action->setChecked(superScript);
m_valign_sub_action->setChecked(subScript); m_valign_sub_action->setChecked(subScript);
const int size = font.pointSize(); const int size = font.pointSize();
const int idx = m_font_size_input->findText(QString::number(size)); const int idx = m_font_size_input->findText(QString::number(size));
if (idx != -1) if (idx != -1)
m_font_size_input->setCurrentIndex(idx); m_font_size_input->setCurrentIndex(idx);
m_color_action->setColor(m_editor->textColor()); m_color_action->setColor(m_editor->textColor());
} }
@ -720,7 +720,7 @@ void RichTextEditor::setDefaultFont(QFont font)
if (pointSize > 0 && !qFuzzyCompare(qreal(pointSize), font.pointSizeF())) { if (pointSize > 0 && !qFuzzyCompare(qreal(pointSize), font.pointSizeF())) {
font.setPointSize(pointSize); font.setPointSize(pointSize);
} }
document()->setDefaultFont(font); document()->setDefaultFont(font);
if (font.pointSize() > 0) if (font.pointSize() > 0)
setFontPointSize(font.pointSize()); setFontPointSize(font.pointSize());
@ -740,7 +740,9 @@ QString RichTextEditor::text(Qt::TextFormat format) const
break; break;
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
case Qt::MarkdownText: //This enum value was added in Qt 5.14. case Qt::MarkdownText: //This enum value was added in Qt 5.14.
break; break;
#endif #endif
@ -765,32 +767,32 @@ RichTextEditorDialog::RichTextEditorDialog(QWidget *parent) :
{ {
setWindowTitle(tr("Edit text")); setWindowTitle(tr("Edit text"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_text_edit->setAcceptRichText(false); m_text_edit->setAcceptRichText(false);
connect(m_editor, SIGNAL(textChanged()), this, SLOT(richTextChanged())); connect(m_editor, SIGNAL(textChanged()), this, SLOT(richTextChanged()));
connect(m_editor, SIGNAL(simplifyRichTextChanged(bool)), this, SLOT(richTextChanged())); connect(m_editor, SIGNAL(simplifyRichTextChanged(bool)), this, SLOT(richTextChanged()));
connect(m_text_edit, SIGNAL(textChanged()), this, SLOT(sourceChanged())); connect(m_text_edit, SIGNAL(textChanged()), this, SLOT(sourceChanged()));
// The toolbar needs to be created after the RichTextEditor // The toolbar needs to be created after the RichTextEditor
QToolBar *tool_bar = m_editor->createToolBar(); QToolBar *tool_bar = m_editor->createToolBar();
tool_bar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); tool_bar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
QWidget *rich_edit = new QWidget; QWidget *rich_edit = new QWidget;
QVBoxLayout *rich_edit_layout = new QVBoxLayout(rich_edit); QVBoxLayout *rich_edit_layout = new QVBoxLayout(rich_edit);
rich_edit_layout->addWidget(tool_bar); rich_edit_layout->addWidget(tool_bar);
rich_edit_layout->addWidget(m_editor); rich_edit_layout->addWidget(m_editor);
QWidget *plain_edit = new QWidget; QWidget *plain_edit = new QWidget;
QVBoxLayout *plain_edit_layout = new QVBoxLayout(plain_edit); QVBoxLayout *plain_edit_layout = new QVBoxLayout(plain_edit);
plain_edit_layout->addWidget(m_text_edit); plain_edit_layout->addWidget(m_text_edit);
m_tab_widget->setTabPosition(QTabWidget::South); m_tab_widget->setTabPosition(QTabWidget::South);
m_tab_widget->addTab(rich_edit, tr("Rich Text")); m_tab_widget->addTab(rich_edit, tr("Rich Text"));
m_tab_widget->addTab(plain_edit, tr("Source")); m_tab_widget->addTab(plain_edit, tr("Source"));
connect(m_tab_widget, SIGNAL(currentChanged(int)), connect(m_tab_widget, SIGNAL(currentChanged(int)),
SLOT(tabIndexChanged(int))); SLOT(tabIndexChanged(int)));
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal);
QPushButton *ok_button = buttonBox->button(QDialogButtonBox::Ok); QPushButton *ok_button = buttonBox->button(QDialogButtonBox::Ok);
ok_button->setText(tr("&OK")); ok_button->setText(tr("&OK"));
@ -798,13 +800,13 @@ RichTextEditorDialog::RichTextEditorDialog(QWidget *parent) :
buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("&Cancel")); buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("&Cancel"));
connect(buttonBox, SIGNAL(accepted()), this, SLOT(on_buttonBox_accepted())); connect(buttonBox, SIGNAL(accepted()), this, SLOT(on_buttonBox_accepted()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QVBoxLayout *layout = new QVBoxLayout(this); QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(m_tab_widget); layout->addWidget(m_tab_widget);
layout->addWidget(buttonBox); layout->addWidget(buttonBox);
m_editor->setFocus(); m_editor->setFocus();
} }
RichTextEditorDialog::~RichTextEditorDialog() RichTextEditorDialog::~RichTextEditorDialog()
@ -826,7 +828,7 @@ int RichTextEditorDialog::showDialog()
m_tab_widget->setCurrentIndex(0); m_tab_widget->setCurrentIndex(0);
m_editor->selectAll(); m_editor->selectAll();
m_editor->setFocus(); m_editor->setFocus();
return exec(); return exec();
} }
@ -869,14 +871,14 @@ void RichTextEditorDialog::tabIndexChanged(int newIndex)
// Remember the cursor position, since it is invalidated by setPlainText // Remember the cursor position, since it is invalidated by setPlainText
QTextEdit *new_edit = (newIndex == SourceIndex) ? m_text_edit : m_editor; QTextEdit *new_edit = (newIndex == SourceIndex) ? m_text_edit : m_editor;
const int position = new_edit->textCursor().position(); const int position = new_edit->textCursor().position();
if (newIndex == SourceIndex) { if (newIndex == SourceIndex) {
const QString html = m_editor->text(Qt::RichText); const QString html = m_editor->text(Qt::RichText);
m_text_edit->setPlainText(html); m_text_edit->setPlainText(html);
} else } else
m_editor->setHtml(m_text_edit->toPlainText()); m_editor->setHtml(m_text_edit->toPlainText());
QTextCursor cursor = new_edit->textCursor(); QTextCursor cursor = new_edit->textCursor();
cursor.movePosition(QTextCursor::End); cursor.movePosition(QTextCursor::End);
if (cursor.position() > position) { if (cursor.position() > position) {

View File

@ -210,6 +210,9 @@ bool QETTitleBlockTemplateEditor::edit(
} }
if (!tb_template_orig) { if (!tb_template_orig) {
/// TODO The TBT does not exist, manage error /// TODO The TBT does not exist, manage error
#if TODO_LIST
#pragma message("@TODO The TBT does not exist, manage error")
#endif
return(false); return(false);
} }
@ -247,6 +250,9 @@ bool QETTitleBlockTemplateEditor::edit(
if (!tb_template_orig) { if (!tb_template_orig) {
/// TODO The TBT does not exist, manage error /// TODO The TBT does not exist, manage error
#if TODO_LIST
#pragma message("@TODO The TBT does not exist, manage error")
#endif
return(false); return(false);
} }
@ -267,12 +273,18 @@ bool QETTitleBlockTemplateEditor::edit(const QString &file_path)
TitleBlockTemplate *tbt = new TitleBlockTemplate(); TitleBlockTemplate *tbt = new TitleBlockTemplate();
bool loading = tbt -> loadFromXmlFile(file_path); bool loading = tbt -> loadFromXmlFile(file_path);
if (!loading) { if (!loading) {
#if TODO_LIST
#pragma message("@TODO the file opening failed, warn the user?")
#endif
/// TODO the file opening failed, warn the user? /// TODO the file opening failed, warn the user?
return(false); return(false);
} }
bool editing = edit(tbt); bool editing = edit(tbt);
if (!editing) { if (!editing) {
#if TODO_LIST
#pragma message("@TODO the file editing failed, warn the user?")
#endif
/// TODO the file editing failed, warn the user? /// TODO the file editing failed, warn the user?
return(false); return(false);
} }

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -35,17 +35,20 @@ class QETProject;
*/ */
class QETTitleBlockTemplateEditor : public QETMainWindow { class QETTitleBlockTemplateEditor : public QETMainWindow {
Q_OBJECT Q_OBJECT
// constructor, destructor // constructor, destructor
public: public:
QETTitleBlockTemplateEditor(QWidget * = nullptr); QETTitleBlockTemplateEditor(QWidget * = nullptr);
~QETTitleBlockTemplateEditor() override; ~QETTitleBlockTemplateEditor() override;
private: private:
QETTitleBlockTemplateEditor(const QETTitleBlockTemplateEditor &); QETTitleBlockTemplateEditor(const QETTitleBlockTemplateEditor &);
// attributes // attributes
private: private:
/// menus TODO /// menus TODO
#if TODO_LIST
#pragma message("@TODO menus")
#endif
QMenu *file_menu_, *edit_menu_, *display_menu_; QMenu *file_menu_, *edit_menu_, *display_menu_;
/// actions /// actions
QAction *new_, *open_, *open_from_file_, *save_, *save_as_, *save_as_file_, *quit_; QAction *new_, *open_, *open_from_file_, *save_, *save_as_, *save_as_file_, *quit_;
@ -80,19 +83,19 @@ class QETTitleBlockTemplateEditor : public QETMainWindow {
QUndoStack *undo_stack_; QUndoStack *undo_stack_;
QUndoView *undo_view_; QUndoView *undo_view_;
QDockWidget *undo_dock_widget_; QDockWidget *undo_dock_widget_;
// methods // methods
public: public:
TitleBlockTemplateLocation location() const; TitleBlockTemplateLocation location() const;
bool isEditing(const QString &ilepath); bool isEditing(const QString &ilepath);
void setOpenForDuplication(bool); void setOpenForDuplication(bool);
bool openForDuplication() const; bool openForDuplication() const;
protected: protected:
bool canClose(); bool canClose();
void firstActivation(QEvent *) override; void firstActivation(QEvent *) override;
void closeEvent(QCloseEvent *) override; void closeEvent(QCloseEvent *) override;
private: private:
void initActions(); void initActions();
void initMenus(); void initMenus();
@ -100,7 +103,7 @@ class QETTitleBlockTemplateEditor : public QETMainWindow {
void initWidgets(); void initWidgets();
void initLogoManager(); void initLogoManager();
QString currentlyEditedTitle() const; QString currentlyEditedTitle() const;
public slots: public slots:
void readSettings(); void readSettings();
void writeSettings(); void writeSettings();
@ -122,7 +125,7 @@ class QETTitleBlockTemplateEditor : public QETMainWindow {
void quit(); void quit();
void savePreviewWidthToApplicationSettings(int, int); void savePreviewWidthToApplicationSettings(int, int);
void editTemplateInformation(); void editTemplateInformation();
private slots: private slots:
TitleBlockTemplateLocation getTitleBlockTemplateLocationFromUser(const QString & = QString(), bool existing_only = true); TitleBlockTemplateLocation getTitleBlockTemplateLocationFromUser(const QString & = QString(), bool existing_only = true);
void pushCellUndoCommand(ModifyTitleBlockCellCommand *); void pushCellUndoCommand(ModifyTitleBlockCellCommand *);

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -48,10 +48,10 @@ TitleBlockTemplateLogoManager::~TitleBlockTemplateLogoManager()
QString TitleBlockTemplateLogoManager::currentLogo() const QString TitleBlockTemplateLogoManager::currentLogo() const
{ {
if (!managed_template_) return QString(); if (!managed_template_) return QString();
QListWidgetItem *current_item = logos_view_ -> currentItem(); QListWidgetItem *current_item = logos_view_ -> currentItem();
if (!current_item) return QString(); if (!current_item) return QString();
return(current_item -> text()); return(current_item -> text());
} }
@ -78,7 +78,7 @@ void TitleBlockTemplateLogoManager::emitLogosChangedSignal()
void TitleBlockTemplateLogoManager::initWidgets() void TitleBlockTemplateLogoManager::initWidgets()
{ {
open_dialog_dir_.setPath(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); open_dialog_dir_.setPath(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
setWindowTitle(tr("Gestionnaire de logos")); setWindowTitle(tr("Gestionnaire de logos"));
setWindowIcon(QET::Icons::InsertImage); setWindowIcon(QET::Icons::InsertImage);
setWindowFlags(Qt::Dialog); setWindowFlags(Qt::Dialog);
@ -100,21 +100,21 @@ void TitleBlockTemplateLogoManager::initWidgets()
rename_button_ = new QPushButton(QET::Icons::EditRename, tr("Renommer")); rename_button_ = new QPushButton(QET::Icons::EditRename, tr("Renommer"));
logo_type_ = new QLabel(tr("Type :")); logo_type_ = new QLabel(tr("Type :"));
buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok); buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok);
hlayout1_ = new QHBoxLayout(); hlayout1_ = new QHBoxLayout();
hlayout1_ -> addWidget(logo_name_label_); hlayout1_ -> addWidget(logo_name_label_);
hlayout1_ -> addWidget(logo_name_); hlayout1_ -> addWidget(logo_name_);
hlayout1_ -> addWidget(rename_button_); hlayout1_ -> addWidget(rename_button_);
hlayout0_ = new QHBoxLayout(); hlayout0_ = new QHBoxLayout();
hlayout0_ -> addWidget(export_button_); hlayout0_ -> addWidget(export_button_);
hlayout0_ -> addWidget(delete_button_); hlayout0_ -> addWidget(delete_button_);
vlayout1_ = new QVBoxLayout(); vlayout1_ = new QVBoxLayout();
vlayout1_ -> addLayout(hlayout1_); vlayout1_ -> addLayout(hlayout1_);
vlayout1_ -> addWidget(logo_type_); vlayout1_ -> addWidget(logo_type_);
logo_box_ -> setLayout(vlayout1_); logo_box_ -> setLayout(vlayout1_);
vlayout0_ = new QVBoxLayout(); vlayout0_ = new QVBoxLayout();
vlayout0_ -> addWidget(logos_label_); vlayout0_ -> addWidget(logos_label_);
vlayout0_ -> addWidget(logos_view_); vlayout0_ -> addWidget(logos_view_);
@ -122,7 +122,7 @@ void TitleBlockTemplateLogoManager::initWidgets()
vlayout0_ -> addLayout(hlayout0_); vlayout0_ -> addLayout(hlayout0_);
vlayout0_ -> addWidget(logo_box_); vlayout0_ -> addWidget(logo_box_);
setLayout(vlayout0_); setLayout(vlayout0_);
connect( connect(
logos_view_, logos_view_,
SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)),
@ -142,7 +142,7 @@ void TitleBlockTemplateLogoManager::fillView()
{ {
if (!managed_template_) return; if (!managed_template_) return;
logos_view_ -> clear(); logos_view_ -> clear();
foreach (QString logo_name, managed_template_ -> logos()) { foreach (QString logo_name, managed_template_ -> logos()) {
QIcon current_icon; QIcon current_icon;
QPixmap current_logo = managed_template_ -> bitmapLogo(logo_name); QPixmap current_logo = managed_template_ -> bitmapLogo(logo_name);
@ -164,7 +164,7 @@ void TitleBlockTemplateLogoManager::fillView()
qlwi -> setTextAlignment(Qt::AlignBottom | Qt::AlignHCenter); qlwi -> setTextAlignment(Qt::AlignBottom | Qt::AlignHCenter);
logos_view_ -> insertItem(0, qlwi); logos_view_ -> insertItem(0, qlwi);
} }
QListWidgetItem *current_item = logos_view_ -> currentItem(); QListWidgetItem *current_item = logos_view_ -> currentItem();
updateLogoInformations(current_item, nullptr); updateLogoInformations(current_item, nullptr);
} }
@ -195,7 +195,7 @@ QString TitleBlockTemplateLogoManager::confirmLogoName(const QString &initial_na
if (!rename_dialog) { if (!rename_dialog) {
rename_dialog = new QDialog(this); rename_dialog = new QDialog(this);
rename_dialog -> setWindowTitle(tr("Logo déjà existant")); rename_dialog -> setWindowTitle(tr("Logo déjà existant"));
rd_label = new QLabel(); rd_label = new QLabel();
rd_label -> setWordWrap(true); rd_label -> setWordWrap(true);
rd_input = new QLineEdit(); rd_input = new QLineEdit();
@ -203,13 +203,13 @@ QString TitleBlockTemplateLogoManager::confirmLogoName(const QString &initial_na
QPushButton *replace_button = rd_buttons -> addButton(tr("Remplacer"), QDialogButtonBox::YesRole); QPushButton *replace_button = rd_buttons -> addButton(tr("Remplacer"), QDialogButtonBox::YesRole);
QPushButton *rename_button = rd_buttons -> addButton(tr("Renommer"), QDialogButtonBox::NoRole); QPushButton *rename_button = rd_buttons -> addButton(tr("Renommer"), QDialogButtonBox::NoRole);
QPushButton *cancel_button = rd_buttons -> addButton(QDialogButtonBox::Cancel); QPushButton *cancel_button = rd_buttons -> addButton(QDialogButtonBox::Cancel);
QVBoxLayout *rd_vlayout0 = new QVBoxLayout(); QVBoxLayout *rd_vlayout0 = new QVBoxLayout();
rd_vlayout0 -> addWidget(rd_label); rd_vlayout0 -> addWidget(rd_label);
rd_vlayout0 -> addWidget(rd_input); rd_vlayout0 -> addWidget(rd_input);
rd_vlayout0 -> addWidget(rd_buttons); rd_vlayout0 -> addWidget(rd_buttons);
rename_dialog -> setLayout(rd_vlayout0); rename_dialog -> setLayout(rd_vlayout0);
QSignalMapper *signal_mapper = new QSignalMapper(rename_dialog); QSignalMapper *signal_mapper = new QSignalMapper(rename_dialog);
signal_mapper -> setMapping(replace_button, QDialogButtonBox::YesRole); signal_mapper -> setMapping(replace_button, QDialogButtonBox::YesRole);
signal_mapper -> setMapping(rename_button, QDialogButtonBox::NoRole); signal_mapper -> setMapping(rename_button, QDialogButtonBox::NoRole);
@ -235,6 +235,9 @@ QString TitleBlockTemplateLogoManager::confirmLogoName(const QString &initial_na
} else if (answer == QDialogButtonBox::NoRole) { } else if (answer == QDialogButtonBox::NoRole) {
// the user provided another name // the user provided another name
name = rd_input -> text(); name = rd_input -> text();
#if TODO_LIST
#pragma message("@TODO prevent the user from entering an empty name")
#endif
/// TODO prevent the user from entering an empty name /// TODO prevent the user from entering an empty name
} else { } else {
// the user cancelled the operation // the user cancelled the operation
@ -271,7 +274,7 @@ void TitleBlockTemplateLogoManager::updateLogoInformations(QListWidgetItem *curr
void TitleBlockTemplateLogoManager::addLogo() void TitleBlockTemplateLogoManager::addLogo()
{ {
if (!managed_template_) return; if (!managed_template_) return;
QString filepath = QFileDialog::getOpenFileName( QString filepath = QFileDialog::getOpenFileName(
this, this,
tr("Choisir une image / un logo"), tr("Choisir une image / un logo"),
@ -279,18 +282,18 @@ void TitleBlockTemplateLogoManager::addLogo()
tr("Images vectorielles (*.svg);;Images bitmap (*.png *.jpg *.jpeg *.gif *.bmp *.xpm);;Tous les fichiers (*)") tr("Images vectorielles (*.svg);;Images bitmap (*.png *.jpg *.jpeg *.gif *.bmp *.xpm);;Tous les fichiers (*)")
); );
if (filepath.isEmpty()) return; if (filepath.isEmpty()) return;
// that filepath needs to point to a valid, readable file // that filepath needs to point to a valid, readable file
QFileInfo filepath_info(filepath); QFileInfo filepath_info(filepath);
if (!filepath_info.exists() || !filepath_info.isReadable()) { if (!filepath_info.exists() || !filepath_info.isReadable()) {
QMessageBox::critical(this, tr("Erreur"), tr("Impossible d'ouvrir le fichier spécifié")); QMessageBox::critical(this, tr("Erreur"), tr("Impossible d'ouvrir le fichier spécifié"));
return; return;
} }
// ensure we can use the file name to add the logo // ensure we can use the file name to add the logo
QString logo_name = confirmLogoName(filepath_info.fileName()); QString logo_name = confirmLogoName(filepath_info.fileName());
if (logo_name.isNull()) return; if (logo_name.isNull()) return;
open_dialog_dir_ = QDir(filepath); open_dialog_dir_ = QDir(filepath);
if (managed_template_ -> addLogoFromFile(filepath, logo_name)) { if (managed_template_ -> addLogoFromFile(filepath, logo_name)) {
fillView(); fillView();
@ -305,7 +308,7 @@ void TitleBlockTemplateLogoManager::exportLogo()
{ {
QString current_logo = currentLogo(); QString current_logo = currentLogo();
if (current_logo.isNull()) return; if (current_logo.isNull()) return;
QString filepath = QFileDialog::getSaveFileName( QString filepath = QFileDialog::getSaveFileName(
this, this,
tr("Choisir un fichier pour exporter ce logo"), tr("Choisir un fichier pour exporter ce logo"),
@ -313,7 +316,7 @@ void TitleBlockTemplateLogoManager::exportLogo()
tr("Tous les fichiers (*);;Images vectorielles (*.svg);;Images bitmap (*.png *.jpg *.jpeg *.gif *.bmp *.xpm)") tr("Tous les fichiers (*);;Images vectorielles (*.svg);;Images bitmap (*.png *.jpg *.jpeg *.gif *.bmp *.xpm)")
); );
if (filepath.isEmpty()) return; if (filepath.isEmpty()) return;
bool save_logo = managed_template_ -> saveLogoToFile(current_logo, filepath); bool save_logo = managed_template_ -> saveLogoToFile(current_logo, filepath);
if (!save_logo) { if (!save_logo) {
QMessageBox::critical(this, tr("Erreur"), QString(tr("Impossible d'exporter vers le fichier spécifié"))); QMessageBox::critical(this, tr("Erreur"), QString(tr("Impossible d'exporter vers le fichier spécifié")));
@ -329,7 +332,7 @@ void TitleBlockTemplateLogoManager::removeLogo()
{ {
QString current_logo = currentLogo(); QString current_logo = currentLogo();
if (current_logo.isNull()) return; if (current_logo.isNull()) return;
if (managed_template_ -> removeLogo(current_logo)) { if (managed_template_ -> removeLogo(current_logo)) {
fillView(); fillView();
emitLogosChangedSignal(); emitLogosChangedSignal();
@ -343,7 +346,7 @@ void TitleBlockTemplateLogoManager::renameLogo()
{ {
QString current_logo = currentLogo(); QString current_logo = currentLogo();
if (current_logo.isNull()) return; if (current_logo.isNull()) return;
QString entered_name = logo_name_ -> text(); QString entered_name = logo_name_ -> text();
QString warning_title = tr("Renommer un logo"); QString warning_title = tr("Renommer un logo");
if (entered_name == current_logo) { if (entered_name == current_logo) {
@ -354,7 +357,7 @@ void TitleBlockTemplateLogoManager::renameLogo()
); );
return; return;
} }
if (entered_name.trimmed().isEmpty()) { if (entered_name.trimmed().isEmpty()) {
QMessageBox::warning( QMessageBox::warning(
this, this,
@ -363,7 +366,7 @@ void TitleBlockTemplateLogoManager::renameLogo()
); );
return; return;
} }
if (managed_template_ -> logos().contains(entered_name)) { if (managed_template_ -> logos().contains(entered_name)) {
QMessageBox::warning( QMessageBox::warning(
this, this,
@ -372,7 +375,7 @@ void TitleBlockTemplateLogoManager::renameLogo()
); );
return; return;
} }
if (managed_template_ -> renameLogo(current_logo, entered_name)) { if (managed_template_ -> renameLogo(current_logo, entered_name)) {
fillView(); fillView();
emitLogosChangedSignal(); emitLogosChangedSignal();
@ -386,7 +389,7 @@ void TitleBlockTemplateLogoManager::renameLogo()
void TitleBlockTemplateLogoManager::setReadOnly(bool read_only) { void TitleBlockTemplateLogoManager::setReadOnly(bool read_only) {
if (read_only_ == read_only) return; if (read_only_ == read_only) return;
read_only_ = read_only; read_only_ = read_only;
add_button_ -> setEnabled(!read_only_); add_button_ -> setEnabled(!read_only_);
delete_button_ -> setEnabled(!read_only_); delete_button_ -> setEnabled(!read_only_);
rename_button_ -> setEnabled(!read_only_); rename_button_ -> setEnabled(!read_only_);

View File

@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -148,7 +148,7 @@ QList<TitleBlockCell *> TitleBlockTemplateView::cut()
{ {
if (!tbtemplate_) return(QList<TitleBlockCell *>()); if (!tbtemplate_) return(QList<TitleBlockCell *>());
QList<TitleBlockCell *> copied_cells = copy(); QList<TitleBlockCell *> copied_cells = copy();
if (!copied_cells.isEmpty()) { if (!copied_cells.isEmpty()) {
CutTemplateCellsCommand *cut_command = new CutTemplateCellsCommand(tbtemplate_); CutTemplateCellsCommand *cut_command = new CutTemplateCellsCommand(tbtemplate_);
cut_command -> setCutCells(copied_cells); cut_command -> setCutCells(copied_cells);
@ -165,7 +165,7 @@ QList<TitleBlockCell *> TitleBlockTemplateView::copy()
{ {
if (!tbtemplate_) return(QList<TitleBlockCell *>()); if (!tbtemplate_) return(QList<TitleBlockCell *>());
QList<TitleBlockCell *> copied_cells = selectedCells(); QList<TitleBlockCell *> copied_cells = selectedCells();
QDomDocument xml_export; QDomDocument xml_export;
QDomElement tbtpartial = xml_export.createElement("titleblocktemplate-partial"); QDomElement tbtpartial = xml_export.createElement("titleblocktemplate-partial");
xml_export.appendChild(tbtpartial); xml_export.appendChild(tbtpartial);
@ -176,10 +176,10 @@ QList<TitleBlockCell *> TitleBlockTemplateView::copy()
tbtpartial.setAttribute("row_span", cell -> row_span); tbtpartial.setAttribute("row_span", cell -> row_span);
tbtpartial.setAttribute("col_span", cell -> col_span); tbtpartial.setAttribute("col_span", cell -> col_span);
} }
QClipboard *clipboard = QApplication::clipboard(); QClipboard *clipboard = QApplication::clipboard();
clipboard -> setText(xml_export.toString()); clipboard -> setText(xml_export.toString());
return(copied_cells); return(copied_cells);
} }
@ -199,20 +199,20 @@ bool TitleBlockTemplateView::mayPaste()
QList<TitleBlockCell> TitleBlockTemplateView::pastedCells() QList<TitleBlockCell> TitleBlockTemplateView::pastedCells()
{ {
QList<TitleBlockCell> pasted_cells; QList<TitleBlockCell> pasted_cells;
// retrieve the clipboard content and parse it as XML // retrieve the clipboard content and parse it as XML
QClipboard *clipboard = QApplication::clipboard(); QClipboard *clipboard = QApplication::clipboard();
QDomDocument xml_import; QDomDocument xml_import;
if (!xml_import.setContent(clipboard -> text().trimmed())) { if (!xml_import.setContent(clipboard -> text().trimmed())) {
return(pasted_cells); return(pasted_cells);
} }
// ensure the XML document describes cells that can be pasted // ensure the XML document describes cells that can be pasted
if (xml_import.documentElement().tagName() != "titleblocktemplate-partial") { if (xml_import.documentElement().tagName() != "titleblocktemplate-partial") {
return(pasted_cells); return(pasted_cells);
} }
// load pasted cells // load pasted cells
QDomElement paste_root = xml_import.documentElement(); QDomElement paste_root = xml_import.documentElement();
for (QDomElement e = paste_root.firstChildElement() ; !e.isNull() ; e = e.nextSiblingElement()) { for (QDomElement e = paste_root.firstChildElement() ; !e.isNull() ; e = e.nextSiblingElement()) {
@ -228,12 +228,12 @@ QList<TitleBlockCell> TitleBlockTemplateView::pastedCells()
} }
cell.num_row = row_num; cell.num_row = row_num;
cell.num_col = col_num; cell.num_col = col_num;
// parse the rowspan and colspan attributes // parse the rowspan and colspan attributes
if (QET::attributeIsAnInteger(e, "rowspan", &row_span) && row_span > 0) { if (QET::attributeIsAnInteger(e, "rowspan", &row_span) && row_span > 0) {
cell.row_span = row_span; cell.row_span = row_span;
} }
if (QET::attributeIsAnInteger(e, "colspan", &col_span) && col_span > 0) { if (QET::attributeIsAnInteger(e, "colspan", &col_span) && col_span > 0) {
cell.col_span = col_span; cell.col_span = col_span;
} }
@ -251,23 +251,23 @@ void TitleBlockTemplateView::paste()
if (!tbtemplate_) return; if (!tbtemplate_) return;
QList<TitleBlockCell> pasted_cells = pastedCells(); QList<TitleBlockCell> pasted_cells = pastedCells();
if (!pasted_cells.count()) return; if (!pasted_cells.count()) return;
// the top left cell among the selected ones will be used to position the pasted cells // the top left cell among the selected ones will be used to position the pasted cells
TitleBlockTemplateVisualCell *selected_cell = selectedCellsSet().topLeftCell(); TitleBlockTemplateVisualCell *selected_cell = selectedCellsSet().topLeftCell();
if (!selected_cell) return; if (!selected_cell) return;
TitleBlockCell *erased_cell = selected_cell -> cell(); TitleBlockCell *erased_cell = selected_cell -> cell();
if (!erased_cell) return; if (!erased_cell) return;
// change num_row and num_col attributes of pasted cells so they get positionned relatively to selected_cell // change num_row and num_col attributes of pasted cells so they get positionned relatively to selected_cell
normalizeCells(pasted_cells, erased_cell -> num_row, erased_cell -> num_col); normalizeCells(pasted_cells, erased_cell -> num_row, erased_cell -> num_col);
PasteTemplateCellsCommand *paste_command = new PasteTemplateCellsCommand(tbtemplate_); PasteTemplateCellsCommand *paste_command = new PasteTemplateCellsCommand(tbtemplate_);
foreach (TitleBlockCell cell, pasted_cells) { foreach (TitleBlockCell cell, pasted_cells) {
TitleBlockCell *erased_cell = tbtemplate_ -> cell(cell.num_row, cell.num_col); TitleBlockCell *erased_cell = tbtemplate_ -> cell(cell.num_row, cell.num_col);
if (!erased_cell) continue; if (!erased_cell) continue;
paste_command -> addCell(erased_cell, *erased_cell, cell); paste_command -> addCell(erased_cell, *erased_cell, cell);
} }
requestGridModification(paste_command); requestGridModification(paste_command);
} }
@ -345,7 +345,7 @@ void TitleBlockTemplateView::addRowAfter()
void TitleBlockTemplateView::editColumn(HelperCell *cell) { void TitleBlockTemplateView::editColumn(HelperCell *cell) {
int index = cell ? cell -> index : lastContextMenuCellIndex(); int index = cell ? cell -> index : lastContextMenuCellIndex();
if (index == -1) return; if (index == -1) return;
TitleBlockDimension dimension_before = tbtemplate_ -> columnDimension(index); TitleBlockDimension dimension_before = tbtemplate_ -> columnDimension(index);
TitleBlockDimensionWidget dialog(true, this); TitleBlockDimensionWidget dialog(true, this);
dialog.setReadOnly(read_only_); dialog.setReadOnly(read_only_);
@ -371,7 +371,7 @@ void TitleBlockTemplateView::editColumn(HelperCell *cell) {
void TitleBlockTemplateView::editRow(HelperCell *cell) { void TitleBlockTemplateView::editRow(HelperCell *cell) {
int index = cell ? cell -> index : lastContextMenuCellIndex(); int index = cell ? cell -> index : lastContextMenuCellIndex();
if (index == -1) return; if (index == -1) return;
TitleBlockDimension dimension_before = TitleBlockDimension(tbtemplate_ -> rowDimension(index)); TitleBlockDimension dimension_before = TitleBlockDimension(tbtemplate_ -> rowDimension(index));
TitleBlockDimensionWidget dialog(false, this); TitleBlockDimensionWidget dialog(false, this);
dialog.setReadOnly(read_only_); dialog.setReadOnly(read_only_);
@ -416,7 +416,7 @@ void TitleBlockTemplateView::mergeSelectedCells()
{ {
// retrieve the selected cells // retrieve the selected cells
TitleBlockTemplateCellsSet selected_cells = selectedCellsSet(); TitleBlockTemplateCellsSet selected_cells = selectedCellsSet();
MergeCellsCommand *merge_command = new MergeCellsCommand(selected_cells, tbtemplate_); MergeCellsCommand *merge_command = new MergeCellsCommand(selected_cells, tbtemplate_);
if (merge_command -> isValid()) requestGridModification(merge_command); if (merge_command -> isValid()) requestGridModification(merge_command);
} }
@ -428,7 +428,7 @@ void TitleBlockTemplateView::splitSelectedCell()
{ {
// retrieve the selected cells // retrieve the selected cells
TitleBlockTemplateCellsSet selected_cells = selectedCellsSet(); TitleBlockTemplateCellsSet selected_cells = selectedCellsSet();
SplitCellsCommand *split_command = new SplitCellsCommand(selected_cells, tbtemplate_); SplitCellsCommand *split_command = new SplitCellsCommand(selected_cells, tbtemplate_);
if (split_command -> isValid()) requestGridModification(split_command); if (split_command -> isValid()) requestGridModification(split_command);
} }
@ -439,6 +439,9 @@ void TitleBlockTemplateView::splitSelectedCell()
*/ */
void TitleBlockTemplateView::drawBackground(QPainter *painter, const QRectF &rect) { void TitleBlockTemplateView::drawBackground(QPainter *painter, const QRectF &rect) {
QGraphicsView::drawBackground(painter, rect); QGraphicsView::drawBackground(painter, rect);
#if TODO_LIST
#pragma message("@TODO shouldn't we draw a large uniform rect?")
#endif
if (!tbtemplate_) return; // TODO shouldn't we draw a large uniform rect? if (!tbtemplate_) return; // TODO shouldn't we draw a large uniform rect?
} }
@ -483,16 +486,16 @@ void TitleBlockTemplateView::analyzeSelectedCells(bool *can_merge,
bool *can_split, bool *can_split,
int *count) { int *count) {
if (!can_merge && !can_split) return; if (!can_merge && !can_split) return;
if (!tbtemplate_) { if (!tbtemplate_) {
if (can_merge) *can_merge = false; if (can_merge) *can_merge = false;
if (can_split) *can_split = false; if (can_split) *can_split = false;
return; return;
} }
// retrieve the selected cells // retrieve the selected cells
TitleBlockTemplateCellsSet selected_cells = selectedCellsSet(); TitleBlockTemplateCellsSet selected_cells = selectedCellsSet();
if (can_merge) { if (can_merge) {
*can_merge = MergeCellsCommand::canMerge(selected_cells, tbtemplate_); *can_merge = MergeCellsCommand::canMerge(selected_cells, tbtemplate_);
} }
@ -518,11 +521,11 @@ QSizeF TitleBlockTemplateView::templateSize() const
qreal TitleBlockTemplateView::templateWidth() const qreal TitleBlockTemplateView::templateWidth() const
{ {
if (!tbtemplate_) return(0); if (!tbtemplate_) return(0);
qreal width = DEFAULT_ROWS_HELPER_CELLS_WIDTH; qreal width = DEFAULT_ROWS_HELPER_CELLS_WIDTH;
// the rendered width may exceed the initially planned preview width // the rendered width may exceed the initially planned preview width
width += qMax<int>(preview_width_, tbtemplate_ -> width(preview_width_)); width += qMax<int>(preview_width_, tbtemplate_ -> width(preview_width_));
return(width); return(width);
} }
@ -532,11 +535,11 @@ qreal TitleBlockTemplateView::templateWidth() const
qreal TitleBlockTemplateView::templateHeight() const qreal TitleBlockTemplateView::templateHeight() const
{ {
if (!tbtemplate_) return(0); if (!tbtemplate_) return(0);
qreal height = DEFAULT_PREVIEW_HELPER_CELL_HEIGHT; qreal height = DEFAULT_PREVIEW_HELPER_CELL_HEIGHT;
height += DEFAULT_COLS_HELPER_CELLS_HEIGHT; height += DEFAULT_COLS_HELPER_CELLS_HEIGHT;
height += tbtemplate_ -> height(); height += tbtemplate_ -> height();
return(height); return(height);
} }
@ -579,7 +582,7 @@ void TitleBlockTemplateView::init()
delete_column_ = new QAction(QET::Icons::EditTableDeleteColumn, tr("Supprimer cette colonne", "context menu"), this); delete_column_ = new QAction(QET::Icons::EditTableDeleteColumn, tr("Supprimer cette colonne", "context menu"), this);
delete_row_ = new QAction(QET::Icons::EditTableDeleteRow, tr("Supprimer cette ligne", "context menu"), this); delete_row_ = new QAction(QET::Icons::EditTableDeleteRow, tr("Supprimer cette ligne", "context menu"), this);
change_preview_width_ = new QAction( tr("Modifier la largeur de cet aperçu", "context menu"), this); change_preview_width_ = new QAction( tr("Modifier la largeur de cet aperçu", "context menu"), this);
connect(add_column_before_, SIGNAL(triggered()), this, SLOT(addColumnBefore())); connect(add_column_before_, SIGNAL(triggered()), this, SLOT(addColumnBefore()));
connect(add_row_before_, SIGNAL(triggered()), this, SLOT(addRowBefore())); connect(add_row_before_, SIGNAL(triggered()), this, SLOT(addRowBefore()));
connect(add_column_after_, SIGNAL(triggered()), this, SLOT(addColumnAfter())); connect(add_column_after_, SIGNAL(triggered()), this, SLOT(addColumnAfter()));
@ -589,10 +592,10 @@ void TitleBlockTemplateView::init()
connect(delete_column_, SIGNAL(triggered()), this, SLOT(deleteColumn())); connect(delete_column_, SIGNAL(triggered()), this, SLOT(deleteColumn()));
connect(delete_row_, SIGNAL(triggered()), this, SLOT(deleteRow())); connect(delete_row_, SIGNAL(triggered()), this, SLOT(deleteRow()));
connect(change_preview_width_, SIGNAL(triggered()), this, SLOT(changePreviewWidth())); connect(change_preview_width_, SIGNAL(triggered()), this, SLOT(changePreviewWidth()));
setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setBackgroundBrush(QBrush(QColor(248, 255, 160))); setBackgroundBrush(QBrush(QColor(248, 255, 160)));
connect(scene(), SIGNAL(selectionChanged()), this, SLOT(selectionChanged())); connect(scene(), SIGNAL(selectionChanged()), this, SLOT(selectionChanged()));
} }
@ -605,7 +608,7 @@ void TitleBlockTemplateView::applyColumnsWidths(bool animate) {
// the first column is dedicated to helper cells showing the rows height // the first column is dedicated to helper cells showing the rows height
tbgrid_ -> setColumnFixedWidth(0, DEFAULT_ROWS_HELPER_CELLS_WIDTH); tbgrid_ -> setColumnFixedWidth(0, DEFAULT_ROWS_HELPER_CELLS_WIDTH);
tbgrid_ -> setColumnSpacing(0, 0); tbgrid_ -> setColumnSpacing(0, 0);
// we apply the other columns width based on the title block template data // we apply the other columns width based on the title block template data
QList<int> widths = tbtemplate_ -> columnsWidth(preview_width_); QList<int> widths = tbtemplate_ -> columnsWidth(preview_width_);
int total_applied_width = 0; int total_applied_width = 0;
@ -629,12 +632,12 @@ void TitleBlockTemplateView::applyColumnsWidths(bool animate) {
} }
if (!animate) updateColumnsHelperCells(); if (!animate) updateColumnsHelperCells();
++ apply_columns_widths_count_; ++ apply_columns_widths_count_;
// we systematically parameter some cells // we systematically parameter some cells
total_width_helper_cell_ -> split_size = 0; total_width_helper_cell_ -> split_size = 0;
tbgrid_ -> addItem(total_width_helper_cell_, 0, COL_OFFSET, 1, widths.count()); tbgrid_ -> addItem(total_width_helper_cell_, 0, COL_OFFSET, 1, widths.count());
removeItem(extra_cells_width_helper_cell_); removeItem(extra_cells_width_helper_cell_);
if (total_applied_width < preview_width_) { if (total_applied_width < preview_width_) {
// preview_width is greater than the sum of cells widths // preview_width is greater than the sum of cells widths
// we add an extra column with a helper cell // we add an extra column with a helper cell
@ -657,7 +660,7 @@ void TitleBlockTemplateView::applyColumnsWidths(bool animate) {
).arg(total_applied_width - preview_width_); ).arg(total_applied_width - preview_width_);
total_width_helper_cell_ -> split_size = total_applied_width - preview_width_; total_width_helper_cell_ -> split_size = total_applied_width - preview_width_;
} }
updateDisplayedMinMaxWidth(); updateDisplayedMinMaxWidth();
} }
@ -673,7 +676,7 @@ void TitleBlockTemplateView::applyRowsHeights(bool animate) {
// the second row is dedicated to helper cells showing the columns width // the second row is dedicated to helper cells showing the columns width
tbgrid_ -> setRowFixedHeight(1, DEFAULT_COLS_HELPER_CELLS_HEIGHT); tbgrid_ -> setRowFixedHeight(1, DEFAULT_COLS_HELPER_CELLS_HEIGHT);
tbgrid_ -> setRowSpacing(1, 0); tbgrid_ -> setRowSpacing(1, 0);
QList<int> heights = tbtemplate_ -> rowsHeights(); QList<int> heights = tbtemplate_ -> rowsHeights();
for (int i = 0 ; i < heights.count() ; ++ i) { for (int i = 0 ; i < heights.count() ; ++ i) {
tbgrid_ -> setRowSpacing(ROW_OFFSET + i, 0); tbgrid_ -> setRowSpacing(ROW_OFFSET + i, 0);
@ -690,7 +693,7 @@ void TitleBlockTemplateView::applyRowsHeights(bool animate) {
connect(animation, SIGNAL(finished()), this, SLOT(updateRowsHelperCells())); connect(animation, SIGNAL(finished()), this, SLOT(updateRowsHelperCells()));
animation -> start(QAbstractAnimation::DeleteWhenStopped); animation -> start(QAbstractAnimation::DeleteWhenStopped);
} }
} }
if (!animate) updateRowsHelperCells(); if (!animate) updateRowsHelperCells();
++ apply_rows_heights_count_; ++ apply_rows_heights_count_;
@ -736,7 +739,7 @@ void TitleBlockTemplateView::addCells()
{ {
int col_count = tbtemplate_ -> columnsCount(); int col_count = tbtemplate_ -> columnsCount();
int row_count = tbtemplate_ -> rowsCount(); int row_count = tbtemplate_ -> rowsCount();
// we add a big cell to show the total width // we add a big cell to show the total width
total_width_helper_cell_ = new SplittedHelperCell(); total_width_helper_cell_ = new SplittedHelperCell();
total_width_helper_cell_ -> setType(QET::Absolute); total_width_helper_cell_ -> setType(QET::Absolute);
@ -748,12 +751,12 @@ void TitleBlockTemplateView::addCells()
connect(total_width_helper_cell_, SIGNAL(doubleClicked(HelperCell*)), connect(total_width_helper_cell_, SIGNAL(doubleClicked(HelperCell*)),
this, SLOT(changePreviewWidth())); this, SLOT(changePreviewWidth()));
tbgrid_ -> addItem(total_width_helper_cell_, 0, COL_OFFSET, 1, col_count); tbgrid_ -> addItem(total_width_helper_cell_, 0, COL_OFFSET, 1, col_count);
// we also initialize an extra helper cells that shows the preview width is // we also initialize an extra helper cells that shows the preview width is
// too long for the current cells widths // too long for the current cells widths
extra_cells_width_helper_cell_ = new HelperCell(); extra_cells_width_helper_cell_ = new HelperCell();
extra_cells_width_helper_cell_ -> background_color = QColor(Qt::red); extra_cells_width_helper_cell_ -> background_color = QColor(Qt::red);
// we add one cell per column to show their respective width // we add one cell per column to show their respective width
for (int i = 0 ; i < col_count ; ++ i) { for (int i = 0 ; i < col_count ; ++ i) {
TitleBlockDimension current_col_dim = tbtemplate_ -> columnDimension(i); TitleBlockDimension current_col_dim = tbtemplate_ -> columnDimension(i);
@ -769,7 +772,7 @@ void TitleBlockTemplateView::addCells()
this, SLOT(editColumn(HelperCell *))); this, SLOT(editColumn(HelperCell *)));
tbgrid_ -> addItem(current_col_cell, 1, COL_OFFSET + i, 1, 1); tbgrid_ -> addItem(current_col_cell, 1, COL_OFFSET + i, 1, 1);
} }
// we add one cell per row to show their respective height // we add one cell per row to show their respective height
QList<int> heights = tbtemplate_ -> rowsHeights(); QList<int> heights = tbtemplate_ -> rowsHeights();
for (int i = 0 ; i < row_count ; ++ i) { for (int i = 0 ; i < row_count ; ++ i) {
@ -785,7 +788,7 @@ void TitleBlockTemplateView::addCells()
this, SLOT(editRow(HelperCell *))); this, SLOT(editRow(HelperCell *)));
tbgrid_ -> addItem(current_row_cell, ROW_OFFSET + i, 0, 1, 1); tbgrid_ -> addItem(current_row_cell, ROW_OFFSET + i, 0, 1, 1);
} }
// eventually we add the cells composing the titleblock template // eventually we add the cells composing the titleblock template
for (int i = 0 ; i < col_count ; ++ i) { for (int i = 0 ; i < col_count ; ++ i) {
for (int j = 0 ; j < row_count ; ++ j) { for (int j = 0 ; j < row_count ; ++ j) {
@ -793,7 +796,7 @@ void TitleBlockTemplateView::addCells()
if (cell -> spanner_cell) continue; if (cell -> spanner_cell) continue;
TitleBlockTemplateVisualCell *cell_item = new TitleBlockTemplateVisualCell(); TitleBlockTemplateVisualCell *cell_item = new TitleBlockTemplateVisualCell();
cell_item -> setTemplateCell(tbtemplate_, cell); cell_item -> setTemplateCell(tbtemplate_, cell);
int row_span = 0, col_span = 0; int row_span = 0, col_span = 0;
if (cell -> span_state != TitleBlockCell::Disabled) { if (cell -> span_state != TitleBlockCell::Disabled) {
row_span = cell -> applied_row_span; row_span = cell -> applied_row_span;
@ -812,7 +815,7 @@ void TitleBlockTemplateView::refresh()
int col_count = tbtemplate_ -> columnsCount(); int col_count = tbtemplate_ -> columnsCount();
int row_count = tbtemplate_ -> rowsCount(); int row_count = tbtemplate_ -> rowsCount();
if (row_count < 1 || col_count < 1) return; if (row_count < 1 || col_count < 1) return;
for (int i = 0 ; i < col_count ; ++ i) { for (int i = 0 ; i < col_count ; ++ i) {
for (int j = 0 ; j < row_count ; ++ j) { for (int j = 0 ; j < row_count ; ++ j) {
if (QGraphicsLayoutItem *item = tbgrid_ -> itemAt(ROW_OFFSET + j, COL_OFFSET + i)) { if (QGraphicsLayoutItem *item = tbgrid_ -> itemAt(ROW_OFFSET + j, COL_OFFSET + i)) {
@ -846,7 +849,7 @@ void TitleBlockTemplateView::fillWithEmptyCells()
int col_count = tbtemplate_ -> columnsCount(); int col_count = tbtemplate_ -> columnsCount();
int row_count = tbtemplate_ -> rowsCount(); int row_count = tbtemplate_ -> rowsCount();
if (row_count < 1 || col_count < 1) return; if (row_count < 1 || col_count < 1) return;
for (int i = 0 ; i < col_count ; ++ i) { for (int i = 0 ; i < col_count ; ++ i) {
for (int j = 0 ; j < row_count ; ++ j) { for (int j = 0 ; j < row_count ; ++ j) {
if (tbgrid_ -> itemAt(ROW_OFFSET + j, COL_OFFSET + i)) continue; if (tbgrid_ -> itemAt(ROW_OFFSET + j, COL_OFFSET + i)) continue;
@ -861,7 +864,7 @@ void TitleBlockTemplateView::fillWithEmptyCells()
} }
/** /**
@param event Object describing the received event @param event Object describing the received event
*/ */
bool TitleBlockTemplateView::event(QEvent *event) { bool TitleBlockTemplateView::event(QEvent *event) {
if (first_activation_ && event -> type() == QEvent::WindowActivate) { if (first_activation_ && event -> type() == QEvent::WindowActivate) {
@ -885,7 +888,7 @@ void TitleBlockTemplateView::normalizeCells(
int y) const int y) const
{ {
if (!cells.count()) return; if (!cells.count()) return;
int min_row = cells.at(0).num_row; int min_row = cells.at(0).num_row;
int min_col = cells.at(0).num_col; int min_col = cells.at(0).num_col;
for (int i = 1 ; i < cells.count() ; ++ i) { for (int i = 1 ; i < cells.count() ; ++ i) {
@ -901,7 +904,7 @@ void TitleBlockTemplateView::normalizeCells(
/** /**
Load the \a tbt title block template. Load the \a tbt title block template.
If a different template was previously loaded, it is deleted. If a different template was previously loaded, it is deleted.
*/ */
void TitleBlockTemplateView::loadTemplate(TitleBlockTemplate *tbt) { void TitleBlockTemplateView::loadTemplate(TitleBlockTemplate *tbt) {
if (tbgrid_) { if (tbgrid_) {
@ -913,9 +916,9 @@ void TitleBlockTemplateView::loadTemplate(TitleBlockTemplate *tbt) {
if (tbtemplate_ && tbtemplate_ != tbt) { if (tbtemplate_ && tbtemplate_ != tbt) {
delete tbtemplate_; delete tbtemplate_;
} }
tbtemplate_ = tbt; tbtemplate_ = tbt;
// initialize a grid layout with no margin // initialize a grid layout with no margin
tbgrid_ = new QGraphicsGridLayout(); tbgrid_ = new QGraphicsGridLayout();
tbgrid_ -> setContentsMargins(0, 0, 0, 0); tbgrid_ -> setContentsMargins(0, 0, 0, 0);
@ -926,7 +929,7 @@ void TitleBlockTemplateView::loadTemplate(TitleBlockTemplate *tbt) {
// apply rows and columns dimensions // apply rows and columns dimensions
applyColumnsWidths(false); applyColumnsWidths(false);
applyRowsHeights(false); applyRowsHeights(false);
// assign the layout to a basic QGraphicsWidget // assign the layout to a basic QGraphicsWidget
form_ = new QGraphicsWidget(); form_ = new QGraphicsWidget();
// enforce the layout direction to avoid reversing the template rendering // enforce the layout direction to avoid reversing the template rendering
@ -959,6 +962,9 @@ QList<QAction *> TitleBlockTemplateView::columnsActions() const
*/ */
void TitleBlockTemplateView::updateLayout() void TitleBlockTemplateView::updateLayout()
{ {
#if TODO_LIST
#pragma message("@TODO we should try to update the grid instead of deleting-and-reloading it")
#endif
// TODO we should try to update the grid instead of deleting-and-reloading it // TODO we should try to update the grid instead of deleting-and-reloading it
loadTemplate(tbtemplate_); loadTemplate(tbtemplate_);
} }
@ -990,7 +996,7 @@ void TitleBlockTemplateView::updateDisplayedMinMaxWidth()
if (!tbtemplate_) return; if (!tbtemplate_) return;
int min_width = tbtemplate_ -> minimumWidth(); int min_width = tbtemplate_ -> minimumWidth();
int max_width = tbtemplate_ -> maximumWidth(); int max_width = tbtemplate_ -> maximumWidth();
QString min_max_width_sentence; QString min_max_width_sentence;
if (max_width != -1) { if (max_width != -1) {
min_max_width_sentence = QString( min_max_width_sentence = QString(
@ -1007,23 +1013,23 @@ void TitleBlockTemplateView::updateDisplayedMinMaxWidth()
) )
).arg(min_width); ).arg(min_width);
} }
// the tooltip may also display the split label for readability purpose // the tooltip may also display the split label for readability purpose
if (total_width_helper_cell_ -> split_size) { if (total_width_helper_cell_ -> split_size) {
min_max_width_sentence += "---\n"; min_max_width_sentence += "---\n";
min_max_width_sentence += total_width_helper_cell_ -> split_label; min_max_width_sentence += total_width_helper_cell_ -> split_label;
} }
total_width_helper_cell_ -> setToolTip(makePrettyToolTip(min_max_width_sentence)); total_width_helper_cell_ -> setToolTip(makePrettyToolTip(min_max_width_sentence));
} }
/** /**
@param read_only whether this view should be read only. @param read_only whether this view should be read only.
*/ */
void TitleBlockTemplateView::setReadOnly(bool read_only) { void TitleBlockTemplateView::setReadOnly(bool read_only) {
if (read_only_ == read_only) return; if (read_only_ == read_only) return;
read_only_ = read_only; read_only_ = read_only;
add_column_before_ -> setEnabled(!read_only_); add_column_before_ -> setEnabled(!read_only_);
add_row_before_ -> setEnabled(!read_only_); add_row_before_ -> setEnabled(!read_only_);
@ -1142,11 +1148,11 @@ TitleBlockTemplateCellsSet TitleBlockTemplateView::makeCellsSetFromGraphicsItems
*/ */
QString TitleBlockTemplateView::makePrettyToolTip(const QString &string) { QString TitleBlockTemplateView::makePrettyToolTip(const QString &string) {
QString css_style = QString("white-space: pre;"); QString css_style = QString("white-space: pre;");
QString final_tooltip_content = QString( QString final_tooltip_content = QString(
"<div style=\"%1\">%2</div>" "<div style=\"%1\">%2</div>"
).arg(css_style).arg(string); ).arg(css_style).arg(string);
return(final_tooltip_content); return(final_tooltip_content);
} }
@ -1164,11 +1170,11 @@ void TitleBlockTemplateView::updateLastContextMenuCell(HelperCell *last_context_
void TitleBlockTemplateView::adjustSceneRect() void TitleBlockTemplateView::adjustSceneRect()
{ {
QRectF old_scene_rect = scene() -> sceneRect(); QRectF old_scene_rect = scene() -> sceneRect();
// rectangle including everything on the scene // rectangle including everything on the scene
QRectF bounding_rect(QPointF(0, 0), templateSize()); QRectF bounding_rect(QPointF(0, 0), templateSize());
scene() -> setSceneRect(bounding_rect); scene() -> setSceneRect(bounding_rect);
// met a jour la scene // met a jour la scene
scene() -> update(old_scene_rect.united(bounding_rect)); scene() -> update(old_scene_rect.united(bounding_rect));
} }

View File

@ -397,7 +397,9 @@ void TitleBlockTemplate::parseRows(const QString &rows_string) {
QStringList rows_descriptions = QStringList rows_descriptions =
rows_string.split(QChar(';'), QString::SkipEmptyParts); rows_string.split(QChar(';'), QString::SkipEmptyParts);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
QStringList rows_descriptions = QStringList rows_descriptions =
rows_string.split(QChar(';'), Qt::SkipEmptyParts); rows_string.split(QChar(';'), Qt::SkipEmptyParts);
#endif #endif
@ -437,7 +439,9 @@ void TitleBlockTemplate::parseColumns(const QString &cols_string) {
QStringList cols_descriptions = QStringList cols_descriptions =
cols_string.split(QChar(';'), QString::SkipEmptyParts); cols_string.split(QChar(';'), QString::SkipEmptyParts);
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.14 or later") #pragma message("@TODO remove code for QT 5.14 or later")
#endif
QStringList cols_descriptions = QStringList cols_descriptions =
cols_string.split(QChar(';'), Qt::SkipEmptyParts); cols_string.split(QChar(';'), Qt::SkipEmptyParts);
#endif #endif
@ -1378,7 +1382,9 @@ bool TitleBlockTemplate::removeLogo(const QString &logo_name) {
if (!data_logos_.contains(logo_name)) { if (!data_logos_.contains(logo_name)) {
return(false); return(false);
} }
#if TODO_LIST
#pragma message("@TODO check existing cells using this logo.") #pragma message("@TODO check existing cells using this logo.")
#endif
/// TODO check existing cells using this logo. /// TODO check existing cells using this logo.
if (vector_logos_.contains(logo_name)) { if (vector_logos_.contains(logo_name)) {
delete vector_logos_.take(logo_name); delete vector_logos_.take(logo_name);
@ -1404,7 +1410,9 @@ bool TitleBlockTemplate::renameLogo(const QString &logo_name,
|| data_logos_.contains(new_name)) { || data_logos_.contains(new_name)) {
return(false); return(false);
} }
#if TODO_LIST
#pragma message("@TODO check existing cells using this logo.")
#endif
/// TODO check existing cells using this logo. /// TODO check existing cells using this logo.
if (vector_logos_.contains(logo_name)) { if (vector_logos_.contains(logo_name)) {
vector_logos_.insert(new_name, vector_logos_.take(logo_name)); vector_logos_.insert(new_name, vector_logos_.take(logo_name));
@ -1755,7 +1763,9 @@ QStringList TitleBlockTemplate::listOfVariables()
|| cells_[i][j] -> cell_type || cells_[i][j] -> cell_type
== TitleBlockCell::EmptyCell) == TitleBlockCell::EmptyCell)
continue; continue;
#if TODO_LIST
#pragma message("@TODO not works on all cases...") #pragma message("@TODO not works on all cases...")
#endif
// TODO: not works on all cases... // TODO: not works on all cases...
list << cells_[i][j] -> value.name().replace("%",""); list << cells_[i][j] -> value.name().replace("%","");
} }

View File

@ -83,7 +83,9 @@ int BOMExportDialog::exec()
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) // ### Qt 6: remove
stream << getBom() << endl; stream << getBom() << endl;
#else #else
#if TODO_LIST
#pragma message("@TODO remove code for QT 5.15 or later") #pragma message("@TODO remove code for QT 5.15 or later")
#endif
stream << getBom() << &Qt::endl(stream); stream << getBom() << &Qt::endl(stream);
#endif #endif
} }

View File

@ -67,23 +67,23 @@ DiagramPropertiesDialog::DiagramPropertiesDialog(Diagram *diagram, QWidget *pare
//Conductor widget //Conductor widget
m_cpw = new ConductorPropertiesWidget(conductors, this); m_cpw = new ConductorPropertiesWidget(conductors, this);
m_cpw -> setReadOnly(diagram_is_read_only); m_cpw -> setReadOnly(diagram_is_read_only);
QComboBox *autonum_combobox = m_cpw->autonumComboBox(); QComboBox *autonum_combobox = m_cpw->autonumComboBox();
autonum_combobox->addItems(diagram->project()->conductorAutoNum().keys()); autonum_combobox->addItems(diagram->project()->conductorAutoNum().keys());
autonum_combobox->setCurrentIndex(autonum_combobox->findText(diagram->conductorsAutonumName())); autonum_combobox->setCurrentIndex(autonum_combobox->findText(diagram->conductorsAutonumName()));
connect(m_cpw->editAutonumPushButton(), &QPushButton::clicked, this, &DiagramPropertiesDialog::editAutonum); connect(m_cpw->editAutonumPushButton(), &QPushButton::clicked, this, &DiagramPropertiesDialog::editAutonum);
// Buttons // Buttons
QDialogButtonBox boutons(diagram_is_read_only ? QDialogButtonBox::Ok : QDialogButtonBox::Ok | QDialogButtonBox::Cancel); QDialogButtonBox boutons(diagram_is_read_only ? QDialogButtonBox::Ok : QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(&boutons, SIGNAL(accepted()), this, SLOT(accept())); connect(&boutons, SIGNAL(accepted()), this, SLOT(accept()));
connect(&boutons, SIGNAL(rejected()), this, SLOT(reject())); connect(&boutons, SIGNAL(rejected()), this, SLOT(reject()));
QGridLayout *glayout = new QGridLayout; QGridLayout *glayout = new QGridLayout;
glayout->addWidget(border_infos,0,0); glayout->addWidget(border_infos,0,0);
glayout->addWidget(titleblock_infos, 1, 0); glayout->addWidget(titleblock_infos, 1, 0);
glayout->addWidget(m_cpw, 0, 1, 0, 1); glayout->addWidget(m_cpw, 0, 1, 0, 1);
QVBoxLayout vlayout(this); QVBoxLayout vlayout(this);
vlayout.addLayout(glayout); vlayout.addLayout(glayout);
vlayout.addWidget(&boutons); vlayout.addWidget(&boutons);
@ -107,6 +107,9 @@ DiagramPropertiesDialog::DiagramPropertiesDialog(Diagram *diagram, QWidget *pare
// Conducteur have change // Conducteur have change
if (new_conductors != conductors) { if (new_conductors != conductors) {
#if TODO_LIST
#pragma message("@TODO implement an undo command to allow the user to undo/redo this action")
#endif
/// TODO implement an undo command to allow the user to undo/redo this action /// TODO implement an undo command to allow the user to undo/redo this action
diagram -> defaultConductorProperties = new_conductors; diagram -> defaultConductorProperties = new_conductors;
} }