id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
749,414
docbookgeneratorjob.cpp
KDE_umbrello/umbrello/docgenerators/docbookgeneratorjob.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "docbookgeneratorjob.h" #include "docbookgenerator.h" #include "debug_utils.h" #include "file_utils.h" #include "uml.h" #include "umldoc.h" #include <libxml/xmlmemory.h> #include <libxml/debugXML.h> #include <libxml/HTMLtree.h> #include <libxml/xmlIO.h> #include <libxml/xinclude.h> #include <libxml/catalog.h> #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> // kde includes #include <KLocalizedString> // qt includes #include <QTextStream> #include <QStandardPaths> #include <QTemporaryFile> extern int xmlLoadExtDtdDefaultValue; #ifdef USE_SDOCBOOK_LOCAL_COPY #define MAX_PATHS 64 static xmlExternalEntityLoader defaultEntityLoader = NULL; static xmlChar *paths[MAX_PATHS + 1]; static int nbpaths = 0; static QHash<QString,QString> replaceURLList; /* * Entity loading control and customization. * taken from kdelibs/kdoctools/xslt.cpp */ static xmlParserInputPtr xsltprocExternalEntityLoader(const char *_URL, const char *ID,xmlParserCtxtPtr ctxt) { xmlParserInputPtr ret; warningSAXFunc warning = NULL; // use local available dtd versions instead of fetching it every time from the internet QString url = QLatin1String(_URL); QHash<QString, QString>::const_iterator i; for(i = replaceURLList.constBegin(); i != replaceURLList.constEnd(); i++) { if (url.startsWith(i.key())) { url.replace(i.key(),i.value()); qDebug() << "converted" << _URL << "to" << url; } } QByteArray URL = url.toLatin1(); if ((ctxt != NULL) && (ctxt->sax != NULL)) { warning = ctxt->sax->warning; ctxt->sax->warning = NULL; } if (defaultEntityLoader != NULL) { ret = defaultEntityLoader(URL.constData(), ID, ctxt); if (ret != NULL) { if (warning != NULL) ctxt->sax->warning = warning; qDebug() << "Loaded URL=\"" << URL << "\" ID=\"" << ID << "\""; return(ret); } } int j = URL.lastIndexOf("/"); const char *lastsegment = j > -1 ? URL.constData()+j+1 : URL.constData(); for (int i = 0;i < nbpaths;i++) { xmlChar *newURL; newURL = xmlStrdup((const xmlChar *) paths[i]); newURL = xmlStrcat(newURL, (const xmlChar *) "/"); newURL = xmlStrcat(newURL, (const xmlChar *) lastsegment); if (newURL != NULL) { if (defaultEntityLoader != NULL) { ret = defaultEntityLoader((const char *)newURL, ID, ctxt); if (ret != NULL) { if (warning != NULL) ctxt->sax->warning = warning; qDebug() << "Loaded URL=\"" << newURL << "\" ID=\"" << ID << "\""; xmlFree(newURL); return(ret); } } xmlFree(newURL); } } if (warning != NULL) { ctxt->sax->warning = warning; if (_URL != NULL) warning(ctxt, "failed to load external entity \"%s\"\n", _URL); else if (ID != NULL) warning(ctxt, "failed to load external entity \"%s\"\n", ID); } return(NULL); } #endif DocbookGeneratorJob::DocbookGeneratorJob(QObject* parent): QThread(parent) { } void DocbookGeneratorJob::run() { UMLApp* app = UMLApp::app(); UMLDoc* umlDoc = app->document(); QTemporaryFile file; // we need this tmp file if we are writing to a remote file file.setAutoRemove(false); // lets open the file for writing if (!file.open()) { logError1("DocbookGeneratorJob::run: There was a problem saving file %1", file.fileName()); return; } umlDoc->saveToXMI(file); // save the xmi stuff to it file.close(); xsltStylesheetPtr cur = nullptr; xmlDocPtr doc, res; const char *params[16 + 1]; int nbparams = 0; params[nbparams] = nullptr; // use public xml catalogs xmlLoadCatalogs(File_Utils::xmlCatalogFilePath().toLocal8Bit().constData()); QString xsltFile = DocbookGenerator::customXslFile(); #ifdef USE_SDOCBOOK_LOCAL_COPY if (!defaultEntityLoader) { defaultEntityLoader = xmlGetExternalEntityLoader(); xmlSetExternalEntityLoader(xsltprocExternalEntityLoader); QFileInfo xsltFilePath(xsltFile); // Note: This would not be required if the dtd were registered in global xml catalog QString sdocbookDtdUrlTmpl(QStringLiteral("file://%1/simple4125/sdocbook.dtd")); replaceURLList[QStringLiteral("http://www.oasis-open.org/docbook/xml/simple/4.1.2.5/sdocbook.dtd")] = sdocbookDtdUrlTmpl.arg(xsltFilePath.absolutePath()); } #endif xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 1; QByteArray byteArrXslFnam = xsltFile.toLatin1(); cur = xsltParseStylesheetFile((const xmlChar*)byteArrXslFnam.constData()); if (cur == nullptr) { logError1("DocbookGeneratorJob::run: There was a problem parsing stylesheet %1", xsltFile); return; } QString strFnam = file.fileName(); QByteArray byteArrFnam = strFnam.toLatin1(); // toLocal8Bit(); doc = xmlParseFile(byteArrFnam.constData()); if (doc == nullptr) { logError1("DocbookGeneratorJob::run: There was a problem parsing file %1", file.fileName()); xsltFreeStylesheet(cur); return; } res = xsltApplyStylesheet(cur, doc, params); if (res == nullptr) { logError2("DocbookGeneratorJob::run: There was a problem applying stylesheet %1 to %2", xsltFile, file.fileName()); xmlFreeDoc(doc); xsltFreeStylesheet(cur); return; } QTemporaryFile tmpDocBook; tmpDocBook.setAutoRemove(false); tmpDocBook.open(); umlDoc->writeToStatusBar(i18n("Exporting to DocBook...")); xsltSaveResultToFd(tmpDocBook.handle(), res, cur); tmpDocBook.close(); xmlFreeDoc(res); xmlFreeDoc(doc); xsltFreeStylesheet(cur); xsltCleanupGlobals(); xmlCleanupParser(); Q_EMIT docbookGenerated(tmpDocBook.fileName()); }
6,314
C++
.cpp
171
30.292398
110
0.641899
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,415
xhtmlgenerator.cpp
KDE_umbrello/umbrello/docgenerators/xhtmlgenerator.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2006 Gael de Chalendar (aka Kleag) kleag@free.fr SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "xhtmlgenerator.h" #define DBG_SRC QStringLiteral("XhtmlGenerator") #include "debug_utils.h" #include "docbook2xhtmlgeneratorjob.h" #include "uml.h" #include "umldoc.h" #include "umlviewimageexportermodel.h" #include "docbookgenerator.h" #include <kjobwidgets.h> #include <KLocalizedString> #include <KMessageBox> #include <kio/job.h> #include <QApplication> #include <QFile> #include <QRegularExpression> #include <QStandardPaths> #include <QTextStream> DEBUG_REGISTER(XhtmlGenerator) /** * Constructor. */ XhtmlGenerator::XhtmlGenerator() { m_umlDoc = UMLApp::app()->document(); m_pStatus = true; m_pThreadFinished = false; m_d2xg = nullptr; } /** * Destructor. */ XhtmlGenerator::~XhtmlGenerator() { } /** * Exports the current model to XHTML in a directory named as the model * with the .xmi suffix removed. The XHTML file will have the same name * with the .html suffix. Figures will be named as the corresponding * diagrams in the GUI * @todo change file naming to avoid paths with spaces or non-ASCII chars * @todo better handling of error conditions * @return true if saving is successful and false otherwise. */ bool XhtmlGenerator::generateXhtmlForProject() { QUrl url = m_umlDoc->url(); QString fileName = url.fileName(); fileName.remove(QRegularExpression(QStringLiteral(".xmi$"))); url.setPath(fileName); logDebug1("XhtmlGenerator::generateXhtmlForProject: Exporting to directory %1", url.path()); return generateXhtmlForProjectInto(url); } /** * Exports the current model to XHTML in the given directory * @param destDir the directory where the XHTML file and the figures will * be written * @todo better handling of error conditions * @return true if saving is successful and false otherwise. */ bool XhtmlGenerator::generateXhtmlForProjectInto(const QUrl& destDir) { logDebug0("XhtmlGenerator::generateXhtmlForProjectInto: First convert to docbook"); m_destDir = destDir; // KUrl url(QStringLiteral("file://")+m_tmpDir.name()); DocbookGenerator* docbookGenerator = new DocbookGenerator; docbookGenerator->generateDocbookForProjectInto(destDir); logDebug0("XhtmlGenerator::generateXhtmlForProjectInto: Connecting..."); connect(docbookGenerator, SIGNAL(finished(bool)), this, SLOT(slotDocbookToXhtml(bool))); return true; } /** * This slot is triggered when the first part, xmi to docbook, is finished * @param status status to continue with converting */ void XhtmlGenerator::slotDocbookToXhtml(bool status) { logDebug0("XhtmlGenerator::slotDocbookToXhtml: Now convert docbook to html..."); if (!status) { logWarn0("XhtmlGenerator::slotDocbookToXhtml: Error in converting to docbook"); m_pStatus = false; return; } else { QUrl url = m_umlDoc->url(); QString fileName = url.fileName(); fileName.replace(QRegularExpression(QStringLiteral(".xmi$")), QStringLiteral(".docbook")); url.setPath(m_destDir.path() + QLatin1Char('/') + fileName); m_umlDoc->writeToStatusBar(i18n("Generating XHTML...")); m_d2xg = new Docbook2XhtmlGeneratorJob(url, this); connect(m_d2xg, SIGNAL(xhtmlGenerated(QString)), this, SLOT(slotHtmlGenerated(QString))); connect(m_d2xg, SIGNAL(finished()), this, SLOT(threadFinished())); logDebug0("XhtmlGenerator::slotDocbookToXhtml: Threading."); m_d2xg->start(); } } /** * Triggered when the copying of the HTML result file is finished. * Emits the signal finished(). * @param tmpFileName temporary file name */ void XhtmlGenerator::slotHtmlGenerated(const QString& tmpFileName) { logDebug1("XhtmlGenerator: HTML generated %1", tmpFileName); QUrl url = m_umlDoc->url(); QString fileName = url.fileName(); fileName.replace(QRegularExpression(QStringLiteral(".xmi$")), QStringLiteral(".html")); url.setPath(m_destDir.path() + QLatin1Char('/') + fileName); KIO::Job* htmlCopyJob = KIO::file_copy(QUrl::fromLocalFile(tmpFileName), url, -1, KIO::Overwrite | KIO::HideProgressInfo); KJobWidgets::setWindow(htmlCopyJob, (QWidget*)UMLApp::app()); htmlCopyJob->exec(); if (!htmlCopyJob->error()) { m_umlDoc->writeToStatusBar(i18n("XHTML Generation Complete...")); } else { m_pStatus = false; return; } m_umlDoc->writeToStatusBar(i18n("Copying CSS...")); QString cssBaseName = QStringLiteral("xmi.css"); QString cssFileName(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("umbrello5/") + cssBaseName)); if (cssFileName.isEmpty()) cssFileName = QStringLiteral(DOCGENERATORS_DIR) + QLatin1Char('/') + cssBaseName; QUrl cssUrl = m_destDir; cssUrl.setPath(cssUrl.path() + QLatin1Char('/') + cssBaseName); KIO::Job* cssJob = KIO::file_copy(QUrl::fromLocalFile(cssFileName), cssUrl, -1, KIO::Overwrite | KIO::HideProgressInfo); KJobWidgets::setWindow(cssJob, (QWidget*)UMLApp::app()); cssJob->exec(); if (!cssJob->error()) { m_umlDoc->writeToStatusBar(i18n("Finished Copying CSS...")); m_pStatus = true; } else { m_umlDoc->writeToStatusBar(i18n("Failed Copying CSS...")); m_pStatus = false; } while (m_pThreadFinished == false) { // wait for thread to finish qApp->processEvents(); } Q_EMIT finished(m_pStatus); } /** * Invoked when a thread is finished */ void XhtmlGenerator::threadFinished() { m_pThreadFinished = true; delete m_d2xg; m_d2xg = nullptr; } /** * return custom xsl file for generating html * * @return filename with path */ QString XhtmlGenerator::customXslFile() { QString xslBaseName = QStringLiteral("docbook2xhtml.xsl"); QString xsltFileName(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("umbrello5/") + xslBaseName)); if (xsltFileName.isEmpty()) xsltFileName = QStringLiteral(DOCGENERATORS_DIR) + QLatin1Char('/') + xslBaseName; logDebug1("XhtmlGenerator::customXslFile returning %1", xsltFileName); return xsltFileName; }
6,330
C++
.cpp
168
33.785714
130
0.721055
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,416
main.cpp
KDE_umbrello/umbrello/docgenerators/main.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include <unistd.h> #include <libxml/xmlmemory.h> #include <libxml/debugXML.h> #include <libxml/HTMLtree.h> #include <libxml/xmlIO.h> #include <libxml/DOCBparser.h> #include <libxml/xinclude.h> #include <libxml/catalog.h> #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> // kde includes #include <kaboutdata.h> #include <kcmdlineargs.h> #include <kconfig.h> #include <KLocalizedString> #include <ktip.h> #include <kwin.h> #include "version.h" extern int xmlLoadExtDtdDefaultValue; static const char description[] = I18N_NOOP("Umbrello UML Modeller autonomous code generator"); // INSERT A DESCRIPTION FOR YOUR APPLICATION HERE int main(int argc, char *argv[]) { xsltStylesheetPtr cur = nullptr; xmlDocPtr doc, res; const char *params[16 + 1]; int nbparams = 0; params[nbparams] = nullptr; KAboutData aboutData("umbodoc", 0, ki18n("Umbrello UML Modeller autonomous code generator"), umbrelloVersion(), ki18n(description), KAboutData::License_GPL, ki18n("(c) 2006 Gael de Chalendar (aka Kleag), (c) 2002-2006 Umbrello UML Modeller Authors"), KLocalizedString(), "https://apps.kde.org/umbrello"); aboutData.addAuthor(ki18n("Gael de Chalendar (aka Kleag)"),KLocalizedString(), "kleag@free.fr"); aboutData.addAuthor(ki18n("Umbrello UML Modeller Authors"), KLocalizedString(), "umbrello-devel@kde.org"); KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineOptions options; options.add("+[File]", ki18n("File to transform")); options.add("xslt <url>", ki18n("The XSLT file to use")); KCmdLineArgs::addCmdLineOptions(options); // Add our own options. KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); QCStringList xsltOpt = args->getOptionList("xslt"); if (xsltOpt.size() > 0) { QString xsltFile(xsltOpt.last()); xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 1; cur = xsltParseStylesheetFile((const xmlChar *)xsltFile.latin1()); doc = xmlParseFile(args->url(0).url().latin1()); res = xsltApplyStylesheet(cur, doc, params); xsltSaveResultToFile(stdout, res, cur); xsltFreeStylesheet(cur); xmlFreeDoc(res); xmlFreeDoc(doc); xsltCleanupGlobals(); xmlCleanupParser(); } return(0); }
2,482
C++
.cpp
65
34.323077
137
0.724282
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,417
docbookgenerator.cpp
KDE_umbrello/umbrello/docgenerators/docbookgenerator.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2006 Gael de Chalendar (aka Kleag) kleag@free.fr SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "docbookgenerator.h" #define DBG_SRC QStringLiteral("DocbookGenerator") #include "debug_utils.h" #include "docbookgeneratorjob.h" #include "optionstate.h" #include "uml.h" #include "umldoc.h" #include "umlviewimageexportermodel.h" #include <kjobwidgets.h> #include <KLocalizedString> #include <KMessageBox> #include <KIO/Job> #include <KIO/FileCopyJob> #include <QApplication> #include <QFile> #include <QRegularExpression> #include <QTextStream> DEBUG_REGISTER(DocbookGenerator) /** * Constructor. */ DocbookGenerator::DocbookGenerator() { umlDoc = UMLApp::app()->document(); m_pStatus = true; m_pThreadFinished = false; docbookGeneratorJob = nullptr; } /** * Destructor. */ DocbookGenerator::~DocbookGenerator() { } /** * Exports the current model to docbook in a directory named as the model * with the .xmi suffix removed. The docbook file will have the same name * with the .docbook suffix. Figures will be named as the corresponding * diagrams in the GUI * @todo change file naming to avoid paths with spaces or non-ASCII chars * @todo better handling of error conditions * @return true if saving is successful and false otherwise. */ bool DocbookGenerator::generateDocbookForProject() { QUrl url = umlDoc->url(); QString fileName = url.fileName(); fileName.remove(QRegularExpression(QStringLiteral(".xmi$"))); url.setPath(url.path() + QLatin1Char('/') + fileName); logDebug1("DocbookGenerator::generateDocbookForProject: Exporting to directory %1", url.path()); generateDocbookForProjectInto(url); return true; } /** * Exports the current model to docbook in the given directory * @param destDir the directory where the docbook file and the figures will * be written * @todo better handling of error conditions * @return true if saving is successful and false otherwise. */ void DocbookGenerator::generateDocbookForProjectInto(const QUrl& destDir) { m_destDir = destDir; umlDoc->writeToStatusBar(i18n("Exporting all views...")); UMLViewList views = UMLApp::app()->document()->viewIterator(); QStringList errors = UMLViewImageExporterModel().exportViews(views, UMLViewImageExporterModel::mimeTypeToImageType(QStringLiteral("image/png")), destDir, false); if (!errors.empty()) { KMessageBox::errorList(UMLApp::app(), i18n("Some errors happened when exporting the images:"), errors); return; } umlDoc->writeToStatusBar(i18n("Generating Docbook...")); docbookGeneratorJob = new DocbookGeneratorJob(this); connect(docbookGeneratorJob, SIGNAL(docbookGenerated(QString)), this, SLOT(slotDocbookGenerationFinished(QString))); connect(docbookGeneratorJob, SIGNAL(finished()), this, SLOT(threadFinished())); logDebug0("DocbookGenerator::generateDocbookForProjectInto: Threading."); docbookGeneratorJob->start(); } void DocbookGenerator::slotDocbookGenerationFinished(const QString& tmpFileName) { logDebug1("DocbookGenerator: Generation finished (%1)", tmpFileName); QUrl url = umlDoc->url(); QString fileName = url.fileName(); fileName.replace(QRegularExpression(QStringLiteral(".xmi$")), QStringLiteral(".docbook")); url.setPath(m_destDir.path() + QLatin1Char('/') + fileName); KIO::Job* job = KIO::file_copy(QUrl::fromLocalFile(tmpFileName), url, -1, KIO::Overwrite | KIO::HideProgressInfo); KJobWidgets::setWindow(job, (QWidget*)UMLApp::app()); job->exec(); if (!job->error()) { umlDoc->writeToStatusBar(i18n("Docbook Generation Complete...")); m_pStatus = true; } else { umlDoc->writeToStatusBar(i18n("Docbook Generation Failed...")); m_pStatus = false; } while (m_pThreadFinished == false) { // wait for thread to finish qApp->processEvents(); } Q_EMIT finished(m_pStatus); } void DocbookGenerator::threadFinished() { m_pThreadFinished = true; delete docbookGeneratorJob; docbookGeneratorJob = nullptr; } /** * return custom xsl file for generating docbook * * @return filename with path */ QString DocbookGenerator::customXslFile() { QString xslBaseName; if (Settings::optionState().generalState.uml2) { xslBaseName = QStringLiteral("xmi2docbook.xsl"); } else { xslBaseName = QStringLiteral("xmi1docbook.xsl"); } QString xsltFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("umbrello5/") + xslBaseName)); if (xsltFile.isEmpty()) xsltFile = QStringLiteral(DOCGENERATORS_DIR) + QLatin1Char('/') + xslBaseName; logDebug1("DocbookGenerator::customXslFile returning %1", xsltFile); return xsltFile; }
4,872
C++
.cpp
131
33.732824
126
0.740521
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,418
widgetbasepopupmenu.cpp
KDE_umbrello/umbrello/menus/widgetbasepopupmenu.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "widgetbasepopupmenu.h" // app includes #include "activitywidget.h" #include "category.h" #include "classifier.h" #include "combinedfragmentwidget.h" #include "debug_utils.h" #include "entitywidget.h" #include "floatingtextwidget.h" #include "forkjoinwidget.h" #include "interfacewidget.h" #include "notewidget.h" #include "objectwidget.h" #include "objectnodewidget.h" #include "pinportbase.h" #include "statewidget.h" #include "uml.h" #include "umldoc.h" #include "umllistview.h" #include "umlscene.h" // kde includes #include <KLocalizedString> static const bool CHECKABLE = true; /** * Constructs the popup menu for a scene widget. * * @param parent The parent to ListPopupMenu. * @param widget The WidgetBase to represent a menu for. * @param multi True if multiple items are selected. * @param uniqueType The type of widget shared by all selected widgets */ WidgetBasePopupMenu::WidgetBasePopupMenu(QWidget * parent, WidgetBase * widget, bool multi, WidgetBase::WidgetType uniqueType) : ListPopupMenu(parent) { if (!widget) return; if (multi) { insertMultiSelectionMenu(uniqueType); } else { insertSingleSelectionMenu(widget); } bool bCutState = UMLApp::app()->isCutCopyState(); setActionEnabled(mt_Cut, bCutState); setActionEnabled(mt_Copy, bCutState); bool pasteAvailable = false; if (widget->isNoteWidget() && UMLApp::app()->listView()->startedCopy()) { NoteWidget::s_pCurrentNote = widget->asNoteWidget(); pasteAvailable = true; } setActionEnabled(mt_Paste, pasteAvailable); setActionChecked(mt_AutoResize, widget->autoResize()); setupActionsData(); } /** * Creates the "Show" submenu in the context menu of one classifier widget */ void WidgetBasePopupMenu::makeClassifierShowPopup(ClassifierWidget *c) { WidgetBase::WidgetType type = c->baseType(); QMenu* show = newMenu(i18n("Show"), this); show->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Show)); #ifdef ENABLE_WIDGET_SHOW_DOC insert(mt_Show_Documentation, show, i18n("Documentation"), CHECKABLE); setActionChecked(mt_Show_Documentation, c->visualProperty(ClassifierWidget::ShowDocumentation)); #endif if (type == WidgetBase::wt_Class) { insert(mt_Show_Attributes, show, i18n("Attributes"), CHECKABLE); setActionChecked(mt_Show_Attributes, c->visualProperty(ClassifierWidget::ShowAttributes)); } insert(mt_Show_Operations, show, i18n("Operations"), CHECKABLE); setActionChecked(mt_Show_Operations, c->visualProperty(ClassifierWidget::ShowOperations)); insert(mt_Show_Public_Only, show, i18n("Public Only"), CHECKABLE); setActionChecked(mt_Show_Public_Only, c->visualProperty(ClassifierWidget::ShowPublicOnly)); insert(mt_Visibility, show, i18n("Visibility"), CHECKABLE); setActionChecked(mt_Visibility, c->visualProperty(ClassifierWidget::ShowVisibility)); insert(mt_Show_Operation_Signature, show, i18n("Operation Signature"), CHECKABLE); bool sig = (c->operationSignature() == Uml::SignatureType::SigNoVis || c->operationSignature() == Uml::SignatureType::ShowSig); setActionChecked(mt_Show_Operation_Signature, sig); if (type == WidgetBase::wt_Class) { insert(mt_Show_Attribute_Signature, show, i18n("Attribute Signature"), CHECKABLE); sig = (c->attributeSignature() == Uml::SignatureType::SigNoVis || c->attributeSignature() == Uml::SignatureType::ShowSig); setActionChecked(mt_Show_Attribute_Signature, sig); } insert(mt_Show_Packages, show, i18n("Package"), CHECKABLE); setActionChecked(mt_Show_Packages, c->visualProperty(ClassifierWidget::ShowPackage)); insert(mt_Show_Stereotypes, show, i18n("Stereotype"), CHECKABLE); setActionChecked(mt_Show_Stereotypes, c->showStereotype() != Uml::ShowStereoType::None); addMenu(show); } /** * Creates the "Show" submenu the context menu of multiple classifier widgets */ void WidgetBasePopupMenu::makeMultiClassifierShowPopup(WidgetBase::WidgetType type) { QMenu* show = newMenu(i18n("Show"), this); show->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Show)); QMenu* attributes = newMenu(i18n("Attributes"), this); if (type == WidgetBase::wt_Class) { insert(mt_Show_Attributes_Selection, attributes, i18n("Show")); insert(mt_Hide_Attributes_Selection, attributes, i18n("Hide")); insert(mt_Show_Attribute_Signature_Selection, attributes, i18n("Show Signatures")); insert(mt_Hide_Attribute_Signature_Selection, attributes, i18n("Hide Signatures")); } show->addMenu(attributes); QMenu* operations = newMenu(i18n("Operations"), this); insert(mt_Show_Operations_Selection, operations, i18n("Show")); insert(mt_Hide_Operations_Selection, operations, i18n("Hide")); insert(mt_Show_Operation_Signature_Selection, operations, i18n("Show Signatures")); insert(mt_Hide_Operation_Signature_Selection, operations, i18n("Hide Signatures")); show->addMenu(operations); QMenu* visibility = newMenu(i18n("Visibility"), this); insert(mt_Show_Visibility_Selection, visibility, i18n("Show")); insert(mt_Hide_Visibility_Selection, visibility, i18n("Hide")); insert(mt_Hide_NonPublic_Selection, visibility, i18n("Hide Non-public members")); insert(mt_Show_NonPublic_Selection, visibility, i18n("Show Non-public members")); show->addMenu(visibility); QMenu* packages = newMenu(i18n("Packages"), this); insert(mt_Show_Packages_Selection, packages, i18n("Show")); insert(mt_Hide_Packages_Selection, packages, i18n("Hide")); show->addMenu(packages); if (type == WidgetBase::wt_Class) { QMenu* stereotypes = newMenu(i18n("Stereotypes"), this); insert(mt_Show_Stereotypes_Selection, stereotypes, i18n("Show")); insert(mt_Hide_Stereotypes_Selection, stereotypes, i18n("Hide")); show->addMenu(stereotypes); } addMenu(show); } /** * Inserts the menu actions for a widget * * @param widget widget to generate the menu for */ void WidgetBasePopupMenu::insertSingleSelectionMenu(WidgetBase* widget) { WidgetBase::WidgetType type = widget->baseType(); switch (type) { case WidgetBase::wt_Actor: case WidgetBase::wt_UseCase: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); insertStdItems(true, type); insert(mt_Rename); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Category: { insertSubMenuNew(type); insertSubMenuCategoryType(widget->umlObject()->asUMLCategory()); insertSubMenuColor(widget->useFillColor()); insertStdItems(true, type); insert(mt_Rename); insert(mt_Change_Font); break; } case WidgetBase::wt_Class: { ClassifierWidget* c = widget->asClassifierWidget(); if (!c) break; insertSubMenuNew(type); makeClassifierShowPopup(c); insertSubMenuColor(c->useFillColor()); addSeparator(); if (c->linkedDiagram()) insert(mt_GoToStateDiagram); if (UMLApp::app()->document()->views(Uml::DiagramType::State).size() > 0) insert(mt_SelectStateDiagram); if (c->linkedDiagram()) insert(mt_RemoveStateDiagram); insertStdItems(true, type); insert(mt_Rename); insert(mt_Change_Font); if (c->umlObject() && c->umlObject()->stereotype() == QStringLiteral("class-or-package")) { insert(mt_ChangeToClass, i18n("Change into Class")); insert(mt_ChangeToPackage, i18n("Change into Package")); } else { insert(mt_Refactoring, Icon_Utils::SmallIcon(Icon_Utils::it_Refactor), i18n("Refactor")); insert(mt_ViewCode, Icon_Utils::SmallIcon(Icon_Utils::it_View_Code), i18n("View Code")); UMLClassifier *umlc = c->classifier(); if (umlc->isAbstract() && umlc->getAttributeList().size() == 0) insert(mt_ChangeToInterface, i18n("Change into Interface")); } insert(mt_Properties); } break; case WidgetBase::wt_Interface: { InterfaceWidget* c = widget->asInterfaceWidget(); if (!c) break; insertSubMenuNew(type); makeClassifierShowPopup(c); insertSubMenuColor(c->useFillColor()); insertStdItems(true, type); insert(mt_Rename); insert(mt_Change_Font); insert(mt_DrawAsCircle, i18n("Draw as Circle"), CHECKABLE); setActionChecked(mt_DrawAsCircle, c->visualProperty(ClassifierWidget::DrawAsCircle)); insert(mt_ChangeToClass, i18n("Change into Class")); insert(mt_Properties); } break; case WidgetBase::wt_Instance: insertSubMenuNew(type); insert(mt_InstanceAttribute); insert(mt_Rename_Object); insert(mt_Rename, i18n("Rename Class...")); insertStdItems(true, type); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Enum: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); insertStdItems(true, type); insert(mt_Rename); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Entity: insertSubMenuNew(type); insertSubMenuShowEntity(widget->asEntityWidget()); insertSubMenuColor(widget->useFillColor()); insertStdItems(true, type); insert(mt_Rename); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Datatype: case WidgetBase::wt_Package: case WidgetBase::wt_Component: case WidgetBase::wt_Node: case WidgetBase::wt_Artifact: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); insertStdItems(false, type); insert(mt_Rename); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Port: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); insertStdItems(false); insert(mt_NameAsTooltip, i18n("Name as Tooltip"), true); { PinPortBase *pW = static_cast<PinPortBase*>(widget); FloatingTextWidget *ft = pW->floatingTextWidget(); if (ft == nullptr) m_actions[mt_NameAsTooltip]->setChecked(true); } insert(mt_Delete); insert(mt_Properties); break; case WidgetBase::wt_Object: //Used for sequence diagram and collaboration diagram widgets insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); if (widget->umlScene() && widget->umlScene()->isSequenceDiagram()) { addSeparator(); MenuType tabUp = mt_Up; insert(mt_Up, Icon_Utils::SmallIcon(Icon_Utils::it_Arrow_Up), i18n("Move Up")); insert(mt_Down, Icon_Utils::SmallIcon(Icon_Utils::it_Arrow_Down), i18n("Move Down")); if (!(static_cast<ObjectWidget*>(widget))->canTabUp()) { setActionEnabled(tabUp, false); } } insertStdItems(true, type); insert(mt_Rename_Object); insert(mt_Rename, i18n("Rename Class...")); if (widget->asObjectWidget() && widget->umlScene() && widget->umlScene()->isSequenceDiagram()) { insert(widget->asObjectWidget()->showDestruction() ? mt_Hide_Destruction_Box : mt_Show_Destruction_Box); } insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Message: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); insertStdItems(false, type); //insert(mt_Change_Font); //insert(mt_Operation, Icon_Utils::SmallIcon(Icon_Utils::it_Operation_New), i18n("New Operation...")); //insert(mt_Select_Operation, i18n("Select Operation...")); break; case WidgetBase::wt_Note: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); addSeparator(); insert(mt_Cut); insert(mt_Copy); insert(mt_Paste); insert(mt_Clear, Icon_Utils::SmallIcon(Icon_Utils::it_Clear), i18nc("clear note", "Clear")); addSeparator(); insert(mt_Rename, i18n("Change Text...")); insert(mt_Resize); insert(mt_AutoResize, i18n("Auto resize"), CHECKABLE); insert(mt_Delete); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Box: insertSubMenuNew(type); insertStdItems(false, type); insert(mt_Line_Color); break; case WidgetBase::wt_State: { StateWidget* pState = static_cast< StateWidget *>(widget); switch (pState->stateType()) { case StateWidget::Combined: insert(mt_EditCombinedState); addSeparator(); break; default: break; } insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); insertStdItems(true, type); switch (pState->stateType()) { case StateWidget::Combined: insert(mt_Change_Font); insert(mt_Properties); break; case StateWidget::Normal: insert(mt_Rename, i18n("Change State Name...")); insert(mt_Change_Font); insert(mt_Properties); break; case StateWidget::Fork: case StateWidget::Join: insert(pState->drawVertical() ? mt_FlipHorizontal : mt_FlipVertical); break; default: break; } } break; case WidgetBase::wt_ForkJoin: insertSubMenuNew(type); { ForkJoinWidget *pForkJoin = static_cast<ForkJoinWidget*>(widget); insert(pForkJoin->orientation() == Qt::Vertical ? mt_FlipHorizontal : mt_FlipVertical); insert(mt_Fill_Color); } break; case WidgetBase::wt_Activity: insertSubMenuNew(type); { ActivityWidget* pActivity = static_cast<ActivityWidget *>(widget); if(pActivity->activityType() == ActivityWidget::Normal || pActivity->activityType() == ActivityWidget::Invok || pActivity->activityType() == ActivityWidget::Param) { insertSubMenuColor(widget->useFillColor()); } insertStdItems(false, type); if(pActivity->activityType() == ActivityWidget::Normal || pActivity->activityType() == ActivityWidget::Invok || pActivity->activityType() == ActivityWidget::Param) { insert(mt_Rename, i18n("Change Activity Name...")); insert(mt_Change_Font); insert(mt_Properties); } } break; case WidgetBase::wt_ObjectNode: insertSubMenuNew(type); { ObjectNodeWidget* objWidget = static_cast<ObjectNodeWidget *>(widget); if (objWidget->objectNodeType() == ObjectNodeWidget::Buffer || objWidget->objectNodeType() == ObjectNodeWidget::Data || objWidget->objectNodeType() == ObjectNodeWidget::Flow) { insertSubMenuColor(widget->useFillColor()); } insertStdItems(false, type); if (objWidget->objectNodeType() == ObjectNodeWidget::Buffer || objWidget->objectNodeType() == ObjectNodeWidget::Data || objWidget->objectNodeType() == ObjectNodeWidget::Flow) { insert(mt_Rename, i18n("Change Object Node Name...")); insert(mt_Change_Font); insert(mt_Properties); } } break; case WidgetBase::wt_Pin: case WidgetBase::wt_Signal: case WidgetBase::wt_FloatingDashLine: case WidgetBase::wt_Precondition: insertSubMenuNew(type); insertSubMenuColor(widget->useFillColor()); addSeparator(); insert(mt_Cut); insert(mt_Copy); insert(mt_Paste); insert(mt_Clear, Icon_Utils::SmallIcon(Icon_Utils::it_Clear), i18nc("clear precondition", "Clear")); addSeparator(); insert(mt_Rename, i18n("Change Text...")); if (type == WidgetBase::wt_Pin) { insert(mt_NameAsTooltip, i18n("Name as Tooltip"), true); PinPortBase *pW = static_cast<PinPortBase*>(widget); FloatingTextWidget *ft = pW->floatingTextWidget(); if (ft == nullptr) m_actions[mt_NameAsTooltip]->setChecked(true); } insert(mt_Delete); insert(mt_Change_Font); if (type == WidgetBase::wt_Precondition) insert(mt_Properties); break; case WidgetBase::wt_CombinedFragment: insertSubMenuNew(type); // for alternative and parallel combined fragments if ((static_cast<CombinedFragmentWidget*>(widget))->combinedFragmentType() == CombinedFragmentWidget::Alt || (static_cast<CombinedFragmentWidget*>(widget))->combinedFragmentType() == CombinedFragmentWidget::Par) { insert(mt_AddInteractionOperand, i18n("Add Interaction Operand")); addSeparator(); } insertSubMenuColor(widget->useFillColor()); addSeparator(); insert(mt_Cut); insert(mt_Copy); insert(mt_Paste); insert(mt_Clear, Icon_Utils::SmallIcon(Icon_Utils::it_Clear), i18nc("clear combined fragment", "Clear")); addSeparator(); insert(mt_Rename, i18n("Change Text...")); insert(mt_Delete); insert(mt_Change_Font); insert(mt_Properties); break; case WidgetBase::wt_Text: insertSubMenuNew(type); switch((static_cast<FloatingTextWidget*>(widget))->textRole()) { case Uml::TextRole::MultiB: insertAssociationTextItem(i18n("Change Multiplicity..."), mt_Rename_MultiB); break; case Uml::TextRole::MultiA: insertAssociationTextItem(i18n("Change Multiplicity..."), mt_Rename_MultiA); break; case Uml::TextRole::Name: insertAssociationTextItem(i18n("Change Name"), mt_Rename_Name); break; case Uml::TextRole::RoleAName: insertAssociationTextItem(i18n("Change Role A Name..."), mt_Rename_RoleAName); break; case Uml::TextRole::RoleBName: insertAssociationTextItem(i18n("Change Role B Name..."), mt_Rename_RoleBName); break; case Uml::TextRole::ChangeA: case Uml::TextRole::ChangeB: insert(mt_Change_Font); insert(mt_Reset_Label_Positions); insert(mt_Properties); break; case Uml::TextRole::Coll_Message_Self: case Uml::TextRole::Coll_Message: case Uml::TextRole::Seq_Message_Self: case Uml::TextRole::Seq_Message: insert(mt_Change_Font); insert(mt_Operation, Icon_Utils::SmallIcon(Icon_Utils::it_Operation_New), i18n("New Operation...")); insert(mt_Select_Operation, i18n("Select Operation...")); break; case Uml::TextRole::Floating: default: insertStdItems(false, type); insert(mt_Rename, i18n("Change Text...")); insert(mt_Change_Font); break; } break; default: logWarn1("WidgetBasePopupMenu::insertSingleSelectionMenu unhandled WidgetType %1", WidgetBase::toString(type)); break; }//end switch } /** * Inserts the menu actions that work on the whole selection of widgets */ void WidgetBasePopupMenu::insertMultiSelectionMenu(WidgetBase::WidgetType uniqueType) { insertSubMenuAlign(); QMenu* color = newMenu(i18nc("color menu", "Color"), this); insert(mt_Line_Color_Selection, color, Icon_Utils::SmallIcon(Icon_Utils::it_Color_Line), i18n("Line Color...")); insert(mt_Fill_Color_Selection, color, Icon_Utils::SmallIcon(Icon_Utils::it_Color_Fill), i18n("Fill Color...")); insert(mt_Set_Use_Fill_Color_Selection, color, i18n("Use Fill Color")); insert(mt_Unset_Use_Fill_Color_Selection, color, i18n("No Fill Color")); // Add menu actions specific to classifiers if (uniqueType == WidgetBase::wt_Class || uniqueType == WidgetBase::wt_Interface) { makeMultiClassifierShowPopup(uniqueType); } addMenu(color); addSeparator(); insert(mt_Cut); insert(mt_Copy); addSeparator(); insert(mt_Clone); insert(mt_Delete); insert(mt_Resize); addSeparator(); insert(mt_Change_Font_Selection, Icon_Utils::SmallIcon(Icon_Utils::it_Change_Font), i18n("Change Font...")); } /** * Shortcut for the frequently used insert() calls. * * @param insertLeadingSeparator Set this true if the group shall * start with a separator. * @param type The WidgetType for which to insert the menu items. * If no argument is supplied then a Rename item will be * included. */ void WidgetBasePopupMenu::insertStdItems(bool insertLeadingSeparator, WidgetBase::WidgetType type) { if (insertLeadingSeparator) addSeparator(); insert(mt_Cut); insert(mt_Copy); insert(mt_Paste); addSeparator(); if (type == WidgetBase::wt_UMLWidget) insert(mt_Rename); else if (Model_Utils::isCloneable(type)) { insert(mt_Clone); insert(mt_Remove); } else insert(mt_Delete); insert(mt_Resize); insert(mt_AutoResize, i18n("Auto resize"), CHECKABLE); } /** * Add the align actions submenu */ void WidgetBasePopupMenu::insertSubMenuAlign() { QMenu* alignment = newMenu(i18nc("align menu", "Align"), this); insert(mt_Align_Right, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_Right), i18n("Align Right")); insert(mt_Align_Left, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_Left), i18n("Align Left")); insert(mt_Align_Top, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_Top), i18n("Align Top")); insert(mt_Align_Bottom, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_Bottom), i18n("Align Bottom")); insert(mt_Align_VerticalMiddle, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_VerticalMiddle), i18n("Align Vertical Middle")); insert(mt_Align_HorizontalMiddle, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_HorizontalMiddle), i18n("Align Horizontal Middle")); insert(mt_Align_VerticalDistribute, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_VerticalDistribute), i18n("Align Vertical Distribute")); insert(mt_Align_HorizontalDistribute, alignment, Icon_Utils::SmallIcon(Icon_Utils::it_Align_HorizontalDistribute), i18n("Align Horizontal Distribute")); addMenu(alignment); } /** * Shortcut for commonly used sub menu initializations. * * @param fc The "Use Fill Color" is checked. */ void WidgetBasePopupMenu::insertSubMenuColor(bool fc) { QMenu* color = newMenu(i18nc("color menu", "Color"), this); insert(mt_Line_Color, color); insert(mt_Fill_Color, color); insert(mt_Use_Fill_Color, color, i18n("Use Fill Color"), CHECKABLE); setActionChecked(mt_Use_Fill_Color, fc); addMenu(color); } /** * Shortcut for commonly used sub menu initializations. * * @param type The widget type for which to set up the menu. */ void WidgetBasePopupMenu::insertSubMenuNew(WidgetBase::WidgetType type) { QMenu * menu = makeNewMenu(); switch (type) { case WidgetBase::wt_Activity: insert(mt_Initial_Activity, menu); insert(mt_Activity, menu); insert(mt_End_Activity, menu); insert(mt_Final_Activity, menu); insert(mt_Branch, menu); insert(mt_Fork, menu); insert(mt_Invoke_Activity, menu); insert(mt_Param_Activity, menu); insert(mt_Activity_Transition, menu); insert(mt_Exception, menu); insert(mt_PrePostCondition, menu); insert(mt_Send_Signal, menu); insert(mt_Accept_Signal, menu); insert(mt_Accept_Time_Event, menu); insert(mt_Region, menu); insert(mt_Pin, menu); insert(mt_Object_Node, menu); break; case WidgetBase::wt_Actor: case WidgetBase::wt_UseCase: insert(mt_Actor, menu); insert(mt_UseCase, menu); break; case WidgetBase::wt_Component: insert(mt_Subsystem, menu); insert(mt_Component, menu); if (Settings::optionState().generalState.uml2) { insert(mt_Port, menu); insert(mt_InterfaceProvided, menu); insert(mt_InterfaceRequired, menu); } else { insert(mt_InterfaceComponent, menu); } insert(mt_Artifact, menu); break; case WidgetBase::wt_Class: insert(mt_Attribute, menu); insert(mt_Operation, menu); insert(mt_Template, menu); insert(mt_Class, menu); insert(mt_Interface, menu); insert(mt_Datatype, menu); insert(mt_Enum, menu); insert(mt_State_Diagram, menu); break; case WidgetBase::wt_Interface: insert(mt_Operation, menu); insert(mt_Template, menu); insert(mt_Class, menu); insert(mt_Interface, menu); insert(mt_Datatype, menu); insert(mt_Enum, menu); break; case WidgetBase::wt_Entity: insert(mt_EntityAttribute, menu); insert(mt_PrimaryKeyConstraint, menu); insert(mt_UniqueConstraint, menu); insert(mt_ForeignKeyConstraint, menu); insert(mt_CheckConstraint, menu); break; case WidgetBase::wt_Enum: insert(mt_EnumLiteral, menu); break; case WidgetBase::wt_Port: insert(mt_InterfaceProvided, menu); insert(mt_InterfaceRequired, menu); break; case WidgetBase::wt_State: insert(mt_State, menu); insert(mt_End_State, menu); insert(mt_StateTransition, menu); insert(mt_Junction, menu); insert(mt_DeepHistory, menu); insert(mt_ShallowHistory, menu); insert(mt_Choice, menu); insert(mt_StateFork, menu); insert(mt_StateJoin, menu); insert(mt_CombinedState, menu); break; default: break; } insert(mt_Note, menu); insert(mt_FloatText, menu); addMenu(menu); } void WidgetBasePopupMenu::insertSubMenuShowEntity(EntityWidget *widget) { QMenu* show = newMenu(i18n("Show"), this); show->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Show)); insert(mt_Show_Attribute_Signature, show, i18n("Attribute Signature"), CHECKABLE); setActionChecked(mt_Show_Attribute_Signature, widget->showAttributeSignature()); insert(mt_Show_Stereotypes, show, i18n("Stereotype"), CHECKABLE); setActionChecked(mt_Show_Stereotypes, widget->showStereotype()); addMenu(show); }
27,926
C++
.cpp
677
32.626292
156
0.633706
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,419
umlscenepopupmenu.cpp
KDE_umbrello/umbrello/menus/umlscenepopupmenu.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlscenepopupmenu.h" // app includes #include "debug_utils.h" #include "layoutgenerator.h" #include "uml.h" #include "umlscene.h" // kde includes #include <KLocalizedString> UMLScenePopupMenu::UMLScenePopupMenu(QWidget *parent, UMLScene *scene) : ListPopupMenu(parent), m_scene(scene) { const bool CHECKABLE = true; Uml::DiagramType::Enum type = scene->type(); switch(type) { case Uml::DiagramType::UseCase: case Uml::DiagramType::Class: case Uml::DiagramType::Object: case Uml::DiagramType::State: case Uml::DiagramType::Activity: case Uml::DiagramType::Component: case Uml::DiagramType::Deployment: case Uml::DiagramType::EntityRelationship: case Uml::DiagramType::Sequence: case Uml::DiagramType::Collaboration: if (type == Uml::DiagramType::State && scene->widgetLink()) { if (scene->widgetLink()->isStateWidget()) { insert(mt_ReturnToCombinedState); addSeparator(); } else if (scene->widgetLink()->isClassWidget()) { insert(mt_ReturnToClass); addSeparator(); } } insertSubMenuNew(type); addSeparator(); insert(mt_Undo); insert(mt_Redo); addSeparator(); insert(mt_Cut); insert(mt_Copy); insert(mt_Paste); addSeparator(); insert(mt_Clear, Icon_Utils::SmallIcon(Icon_Utils::it_Clear), i18n("Clear Diagram")); insert(mt_Export_Image); addSeparator(); insertLayoutItems(); insert(mt_SnapToGrid, i18n("Snap to Grid"), CHECKABLE); setActionChecked(mt_SnapToGrid, scene->snapToGrid()); insert(mt_SnapComponentSizeToGrid, i18n("Snap Component Size to Grid"), CHECKABLE); setActionChecked(mt_SnapComponentSizeToGrid, scene->snapComponentSizeToGrid()); insert(mt_ShowSnapGrid, i18n("Show Grid"), CHECKABLE); setActionChecked(mt_ShowSnapGrid, scene->isSnapGridVisible()); insert(mt_ShowDocumentationIndicator, i18n("Show Documentation Indicator"), CHECKABLE); setActionChecked(mt_ShowDocumentationIndicator, scene->isShowDocumentationIndicator()); insert(mt_Properties); break; #ifndef CHECK_SWITCH default: break; #endif } bool bCutState = UMLApp::app()->isCutCopyState(); setActionEnabled(mt_Undo, UMLApp::app()->isUndoActionEnabled()); setActionEnabled(mt_Redo, UMLApp::app()->isRedoActionEnabled()); setActionEnabled(mt_Cut, bCutState); setActionEnabled(mt_Copy, bCutState); setActionEnabled(mt_Paste, UMLApp::app()->isPasteState()); setupActionsData(); if (IS_DEBUG_ENABLED()) dumpActions(Uml::DiagramType::toString(type)); } void UMLScenePopupMenu::insertLayoutItems() { QList<MenuType> types; types << mt_Apply_Layout << mt_Apply_Layout1 << mt_Apply_Layout2 << mt_Apply_Layout3 << mt_Apply_Layout4 << mt_Apply_Layout5 << mt_Apply_Layout6 << mt_Apply_Layout7 << mt_Apply_Layout8 << mt_Apply_Layout9; LayoutGenerator generator; if (generator.isEnabled()) { QHash<QString, QString> configFiles; if (LayoutGenerator::availableConfigFiles(m_scene, configFiles)) { int i = 0; for(const QString &key : configFiles.keys()) { if (i >= types.size()) break; if (key == QStringLiteral("export") && !Settings::optionState().autoLayoutState.showExportLayout) continue; insert(types[i], QPixmap(), i18n("apply '%1'", configFiles[key])); QAction* action = getAction(types[i]); QMap<QString, QVariant> map = action->data().toMap(); map[toString(dt_ApplyLayout)] = QVariant(key); action->setData(QVariant(map)); i++; } addSeparator(); } } else { logWarn0("UMLScenePopupMenu::insertLayoutItems could not add autolayout entries " "because graphviz was not found."); } } void UMLScenePopupMenu::insertSubMenuNew(Uml::DiagramType::Enum type) { QMenu * menu = makeNewMenu(); switch(type) { case Uml::DiagramType::UseCase: insert(mt_Actor, menu); insert(mt_UseCase, menu); break; case Uml::DiagramType::Class: insert(mt_Import_from_File, menu); insert(mt_Class, menu); insert(mt_Interface, menu); insert(mt_Datatype, menu); insert(mt_Enum, menu); insert(mt_Package, menu); break; case Uml::DiagramType::Object: insert(mt_Instance, menu); break; case Uml::DiagramType::State: insert(mt_Initial_State, menu); insert(mt_State, menu); insert(mt_End_State, menu); insert(mt_Junction, menu); insert(mt_DeepHistory, menu); insert(mt_ShallowHistory, menu); insert(mt_Choice, menu); insert(mt_StateFork, menu); insert(mt_StateJoin, menu); insert(mt_CombinedState, menu); break; case Uml::DiagramType::Activity: insert(mt_Initial_Activity, menu); insert(mt_Activity, menu); insert(mt_End_Activity, menu); insert(mt_Final_Activity, menu); insert(mt_Branch, menu); insert(mt_Fork, menu); insert(mt_Invoke_Activity, menu); insert(mt_Param_Activity, menu); insert(mt_Activity_Transition, menu); insert(mt_Exception, menu); insert(mt_PrePostCondition, menu); insert(mt_Send_Signal, menu); insert(mt_Accept_Signal, menu); insert(mt_Accept_Time_Event, menu); insert(mt_Region, menu); insert(mt_Pin, menu); insert(mt_Object_Node, menu); break; case Uml::DiagramType::Component: insert(mt_Subsystem, menu); insert(mt_Component, menu); insert(mt_InterfaceComponent, menu); insert(mt_Artifact, menu); break; case Uml::DiagramType::Deployment: insert(mt_Node, menu); break; case Uml::DiagramType::EntityRelationship: insert(mt_Entity, menu); insert(mt_Category, menu); break; case Uml::DiagramType::Sequence: insert(mt_Import_from_File, menu); insert(mt_Object, menu); if (m_scene->onWidgetLine(m_scene->pos())) { insert(mt_MessageCreation, menu); insert(mt_MessageDestroy, menu); insert(mt_MessageSynchronous, menu); insert(mt_MessageAsynchronous, menu); insert(mt_MessageLost, menu); } else if (m_scene->widgetOnDiagram(WidgetBase::wt_Object)){ insert(mt_MessageFound, menu); } break; case Uml::DiagramType::Collaboration: insert(mt_Object, menu); break; default: delete menu; return; } insert(mt_Note, menu); insert(mt_FloatText, menu); addMenu(menu); }
7,665
C++
.cpp
197
28.233503
99
0.582942
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,420
umllistviewpopupmenu.cpp
KDE_umbrello/umbrello/menus/umllistviewpopupmenu.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umllistviewpopupmenu.h" #include "debug_utils.h" #include "folder.h" #include "optionstate.h" #include "model_utils.h" #include "uml.h" // only needed for log{Warn,Error} // kde includes #include <KLocalizedString> UMLListViewPopupMenu::UMLListViewPopupMenu(QWidget *parent, UMLListViewItem *item) : ListPopupMenu(parent) { UMLObject *object = item->umlObject(); UMLListViewItem::ListViewType type = item->type(); switch(type) { case UMLListViewItem::lvt_Logical_View: insertContainerItems(true, true, true); addSeparator(); insert(mt_Paste); addSeparator(); insert(mt_Import_Project); insert(mt_Import_Class); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Component_View: insertSubMenuNew(type); addSeparator(); insert(mt_Paste); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Deployment_View: insertSubMenuNew(type); addSeparator(); insert(mt_Paste); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_EntityRelationship_Model: insertSubMenuNew(type); addSeparator(); insert(mt_Paste); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_UseCase_View: insertSubMenuNew(type); addSeparator(); // insert(mt_Cut); // insert(mt_Copy); insert(mt_Paste); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Logical_Folder: insertContainerItems(true, true, true); insertStdItems(); insert(mt_Import_Project); insertSubmodelAction(); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Datatype_Folder: insertSubMenuNew(type); insertStdItems(); insertSubmodelAction(); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Component_Folder: insertSubMenuNew(type); insertStdItems(); insertSubmodelAction(); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Deployment_Folder: insertSubMenuNew(type); insertStdItems(); insertSubmodelAction(); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_UseCase_Folder: insertSubMenuNew(type); insertStdItems(); insertSubmodelAction(); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_EntityRelationship_Folder: insertSubMenuNew(type); insertStdItems(); insertSubmodelAction(); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_UseCase_Diagram: case UMLListViewItem::lvt_Sequence_Diagram: case UMLListViewItem::lvt_Class_Diagram: case UMLListViewItem::lvt_Object_Diagram: case UMLListViewItem::lvt_Collaboration_Diagram: case UMLListViewItem::lvt_State_Diagram: case UMLListViewItem::lvt_Activity_Diagram: case UMLListViewItem::lvt_Component_Diagram: case UMLListViewItem::lvt_Deployment_Diagram: case UMLListViewItem::lvt_EntityRelationship_Diagram: insert(mt_Rename); insertStdItems(false); insert(mt_Clone); insert(mt_Export_Image); insert(mt_Properties); break; case UMLListViewItem::lvt_Artifact: insert(mt_Open_File); insert(mt_Rename); insertStdItems(true); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Class: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); addSeparator(); if (object && object->stereotype() == QStringLiteral("class-or-package")) { insert(mt_ChangeToClass, i18n("Change into Class")); insert(mt_ChangeToPackage, i18n("Change into Package")); } addSeparator(); insert(mt_Properties); break; case UMLListViewItem::lvt_Package: insertContainerItems(true, false, true); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Subsystem: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Component: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); addSeparator(); insert(mt_Expand_All); insert(mt_Collapse_All); break; case UMLListViewItem::lvt_Datatype: // Renaming, cut/paste etc shall not be offered for programming // language predefined types if (object && !Model_Utils::isCommonDataType(object->name())) { insert(mt_Rename); insertStdItems(false); } insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_EnumLiteral: case UMLListViewItem::lvt_Port: case UMLListViewItem::lvt_Node: case UMLListViewItem::lvt_Actor: case UMLListViewItem::lvt_UseCase: case UMLListViewItem::lvt_Attribute: case UMLListViewItem::lvt_EntityAttribute: case UMLListViewItem::lvt_InstanceAttribute: case UMLListViewItem::lvt_Operation: case UMLListViewItem::lvt_Template: insert(mt_Rename); insertStdItems(false); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Interface: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Enum: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Category: insertSubMenuCategoryType(object->asUMLCategory()); insert(mt_Rename); insertStdItems(false); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Entity: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Instance: insertSubMenuNew(type); insert(mt_Rename); insertStdItems(); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_UniqueConstraint: case UMLListViewItem::lvt_PrimaryKeyConstraint: case UMLListViewItem::lvt_ForeignKeyConstraint: case UMLListViewItem::lvt_CheckConstraint: insert(mt_Rename); insert(mt_Delete); insert(mt_Show); insert(mt_Properties); break; case UMLListViewItem::lvt_Model: insert(mt_Model, i18n("Rename...")); break; case UMLListViewItem::lvt_Properties: insert(mt_Expand_All); insert(mt_Collapse_All); insert(mt_Properties); break; case UMLListViewItem::lvt_Properties_AutoLayout: case UMLListViewItem::lvt_Properties_Class: case UMLListViewItem::lvt_Properties_CodeImport: case UMLListViewItem::lvt_Properties_CodeGeneration: case UMLListViewItem::lvt_Properties_CodeViewer: case UMLListViewItem::lvt_Properties_Font: case UMLListViewItem::lvt_Properties_General: case UMLListViewItem::lvt_Properties_UserInterface: insert(mt_Properties); break; #ifndef CHECK_SWITCH default: break; #endif } setupActionsData(); } /** * Override of related method from class ListPopupMenu * @param type list view type */ void UMLListViewPopupMenu::insertSubMenuNew(UMLListViewItem::ListViewType type) { QMenu * menu = makeNewMenu(); switch(type) { case UMLListViewItem::lvt_Deployment_View: insert(mt_Deployment_Folder, menu); insert(mt_Node, menu); insert(mt_Deployment_Diagram, menu); break; case UMLListViewItem::lvt_EntityRelationship_Model: insert(mt_EntityRelationship_Folder, menu); insert(mt_Entity, menu); insert(mt_Category, menu); insert(mt_EntityRelationship_Diagram, menu); break; case UMLListViewItem::lvt_UseCase_View: insert(mt_UseCase_Folder, menu); insert(mt_Actor, menu); insert(mt_UseCase, menu); insert(mt_UseCase_Diagram, menu); break; case UMLListViewItem::lvt_Component_View: case UMLListViewItem::lvt_Component_Folder: insert(mt_Component_Folder, menu); insert(mt_Subsystem, menu); insert(mt_Component, menu); insert(mt_Artifact, menu); insert(mt_Component_Diagram, menu); break; case UMLListViewItem::lvt_Datatype_Folder: insert(mt_Datatype, menu); break; case UMLListViewItem::lvt_Deployment_Folder: insert(mt_Deployment_Folder, menu); insert(mt_Node, menu); insert(mt_Deployment_Diagram, menu); break; case UMLListViewItem::lvt_UseCase_Folder: insert(mt_UseCase_Folder, menu); insert(mt_Actor, menu); insert(mt_UseCase, menu); insert(mt_UseCase_Diagram, menu); break; case UMLListViewItem::lvt_EntityRelationship_Folder: insert(mt_EntityRelationship_Folder, menu); insert(mt_Entity, menu); insert(mt_EntityRelationship_Diagram, menu); break; case UMLListViewItem::lvt_Class: insert(mt_Attribute, menu); insert(mt_Operation, menu); insert(mt_Template, menu); insertContainerItems(menu, false, false, false); break; case UMLListViewItem::lvt_Component: insert(mt_Component, menu); if (Settings::optionState().generalState.uml2) insert(mt_Port, menu); insert(mt_Artifact, menu); break; case UMLListViewItem::lvt_Interface: insert(mt_Operation, menu); insert(mt_Template, menu); insertContainerItems(menu, false, false, false); break; case UMLListViewItem::lvt_Entity: insert(mt_EntityAttribute, menu); insert(mt_PrimaryKeyConstraint, menu); insert(mt_UniqueConstraint, menu); insert(mt_ForeignKeyConstraint, menu); insert(mt_CheckConstraint, menu); break; case UMLListViewItem::lvt_Enum: insert(mt_EnumLiteral, menu); break; //case UMLListViewItem::lvt_Object: // break; case UMLListViewItem::lvt_Subsystem: insert(mt_Subsystem, menu); insert(mt_Component, menu); insert(mt_Artifact, menu); break; default: delete menu; return; } addMenu(menu); } void UMLListViewPopupMenu::insertStdItems(bool insertLeadingSeparator) { if (insertLeadingSeparator) addSeparator(); insert(mt_Cut); insert(mt_Copy); insert(mt_Paste); addSeparator(); insert(mt_Delete); } /** * Inserts a menu item for externalization/de-externalization * of a folder. */ void UMLListViewPopupMenu::insertSubmodelAction() { const Settings::OptionState& ostat = Settings::optionState(); if (ostat.generalState.tabdiagrams) { // Umbrello currently does not support External Folders // in combination with Tabbed Diagrams. // If you need external folders then disable the tabbed diagrams // in the General Settings. return; } UMLObject *o = Model_Utils::treeViewGetCurrentObject(); if (o == nullptr) { logError0("UMLListViewPopupMenu::insertSubmodelAction: " "Model_Utils::treeViewGetCurrentObject() returns NULL"); return; } const UMLFolder *f = o->asUMLFolder(); if (f == nullptr) { logError1("UMLListViewPopupMenu::insertSubmodelAction: %1 is not a Folder", o->name()); return; } QString submodelFile = f->folderFile(); if (submodelFile.isEmpty()) { insert(mt_Externalize_Folder); } else { insert(mt_Internalize_Folder); } }
14,490
C++
.cpp
407
24.872236
95
0.587486
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,421
associationwidgetpopupmenu.cpp
KDE_umbrello/umbrello/menus/associationwidgetpopupmenu.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "associationwidgetpopupmenu.h" // app includes #include "assocrules.h" #include "associationline.h" #include "associationwidget.h" #include "debug_utils.h" // kde includes #include <KLocalizedString> enum class LocalTriggerType { AnchorSelected, AssociationSelected, CollaborationMessage, AttributeAssociation, FullAssociation }; /** * Constructs the popup menu for a scene widget. * * @param parent The parent to ListPopupMenu. * @param type The type of widget shared by all selected widgets. * @param widget The AssociationWidget to represent a menu for. */ AssociationWidgetPopupMenu::AssociationWidgetPopupMenu(QWidget *parent, Uml::AssociationType::Enum type, AssociationWidget *widget) : ListPopupMenu(parent) { LocalTriggerType triggerType = LocalTriggerType::AssociationSelected; if (type == Uml::AssociationType::Anchor) { triggerType = LocalTriggerType::AnchorSelected; } else if (widget->isCollaboration()) { triggerType = LocalTriggerType::CollaborationMessage; } else if (!widget->association()) { triggerType = LocalTriggerType::AttributeAssociation; } else if (AssocRules::allowRole(type)) { triggerType = LocalTriggerType::FullAssociation; } switch (triggerType) { case LocalTriggerType::AnchorSelected: insert(mt_Delete, Icon_Utils::SmallIcon(Icon_Utils::it_Delete), i18n("Delete Anchor")); break; case LocalTriggerType::AssociationSelected: case LocalTriggerType::AttributeAssociation: case LocalTriggerType::FullAssociation: case LocalTriggerType::CollaborationMessage: if (widget->isPointAddable()) insert(mt_Add_Point, Icon_Utils::SmallIcon(Icon_Utils::it_Add_Point), i18n("Add Point")); if (widget->isPointRemovable()) insert(mt_Delete_Point, Icon_Utils::SmallIcon(Icon_Utils::it_Delete_Point), i18n("Delete Point")); if (!widget->isAutoLayouted()) insert(mt_Auto_Layout_Spline, i18n("Choose Spline points automatically")); if (widget->isLayoutChangeable()) { addSeparator(); insertSubMenuLayout(widget->associationLine()); } addSeparator(); insert(mt_Delete); break; default: break; } switch(triggerType) { case LocalTriggerType::AttributeAssociation: case LocalTriggerType::FullAssociation: insert(mt_Rename_Name, i18n("Change Association Name...")); insert(mt_Rename_RoleAName, i18n("Change Role A Name...")); insert(mt_Rename_RoleBName, i18n("Change Role B Name...")); insert(mt_Change_Font); insert(mt_Reset_Label_Positions); break; case LocalTriggerType::CollaborationMessage: insert(mt_Change_Font); insert(mt_New_Operation); insert(mt_Select_Operation, i18n("Select Operation...")); break; default: break; } insert(mt_Line_Color); insert(mt_Properties); setActionChecked(mt_AutoResize, widget->autoResize()); setupActionsData(); } /** * Inserts a sub menu for association layouts. */ void AssociationWidgetPopupMenu::insertSubMenuLayout(const AssociationLine& associationLine) { QMenu* layout = newMenu(i18nc("Layout menu", "Layout"), this); insert(mt_LayoutPolyline, layout, i18n("Polyline"), true); insert(mt_LayoutDirect, layout, i18n("Direct"), true); insert(mt_LayoutSpline, layout, i18n("Spline"), true); insert(mt_LayoutOrthogonal, layout, i18n("Orthogonal"), true); switch (associationLine.layout()) { case Uml::LayoutType::Direct: m_actions[mt_LayoutDirect]->setChecked(true); break; case Uml::LayoutType::Orthogonal: m_actions[mt_LayoutOrthogonal]->setChecked(true); break; case Uml::LayoutType::Spline: m_actions[mt_LayoutSpline]->setChecked(true); break; case Uml::LayoutType::Polyline: default: m_actions[mt_LayoutPolyline]->setChecked(true); break; } addMenu(layout); }
4,175
C++
.cpp
106
33.603774
131
0.701724
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,422
listpopupmenu.cpp
KDE_umbrello/umbrello/menus/listpopupmenu.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "listpopupmenu.h" // app includes #include "activitywidget.h" #include "associationline.h" #include "associationwidget.h" #include "category.h" #include "classifier.h" #include "classifierwidget.h" #include "combinedfragmentwidget.h" #include "debug_utils.h" #include "floatingtextwidget.h" #include "folder.h" #include "forkjoinwidget.h" #include "layoutgenerator.h" #include "model_utils.h" #include "objectnodewidget.h" #include "objectwidget.h" #include "notewidget.h" #include "pinportbase.h" #include "preconditionwidget.h" #include "signalwidget.h" #include "statewidget.h" #include "uml.h" #include "umldoc.h" #include "umlscene.h" #include "umlview.h" #include "umllistview.h" #include "umllistviewitem.h" #include "widget_utils.h" #include "widgetbase.h" // kde includes #include <KLocalizedString> #include <kactioncollection.h> DEBUG_REGISTER_DISABLED(ListPopupMenu) static const bool CHECKABLE = true; // uncomment to see not handled switch cases //#define CHECK_SWITCH class DebugMenu { public: DebugMenu(ListPopupMenu::MenuType _m) : m(_m) {} DebugMenu(const QString & _m) : menu(_m) {} ListPopupMenu::MenuType m{ListPopupMenu::mt_Undefined}; QString menu; }; class ListPopupMenuPrivate { public: QList<DebugMenu> debugActions; ~ListPopupMenuPrivate() { debugActions.clear(); } }; #define DEBUG_AddAction(m) d->debugActions.append(DebugMenu(m)) #define DEBUG_StartMenu(m) d->debugActions.append(DebugMenu(m->title() + QStringLiteral(" - start"))) #define DEBUG_EndMenu(m) d->debugActions.append(DebugMenu(m->title() + QStringLiteral(" - end"))) /** * Constructs the popup menu * * @param parent The parent to ListPopupMenu. */ ListPopupMenu::ListPopupMenu(QWidget *parent) : QMenu(parent), d(new ListPopupMenuPrivate) { } /** * Standard destructor. */ ListPopupMenu::~ListPopupMenu() { qDeleteAll(m_actions); m_actions.clear(); delete d; } QMenu *ListPopupMenu::newMenu(const QString &title, QWidget *widget) { QMenu *menu = new QMenu(title, widget); DEBUG_StartMenu(menu); return menu; } void ListPopupMenu::addMenu(QMenu *menu) { QMenu::addMenu(menu); DEBUG_EndMenu(menu); } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. */ void ListPopupMenu::insert(MenuType m) { insert(m, this); } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. * @param menu The QMenu for which to insert a menu item. * @param s The entry to be inserted from the action collection */ void ListPopupMenu::insertFromActionKey(const MenuType m, QMenu *menu, const QString &s) { QAction* action = UMLApp::app()->actionCollection()->action(s); insert(m, menu, action->icon(), action->text()); } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. * @param menu The QMenu for which to insert a menu item. */ void ListPopupMenu::insert(const MenuType m, QMenu* menu) { // Preprocessor macro for List Popup Menu Insert Small Icon #define LPMISI(IT, TXT) m_actions[m] = menu->addAction(Icon_Utils::SmallIcon(Icon_Utils::IT), TXT) // Preprocessor macro for List Popup Menu Insert Bar Icon #define LPMIBI(IT, TXT) m_actions[m] = menu->addAction(Icon_Utils::BarIcon(Icon_Utils::IT), TXT) DEBUG_AddAction(m); Q_ASSERT(menu != nullptr); switch (m) { case mt_Accept_Signal: LPMISI(it_Accept_Signal, i18n("Accept Signal")); break; case mt_Accept_Time_Event: LPMISI(it_Accept_TimeEvent, i18n("Accept Time Event")); break; case mt_Activity: LPMISI(it_UseCase, i18n("Activity...")); break; case mt_Activity_Transition: LPMISI(it_Activity_Transition, i18n("Activity Transition")); break; case mt_Actor: LPMISI(it_Actor, i18n("Actor")); break; //case mt_Actor: LPMISI(it_Actor, i18n("Actor...")); break; case mt_Artifact: LPMISI(it_Artifact, i18n("Artifact")); break; //case mt_Artifact: LPMISI(it_Artifact, i18n("Artifact...")); break; case mt_Attribute: LPMISI(it_Public_Attribute, i18n("Attribute")); break; //case mt_Attribute: LPMISI(it_Public_Attribute, i18n("Attribute...")); break; case mt_Branch: LPMISI(it_Branch, i18n("Branch/Merge")); break; case mt_Category: LPMISI(it_Category, i18n("Category")); break; //case mt_Category: LPMISI(it_Category, i18n("Category...")); break; case mt_Change_Font: LPMISI(it_Change_Font, i18n("Change Font...")); break; case mt_CheckConstraint: LPMISI(it_Constraint_Check, i18n("Check Constraint...")); break; case mt_Choice: LPMISI(it_Choice_Rhomb, i18n("Choice")); break; case mt_Class: LPMISI(it_Class, i18nc("new class menu item", "Class...")); break; case mt_Clone: LPMIBI(it_Duplicate, i18nc("duplicate action", "Duplicate")); break; case mt_Collapse_All: m_actions[m] = menu->addAction(i18n("Collapse All")); break; case mt_CombinedState: LPMISI(it_State, i18nc("add new combined state", "Combined state...")); break; case mt_Component: LPMISI(it_Component, i18n("Component")); break; //case mt_Component: LPMISI(it_Component, i18n("Component...")); break; case mt_Component_Diagram: insertFromActionKey(m, menu, QStringLiteral("new_component_diagram")); break; case mt_Component_Folder: LPMIBI(it_Folder, i18n("Folder")); break; case mt_Copy: LPMISI(it_Copy, i18n("Copy")); break; case mt_Cut: LPMISI(it_Cut, i18n("Cut")); break; case mt_Datatype: LPMISI(it_Datatype, i18n("Datatype...")); break; case mt_DeepHistory: LPMISI(it_History_Deep, i18n("Deep History")); break; case mt_Delete: LPMISI(it_Delete, i18n("Delete")); break; case mt_Deployment_Diagram: insertFromActionKey(m, menu, QStringLiteral("new_deployment_diagram")); break; case mt_Deployment_Folder: LPMIBI(it_Folder, i18n("Folder")); break; case mt_EditCombinedState: LPMISI(it_State, i18n("Edit combined state")); break; case mt_End_Activity: LPMISI(it_EndState, i18n("End Activity")); break; case mt_End_State: LPMISI(it_EndState, i18n("End State")); break; case mt_Entity: LPMISI(it_Entity, i18n("Entity")); break; //case mt_Entity: LPMISI(it_Entity, i18n("Entity...")); break; case mt_EntityAttribute: LPMISI(it_Entity_Attribute, i18n("Entity Attribute...")); break; case mt_EntityRelationship_Diagram: insertFromActionKey(m, menu, QStringLiteral("new_entityrelationship_diagram")); break; case mt_EntityRelationship_Folder: LPMIBI(it_Folder, i18n("Folder")); break; case mt_Enum: LPMISI(it_Enum, i18n("Enum...")); break; case mt_EnumLiteral: LPMISI(it_Enum_Literal, i18n("Enum Literal...")); break; case mt_Exception: LPMISI(it_Exception, i18n("Exception")); break; case mt_Expand_All: m_actions[m] = menu->addAction(i18n("Expand All")); break; case mt_Export_Image: LPMISI(it_Export_Picture, i18n("Export as Picture...")); break; case mt_Externalize_Folder: m_actions[m] = menu->addAction(i18n("Externalize Folder...")); break; case mt_Fill_Color: LPMISI(it_Color_Fill, i18n("Fill Color...")); break; case mt_Final_Activity: LPMISI(it_Activity_Final, i18n("Final Activity")); break; case mt_FlipHorizontal: m_actions[m] = menu->addAction(i18n("Flip Horizontal")); break; case mt_FlipVertical: m_actions[m] = menu->addAction(i18n("Flip Vertical")); break; case mt_FloatText: LPMISI(it_Text, i18n("Text Line...")); break; case mt_ForeignKeyConstraint: LPMISI(it_Constraint_ForeignKey, i18n("Foreign Key Constraint...")); break; case mt_Fork: LPMISI(it_Fork_Join, i18n("Fork")); break; case mt_GoToStateDiagram: LPMISI(it_Remove, i18n("Go to state diagram")); break; case mt_Hide_Destruction_Box: LPMISI(it_Message_Destroy, i18n("Hide destruction box")); break; case mt_Import_Class: LPMIBI(it_Import_File, i18n("Import File(s)...")); break; case mt_Import_Project: LPMIBI(it_Import_Project, i18n("Import from Directory...")); break; case mt_Import_from_File: LPMISI(it_Import_File, i18n("from file...")); break; case mt_Initial_Activity: LPMISI(it_InitialState, i18n("Initial Activity")); break; case mt_Initial_State: LPMISI(it_InitialState, i18n("Initial State")); break; case mt_Instance: LPMISI(it_Instance, i18nc("new instance menu item", "Instance...")); break; case mt_InstanceAttribute: LPMISI(it_Attribute_New, i18n("New Attribute...")); break; case mt_Interface: LPMISI(it_Interface, i18n("Interface")); break; case mt_InterfaceComponent: LPMISI(it_Interface_Provider, i18n("Interface")); break; case mt_InterfaceProvided: LPMISI(it_Interface_Provider, i18n("Provided interface")); break; case mt_InterfaceRequired: LPMISI(it_Interface_Requirement, i18n("Required interface")); break; case mt_Internalize_Folder: m_actions[m] = menu->addAction(i18n("Internalize Folder")); break; case mt_Junction: LPMISI(it_Junction, i18n("Junction")); break; case mt_Line_Color: LPMISI(it_Color_Line, i18n("Line Color...")); break; case mt_Logical_Folder: LPMIBI(it_Folder, i18n("Folder")); break; case mt_MessageAsynchronous: LPMISI(it_Message_Async, i18n("Asynchronous Message")); break; case mt_MessageCreation: LPMISI(it_Message_Creation, i18n("Creation Message")); break; case mt_MessageDestroy: LPMISI(it_Message_Destroy, i18n("Destroy Message")); break; case mt_MessageFound: LPMISI(it_Message_Found, i18n("Found Message")); break; case mt_MessageLost: LPMISI(it_Message_Lost, i18n("Lost Message")); break; case mt_MessageSynchronous: LPMISI(it_Message_Sync, i18n("Synchronous Message")); break; case mt_New_Activity: LPMISI(it_State_Activity, i18n("Activity...")); break; case mt_New_Attribute: LPMISI(it_Attribute_New, i18n("New Attribute...")); break; case mt_New_EntityAttribute: LPMISI(it_Entity_Attribute_New, i18n("New Entity Attribute...")); break; case mt_New_EnumLiteral: LPMISI(it_Literal_New, i18n("New Literal...")); break; case mt_New_InstanceAttribute: LPMISI(it_Attribute_New, i18n("New Attribute...")); break; case mt_New_Operation: LPMISI(it_Operation_Public_New, i18n("New Operation...")); break; case mt_New_Parameter: LPMISI(it_Parameter_New, i18n("New Parameter...")); break; case mt_New_Template: LPMISI(it_Template_New, i18n("New Template...")); break; case mt_Node: LPMISI(it_Node, i18n("Node")); break; //case mt_Node: LPMISI(it_Node, i18n("Node...")); break; case mt_Note: LPMISI(it_Note, i18n("Note...")); break; case mt_Object: LPMISI(it_Object, i18n("Object...")); break; case mt_Object_Node: LPMISI(it_Object_Node, i18n("Object Node")); break; case mt_Open_File: LPMISI(it_File_Open, i18n("Open file")); break; case mt_Operation: LPMISI(it_Public_Method, i18n("Operation")); break; //case mt_Operation: LPMISI(it_Public_Method, i18n("Operation...")); break; case mt_Package: LPMISI(it_Package, i18n("Package...")); break; case mt_Paste: LPMISI(it_Paste, i18n("Paste")); break; case mt_Pin: LPMISI(it_Pin, i18n("Pin")); break; case mt_Port: LPMISI(it_Port, i18n("Port")); break; //case mt_Port: LPMISI(it_Port, i18n("Port...")); break; case mt_PrePostCondition: LPMISI(it_Condition_PrePost, i18n("Pre Post Condition")); break; case mt_PrimaryKeyConstraint: LPMISI(it_Constraint_PrimaryKey, i18n("Primary Key Constraint...")); break; case mt_Properties: LPMISI(it_Properties, i18n("Properties")); break; case mt_Redo: LPMISI(it_Redo, i18n("Redo")); break; case mt_Region: LPMISI(it_Region, i18n("Region")); break; case mt_Remove: LPMISI(it_Remove, i18n("Remove")); break; case mt_RemoveStateDiagram: LPMISI(it_Remove, i18n("Remove state diagram")); break; case mt_Rename: LPMISI(it_Rename, i18n("Rename...")); break; case mt_Rename_Object: insert(m, menu, i18n("Rename Object...")); break; case mt_ReturnToCombinedState: LPMISI(it_Redo, i18n("Return to combined state")); break; case mt_ReturnToClass: LPMISI(it_Redo, i18n("Return to class")); break; case mt_Reset_Label_Positions: m_actions[m] = menu->addAction(i18n("Reset Label Positions")); break; case mt_Resize: insert(m, menu, i18n("Resize")); break; case mt_SelectStateDiagram: LPMISI(it_Remove, i18n("Select state diagram")); break; case mt_Send_Signal: LPMISI(it_Send_Signal, i18n("Send Signal")); break; case mt_ShallowHistory: LPMISI(it_History_Shallow, i18n("Shallow History")); break; case mt_Show: LPMISI(it_Show, i18n("Show")); break; case mt_Show_Destruction_Box: LPMISI(it_Message_Destroy, i18n("Show destruction box")); break; case mt_State: LPMISI(it_State, i18nc("add new state", "State...")); break; case mt_StateFork: LPMISI(it_Fork_State, i18n("Fork")); break; case mt_StateJoin: LPMISI(it_Join, i18n("Join")); break; case mt_StateTransition: LPMISI(it_State_Transition, i18n("State Transition")); break; case mt_State_Diagram: insertFromActionKey(m, menu, QStringLiteral("new_state_diagram")); break; case mt_Subsystem: LPMISI(it_Subsystem, i18n("Subsystem")); break; //case mt_Subsystem: LPMISI(it_Subsystem, i18n("Subsystem...")); break; case mt_Template: LPMISI(it_Template_Class, i18n("Template")); break; //case mt_Template: LPMISI(it_Template_New, i18n("Template...")); break; case mt_Undo: LPMISI(it_Undo, i18n("Undo")); break; case mt_UniqueConstraint: LPMISI(it_Constraint_Unique, i18n("Unique Constraint...")); break; case mt_UseCase: LPMISI(it_UseCase, i18n("Use Case")); break; //case mt_UseCase: LPMISI(it_UseCase, i18n("Use Case...")); break; case mt_UseCase_Diagram: insertFromActionKey(m, menu, QStringLiteral("new_use_case_diagram")); break; case mt_UseCase_Folder: LPMIBI(it_Folder, i18n("Folder")); break; default: logWarn1("ListPopupMenu::insert called on unimplemented MenuType %1", toString(m)); break; } #undef LPMISI #undef LPMIBI } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. * @param icon The icon for this action. * @param text The text for this action. */ void ListPopupMenu::insert(const MenuType m, const QIcon & icon, const QString & text) { DEBUG_AddAction(m); m_actions[m] = addAction(icon, text); } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. * @param text The text for this action. * @param checkable Sets the action to checkable. */ void ListPopupMenu::insert(const MenuType m, const QString & text, const bool checkable) { insert(m, this, text, checkable); } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. * @param menu The QMenu for which to insert a menu item. * @param icon The icon for this action. * @param text The text for this action. */ void ListPopupMenu::insert(const MenuType m, QMenu* menu, const QIcon & icon, const QString & text) { DEBUG_AddAction(m); m_actions[m] = menu->addAction(icon, text); } /** * Shortcut for the frequently used addAction() calls. * * @param m The MenuType for which to insert a menu item. * @param menu The QMenu for which to insert a menu item. * @param text The text for this action. * @param checkable Sets the action to checkable. */ void ListPopupMenu::insert(const MenuType m, QMenu* menu, const QString & text, const bool checkable) { DEBUG_AddAction(m); m_actions[m] = menu->addAction(text); if (checkable) { QAction* action = getAction(m); if (action) action->setCheckable(checkable); } } /** * Shortcut for inserting standard model items (Class, Interface, * Datatype, Enum, Package) as well as diagram choices. * * @param folders Set this true if folders shall be included as choices. * @param diagrams Set this true if diagram types shall be included as choices. * @param packages Set this true if packages shall be included as choices. */ void ListPopupMenu::insertContainerItems(bool folders, bool diagrams, bool packages) { QMenu* menu = newMenu(i18nc("new container menu", "New"), this); menu->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_New)); insertContainerItems(menu, folders, diagrams, packages); addMenu(menu); } /** * Shortcut for inserting standard model items (Class, Interface, * Datatype, Enum, Package) as well as diagram choices. * * @param menu Menu to add the menu entries * @param folders Set this true if folders shall be included as choices. * @param diagrams Set this true if diagram types shall be included as choices. * @param packages Set this true if packages shall be included as choices. */ void ListPopupMenu::insertContainerItems(QMenu* menu, bool folders, bool diagrams, bool packages) { if (folders) insert(mt_Logical_Folder, menu, Icon_Utils::BarIcon(Icon_Utils::it_Folder), i18n("Folder")); insert(mt_Class, menu); insert(mt_Interface, menu); insert(mt_Datatype, menu); insert(mt_Enum, menu); insert(mt_Instance, menu); if (packages) insert(mt_Package, menu); if (diagrams) { insertFromActionKey(mt_Class_Diagram, menu, QStringLiteral("new_class_diagram")); insertFromActionKey(mt_Sequence_Diagram, menu, QStringLiteral("new_sequence_diagram")); insertFromActionKey(mt_Collaboration_Diagram, menu, QStringLiteral("new_collaboration_diagram")); insertFromActionKey(mt_State_Diagram, menu, QStringLiteral("new_state_diagram")); insertFromActionKey(mt_Activity_Diagram, menu, QStringLiteral("new_activity_diagram")); } } /** * Inserts a menu item for an association related text * (such as name, role, multiplicity etc.) * * @param label The menu text. * @param mt The menu type. */ void ListPopupMenu::insertAssociationTextItem(const QString &label, MenuType mt) { insert(mt, label); insert(mt_Change_Font); insert(mt_Reset_Label_Positions); insert(mt_Properties); } /** * Convenience method to extract the ListPopupMenu type from an action. * @param action the action which was called * @return menu type enum value */ ListPopupMenu::MenuType ListPopupMenu::typeFromAction(QAction *action) { ListPopupMenu *menu = ListPopupMenu::menuFromAction(action); if (menu) { return menu->getMenuType(action); } else { logError0("typeFromAction: Action's data field does not contain ListPopupMenu pointer!"); return mt_Undefined; } } /** * Utility: Convert a MenuType value to an ObjectType value. */ UMLObject::ObjectType ListPopupMenu::convert_MT_OT(MenuType mt) { UMLObject::ObjectType type = UMLObject::ot_UMLObject; switch (mt) { case mt_UseCase: type = UMLObject::ot_UseCase; break; case mt_Actor: type = UMLObject::ot_Actor; break; case mt_Class: type = UMLObject::ot_Class; break; case mt_Datatype: type = UMLObject::ot_Datatype; break; case mt_Attribute: type = UMLObject::ot_Attribute; break; case mt_Interface: type = UMLObject::ot_Interface; break; case mt_Template: type = UMLObject::ot_Template; break; case mt_Enum: type = UMLObject::ot_Enum; break; case mt_EnumLiteral: type = UMLObject::ot_EnumLiteral; break; case mt_EntityAttribute: type = UMLObject::ot_EntityAttribute; break; case mt_Operation: type = UMLObject::ot_Operation; break; case mt_Category: type = UMLObject::ot_Category; break; case mt_InstanceAttribute: type = UMLObject::ot_InstanceAttribute; break; default: break; } return type; } /** * Returns the data from the given action to the given key. */ QVariant ListPopupMenu::dataFromAction(DataType key, QAction* action) { QVariant data = action->data(); QMap<QString, QVariant> map = data.toMap(); return map[ListPopupMenu::toString(key)]; } /** * Convenience method to extract the ListPopupMenu pointer stored in QAction * objects belonging to ListPopupMenu. */ ListPopupMenu* ListPopupMenu::menuFromAction(QAction *action) { if (action) { QVariant value = dataFromAction(dt_MenuPointer, action); if (value.canConvert<ListPopupMenu*>()) { return qvariant_cast<ListPopupMenu*>(value); } } return nullptr; } /** * Create the 'new' menu * @return menu instance */ QMenu *ListPopupMenu::makeNewMenu() { QMenu *menu = newMenu(i18nc("new sub menu", "New"), this); menu->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_New)); return menu; } /** * Creates a popup menu for a single category Object * @param category The UMLCategory for which the category menu is created */ void ListPopupMenu::insertSubMenuCategoryType(UMLCategory* category) { QMenu* menu = newMenu(i18nc("category type sub menu", "Category Type"), this); insert(mt_DisjointSpecialisation, menu, i18n("Disjoint(Specialisation)"), CHECKABLE); insert(mt_OverlappingSpecialisation, menu, i18n("Overlapping(Specialisation)"), CHECKABLE); insert(mt_Union, menu, i18n("Union"), CHECKABLE); setActionChecked(mt_DisjointSpecialisation, category->getType()==UMLCategory::ct_Disjoint_Specialisation); setActionChecked(mt_OverlappingSpecialisation, category->getType()==UMLCategory::ct_Overlapping_Specialisation); setActionChecked(mt_Union, category->getType()==UMLCategory::ct_Union); addMenu(menu); } /** * Get the action from the menu type as index. */ QAction* ListPopupMenu::getAction(MenuType idx) { return m_actions.value(idx, nullptr); } // /** // * Get the MenuType from the action. // */ // ListPopupMenu::MenuType ListPopupMenu::getMenuType(KAction* action) // { // return m_actions.key(action); // } /** * Get the MenuType from the action. */ ListPopupMenu::MenuType ListPopupMenu::getMenuType(QAction* action) { QList<MenuType> keyList = m_actions.keys(action); if (keyList.empty() || /* all key-value pairs are unique*/ keyList.count() > 1) { return mt_Undefined; } else { // we return the first (only) value return keyList.first(); } } /** * Checks the action item. * * @param idx The MenuType for which to check the menu item. * @param value The value. */ void ListPopupMenu::setActionChecked(MenuType idx, bool value) { QAction* action = getAction(idx); if (action && action->isCheckable()) { action->setChecked(value); } else { DEBUG() << "called on unknown MenuType " << toString(idx); } } /** * Enables the action item. * * @param idx The MenuType for which to enable the menu item. * @param value The value. */ void ListPopupMenu::setActionEnabled(MenuType idx, bool value) { QAction* action = getAction(idx); if (action) { action->setEnabled(value); } else { DEBUG() << "called on unknown MenuType " << toString(idx); } } /** * Sets up actions added to the ListPopupMenu to have their data field set to * pointer to this ListPopupMenu object, so that this menu pointer can be * retrieved in UMLWidget::slotMenuSelection * * @note This might seem like an ugly hack, but this is the only solution which * helped in avoiding storage of ListPopupMenu pointer in each UMLWidget. */ void ListPopupMenu::setupActionsData() { for(QAction *action : m_actions) { QMap<QString, QVariant> map = action->data().toMap(); map[toString(dt_MenuPointer)] = QVariant::fromValue(this); action->setData(QVariant(map)); } } /** * Convert enum MenuType to string. */ QString ListPopupMenu::toString(MenuType menu) { return QLatin1String(ENUM_NAME(ListPopupMenu, MenuType, menu)); } /** * Convert enum DataType to string. */ QString ListPopupMenu::toString(DataType data) { return QLatin1String(ENUM_NAME(ListPopupMenu, DataType, data)); } //QList<DebugMenu> &ListPopupMenu::debugActions() //{ // return d->debugActions; //} /** * dump collected actions * @param title optional menu title */ void ListPopupMenu::dumpActions(const QString &title) { qDebug().nospace() << title; for(DebugMenu e : d->debugActions) { if (!e.menu.isEmpty()) qDebug().nospace() << " " << e.menu; else qDebug().nospace() << " " << toString(e.m); } }
27,925
C++
.cpp
595
43.168067
134
0.621409
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,423
dialogspopupmenu.cpp
KDE_umbrello/umbrello/menus/dialogspopupmenu.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "dialogspopupmenu.h" // app includes #include "debug_utils.h" #include "uml.h" // Only needed for log{Warn,Error} // kde includes #include <KLocalizedString> DialogsPopupMenu::DialogsPopupMenu(QWidget *parent, TriggerType type) : ListPopupMenu(parent) { switch(type) { case tt_New_Parameter: insert(mt_New_Parameter); break; case tt_New_Operation: insert(mt_New_Operation); break; case tt_New_Attribute: insert(mt_New_Attribute); break; case tt_New_InstanceAttribute: insert(mt_New_InstanceAttribute); break; case tt_New_Template: insert(mt_New_Template); break; case tt_New_EnumLiteral: insert(mt_New_EnumLiteral); break; case tt_New_EntityAttribute: insert(mt_New_EntityAttribute); break; case tt_New_Activity: insertSubMenuNew(type); break; case tt_Activity_Selected: insertSubMenuNew(type); insert(mt_Rename); insert(mt_Delete); break; case tt_Parameter_Selected: insert(mt_New_Parameter); insert(mt_Rename); insert(mt_Delete); insert(mt_Properties); break; case tt_Operation_Selected: insert(mt_New_Operation); insert(mt_Delete); insert(mt_Properties); break; case tt_Attribute_Selected: insert(mt_New_Attribute); insert(mt_Delete); insert(mt_Properties); break; case tt_InstanceAttribute_Selected: insert(mt_New_InstanceAttribute); insert(mt_Delete); insert(mt_Properties); break; case tt_Template_Selected: insert(mt_New_Attribute, Icon_Utils::SmallIcon(Icon_Utils::it_Template_New), i18n("New Template...")); insert(mt_Delete); insert(mt_Properties); break; case tt_EnumLiteral_Selected: insert(mt_New_EnumLiteral); insert(mt_Delete); insert(mt_Properties); break; case tt_EntityAttribute_Selected: insert(mt_New_EntityAttribute); insert(mt_Delete); insert(mt_Properties); break; default: logWarn1("DialogsPopupMenu: unknown menu type %1", type); break; }//end switch setupActionsData(); } /** * Shortcut for commonly used sub menu initializations. * * @param type The MenuType for which to set up the menu. */ void DialogsPopupMenu::insertSubMenuNew(TriggerType type) { QMenu * menu = makeNewMenu(); switch (type) { case tt_New_Activity: case tt_Activity_Selected: break; default: break; } addMenu(menu); } /** * Convert enum MenuType to string. */ QString DialogsPopupMenu::toString(TriggerType type) { return QLatin1String(ENUM_NAME(DialogsPopupMenu, TriggerType, type)); } QDebug operator<<(QDebug out, DialogsPopupMenu::TriggerType type) { out.nospace() << "ListPopupMenu::TriggerType: " << DialogsPopupMenu::toString(type); return out.space(); }
3,212
C++
.cpp
114
21.885965
110
0.651707
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,424
findresults.cpp
KDE_umbrello/umbrello/finder/findresults.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "findresults.h" // app includes #include "uml.h" #include "umldocfinder.h" #include "umllistviewfinder.h" #include "umlscenefinder.h" #include "umlview.h" FindResults::FindResults() { } FindResults::~FindResults() { } /** * Collect items limited by a filter, a category and a text * * @param filter filter to limit the search * @param category category to search for (currently unsupported) * @param text * @return Number of items found */ int FindResults::collect(UMLFinder::Filter filter, UMLFinder::Category category, const QString &text) { Q_UNUSED(category); clear(); if (filter == UMLFinder::TreeView) { m_listViewFinder.append(UMLListViewFinder()); return m_listViewFinder.last().collect(category, text); } else if (filter == UMLFinder::CurrentDiagram) { m_sceneFinder.append(UMLSceneFinder(UMLApp::app()->currentView())); return m_sceneFinder.last().collect(category, text); } else if (filter == UMLFinder::AllDiagrams) { m_docFinder.append(UMLDocFinder()); return m_docFinder.last().collect(category, text); } return 0; } /** * Clear the find results. */ void FindResults::clear() { m_docFinder.clear(); m_listViewFinder.clear(); m_sceneFinder.clear(); } /** * Show next item. * * @return false if no more items are available * @return true an item has been displayed */ bool FindResults::displayNext() { UMLFinder *finder = nullptr; if (m_listViewFinder.size() > 0) finder = &m_listViewFinder.first(); else if (m_sceneFinder.size() > 0) finder = &m_sceneFinder.first(); else if (m_docFinder.size() > 0) finder = &m_docFinder.first(); if (finder == nullptr) return false; UMLFinder::Result result = finder->displayNext(); if (result == UMLFinder::Empty) return false; else if (result == UMLFinder::End) return finder->displayNext() == UMLFinder::Found; else if (result == UMLFinder::NotFound) return displayNext(); return true; } /** * Show previous item. * * @return false if no more items are available * @return true an item has been displayed */ bool FindResults::displayPrevious() { UMLFinder *finder = nullptr; if (m_listViewFinder.size() > 0) finder = &m_listViewFinder.first(); else if (m_sceneFinder.size() > 0) finder = &m_sceneFinder.first(); else if (m_docFinder.size() > 0) finder = &m_docFinder.first(); if (finder == nullptr) return false; UMLFinder::Result result = finder->displayPrevious(); if (result == UMLFinder::Empty) return false; else if (result == UMLFinder::End) return finder->displayPrevious() == UMLFinder::Found; else if (result == UMLFinder::NotFound) return displayNext(); return true; }
3,002
C++
.cpp
104
24.759615
101
0.672664
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,425
umlfinder.cpp
KDE_umbrello/umbrello/finder/umlfinder.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlfinder.h" #include "umlobject.h" UMLFinder::UMLFinder() : m_index(-1) { } UMLFinder::~UMLFinder() { } bool UMLFinder::includeObject(UMLFinder::Category category, UMLObject *o) { if (!o) return false; UMLObject::ObjectType type = o->baseType(); return category == All || (category == Classes && type == UMLObject::ot_Class) || (category == Interfaces && type == UMLObject::ot_Interface) || (category == Packages && type == UMLObject::ot_Package) || (category == Operations && type == UMLObject::ot_Operation) || (category == Attributes && type == UMLObject::ot_Attribute) ; }
830
C++
.cpp
25
28
92
0.63375
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
749,426
umldocfinder.cpp
KDE_umbrello/umbrello/finder/umldocfinder.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umldocfinder.h" // app include #include "uml.h" #include "umldoc.h" #include "umlscenefinder.h" #include "umlview.h" #include "umlwidget.h" #include "umlviewlist.h" UMLDocFinder::UMLDocFinder() : UMLFinder() { } UMLDocFinder::~UMLDocFinder() { } int UMLDocFinder::collect(UMLFinder::Category category, const QString &text) { m_sceneFinder.clear(); UMLViewList views = UMLApp::app()->document()->viewIterator(); int counts = 0; for (UMLView *view: views) { UMLSceneFinder finder(view); int count = finder.collect(category, text); if (count > 0) { m_sceneFinder.append(finder); counts += count; } } m_index = 0; return counts; } UMLFinder::Result UMLDocFinder::displayNext() { if (m_sceneFinder.size() == 0) return Empty; if (m_index >= m_sceneFinder.size()) { m_index = 0; return End; } Result result = m_sceneFinder[m_index].displayNext(); if (result == End) { ++m_index; return displayNext(); } else if (result == NotFound) { return displayPrevious(); } return result; } UMLFinder::Result UMLDocFinder::displayPrevious() { if (m_sceneFinder.size() == 0) return Empty; if (m_index < 0) { m_index = m_sceneFinder.size()-1; return End; } Result result = m_sceneFinder[m_index].displayPrevious(); if (result == End) { --m_index; return displayPrevious(); } else if (result == NotFound) { return displayPrevious(); } return result; }
1,748
C++
.cpp
71
19.802817
92
0.629496
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,427
umlscenefinder.cpp
KDE_umbrello/umbrello/finder/umlscenefinder.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlscenefinder.h" #include "floatingtextwidget.h" #include "messagewidget.h" #include "uml.h" #include "umldoc.h" #include "umllistview.h" #include "umlscene.h" #include "umlview.h" UMLSceneFinder::UMLSceneFinder(UMLView *view) : UMLFinder(), m_id(view->umlScene()->ID()) { } UMLSceneFinder::~UMLSceneFinder() { } int UMLSceneFinder::collect(Category category, const QString &text) { Q_UNUSED(category); m_items.clear(); m_index = -1; UMLView *view = UMLApp::app()->document()->findView(m_id); if (!view) return 0; UMLScene *scene = view->umlScene(); for(UMLWidget* w: scene->widgetList()) { if (!includeObject(category, w->umlObject())) continue; if (w->name().contains(text, Qt::CaseInsensitive)) m_items.append(w->id()); } for(MessageWidget* w: scene->messageList()) { if (w->umlObject() && !includeObject(category, w->umlObject())) continue; if (w->name().contains(text, Qt::CaseInsensitive)) m_items.append(w->id()); if (w->floatingTextWidget()->text().contains(text, Qt::CaseInsensitive)) m_items.append(w->id()); } return m_items.size(); } UMLFinder::Result UMLSceneFinder::displayNext() { if (m_items.size() == 0 || UMLApp::app()->document()->findView(m_id) == nullptr) return Empty; if (m_index >= m_items.size()-1) { m_index = -1; return End; } return showItem(m_items.at(++m_index)) ? Found : NotFound; } UMLFinder::Result UMLSceneFinder::displayPrevious() { if (m_items.size() == 0 || UMLApp::app()->document()->findView(m_id) == nullptr) return Empty; if (m_index < 1) { m_index = m_items.size(); return End; } return showItem(m_items.at(--m_index)) ? Found : NotFound; } /** * Show item in diagram. * * @param id ID of uml object to show * @return false scene or widget not found, true otherwise * @return true widget has been shown */ bool UMLSceneFinder::showItem(Uml::ID::Type id) { UMLView *view = UMLApp::app()->document()->findView(m_id); if (!view) return false; UMLScene *scene = view->umlScene(); if (!scene) return false; UMLWidget *w = scene->findWidget(id); if (!w) return false; scene->setIsOpen(true); view->setZoom(100); if (UMLApp::app()->currentView() != view) { UMLApp::app()->setCurrentView(view, false); } view->centerOn(w->pos() + QPointF(w->width(), w->height())/2); scene->clearSelection(); w->setSelected(true); // tree view item display is optional if (!w->umlObject()) { UMLApp::app()->listView()->clearSelection(); return true; } UMLListViewItem * item = UMLApp::app()->listView()->findItem(w->umlObject()->id()); if (!item) { UMLApp::app()->listView()->clearSelection(); return true; } UMLApp::app()->listView()->setCurrentItem(item); return true; }
3,153
C++
.cpp
104
25.336538
92
0.622076
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,428
umllistviewfinder.cpp
KDE_umbrello/umbrello/finder/umllistviewfinder.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umllistviewfinder.h" // app include #include "uml.h" #include "umllistview.h" #include "umlobject.h" UMLListViewFinder::UMLListViewFinder() : UMLFinder() { } UMLListViewFinder::~UMLListViewFinder() { } int UMLListViewFinder::collect(Category category, const QString &text) { Q_UNUSED(category); QList<QTreeWidgetItem*> items = UMLApp::app()->listView()->findItems(text, Qt::MatchContains | Qt::MatchRecursive); m_items.clear(); for (QTreeWidgetItem *item: items) { UMLListViewItem *ui = dynamic_cast<UMLListViewItem *>(item); if (!ui) continue; UMLObject *o = ui->umlObject(); if (!includeObject(category, o)) continue; m_items.append(o->id()); } m_index = -1; return m_items.size(); } UMLFinder::Result UMLListViewFinder::displayNext() { if (m_items.size() == 0) return Empty; if (m_index >= m_items.size()-1) { m_index = -1; return End; } return showItem(m_items.at(++m_index)) ? Found : NotFound; } UMLFinder::Result UMLListViewFinder::displayPrevious() { if (m_items.size() == 0) return Empty; if (m_index < 1) { m_index = m_items.size(); return End; } return showItem(m_items.at(--m_index)) ? Found : NotFound; } /** * Show item in Tree View. * * @param id ID of uml object to show * @return false list view entry not found, true otherwise */ bool UMLListViewFinder::showItem(Uml::ID::Type id) { UMLListViewItem * item = UMLApp::app()->listView()->findItem(id); if (!item) return false; UMLApp::app()->listView()->setCurrentItem(item); return true; }
1,824
C++
.cpp
67
22.940299
119
0.652174
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,429
cmdremovediagram.cpp
KDE_umbrello/umbrello/cmds/cmdremovediagram.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdremovediagram.h" #include "basictypes.h" #include "debug_utils.h" #include "uml.h" #include "umldoc.h" #include "umlscene.h" #include "umlview.h" #include <KLocalizedString> #include <QXmlStreamWriter> namespace Uml { CmdRemoveDiagram::CmdRemoveDiagram(UMLFolder* folder, Uml::DiagramType::Enum type, const QString& name, Uml::ID::Type id) : QUndoCommand(), m_folder(folder), m_type(type), m_name(name), m_sceneId(id) { UMLScene* scene = UMLApp::app()->document()->findView(id)->umlScene(); QString msg = i18n("Remove diagram %1", scene->name()); setText(msg); // Save diagram XMI for undo QString xmi; QXmlStreamWriter stream(&xmi); stream.writeStartElement(QStringLiteral("diagram")); scene->saveToXMI(stream); stream.writeEndElement(); // diagram QString error; int line; QDomDocument domDoc; if (domDoc.setContent(xmi, &error, &line)) { // The first child element contains the diagram XMI m_element = domDoc.firstChild().firstChild().toElement(); // CHECK was: container } else { logWarn3("CmdRemoveDiagram(%1): Cannot set content. Error %2 line %3", scene->name(), error, line); } } CmdRemoveDiagram::~CmdRemoveDiagram() { } void CmdRemoveDiagram::redo() { UMLApp::app()->document()->removeDiagramCmd(m_sceneId); } void CmdRemoveDiagram::undo() { UMLDoc* doc = UMLApp::app()->document(); UMLView* view = doc->createDiagram(m_folder, m_type, m_name, m_sceneId); view->umlScene()->loadFromXMI(m_element); } }
1,996
C++
.cpp
59
25.508475
94
0.594805
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,430
cmdbaseobjectcommand.cpp
KDE_umbrello/umbrello/cmds/cmdbaseobjectcommand.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2007-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdbaseobjectcommand.h" // app includes #include "uml.h" #include "umldoc.h" #include "umlobject.h" // kde includes #include <KLocalizedString> namespace Uml { CmdBaseObjectCommand::CmdBaseObjectCommand(UMLObject* object) { setObject(object); } CmdBaseObjectCommand::~CmdBaseObjectCommand() { } void CmdBaseObjectCommand::setObject(UMLObject* object) { Q_ASSERT(object); m_object = object; m_objectId = object->id(); } UMLObject* CmdBaseObjectCommand::object() { UMLDoc *doc = UMLApp::app()->document(); UMLObject *umlObject = doc->findObjectById(m_objectId); if (!umlObject) umlObject = m_object; return umlObject; } }
909
C++
.cpp
35
20.914286
92
0.673611
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,431
cmdsetstereotype.cpp
KDE_umbrello/umbrello/cmds/cmdsetstereotype.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdsetstereotype.h" // app includes #include "umlobject.h" #include <KLocalizedString> namespace Uml { CmdSetStereotype::CmdSetStereotype(UMLObject * obj, const QString& stereo) : CmdBaseObjectCommand(obj), m_stereo(stereo) { m_oldStereo = obj->stereotype(); setText(i18n("Set stereotype : %1 to %2", m_oldStereo, stereo)); } CmdSetStereotype::~CmdSetStereotype() { } void CmdSetStereotype::redo() { UMLObject *umlObject = object(); if (umlObject) umlObject->setStereotypeCmd(m_stereo); } void CmdSetStereotype::undo() { UMLObject *umlObject = object(); if (umlObject) umlObject->setStereotypeCmd(m_oldStereo); } }
913
C++
.cpp
33
22.090909
92
0.661309
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,432
cmdcreatediagram.cpp
KDE_umbrello/umbrello/cmds/cmdcreatediagram.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2012-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdcreatediagram.h" #include "model_utils.h" #include "umldoc.h" #include "umlscene.h" #include "umlview.h" #include <KLocalizedString> namespace Uml { CmdCreateDiagram::CmdCreateDiagram(UMLDoc* doc, Uml::DiagramType::Enum type, const QString& name, UMLFolder *parent) : QUndoCommand(), m_name(name), m_type(type), m_pUMLDoc(doc), m_pUMLView(nullptr), m_parent(parent) { QString msg = i18n("Create diagram %1: %2", DiagramType::toString(type), name); setText(msg); m_sceneId = Uml::ID::None; } CmdCreateDiagram::~CmdCreateDiagram() { } void CmdCreateDiagram::redo() { if (!m_pUMLDoc->findView(m_type, m_name, true)) { Uml::ModelType::Enum modelType = Model_Utils::convert_DT_MT(m_type); UMLFolder* folder = m_parent ? m_parent : m_pUMLDoc->rootFolder(modelType); m_pUMLView = m_pUMLDoc->createDiagram(folder, m_type, m_name, m_sceneId); } // Remember the scene-ID, it might be auto generated. The ID must // not change after undo/redo because other commands may try to // lookup the diagram later. m_sceneId = m_pUMLView->umlScene()->ID(); } void CmdCreateDiagram::undo() { if (m_pUMLView) { m_pUMLDoc->removeDiagramCmd(m_sceneId); } } }
1,534
C++
.cpp
46
26.934783
120
0.635748
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,433
cmdsetvisibility.cpp
KDE_umbrello/umbrello/cmds/cmdsetvisibility.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdsetvisibility.h" // app includes #include "uml.h" #include "umldoc.h" #include "umlobject.h" #include <KLocalizedString> namespace Uml { CmdSetVisibility::CmdSetVisibility(UMLObject * obj, Visibility::Enum visibility) : CmdBaseObjectCommand(obj), m_visibility(visibility) { setText(i18n("Change visibility : %1", obj->name())); m_oldVisibility = obj->visibility(); } CmdSetVisibility::~CmdSetVisibility() { } void CmdSetVisibility::redo() { UMLObject *umlObject = object(); if (umlObject) umlObject->setVisibilityCmd(m_visibility); } void CmdSetVisibility::undo() { UMLObject *umlObject = object(); if (umlObject) umlObject->setVisibilityCmd(m_oldVisibility); } }
965
C++
.cpp
35
22.257143
92
0.67101
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,434
cmdhandlerename.cpp
KDE_umbrello/umbrello/cmds/cmdhandlerename.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdhandlerename.h" #include "floatingtextwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdHandleRename::CmdHandleRename(FloatingTextWidget* ftw, QString& txt) : QUndoCommand(), m_ftw(ftw), m_newstring(txt) { m_oldstring = ftw->text(); setText(i18n("Change text : %1 to %2", m_oldstring, txt)); } CmdHandleRename::~CmdHandleRename() { } void CmdHandleRename::redo() { m_ftw->changeName(m_newstring); } void CmdHandleRename::undo() { m_ftw->changeName(m_oldstring); } }
758
C++
.cpp
30
20.3
92
0.659249
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,435
cmdbasewidgetcommand.cpp
KDE_umbrello/umbrello/cmds/widget/cmdbasewidgetcommand.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2007-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdbasewidgetcommand.h" // app includes #include "association.h" #include "associationwidget.h" #include "folder.h" #include "messagewidget.h" #include "model_utils.h" #include "uml.h" #include "umldoc.h" #include "umlscene.h" #include "umlview.h" #include "umlwidget.h" namespace Uml { CmdBaseWidgetCommand::CmdBaseWidgetCommand(UMLWidget* widget) : m_isAssoc(false) { setWidget(widget); } CmdBaseWidgetCommand::CmdBaseWidgetCommand(AssociationWidget* widget) : m_isAssoc(true) { setWidget(widget); } CmdBaseWidgetCommand::~CmdBaseWidgetCommand() { } void CmdBaseWidgetCommand::setWidget(UMLWidget* widget) { Q_ASSERT(widget); m_widget = widget; m_assocWidget = nullptr; m_widgetId = widget->localID(); m_scene = widget->umlScene(); m_sceneId = widget->umlScene()->ID(); } void CmdBaseWidgetCommand::setWidget(AssociationWidget* widget) { Q_ASSERT(widget); m_widget = nullptr; m_assocWidget = widget; m_widgetId = widget->id(); m_scene = widget->umlScene(); m_sceneId = widget->umlScene()->ID(); } UMLScene* CmdBaseWidgetCommand::scene() { UMLView* umlView = UMLApp::app()->document()->findView(m_sceneId); if (umlView) return umlView->umlScene(); Q_ASSERT(m_scene.data()); return m_scene; } UMLWidget* CmdBaseWidgetCommand::widget() { UMLWidget* widget = scene()->findWidget(m_widgetId); if (widget) return widget; Q_ASSERT(m_widget.data()); return m_widget; } AssociationWidget* CmdBaseWidgetCommand::assocWidget() { AssociationWidget *widget = scene()->findAssocWidget(m_widgetId); if (widget) return widget; Q_ASSERT(m_assocWidget.data()); return m_assocWidget; } /** * Add widget to scene * * @param widget Pointer to widget to add */ void CmdBaseWidgetCommand::addWidgetToScene(UMLWidget* widget) { scene()->addWidgetCmd(widget); widget->activate(); } /** * Add widget to scene * * @param widget Pointer to widget to add */ void CmdBaseWidgetCommand::addWidgetToScene(AssociationWidget* widget) { widget->clipSize(); if (scene()->addAssociation(widget, false)) { // if view went ok, then append in document UMLAssociation *umla = widget->association(); if (umla) { // association with model representation in UMLDoc Uml::ModelType::Enum m = Model_Utils::convert_DT_MT(scene()->type()); UMLDoc *umldoc = UMLApp::app()->document(); umla->setUMLPackage(umldoc->rootFolder(m)); umldoc->addAssociation(umla); if (umla->getAssocType() == Uml::AssociationType::Containment) { UMLObject *newContainer = widget->widgetForRole(Uml::RoleType::A)->umlObject(); UMLObject *objToBeMoved = widget->widgetForRole(Uml::RoleType::B)->umlObject(); if (newContainer && objToBeMoved) { Model_Utils::treeViewMoveObjectTo(newContainer, objToBeMoved); } } } } widget->activate(); } void CmdBaseWidgetCommand::removeWidgetFromScene(UMLWidget *widget) { if (widget != nullptr) scene()->removeWidgetCmd(widget); } void CmdBaseWidgetCommand::removeWidgetFromScene(AssociationWidget* widget) { if (widget != nullptr) scene()->removeWidgetCmd(widget); } }
3,910
C++
.cpp
122
24.262295
99
0.611465
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,436
cmdchangefillcolor.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangefillcolor.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ /* Created By Krzywda Stanislas and Bouchikhi Mohamed-Amine ;) */ #include "cmdchangefillcolor.h" #include "umlwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeFillColor::CmdChangeFillColor(UMLWidget* widget, const QColor& col) : CmdBaseWidgetCommand(widget), m_color(col) { setText(i18n("Change fill color : %1", widget->name())); m_oldColor = widget->fillColor(); } CmdChangeFillColor::~CmdChangeFillColor() { } void CmdChangeFillColor::redo() { widget()->setFillColorCmd(m_color); } void CmdChangeFillColor::undo() { widget()->setFillColorCmd(m_oldColor); } }
842
C++
.cpp
30
23.333333
92
0.686177
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,437
cmdchangeusefillcolor.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangeusefillcolor.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdchangeusefillcolor.h" #include "umlscene.h" #include "umlwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeUseFillColor::CmdChangeUseFillColor(UMLWidget* widget, bool value) : CmdBaseWidgetCommand(widget), m_newValue(value) { if (value) { setText(i18n("Use fill color : %1", widget->name())); } else { setText(i18n("No fill color : %1", widget->name())); } m_oldValue = widget->useFillColor(); } CmdChangeUseFillColor::~CmdChangeUseFillColor() { } void CmdChangeUseFillColor::redo() { widget()->setUseFillColorCmd(m_newValue); } void CmdChangeUseFillColor::undo() { widget()->setUseFillColorCmd(m_oldValue); } }
941
C++
.cpp
34
22.264706
92
0.658509
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,438
cmdremovewidget.cpp
KDE_umbrello/umbrello/cmds/widget/cmdremovewidget.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdremovewidget.h" // app includes #include "associationwidget.h" #include "debug_utils.h" #include "umlscene.h" #include "umlwidget.h" #include "uml.h" // Only needed for log{Warn,Error} // kde includes #include <KLocalizedString> namespace Uml { /** * Constructor. */ CmdRemoveWidget::CmdRemoveWidget(UMLWidget* widget) : CmdBaseWidgetCommand(widget) { setText(i18n("Remove widget : %1", widget->name())); // save "child" elements for(QGraphicsItem* item : widget->childItems()) { UMLWidget* child = dynamic_cast<UMLWidget*>(item); uIgnoreZeroPointer(child); QString xmi; QXmlStreamWriter kidStream(&xmi); kidStream.writeStartElement(QStringLiteral("child")); child->saveToXMI(kidStream); kidStream.writeEndElement(); // child QString error; int line; QDomDocument domDoc; if (domDoc.setContent(xmi, &error, &line)) { QDomElement domElem = domDoc.firstChild().firstChild().toElement(); if (domElem.isNull()) logWarn1("CmdRemoveWidget(%1): child QDomElement is null", widget->name()); else m_children.append(domElem); } else { logWarn3("CmdRemoveWidget(%1): Cannot set child content. Error %2 line %3", widget->name(), error, line); } } // save "widget" element QString xmi; QXmlStreamWriter stream(&xmi); stream.writeStartElement(QStringLiteral("widget")); widget->saveToXMI(stream); stream.writeEndElement(); // widget QString error; int line; QDomDocument doc; if (doc.setContent(xmi, &error, &line)) { m_element = doc.firstChild().firstChild().toElement(); if (m_element.isNull()) logWarn0("widget QDomElement is null"); } else { logWarn3("CmdRemoveWidget(%1): Cannot set content. Error %2 line %3", widget->name(), error, line); } } /** * Constructor. */ CmdRemoveWidget::CmdRemoveWidget(AssociationWidget* widget) : CmdBaseWidgetCommand(widget) { setText(i18n("Remove widget : %1", widget->name())); // save "widget" element QString xmi; QXmlStreamWriter stream(&xmi); stream.writeStartElement(QStringLiteral("widget")); widget->saveToXMI(stream); stream.writeEndElement(); // widget QString error; int line; QDomDocument doc; if (doc.setContent(xmi, &error, &line)) { m_element = doc.firstChild().firstChild().toElement(); if (m_element.isNull()) logWarn1("CmdRemoveWidget(%1): widget QDomElement is null", widget->name()); } else { logWarn3("CmdRemoveWidget(%1): Cannot set content. Error %2 line %3", widget->name(), error, line); } } /** * Destructor. */ CmdRemoveWidget::~CmdRemoveWidget() { } /** * Remove the widget */ void CmdRemoveWidget::redo() { if (!m_isAssoc) removeWidgetFromScene(widget()); else removeWidgetFromScene(assocWidget()); } /** * Add the widget back */ void CmdRemoveWidget::undo() { if (!m_isAssoc) { QDomElement widgetElement = m_element.firstChild().toElement(); UMLWidget* widget = scene()->loadWidgetFromXMI(widgetElement); if (widget) { addWidgetToScene(widget); } for(QDomElement childElement : m_children) { widgetElement = childElement.firstChild().toElement(); widget = scene()->loadWidgetFromXMI(widgetElement); if (widget != nullptr) { addWidgetToScene(widget); } } } else { AssociationWidget* widget = scene()->findAssocWidget(m_widgetId); if (widget == nullptr) { // If the widget is not found, the add command was undone. Load the // widget back from the saved XMI state. QDomElement widgetElement = m_element.firstChild().toElement(); widget = AssociationWidget::create(scene()); if (widget->loadFromXMI(widgetElement)) { addWidgetToScene(widget); m_assocWidget = widget; m_widgetId = widget->id(); } else delete widget; } } } }
4,905
C++
.cpp
139
25.122302
95
0.56154
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,439
cmdchangevisualproperty.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangevisualproperty.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdchangevisualproperty.h" // app includes #include "classifierwidget.h" #include "debug_utils.h" #include "umlwidget.h" #include "uml.h" // only needed for log{Warn,Error} // kde includes #include <KLocalizedString> namespace Uml { CmdChangeVisualProperty::CmdChangeVisualProperty( ClassifierWidget* widget, ClassifierWidget::VisualProperty property, bool value ) : CmdBaseWidgetCommand(widget), m_property(property), m_newValue(value) { setText(i18n("Change visual property : %1", widget->name())); m_oldValue = widget->visualProperty(property); } CmdChangeVisualProperty::~CmdChangeVisualProperty() { } void CmdChangeVisualProperty::redo() { ClassifierWidget* classifier = widget()->asClassifierWidget(); if (classifier) classifier->setVisualPropertyCmd(m_property, m_newValue); else logWarn1("CmdChangeVisualProperty::redo: could not find classifier widget with id %1", Uml::ID::toString(m_widgetId)); } void CmdChangeVisualProperty::undo() { ClassifierWidget* classifier = widget()->asClassifierWidget(); if (classifier) classifier->setVisualPropertyCmd(m_property, m_oldValue); else logWarn1("CmdChangeVisualProperty::undo: could not find classifier widget with id %1", Uml::ID::toString(m_widgetId)); } }
1,623
C++
.cpp
47
27.93617
98
0.67709
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,440
cmdmovewidget.cpp
KDE_umbrello/umbrello/cmds/widget/cmdmovewidget.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdmovewidget.h" // app includes #include "basictypes.h" #include "umlscene.h" #include "umlwidget.h" #include <KLocalizedString> namespace Uml { CmdMoveWidget::CmdMoveWidget(UMLWidget *widget) : CmdBaseWidgetCommand(widget) { setText(i18n("Move widget : %1", widget->name())); m_pos = widget->pos(); m_posOld = widget->startMovePosition(); } CmdMoveWidget::~CmdMoveWidget() { } void CmdMoveWidget::redo() { UMLWidget* umlWidget = widget(); umlWidget->setPos(m_pos); umlWidget->updateGeometry(); } void CmdMoveWidget::undo() { UMLWidget* umlWidget = widget(); umlWidget->setPos(m_posOld); umlWidget->updateGeometry(); } // bool CmdMoveWidget::mergeWith(const QUndoCommand* other) // { // const CmdMoveWidget* otherCmd = static_cast<const CmdMoveWidget*>(other); // if (m_widgetCtrl != otherCmd->m_widgetCtrl) // return false; // m_x = otherCmd->m_x; // m_y = otherCmd->m_y; // return true; // } }
1,243
C++
.cpp
44
23.977273
92
0.634146
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,441
cmdsettxt.cpp
KDE_umbrello/umbrello/cmds/widget/cmdsettxt.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdsettxt.h" // app includes #define DBG_SRC QStringLiteral("CmdSetTxt") #include "debug_utils.h" #include "floatingtextwidget.h" #include "uml.h" // kde includes #include <KLocalizedString> DEBUG_REGISTER(CmdSetTxt) namespace Uml { CmdSetTxt::CmdSetTxt(FloatingTextWidget* ftw, const QString& txt) : m_ftw(ftw), m_newstring(txt) { setText(i18n("Set text : %1 to %2", ftw->name(), txt)); m_oldstring = ftw->text(); logDebug2("CmdSetTxt oldstring: %1, newstring: %2", m_oldstring, m_newstring); } CmdSetTxt::~CmdSetTxt() { } void CmdSetTxt::redo() { m_ftw->setTextcmd(m_newstring); logDebug3("CmdSetTxt::redo: string after redo %1, oldstring: %2, newstring: %3", m_ftw->text(), m_oldstring, m_newstring); } void CmdSetTxt::undo() { m_ftw->setName(QStringLiteral("balbalbalbalbla")); m_ftw->setTextcmd(m_oldstring); logDebug3("CmdSetTxt::undo: string after undo: %1, oldstring: %2, newstring: %3", m_ftw->text(), m_oldstring, m_newstring); } }
1,261
C++
.cpp
39
26.923077
92
0.648515
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,442
cmdchangemultiplicity.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangemultiplicity.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ /* Created by Bouchikhi Mohamed-Amine */ #include "cmdchangemultiplicity.h" // app includes #include "umlrole.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeMultiplicity::CmdChangeMultiplicity(UMLRole *role, const QString &multi) : m_umlRole(role), m_newMulti(multi) { setText(i18n("Change multiplicity : %1 to %2", role->name(), multi)); m_oldMulti = m_umlRole->multiplicity(); } void CmdChangeMultiplicity::undo() { if (!m_oldMulti.isEmpty()) { m_umlRole->setMultiplicity(m_oldMulti); } else { m_umlRole->setMultiplicity(QString()); } } void CmdChangeMultiplicity::redo() { m_umlRole->setMultiplicity(m_newMulti); } } /* line to add the commands in the undo/redo list : UMLApp::app()->executeCommand(new CmdChangeMulti(UMLRole role, QString newMulti)); */
1,059
C++
.cpp
35
25.285714
92
0.675197
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,443
cmdchangetextcolor.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangetextcolor.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdchangetextcolor.h" // app includes #include "umlscene.h" #include "umlwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeTextColor::CmdChangeTextColor(UMLWidget* widget, const QColor& col) : CmdBaseWidgetCommand(widget), m_newColor(col) { setText(i18n("Change text color : %1", widget->name())); m_oldColor = widget->textColor() ; m_oldUsesDiagramValue = widget->usesDiagramTextColor(); } CmdChangeTextColor::~CmdChangeTextColor() { } void CmdChangeTextColor::redo() { widget()->setTextColorCmd(m_newColor); } void CmdChangeTextColor::undo() { UMLWidget* umlWidget = widget(); umlWidget->setTextColorCmd(m_oldColor); umlWidget->setUsesDiagramTextColor(m_oldUsesDiagramValue); } }
993
C++
.cpp
34
24.235294
92
0.694737
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,444
cmdchangelinecolor.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangelinecolor.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdchangelinecolor.h" // app includes #include "umlwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeLineColor::CmdChangeLineColor(UMLWidget* widget, const QColor& col) : CmdBaseWidgetCommand(widget), m_newColor(col) { setText(i18n("Change line color : %1", widget->name())); m_oldColor = widget->lineColor() ; m_oldUsesDiagramValue = widget->usesDiagramLineColor(); } CmdChangeLineColor::~CmdChangeLineColor() { } void CmdChangeLineColor::redo() { widget()->setLineColorCmd(m_newColor); } void CmdChangeLineColor::undo() { UMLWidget* umlWidget = widget(); umlWidget->setLineColorCmd(m_oldColor); umlWidget->setUsesDiagramLineColor(m_oldUsesDiagramValue); } }
972
C++
.cpp
33
24.333333
92
0.693219
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,445
cmdcreatewidget.cpp
KDE_umbrello/umbrello/cmds/widget/cmdcreatewidget.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdcreatewidget.h" // app includes #include "associationwidget.h" #include "debug_utils.h" #include "model_utils.h" #include "uml.h" #include "umlscene.h" #include "umlwidget.h" // kde includes #include <KLocalizedString> #include <QXmlStreamWriter> namespace Uml { /** * Constructor. */ CmdCreateWidget::CmdCreateWidget(UMLWidget* widget) : CmdBaseWidgetCommand(widget) { setText(i18n("Create widget : %1", widget->name())); QString xmi; QXmlStreamWriter stream(&xmi); stream.writeStartElement(QStringLiteral("widget")); widget->saveToXMI(stream); stream.writeEndElement(); // widget QString error; int line; QDomDocument domDoc; if (domDoc.setContent(xmi, &error, &line)) { m_element = domDoc.firstChild().firstChild().toElement(); } else { logWarn2("CmdCreateWidget: Cannot set content. Error %1 line %2", error, line); } } /** * Constructor. */ CmdCreateWidget::CmdCreateWidget(AssociationWidget* widget) : CmdBaseWidgetCommand(widget) { setText(i18n("Create widget : %1", widget->name())); addWidgetToScene(widget); QString xmi; QXmlStreamWriter stream(&xmi); stream.writeStartElement(QStringLiteral("widget")); widget->saveToXMI(stream); stream.writeEndElement(); // widget QString error; int line; QDomDocument domDoc; if (domDoc.setContent(xmi, &error, &line)) { m_element = domDoc.firstChild().firstChild().toElement(); } else { logWarn2("CmdCreateWidget(assocwidget): Cannot set content. Error %1 line %2", error, line); } } /** * Destructor. */ CmdCreateWidget::~CmdCreateWidget() { } /** * Create the widget */ void CmdCreateWidget::redo() { if (!m_isAssoc) { UMLWidget* widget = m_widget; if (widget == nullptr) { widget = scene()->findWidget(m_widgetId); if (widget == nullptr) { // If the widget is not found, the add command was undone. Load the // widget back from the saved XMI state. QDomElement widgetElement = m_element.firstChild().toElement(); widget = scene()->loadWidgetFromXMI(widgetElement); } } if (widget) { addWidgetToScene(widget); scene()->update(); } } else { AssociationWidget* widget = scene()->findAssocWidget(m_widgetId); if (widget) return; if (m_assocWidget) { scene()->addAssociation(m_assocWidget, false); return; } // If the widget is not found, the add command was undone. Load the // widget back from the saved XMI state. QDomElement widgetElement = m_element.firstChild().toElement(); widget = AssociationWidget::create(scene()); if (widget->loadFromXMI(widgetElement)) { addWidgetToScene(widget); m_assocWidget = widget; m_widgetId = widget->id(); } else delete widget; } } /** * Remove the widget */ void CmdCreateWidget::undo() { if (!m_isAssoc) removeWidgetFromScene(widget()); else removeWidgetFromScene(assocWidget()); } }
3,751
C++
.cpp
117
23.136752
104
0.573322
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,446
cmdchangefont.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangefont.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2007-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdchangefont.h" // app includes #include "umlwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeFont::CmdChangeFont(UMLWidget* widget, QFont font) : CmdBaseWidgetCommand(widget) { setText(i18n("Change font : %1", widget->name())); m_newFont = font; m_oldFont = widget->font(); } void CmdChangeFont::undo() { widget()->setFontCmd(m_oldFont); } void CmdChangeFont::redo() { widget()->setFontCmd(m_newFont); } }
685
C++
.cpp
27
20.666667
92
0.661538
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,447
cmdresizewidget.cpp
KDE_umbrello/umbrello/cmds/widget/cmdresizewidget.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdresizewidget.h" // app includes #include "umlscene.h" #include "umlwidget.h" #include <KLocalizedString> namespace Uml { CmdResizeWidget::CmdResizeWidget(UMLWidget *widget) : CmdBaseWidgetCommand(widget) { Q_ASSERT(widget != nullptr); setText(i18n("Resize widget : %1", widget->name())); m_size = QSizeF(widget->width(), widget->height()); m_sizeOld = widget->startResizeSize(); } CmdResizeWidget::~CmdResizeWidget() { } void CmdResizeWidget::redo() { widget()->setSize(m_size); } void CmdResizeWidget::undo() { widget()->setSize(m_sizeOld); } }
816
C++
.cpp
31
21.451613
92
0.660645
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,448
cmdsetname.cpp
KDE_umbrello/umbrello/cmds/widget/cmdsetname.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdsetname.h" // app includes #include "umlobject.h" // kde includes #include <KLocalizedString> namespace Uml { CmdSetName::CmdSetName(UMLObject * obj, const QString& name) : CmdBaseObjectCommand(obj), m_name(name) { setText(i18n("Set name : %1 to %2", obj->name(), name)); m_oldname = obj->name(); } CmdSetName::~CmdSetName() { } void CmdSetName::redo() { UMLObject *umlObject = object(); if (umlObject) umlObject->setNameCmd(m_name); } void CmdSetName::undo() { UMLObject *umlObject = object(); if (umlObject) umlObject->setNameCmd(m_oldname); } }
849
C++
.cpp
34
19.529412
92
0.62531
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,449
cmdchangelinewidth.cpp
KDE_umbrello/umbrello/cmds/widget/cmdchangelinewidth.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdchangelinewidth.h" // app includes #include "umlscene.h" #include "umlwidget.h" // kde includes #include <KLocalizedString> namespace Uml { CmdChangeLineWidth::CmdChangeLineWidth(UMLWidget* widget, const uint width) : CmdBaseWidgetCommand(widget), m_newWidth(width) { setText(i18n("Change line width : %1", widget->name())); m_oldWidth = widget->lineWidth() ; } CmdChangeLineWidth::~CmdChangeLineWidth() { } void CmdChangeLineWidth::redo() { widget()->setLineWidthCmd(m_newWidth); } void CmdChangeLineWidth::undo() { widget()->setLineWidthCmd(m_oldWidth); } }
821
C++
.cpp
31
21.903226
92
0.68758
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,450
cmdcreateumlobject.cpp
KDE_umbrello/umbrello/cmds/generic/cmdcreateumlobject.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdcreateumlobject.h" // app includes #include "debug_utils.h" #include "package.h" #include "uml.h" #include "umldoc.h" // kde includes #include <KLocalizedString> namespace Uml { /** * Constructor. */ CmdCreateUMLObject::CmdCreateUMLObject(UMLObject* o) : QUndoCommand(), m_obj(o), m_skipSignal(true) { setText(i18n("Create UML object : %1", m_obj->fullyQualifiedName())); m_package = m_obj->umlPackage(); m_type = m_obj->baseType(); m_name = m_obj->name(); } /** * Destructor. */ CmdCreateUMLObject::~CmdCreateUMLObject() { } /** * Create the UMLObject. */ void CmdCreateUMLObject::redo() { // This object was removed from its package when it was deleted // so add it back to its package (if it belonged to one) if (m_package) { Q_ASSERT(m_package->baseType() != UMLObject::ot_Association); // add this object to its parent package m_package->addObject(m_obj); } else { logError1("CmdCreateUMLObject::redo: UMLPackage of %1 is not set", m_obj->name()); } // The first call to redo, the object was created and signalled by the // caller (umlscene). On subsequent calls we use the "umlobject created" // signal to update Umbrello with the re-added object. if (m_skipSignal) { m_skipSignal = false; } else { UMLDoc *doc = UMLApp::app()->document(); doc->signalUMLObjectCreated(m_obj); } } /** * Suppress the UMLObject. */ void CmdCreateUMLObject::undo() { UMLDoc *doc = UMLApp::app()->document(); doc->removeUMLObject(m_obj); } }
1,949
C++
.cpp
66
23
94
0.599359
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,451
cmdremoveumlobject.cpp
KDE_umbrello/umbrello/cmds/generic/cmdremoveumlobject.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdremoveumlobject.h" // app includes #include "uml.h" #include "umldoc.h" // kde includes #include <KLocalizedString> namespace Uml { /** * Constructor. */ CmdRemoveUMLObject::CmdRemoveUMLObject(UMLObject* o) : QUndoCommand(), m_obj(o) { setText(i18n("Remove UML object : %1", m_obj->fullyQualifiedName())); } /** * Destructor. */ CmdRemoveUMLObject::~CmdRemoveUMLObject() { } /** * Remove the UMLObject. */ void CmdRemoveUMLObject::redo() { UMLDoc *doc = UMLApp::app()->document(); doc->removeUMLObject(m_obj); } /** * Suppress the UMLObject. */ void CmdRemoveUMLObject::undo() { UMLDoc *doc = UMLApp::app()->document(); doc->addUMLObject(m_obj); doc->signalUMLObjectCreated(m_obj); } }
1,020
C++
.cpp
45
17.6
92
0.616977
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,452
cmdrenameumlobject.cpp
KDE_umbrello/umbrello/cmds/generic/cmdrenameumlobject.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "cmdrenameumlobject.h" // app includes #include "umlobject.h" // kde includes #include <KLocalizedString> namespace Uml { CmdRenameUMLObject::CmdRenameUMLObject(UMLObject* o, const QString& name) : m_obj(o), m_name(name) { setText(i18n("Rename object : %1 to %2", o->name(), name)); m_oldname = o->name(); } CmdRenameUMLObject::~CmdRenameUMLObject() { } void CmdRenameUMLObject::redo() { m_obj->setNameCmd(m_name); } void CmdRenameUMLObject::undo() { m_obj->setNameCmd(m_oldname); } }
734
C++
.cpp
29
20.758621
92
0.662356
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,453
codeimpselectpage.cpp
KDE_umbrello/umbrello/codeimpwizard/codeimpselectpage.cpp
/* SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch> SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "codeimpselectpage.h" // app includes #include "debug_utils.h" #include "model_utils.h" #include "uml.h" DEBUG_REGISTER(CodeImpSelectPage) // kde includes #include <KLocalizedString> // qt includes #include <QFileSystemModel> /** * Keep the last clicked directory for setting it the next time. */ QString CodeImpSelectPage::s_recentPath; /** * Constructor. * @param parent the parent (wizard) of this wizard page */ CodeImpSelectPage::CodeImpSelectPage(QWidget *parent) : QWizardPage(parent), m_fileList(), m_fileExtensions() { setTitle(i18n("Code Importing Path")); setSubTitle(i18n("Select the code importing path.")); setupUi(this); setupLanguageBox(); connect(ui_languageBox, SIGNAL(activated(int)), this, SLOT(languageChanged(int))); connect(this, SIGNAL(languageChanged()), this, SLOT(changeLanguage())); setupTreeView(); connect(ui_treeView, SIGNAL(clicked(QModelIndex)), this, SLOT(treeClicked(QModelIndex))); connect(ui_treeView, SIGNAL(entered(QModelIndex)), this, SLOT(treeEntered(QModelIndex))); setupFileExtEdit(); connect(ui_fileExtLineEdit, SIGNAL(editingFinished()), this, SLOT(fileExtChanged())); connect(ui_subdirCheckBox, SIGNAL(stateChanged(int)), this, SLOT(subdirStateChanged(int))); connect(ui_selectAllButton, SIGNAL(clicked()), this, SLOT(selectAll())); connect(ui_deselectAllButton, SIGNAL(clicked()), this, SLOT(deselectAll())); setupToolTips(); // update file extensions changeLanguage(); } /** * Destructor. */ CodeImpSelectPage::~CodeImpSelectPage() { } /** * Fills the language combo box with items and * sets the currently selected value. */ void CodeImpSelectPage::setupLanguageBox() { int indexCounter = 0; while (indexCounter < Uml::ProgrammingLanguage::Reserved) { QString language = Uml::ProgrammingLanguage::toString(Uml::ProgrammingLanguage::fromInt(indexCounter)); ui_languageBox->insertItem(indexCounter, language); indexCounter++; } Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage(); ui_languageBox->setCurrentIndex(pl); } /** * Setup the tree view widget. */ void CodeImpSelectPage::setupTreeView() { QFileSystemModel* model = new QFileSystemModel(); model->setRootPath(QString()); model->setNameFilterDisables(false); m_fileExtensions << QStringLiteral("*.h") << QStringLiteral("*.hpp") << QStringLiteral("*.hh") << QStringLiteral("*.hxx") << QStringLiteral("*.H"); //:TODO set according to the current language! model->setNameFilters(m_fileExtensions); ui_treeView->setSelectionMode(QAbstractItemView::MultiSelection); ui_treeView->setModel(model); ui_treeView->setIndentation(20); ui_treeView->setColumnWidth(0, 200); ui_treeView->setSortingEnabled(true); ui_treeView->header() ->setSortIndicator(0, Qt::AscendingOrder); ui_treeView->setWindowTitle(i18n("File System Model")); if (s_recentPath.isEmpty()) { ui_treeView->setCurrentIndex(model->index(QDir::currentPath())); } else { ui_treeView->setCurrentIndex(model->index(s_recentPath)); } ui_treeView->scrollTo(ui_treeView->currentIndex()); ui_treeView->setMouseTracking(true); ui_treeView->show(); } /** * Setup the tree view and file extension widget. * Call it after setupTreeView(), because the extensions are set there. */ void CodeImpSelectPage::setupFileExtEdit() { ui_fileExtLineEdit->setText(m_fileExtensions.join(QStringLiteral(", "))); } /** * Setup the tool tips for every widget. * TODO: Do it here or in the ui file? */ void CodeImpSelectPage::setupToolTips() { ui_languageBox->setToolTip(i18n("Select the desired language to filter files.")); ui_subdirCheckBox->setToolTip(i18n("Select also all the files in the subdirectories.")); ui_selectAllButton->setToolTip(i18n("Select all the files below the current directory.")); ui_deselectAllButton->setToolTip(i18n("Clear all selections.")); ui_fileExtLineEdit->setToolTip(i18n("Add file extensions like e.g. '*.h *.hpp'.")); } /** * Decide if the given file has one of the set extensions. * @param path file info to be examined * @return status if found or not */ bool CodeImpSelectPage::matchFilter(const QFileInfo& path) { bool found = false; QString filename = path.fileName(); for(QString& extension: m_fileExtensions) { extension.remove(QLatin1Char('*')); if (filename.endsWith(extension)) { found = true; break; } } return found; } /** * Slot for the stateChanged event of the subdirectory check box. * @param state check box state (Qt::Checked / Qt::Unchecked) */ void CodeImpSelectPage::subdirStateChanged(int state) { QString strState; switch (state) { case Qt::Unchecked: strState = QStringLiteral("Unchecked"); break; case Qt::Checked: strState = QStringLiteral("Checked"); break; default: strState = QStringLiteral("not known"); break; } logDebug1("CodeImpSelectPage::subdirStateChanged: state set to %1", strState); } /** * Slot for the editingFinished event of the line edit widget for the extensions. */ void CodeImpSelectPage::fileExtChanged() { QString inputStr = ui_fileExtLineEdit->text(); m_fileExtensions = inputStr.split(QRegularExpression(QStringLiteral("[,;: ]*"))); logDebug1("CodeImpSelectPage: editing of file extension line edit finished and set to %1", m_fileExtensions.join(QStringLiteral(" "))); QFileSystemModel* model = (QFileSystemModel*)ui_treeView->model(); model->setNameFilters(m_fileExtensions); } /** * Slot for the clicked event on one of the items of the tree view widget. * @param index the index of the item on which was clicked */ void CodeImpSelectPage::treeClicked(const QModelIndex& index) { if (index.isValid()) { logDebug2("CodeImpSelectPage::treeClicked: item at row=%1 / column=%2", index.row(), index.column()); QFileSystemModel* indexModel = (QFileSystemModel*)index.model(); QFileInfo fileInfo = indexModel->fileInfo(index); if (fileInfo.isDir()) { int rows = indexModel->rowCount(index); logDebug1("CodeImpSelectPage::treeClicked: item has directory and has %1 children", rows); QItemSelectionModel* selectionModel = ui_treeView->selectionModel(); for(int row = 0; row < rows; ++row) { QModelIndex childIndex = indexModel->index(row, 0, index); if (selectionModel->isSelected(index)) { // uDebug() << "select all children"; QFileInfo childInfo = indexModel->fileInfo(childIndex); if (childInfo.isDir() && ui_subdirCheckBox->isChecked()) { treeClicked(childIndex); } else { if (matchFilter(childInfo)) { selectionModel->select(childIndex, QItemSelectionModel::Select); } else { selectionModel->select(childIndex, QItemSelectionModel::Deselect); } } } else { // uDebug() << "deselect all children"; selectionModel->select(childIndex, QItemSelectionModel::Deselect); } } // keep the latest clicked directory s_recentPath = fileInfo.filePath(); } updateSelectionCounter(); Q_EMIT selectionChanged(); } else { logWarn0("CodeImpSelectPage::treeClicked: Index not valid!"); } } void CodeImpSelectPage::treeEntered(const QModelIndex &index) { Q_UNUSED(index); ui_treeView->resizeColumnToContents(0); } /** * Reimplemented QWizardPage method to validate page when user clicks next button. * @return the validation state */ bool CodeImpSelectPage::validatePage() { logDebug1("CodeImpSelectPage::validatePage is entered... recent root path: %1", s_recentPath); return true; } /** * Slot of the activated event of the combo box widget. * Transform signal. * @param id position in combo box */ void CodeImpSelectPage::languageChanged(int id) { Q_UNUSED(id); Q_EMIT languageChanged(); } /** * When the user changes the language, the codegenoptions page * language-dependent stuff has to be updated. */ void CodeImpSelectPage::changeLanguage() { QString plStr = language(); Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromString(plStr); UMLApp::app()->setActiveLanguage(pl); /* :TODO: When the user changes the language, the codegenoptions page * :TODO: language-dependent stuff has to be updated. * :TODO: Is this needed? If yes adapt to new scheme. m_CodeGenOptionsPage->setCodeGenerator(m_doc->getCurrentCodeGenerator()); apply(); */ // set the file extension pattern with which the files are filtered m_fileExtensions = Uml::ProgrammingLanguage::toExtensions(pl); logDebug1("CodeImpSelectPage::changeLanguage: File extensions %1", m_fileExtensions.join(QStringLiteral(" "))); QFileSystemModel* model = (QFileSystemModel*)ui_treeView->model(); model->setNameFilters(m_fileExtensions); ui_fileExtLineEdit->setText(m_fileExtensions.join(QStringLiteral(", "))); } /** * Returns the user selected language used for code generation. * @return the programming language name */ QString CodeImpSelectPage::language() { return ui_languageBox->currentText(); } /** * Returns the list of files, which will be used for code import. * @return the list of the selected files */ QList<QFileInfo> CodeImpSelectPage::selectedFiles() { QList<QFileInfo> fileList; QFileSystemModel* model = (QFileSystemModel*)ui_treeView->model(); QModelIndexList list = ui_treeView->selectionModel()->selectedIndexes(); int row = -1; for(const QModelIndex &idx: list) { if (idx.row() != row && idx.column() == 0) { QFileInfo fileInfo = model->fileInfo(idx); if (fileInfo.isFile() && matchFilter(fileInfo)) { fileList.append(fileInfo); } row = idx.row(); } } return fileList; } /** * Slot for clicked event on the button widget. * Select all items in the current selected directory. * If the checkbox 'ui_subdirCheckBox' is selected * also all the files in the subdirectories are selected. */ void CodeImpSelectPage::selectAll() { QModelIndex currIndex = ui_treeView->selectionModel()->currentIndex(); if (!currIndex.isValid()) { logWarn0("CodeImpSelectPage::selectAll: Invalid index"); return; } QFileSystemModel* model = (QFileSystemModel*)ui_treeView->model(); QFileInfo fileInfo = model->fileInfo(currIndex); if (fileInfo.isDir()) { QItemSelectionModel* selectionModel = ui_treeView->selectionModel(); Q_UNUSED(selectionModel); //... if (ui_subdirCheckBox->isChecked()) { //... ui_treeView->selectAll(); updateSelectionCounter(); } } else { logWarn0("CodeImpSelectPage::selectAll: No directory was selected"); } } /** * Slot for clicked event on the button widget. * Deselects all items in the entire tree. */ void CodeImpSelectPage::deselectAll() { ui_treeView->clearSelection(); updateSelectionCounter(); } /** * Utility method for setting the selection counter. */ void CodeImpSelectPage::updateSelectionCounter() { QList<QFileInfo> files = selectedFiles(); ui_filesNumLabel->setText(QString::number(files.size())); }
12,226
C++
.cpp
340
30.202941
111
0.674489
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,454
codeimportingwizard.cpp
KDE_umbrello/umbrello/codeimpwizard/codeimportingwizard.cpp
/* SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch> SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "codeimportingwizard.h" // local includes #include "codeimpselectpage.h" #include "codeimpstatuspage.h" #include "classifier.h" #include "icon_utils.h" #include "uml.h" // kde includes #include <KLocalizedString> #include <KMessageBox> // qt includes #include <QFileInfo> #include <QWizardPage> /** * Constructor. Sets up the wizard but does not load the wizard pages. * Each wizard page has its own class. * Loading of the wizard pages needs to be done in separate step because * it is too early to do that within the constructor (`this` not finalized). * See https://bugs.kde.org/show_bug.cgi?id=479224 */ CodeImportingWizard::CodeImportingWizard() : QWizard((QWidget*)UMLApp::app()) { setWizardStyle(QWizard::ModernStyle); setPixmap(QWizard::LogoPixmap, Icon_Utils::DesktopIcon(Icon_Utils::it_Code_Gen_Wizard)); setWindowTitle(i18n("Code Importing Wizard")); setOption(QWizard::NoBackButtonOnStartPage, true); } /** * Destructor. */ CodeImportingWizard::~CodeImportingWizard() { } /** * Set up the SelectionPage and the StatusPage. * This needs to be called after constructing the CodeImportingWizard. */ void CodeImportingWizard::setupPages() { setPage(SelectionPage, createSelectionPage()); setPage(StatusPage, createStatusPage()); } /** * Creates the class selection page. * @param classList the list of classes, which have to be imported * @return the wizard page */ QWizardPage* CodeImportingWizard::createSelectionPage() { m_SelectionPage = new CodeImpSelectPage(this); return m_SelectionPage; } /** * Creates the code importing status page, which shows the progress * of the import process. * @return the wizard page */ QWizardPage* CodeImportingWizard::createStatusPage() { m_StatusPage = new CodeImpStatusPage(this); return m_StatusPage; } /** * Returns a list, which contains the classes for importing. * With this function the list of classes to import can be transferred * from the select page to the status page. * @return the file info list */ QList<QFileInfo> CodeImportingWizard::selectedFiles() { return m_SelectionPage->selectedFiles(); }
2,333
C++
.cpp
77
28.155844
92
0.759573
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,455
codeimpstatuspage.cpp
KDE_umbrello/umbrello/codeimpwizard/codeimpstatuspage.cpp
/* SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch> SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ // do not work because there are runtime errors reporting that // objects derived from QObject could not be called in a different thread // #define ENABLE_IMPORT_THREAD #include "codeimpstatuspage.h" // app includes #include "classimport.h" //:TODO: remove it later #include "codeimpthread.h" #include "codeimportingwizard.h" //:TODO: circular reference #include "debug_utils.h" #include "model_utils.h" #include "uml.h" #include "umldoc.h" #include "umllistview.h" //kde includes #include <KLocalizedString> #include <KMessageBox> //qt includes #include <QFileDialog> #include <QListWidget> #include <QTimer> #include <QScrollBar> DEBUG_REGISTER(CodeImpStatusPage) /** * Constructor. * @param parent the parent (wizard) of this wizard page */ CodeImpStatusPage::CodeImpStatusPage(QWidget *parent) : QWizardPage(parent), m_workDone(false), m_savedUndoEnabled(false), m_index(0), m_savedlistViewVisible(false) #ifdef ENABLE_IMPORT_THREAD , m_thread(0) #endif { setTitle(i18n("Status of Code Importing Progress")); setSubTitle(i18n("Press the button 'Start import' to start the code import.\nCheck the success state for every class.")); setupUi(this); ui_tableWidgetStatus->setColumnCount(3); ui_tableWidgetStatus->setColumnWidth(0, 200); ui_tableWidgetStatus->setColumnWidth(1, 200); connect(ui_pushButtonStart, SIGNAL(clicked()), this, SLOT(importCode())); ui_pushButtonStop->setEnabled(false); connect(ui_pushButtonStop, SIGNAL(clicked()), this, SLOT(importCodeStop())); connect(ui_pushButtonClear, SIGNAL(clicked()), this, SLOT(loggerClear())); connect(ui_pushButtonExport, SIGNAL(clicked()), this, SLOT(loggerExport())); } /** * Destructor. */ CodeImpStatusPage::~CodeImpStatusPage() { #ifdef ENABLE_IMPORT_THREAD delete m_thread; #endif } /** * Reimplemented QWizardPage method to initialize page after clicking next button. */ void CodeImpStatusPage::initializePage() { ui_tableWidgetStatus->clearContents(); m_workDone = false; populateStatusList(); } /** * Fills the status list with the selected classes for generation. */ void CodeImpStatusPage::populateStatusList() { CodeImportingWizard* wiz = (CodeImportingWizard*)wizard(); m_files = wiz->selectedFiles(); ui_tableWidgetStatus->setRowCount(m_files.count()); for (int index = 0; index < m_files.count(); ++index) { QFileInfo file = m_files.at(index); logDebug1("CodeImpStatusPage::populateStatusList: file %1", file.fileName()); ui_tableWidgetStatus->setItem(index, 0, new QTableWidgetItem(file.fileName())); ui_tableWidgetStatus->setItem(index, 1, new QTableWidgetItem(i18n("Not Yet Generated"))); CodeImport::LedStatus* led = new CodeImport::LedStatus(70, 70); ui_tableWidgetStatus->setCellWidget(index, 2, led); } if (m_files.count() > 0) { ui_pushButtonStart->setEnabled(true); } else { ui_pushButtonStart->setEnabled(false); } } /** * Slot for the start button. Starts the code import. */ void CodeImpStatusPage::importCode() { ui_tabWidget->setCurrentIndex(1); //show the logger tab ui_pushButtonStart->setEnabled(false); ui_pushButtonStop->setEnabled(true); setCommitPage(true); //:TODO: disable back and cancel button ? UMLDoc* doc = UMLApp::app()->document(); doc->setLoading(true); // hide list view dockwindow to avoid time consuming update on every insert m_savedlistViewVisible = UMLApp::app()->listView()->parentWidget()->isVisible(); UMLApp::app()->listView()->parentWidget()->setVisible(false); ui_textEditLogger->setHtml(i18np("<b>Code import of 1 file:</b><br>", "<b>Code import of %1 files:</b><br>", m_files.size())); ui_textEditLogger->insertHtml(QStringLiteral("\n") + QStringLiteral("<br>")); ui_textEditLogger->moveCursor (QTextCursor::End); ui_textEditLogger->verticalScrollBar()->setValue(ui_textEditLogger->verticalScrollBar()->maximum()); // move Cursor to the end m_index = 0; m_workDone = false; m_savedUndoEnabled = UMLApp::app()->isUndoEnabled(); UMLApp::app()->enableUndo(false); #ifdef ENABLE_IMPORT_THREAD m_thread = new QThread; //connect(thread, SIGNAL(started()), this, SLOT(importCodeFile())); connect(m_thread, SIGNAL(finished(bool)), this, SLOT(importCodeFile(bool))); connect(m_thread, SIGNAL(terminated()), this, SLOT(importCodeStop())); #endif importCodeFile(); } void CodeImpStatusPage::importCodeFile(bool noError) { if (m_index > 0) { if (noError) { messageToLog(m_file.fileName(), i18n("importing file ... DONE<br>")); updateStatus(m_file.fileName(), i18n("Import Done")); } else { messageToLog(m_file.fileName(), i18n("importing file ... FAILED<br>")); updateStatus(m_file.fileName(), i18n("Import Failed")); } } // all files done if (m_index >= m_files.size()) { importCodeFinish(); return; } m_file = m_files.at(m_index++); messageToLog(m_file.fileName(), i18n("importing file ...")); CodeImpThread* worker = new CodeImpThread(m_file); connect(worker, SIGNAL(messageToWiz(QString,QString)), this, SLOT(updateStatus(QString,QString))); connect(worker, SIGNAL(messageToLog(QString,QString)), this, SLOT(messageToLog(QString,QString))); connect(worker, SIGNAL(messageToApp(QString)), this, SLOT(messageToApp(QString))); #ifndef ENABLE_IMPORT_THREAD connect(worker, SIGNAL(finished(bool)), this, SLOT(importNextFile(bool))); connect(worker, SIGNAL(aborted()), this, SLOT(importCodeStop())); worker->run(); worker->deleteLater(); #else worker->moveToThread(m_thread); m_thread->start(); QMetaObject::invokeMethod(worker, "run", Qt::QueuedConnection); // FIXME: when to delete worker and m_thread #endif logDebug1("****** CodeImpStatusPage::importCodeFile starting task for %1", m_file.fileName()); } void CodeImpStatusPage::importNextFile(bool noError) { Q_UNUSED(noError); QTimer::singleShot(10, this, SLOT(importCodeFile())); } void CodeImpStatusPage::importCodeFinish() { UMLDoc* doc = UMLApp::app()->document(); UMLApp::app()->enableUndo(m_savedUndoEnabled); doc->setLoading(false); // Modification is set after the import is made, because the file was modified when adding the classes. // Allowing undo of the whole class importing. I think it eats a lot of memory. // Setting the modification, but without allowing undo. doc->setModified(true); UMLApp::app()->listView()->parentWidget()->setVisible(m_savedlistViewVisible); m_workDone = true; setFinalPage(true); Q_EMIT completeChanged(); #ifdef ENABLE_IMPORT_THREAD delete m_thread; m_thread = 0; #endif } /** * Slot for messageToApp events generated by the code import worker. * @param text the message to write to the status bar of the main window */ void CodeImpStatusPage::messageToApp(const QString& text) { UMLDoc *umldoc = UMLApp::app()->document(); umldoc->writeToStatusBar(text); } /** * Slot for the stop button. Stops the code import. */ void CodeImpStatusPage::importCodeStop() { messageToLog(m_file.fileName(), i18n("importing file ... stopped<br>")); updateStatus(m_file.fileName(), i18n("Import stopped")); UMLApp::app()->enableUndo(m_savedUndoEnabled); UMLDoc* doc = UMLApp::app()->document(); doc->setLoading(false); // Modification is set after the import is made, because the file was modified when adding the classes. // Allowing undo of the whole class importing. I think it eats a lot of memory. // Setting the modification, but without allowing undo. doc->setModified(true); UMLApp::app()->listView()->parentWidget()->setVisible(m_savedlistViewVisible); m_workDone = true; setFinalPage(true); Q_EMIT completeChanged(); #ifdef ENABLE_IMPORT_THREAD delete m_thread; m_thread = 0; #endif } /** * Reimplemented QWizardPage method the enable / disable the next button. * @return complete state */ bool CodeImpStatusPage::isComplete() const { return m_workDone; } /** * Writes messages of the code import to a log device. * @param file the file for which the code was imported * @param text the text to display */ void CodeImpStatusPage::messageToLog(const QString& file, const QString& text) { if (file.isEmpty()) { ui_textEditLogger->insertHtml(QStringLiteral("\n ") + text + QStringLiteral("<br>")); } else { ui_textEditLogger->insertHtml(QStringLiteral("\n<b>") + file + QStringLiteral(":</b> ") + text + QStringLiteral("<br>")); } // move Cursor to the end ui_textEditLogger->verticalScrollBar()->setValue(ui_textEditLogger->verticalScrollBar()->maximum()); } /** * Updates the status of the code import in the status table. * @param file the file for which the code was imported * @param text the text to display */ void CodeImpStatusPage::updateStatus(const QString& file, const QString& text) { logDebug2("CodeImpStatusPage::updateStatus %1 : %2", file, text); QList<QTableWidgetItem*> items = ui_tableWidgetStatus->findItems(file, Qt::MatchFixedString); if (items.count() > 0) { QTableWidgetItem* item = items.at(0); if (!item) { logError1("CodeImpStatusPage::updateStatus(%1): Error finding class in list view", file); } else { int row = ui_tableWidgetStatus->row(item); QTableWidgetItem* status = ui_tableWidgetStatus->item(row, 1); CodeImport::LedStatus* led = (CodeImport::LedStatus*)ui_tableWidgetStatus->cellWidget(row, 2); if (text.isEmpty()) { status->setText(i18n("Not Imported")); led->setColor(Qt::red); led->setOn(true); } else { status->setText(text); led->setOn(true); } } } } /** * Slot for clicked events generated by the clear button of the logger. * Clears the logger widget. */ void CodeImpStatusPage::loggerClear() { ui_textEditLogger->setHtml(QString()); } /** * Slot for clicked events generated by the export button of the logger. * Writes the content of the logger widget to a file. */ void CodeImpStatusPage::loggerExport() { const QString caption = i18n("Umbrello Code Import - Logger Export"); QString fileName = QFileDialog::getSaveFileName(wizard(), caption); if (!fileName.isEmpty()) { QFile file(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out << ui_textEditLogger->toHtml(); file.close(); } else { KMessageBox::error(this, i18n("Cannot open file!"), caption); } } }
11,077
C++
.cpp
297
32.727273
130
0.691634
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,456
codeimpthread.cpp
KDE_umbrello/umbrello/codeimpwizard/codeimpthread.cpp
/* SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch> SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "codeimpthread.h" // app includes #include "classimport.h" // kde includes #include <KLocalizedString> #include <KMessageBox> /** * Constructor. * @param parent QObject which acts as parent to this CodeImpThread * @param file File to import for which the thread shall be spawned */ CodeImpThread::CodeImpThread(QFileInfo& file, QObject* parent) : QObject(parent), m_file(file) { connect(this, SIGNAL(askQuestion(QString,int&)), this, SLOT(questionAsked(QString,int&))); } /** * Destructor. */ CodeImpThread::~CodeImpThread() { } /** * Thread run method. */ void CodeImpThread::run() { ClassImport *classImporter = ClassImport::createImporterByFileExt(m_file.fileName(), this); QString fileName = m_file.absoluteFilePath(); if (classImporter) { Q_EMIT messageToLog(m_file.fileName(), QStringLiteral("start import...")); Q_EMIT messageToWiz(m_file.fileName(), QStringLiteral("started")); Q_EMIT messageToApp(i18n("Importing file: %1", fileName)); // FIXME: ClassImport still uses umldoc->writeToStatusBar for log writing if (!classImporter->importFile(fileName)) { Q_EMIT messageToApp(i18nc("show failed on status bar", "Failed.")); Q_EMIT messageToWiz(m_file.fileName(), QString()); Q_EMIT messageToLog(m_file.fileName(), QStringLiteral("...import failed")); Q_EMIT finished(false); } else { Q_EMIT messageToApp(i18nc("show Ready on status bar", "Ready.")); Q_EMIT messageToWiz(m_file.fileName(), QStringLiteral("finished")); Q_EMIT messageToLog(m_file.fileName(), QStringLiteral("...import finished")); Q_EMIT finished(true); } delete classImporter; } else { Q_EMIT messageToWiz(m_file.fileName(), QStringLiteral("aborted")); Q_EMIT messageToApp(i18n("No code importer for file: %1", fileName)); Q_EMIT aborted(); } } /** * Emit a signal to the main gui thread to show a question box. * @param question the text of the question * @return the code of the answer button KMessageBox::ButtonCode */ int CodeImpThread::emitAskQuestion(const QString& question) { int buttonCode = 0; //QMutexLocker locker(&m_mutex); Q_EMIT askQuestion(question, buttonCode); //m_waitCondition.wait(&m_mutex); return buttonCode; } /** * Emit a signal to the main gui thread to write a log text to the log widget. * @param file the file that is in work * @param text the text which has to be added to the log widget */ void CodeImpThread::emitMessageToLog(const QString& file, const QString& text) { if (file.isEmpty()) { Q_EMIT messageToLog(m_file.fileName(), text); } else { Q_EMIT messageToLog(file, text); } } /** * Slot for signal askQuestion. * @param question the question to ask * @param answer the pressed answer button code @see KMessageBox::ButtonCode */ void CodeImpThread::questionAsked(const QString& question, int& answer) { //QMutexLocker locker(&m_mutex); answer = KMessageBox::questionYesNo(0, question, QStringLiteral("Question code import:")); // @todo i18n //m_waitCondition.wakeOne(); }
3,498
C++
.cpp
98
31.214286
108
0.690174
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,457
node.cpp
KDE_umbrello/umbrello/umlmodel/node.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "node.h" #include <KLocalizedString> /** * Sets up a Node. * * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLNode::UMLNode(const QString & name, Uml::ID::Type id) : UMLCanvasObject(name, id) { init(); } /** * Destructor. */ UMLNode::~UMLNode() { } /** * Initializes key variables of the class. */ void UMLNode::init() { m_BaseType = UMLObject::ot_Node; } /** * Make a clone of this object. */ UMLObject* UMLNode::clone() const { UMLNode *clone = new UMLNode(); UMLObject::copyInto(clone); return clone; } /** * Creates the <UML:Node> XMI element. */ void UMLNode::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Node")); UMLObject::save1end(writer); } /** * Loads the <UML:Node> XMI element (empty.) */ bool UMLNode::load1(QDomElement&) { return true; }
1,042
C++
.cpp
54
17.074074
92
0.687436
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,458
package.cpp
KDE_umbrello/umbrello/umlmodel/package.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header file #include "package.h" // local includes #include "debug_utils.h" #include "dialog_utils.h" #include "uml.h" #include "umldoc.h" #include "classifier.h" #include "association.h" #include "datatype.h" #include "entity.h" #include "folder.h" #include "object_factory.h" #include "optionstate.h" #include "model_utils.h" // kde includes #include <KLocalizedString> #include <KMessageBox> // qt includes using namespace Uml; DEBUG_REGISTER(UMLPackage) /** * Sets up a Package. * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLPackage::UMLPackage(const QString & name, Uml::ID::Type id) : UMLCanvasObject(name, id) { m_BaseType = ot_Package; } /** * Destructor. */ UMLPackage::~UMLPackage() { } /** * Copy the internal presentation of this object into the new object. */ void UMLPackage::copyInto(UMLObject *lhs) const { UMLPackage *target = lhs->asUMLPackage(); UMLCanvasObject::copyInto(target); m_objects.copyInto(&(target->m_objects)); } /** * Make a clone of this object. */ UMLObject* UMLPackage::clone() const { UMLPackage *clone = new UMLPackage(); copyInto(clone); return clone; } /** * Adds an existing association to the matching classifier in the list of concepts. * The selection of the matching classifier depends on the association type: * For generalizations, the assoc is added to the classifier that matches role A. * For aggregations and compositions, the assoc is added to the classifier * that matches role B. * @param assoc the association to add */ void UMLPackage::addAssocToConcepts(UMLAssociation* assoc) { if (! AssociationType::hasUMLRepresentation(assoc->getAssocType())) return; Uml::ID::Type AId = assoc->getObjectId(Uml::RoleType::A); Uml::ID::Type BId = assoc->getObjectId(Uml::RoleType::B); for(UMLObject *o : m_objects) { UMLCanvasObject *c = o->asUMLCanvasObject(); if (c == nullptr) continue; if (AId == c->id() || (BId == c->id())) { if (c->hasAssociation(assoc)) { logDebug2("UMLPackage::addAssocToConcepts: %1 already has association id=%2", c->name(), Uml::ID::toString(assoc->id())); } else { c->addAssociationEnd(assoc); } } UMLPackage *pkg = c->asUMLPackage(); if (pkg) pkg->addAssocToConcepts(assoc); } } /** * Remove the association from the participating concepts. * @param assoc the association to remove */ void UMLPackage::removeAssocFromConcepts(UMLAssociation *assoc) { for(UMLObject *o : m_objects) { UMLCanvasObject *c = o->asUMLCanvasObject(); if (c) { if (c->hasAssociation(assoc)) c->removeAssociationEnd(assoc); UMLPackage *pkg = c->asUMLPackage(); if (pkg) pkg->removeAssocFromConcepts(assoc); } } } /** * Adds an object in this package. * * @param pObject Pointer to the UMLObject to add. * @param interactOnConflict If pObject's name is already present in the package's * contained objects then * - if true then open a dialog asking the user for a * different name; * - if false then return false without inserting pObject. * @return True if the object was actually added. */ bool UMLPackage::addObject(UMLObject *pObject, bool interactOnConflict /* = true */) { if (pObject == nullptr) { logError0("UMLPackage::addObject is called with a null object"); return false; } if (pObject == this) { logError0("UMLPackage::addObject: adding self as child is not allowed"); return false; } if (m_objects.indexOf(pObject) != -1) { logDebug1("UMLPackage::addObject %1: object is already there", pObject->name()); return false; } if (pObject->baseType() == UMLObject::ot_Association) { UMLAssociation *assoc = pObject->asUMLAssociation(); // Adding the UMLAssociation at the participating concepts is done // again later (in UMLAssociation::resolveRef()) if they are not yet // known right here. if (assoc->getObject(Uml::RoleType::A) && assoc->getObject(Uml::RoleType::B)) { UMLPackage *pkg = pObject->umlPackage(); if (pkg != this) { logError2("UMLPackage %1 addObject: assoc's UMLPackage is %2", name(), pkg->name()); } addAssocToConcepts(assoc); } } else if (interactOnConflict) { QString name = pObject->name(); QString oldName = name; UMLObject *o; while ((o = findObject(name)) != nullptr && o->baseType() != UMLObject::ot_Association) { QString prevName = name; name = Model_Utils::uniqObjectName(pObject->baseType(), this); bool ok = Dialog_Utils::askName(i18nc("object name", "Name"), i18n("An object with the name %1\nalready exists in the package %2.\nPlease enter a new name:", prevName, this->name()), name); if (!ok) { name = oldName; continue; } if (name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); continue; } } if (oldName != name) { pObject->setName(name); } } else { QString nameToAdd = pObject->name(); bool found = false; for(const UMLObject *obj : m_objects) { if (obj->name() == nameToAdd) { found = true; break; } } if (found) { logDebug2("UMLPackage %1 addObject: name %2 is already there", name(), nameToAdd); return false; } } m_objects.append(pObject); return true; } /** * Removes an object from this package. * Does not physically delete the object. * Does not emit signals. * * @param pObject Pointer to the UMLObject to be removed. */ void UMLPackage::removeObject(UMLObject *pObject) { if (pObject->baseType() == UMLObject::ot_Association) { UMLAssociation *assoc = pObject->asUMLAssociation(); if (assoc) removeAssocFromConcepts(assoc); else logError0("UMLPackage::removeObject: object asserts to be UMLAssociation but is not"); } if (m_objects.indexOf(pObject) == -1) { logDebug2("UMLPackage %1 removeObject: object with id=%2 not found.", name(), Uml::ID::toString(pObject->id())); return; } // Do not delete a datatype from its root folder but just mark it as inactive. // https://bugs.kde.org/show_bug.cgi?id=427532 // We need this special handling because of the possibility of switching // the active programming language. Without it, // - switching the active language could create dangling references on all // objects referencing the previous language's datatypes; // - the display of the datatypes in the list view or in dialogs get // populated with the types from previously active languages. if (this == UMLApp::app()->document()->datatypeFolder()) { UMLDatatype *dt = pObject->asUMLDatatype(); if (dt) { dt->setActive(false); } else { logWarn2("UMLPackage::removeObject(%1) : Expected Datatype, found %2", pObject->name(), pObject->baseTypeStr()); } } else { m_objects.removeAll(pObject); } } /** * Removes all objects from this package. * Inner containers (e.g. nested packages) are removed recursively. */ void UMLPackage::removeAllObjects() { UMLCanvasObject::removeAllChildObjects(); for (int i = 0; i < m_objects.size(); i++) { UMLObject *o = m_objects.at(i); uIgnoreZeroPointer(o); UMLPackage *pkg = o->asUMLPackage(); if (pkg) pkg->removeAllObjects(); removeObject(o); delete o; } m_objects.clear(); } /** * Returns the list of objects contained in this package. */ UMLObjectList UMLPackage::containedObjects(bool includeInactive /* = false */) const { UMLObjectList result; for(UMLObject *obj : m_objects) { uIgnoreZeroPointer(obj); if (includeInactive) { result.append(obj); } else if (obj->isUMLDatatype()) { UMLDatatype *dt = obj->asUMLDatatype(); if (dt->isActive()) result.append(obj); } else { result.append(obj); } } return result; } /** * Find the object of the given name in the list of contained objects. * * @param name The name to seek. * @return Pointer to the UMLObject found or NULL if not found. */ UMLObject * UMLPackage::findObject(const QString &name) const { const bool caseSensitive = UMLApp::app()->activeLanguageIsCaseSensitive(); for(UMLObject *obj : m_objects) { if (!obj) continue; if (caseSensitive) { if (obj->name() == name) return obj; } else if (obj->name().toLower() == name.toLower()) { return obj; } } return nullptr; } /** * Find the object of the given ID in the list of contained objects. * * @param id The ID to seek. * @return Pointer to the UMLObject found or NULL if not found. */ UMLObject * UMLPackage::findObjectById(Uml::ID::Type id) const { return Model_Utils::findObjectInList(id, m_objects); } /** * Append all packages from this package (and those from nested packages) * to the given UMLPackageList. * * @param packages The list to append to * @param includeNested Whether to include the packages from nested packages * (default:true) */ void UMLPackage::appendPackages(UMLPackageList& packages, bool includeNested) const { for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); ObjectType ot = o->baseType(); if (ot == ot_Package || ot == ot_Folder) { packages.append(o->asUMLPackage()); if (includeNested) { UMLPackage *inner = o->asUMLPackage(); inner->appendPackages(packages); } } } } /** * Append all classifiers from this package (and those from * nested packages) to the given UMLClassifierList. * * @param classifiers The list to append to. * @param includeNested Whether to include the classifiers from * nested packages (default: true.) */ void UMLPackage::appendClassifiers(UMLClassifierList& classifiers, bool includeNested /* = true */) const { for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); ObjectType ot = o->baseType(); if (ot == ot_Class || ot == ot_Interface || ot == ot_Datatype || ot == ot_Enum || ot == ot_Entity) { classifiers.append((UMLClassifier *)o); } else if (includeNested && (ot == ot_Package || ot == ot_Folder)) { UMLPackage *inner = o->asUMLPackage (); inner->appendClassifiers(classifiers); } } } /** * Append all entities from this package (and those * from nested packages) to the given UMLEntityList. * * @param entities The list to append to. * @param includeNested Whether to include the entities from * nested packages (default: true.) */ void UMLPackage::appendEntities(UMLEntityList& entities, bool includeNested /* = true */) const { for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); ObjectType ot = o->baseType(); if (ot == ot_Entity) { UMLEntity *c = o->asUMLEntity(); entities.append(c); } else if (includeNested && (ot == ot_Package || ot == ot_Folder)) { UMLPackage *inner = o->asUMLPackage (); inner->appendEntities(entities); } } } /** * Append all classes, interfaces, and enums from this package (and those * from nested packages) to the given UMLClassifierList. * * @param classifiers The list to append to. * @param includeNested Whether to include the classifiers from * nested packages (default: true.) */ void UMLPackage::appendClassesAndInterfaces(UMLClassifierList& classifiers, bool includeNested /* = true */) const { for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); ObjectType ot = o->baseType(); if (ot == ot_Class || ot == ot_Interface || ot == ot_Enum) { UMLClassifier *c = o->asUMLClassifier(); classifiers.append(c); } else if (includeNested && (ot == ot_Package || ot == ot_Folder)) { UMLPackage *inner = o->asUMLPackage (); inner->appendClassesAndInterfaces(classifiers); } } } /** * Resolve types. Required when dealing with foreign XMI files. * Needs to be called after all UML objects are loaded from file. * Overrides the method from UMLObject. * Calls resolveRef() on each contained object. * * @return True for overall success. */ bool UMLPackage::resolveRef() { bool overallSuccess = UMLCanvasObject::resolveRef(); for(UMLObject *obj : m_objects) { uIgnoreZeroPointer(obj); if (! obj->resolveRef()) { UMLObject::ObjectType ot = obj->baseType(); if (ot != UMLObject::ot_Package && ot != UMLObject::ot_Folder) m_objects.removeAll(obj); overallSuccess = false; } } return overallSuccess; } /** * Creates the <UML:Package> XMI element. */ void UMLPackage::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Package")); if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Namespace.ownedElement")); } // save classifiers etc. for(UMLObject *obj : m_objects) { uIgnoreZeroPointer(obj); obj->saveToXMI (writer); } // save associations for(UMLObject *obj: subordinates()) { obj->saveToXMI (writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); // UML:Namespace.ownedElement } UMLObject::save1end(writer); // UML:Package } /** * Loads the <UML:Package> XMI element. * Auxiliary to UMLObject::loadFromXMI. */ bool UMLPackage::load1(QDomElement& element) { for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; QDomElement tempElement = node.toElement(); QString type = tempElement.tagName(); if (Model_Utils::isCommonXMI1Attribute(type)) continue; if (UMLDoc::tagEq(type, QStringLiteral("Namespace.ownedElement")) || UMLDoc::tagEq(type, QStringLiteral("Element.ownedElement")) || // Embarcadero's Describe UMLDoc::tagEq(type, QStringLiteral("Namespace.contents"))) { //CHECK: Umbrello currently assumes that nested elements // are ownedElements anyway. // Therefore these tags are not further interpreted. if (! load1(tempElement)) return false; continue; } else if (UMLDoc::tagEq(type, QStringLiteral("packagedElement")) || UMLDoc::tagEq(type, QStringLiteral("ownedElement"))) { type = tempElement.attribute(QStringLiteral("xmi:type")); } QString stereoID = tempElement.attribute(QStringLiteral("stereotype")); UMLObject *pObject = Object_Factory::makeObjectFromXMI(type, stereoID); if (!pObject) { logWarn1("UMLPackage::load1 unknown type of umlobject to create: %1", type); continue; } pObject->setUMLPackage(this); if (!pObject->loadFromXMI(tempElement)) { removeObject(pObject); delete pObject; } } return true; }
16,479
C++
.cpp
474
28.253165
161
0.616564
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,459
entity.cpp
KDE_umbrello/umbrello/umlmodel/entity.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "entity.h" // app includes #include "debug_utils.h" #include "entityattribute.h" #include "uniqueconstraint.h" #include "foreignkeyconstraint.h" #include "checkconstraint.h" #include "umldoc.h" #include "uml.h" #include "uniqueid.h" #include "umlentityattributelist.h" #include "umlentityconstraintlist.h" #include "idchangelog.h" #include "umlentityattributedialog.h" #include "umluniqueconstraintdialog.h" #include "umlforeignkeyconstraintdialog.h" #include "umlcheckconstraintdialog.h" // kde includes #include <KLocalizedString> #include <KMessageBox> // qt includes #include <QPointer> DEBUG_REGISTER(UMLEntity) /** * Constructor. */ UMLEntity::UMLEntity(const QString& name, Uml::ID::Type id) : UMLClassifier(name, id), m_PrimaryKey(nullptr) { m_BaseType = UMLObject::ot_Entity; connect(this, SIGNAL(entityAttributeRemoved(UMLClassifierListItem*)), this, SLOT(slotEntityAttributeRemoved(UMLClassifierListItem*))); } /** * Standard destructor. */ UMLEntity::~UMLEntity() { subordinates().clear(); } /** * Overloaded '==' operator. */ bool UMLEntity::operator==(const UMLEntity& rhs) const { return UMLClassifier::operator==(rhs); } /** * Copy the internal presentation of this object into the new * object. */ void UMLEntity::copyInto(UMLObject *lhs) const { UMLEntity *target = lhs->asUMLEntity(); // call base class copy function UMLClassifier::copyInto(target); // copy local data items target->m_PrimaryKey = m_PrimaryKey; } /** * Make a clone of this object. */ UMLObject* UMLEntity::clone() const { UMLEntity* clone = new UMLEntity(); copyInto(clone); return clone; } /** * Create a UMLAttribute. * @param name an optional name for the attribute * @param type an optional type object for the attribute * @param vis the visibility of the attribute * @param iv the initial value for the attribute * @return the just created attribute or null */ UMLAttribute *UMLEntity::createAttribute(const QString &name /*= QString()*/, UMLObject *type /*= nullptr*/, Uml::Visibility::Enum vis /* = Uml::Visibility::Private*/, const QString& iv /* = QString()*/) { Uml::ID::Type id = UniqueID::gen(); QString currentName; if (name.isNull()) { currentName = uniqChildName(UMLObject::ot_EntityAttribute); } else { currentName = name; } UMLEntityAttribute* newAttribute = new UMLEntityAttribute(this, currentName, id, vis, type, iv); int button = QDialog::Accepted; bool goodName = false; //check for name.isNull() stops dialog being shown //when creating attribute via list view while (button == QDialog::Accepted && !goodName && name.isNull()) { QPointer<UMLEntityAttributeDialog> dialog = new UMLEntityAttributeDialog(nullptr, newAttribute); button = dialog->exec(); QString name = newAttribute->name(); if (name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else if (findChildObject(name) != nullptr) { KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name")); } else { goodName = true; } delete dialog; } if (button != QDialog::Accepted) { delete newAttribute; return nullptr; } addEntityAttribute(newAttribute); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newAttribute); return newAttribute; } /** * Creates a Unique Constraint for this Entity. * @param name an optional name * @return the UniqueConstraint created */ UMLUniqueConstraint* UMLEntity::createUniqueConstraint(const QString &name) { Uml::ID::Type id = UniqueID::gen(); QString currentName; if (name.isNull()) { /** * @todo check parameter */ currentName = uniqChildName(UMLObject::ot_UniqueConstraint); } else { currentName = name; } UMLUniqueConstraint* newUniqueConstraint = new UMLUniqueConstraint(this, currentName, id); int button = QDialog::Accepted; bool goodName = false; //check for name.isNull() stops dialog being shown //when creating attribute via list view while (button == QDialog::Accepted && !goodName && name.isNull()) { QPointer<UMLUniqueConstraintDialog> dialog = new UMLUniqueConstraintDialog(nullptr, newUniqueConstraint); button = dialog->exec(); QString name = newUniqueConstraint->name(); if (name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else if (findChildObject(name) != nullptr) { KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name")); } else { goodName = true; } delete dialog; } if (button != QDialog::Accepted) { delete newUniqueConstraint; return nullptr; } addConstraint(newUniqueConstraint); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newUniqueConstraint); emitModified(); return newUniqueConstraint; } /** * Creates a Foreign Key Constraint for this Entity. * @param name an optional name * @return the ForeignKeyConstraint created */ UMLForeignKeyConstraint* UMLEntity::createForeignKeyConstraint(const QString &name) { Uml::ID::Type id = UniqueID::gen(); QString currentName; if (name.isNull()) { currentName = uniqChildName(UMLObject::ot_ForeignKeyConstraint); } else { currentName = name; } UMLForeignKeyConstraint* newForeignKeyConstraint = new UMLForeignKeyConstraint(this, currentName, id); int button = QDialog::Accepted; bool goodName = false; //check for name.isNull() stops dialog being shown //when creating attribute via list view while (button == QDialog::Accepted && !goodName && name.isNull()) { QPointer<UMLForeignKeyConstraintDialog> dialog = new UMLForeignKeyConstraintDialog(nullptr, newForeignKeyConstraint); button = dialog->exec(); QString name = newForeignKeyConstraint->name(); if (name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else if (findChildObject(name) != nullptr) { KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name")); } else { goodName = true; } delete dialog; } if (button != QDialog::Accepted) { return nullptr; } addConstraint(newForeignKeyConstraint); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newForeignKeyConstraint); emitModified(); return newForeignKeyConstraint; } /** * Creates a Check Constraint for this Entity. * @param name an optional name * @return the CheckConstraint created */ UMLCheckConstraint* UMLEntity::createCheckConstraint(const QString &name) { Uml::ID::Type id = UniqueID::gen(); QString currentName; if (name.isNull()) { currentName = uniqChildName(UMLObject::ot_CheckConstraint); } else { currentName = name; } UMLCheckConstraint* newCheckConstraint = new UMLCheckConstraint(this, currentName, id); int button = QDialog::Accepted; bool goodName = false; //check for name.isNull() stops dialog being shown //when creating attribute via list view while (button == QDialog::Accepted && !goodName && name.isNull()) { QPointer<UMLCheckConstraintDialog> dialog = new UMLCheckConstraintDialog(nullptr, newCheckConstraint); button = dialog->exec(); QString name = newCheckConstraint->name(); if (name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else if (findChildObject(name) != nullptr) { KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name")); } else { goodName = true; } delete dialog; } if (button != QDialog::Accepted) { return nullptr; } addConstraint(newCheckConstraint); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newCheckConstraint); emitModified(); return newCheckConstraint; } /** * Adds an entityAttribute. * The entityAttribute object must not belong to any other classifier. * @param name name of the UMLEntityAttribute * @param id id of the UMLEntityAttribute * @return True if the entityAttribute was successfully added. */ UMLObject* UMLEntity::addEntityAttribute(const QString& name, Uml::ID::Type id) { UMLEntityAttribute* literal = new UMLEntityAttribute(this, name, id); subordinates().append(literal); Q_EMIT entityAttributeAdded(literal); UMLObject::emitModified(); connect(literal, SIGNAL(modified()), this, SIGNAL(modified())); return literal; } /** * Adds an already created entityAttribute. * The entityAttribute object must not belong to any other classifier. * @param att Pointer to the UMLEntityAttribute. * @param log Pointer to the IDChangeLog. * @return True if the entityAttribute was successfully added. */ bool UMLEntity::addEntityAttribute(UMLEntityAttribute *att, IDChangeLog* log /* = nullptr*/) { QString name = (QString)att->name(); if (findChildObject(name) == nullptr) { att->setParent(this); subordinates().append(att); Q_EMIT entityAttributeAdded(att); UMLObject::emitModified(); connect(att, SIGNAL(modified()), this, SIGNAL(modified())); return true; } else if (log) { log->removeChangeByNewID(att->id()); delete att; } return false; } /** * Adds an entityAttribute to the entity, at the given position. * If position is negative or too large, the entityAttribute is added * to the end of the list. * TODO: give default value -1 to position (append) - now it conflicts with the method above.. * @param att Pointer to the UMLEntityAttribute. * @param position Position index for the insertion. * @return True if the entityAttribute was successfully added. */ bool UMLEntity::addEntityAttribute(UMLEntityAttribute* att, int position) { Q_ASSERT(att); QString name = (QString)att->name(); if (findChildObject(name) == nullptr) { att->setParent(this); if (position >= 0 && position <= (int)subordinates().count()) { subordinates().insert(position, att); } else { subordinates().append(att); } Q_EMIT entityAttributeAdded(att); UMLObject::emitModified(); connect(att, SIGNAL(modified()), this, SIGNAL(modified())); return true; } return false; } /** * Removes an entityAttribute from the class. * @param att The entityAttribute to remove. * @return Count of the remaining entityAttributes after removal. * Returns -1 if the given entityAttribute was not found. */ int UMLEntity::removeEntityAttribute(UMLClassifierListItem* att) { if (!subordinates().removeAll((UMLEntityAttribute*)att)) { logDebug0("UMLEntity::removeEntityAttribute cannot find att given in list"); return -1; } Q_EMIT entityAttributeRemoved(att); UMLObject::emitModified(); // If we are deleting the object, then we don't need to disconnect..this is done auto-magically // for us by QObject. -b.t. // disconnect(att, SIGNAL(modified()), this, SIGNAL(modified())); delete att; return subordinates().count(); } /** * Returns the number of entityAttributes for the class. * @return The number of entityAttributes for the class. */ int UMLEntity::entityAttributes() const { UMLClassifierListItemList entityAttributes = getFilteredList(UMLObject::ot_EntityAttribute); return entityAttributes.count(); } /** * Emit the entityAttributeRemoved signal. */ void UMLEntity::signalEntityAttributeRemoved(UMLClassifierListItem *eattr) { Q_EMIT entityAttributeRemoved(eattr); } /** * Resolve the types referenced by our UMLEntityAttributes. * Reimplements the method from UMLClassifier. */ bool UMLEntity::resolveRef() { bool success = UMLClassifier::resolveRef(); for(UMLObject *obj : subordinates()) { if (obj->resolveRef()) { UMLClassifierListItem *cli = obj->asUMLClassifierListItem(); if (!cli) return success; switch (cli->baseType()) { case UMLObject::ot_EntityAttribute: Q_EMIT entityAttributeAdded(cli); break; case UMLObject::ot_UniqueConstraint: case UMLObject::ot_ForeignKeyConstraint: Q_EMIT entityConstraintAdded(cli); break; default: break; } } } return success; } /** * Creates the <UML:Entity> element including its entityliterals. */ void UMLEntity::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Entity")); // save entity attributes UMLClassifierListItemList entityAttributes = getFilteredList(UMLObject::ot_EntityAttribute); for(UMLClassifierListItem *pEntityAttribute: entityAttributes) { pEntityAttribute->saveToXMI(writer); } // save entity constraints UMLClassifierListItemList entityConstraints = getFilteredList(UMLObject::ot_EntityConstraint); for(UMLClassifierListItem *cli : entityConstraints) { cli->saveToXMI(writer); } UMLObject::save1end(writer); } /** * Loads the <UML:Entity> element including its entityAttributes. */ bool UMLEntity::load1(QDomElement& element) { QDomNode node = element.firstChild(); while (!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("ownedAttribute")) || UMLDoc::tagEq(tag, QStringLiteral("packagedElement"))) { tag = tempElement.attribute(QStringLiteral("xmi:type")); } if (UMLDoc::tagEq(tag, QStringLiteral("EntityAttribute"))) { // for backward compatibility UMLEntityAttribute* pEntityAttribute = new UMLEntityAttribute(this); if(!pEntityAttribute->loadFromXMI(tempElement)) { return false; } subordinates().append(pEntityAttribute); } else if (UMLDoc::tagEq(tag, QStringLiteral("UniqueConstraint"))) { UMLUniqueConstraint* pUniqueConstraint = new UMLUniqueConstraint(this); if (!pUniqueConstraint->loadFromXMI(tempElement)) { return false; } addConstraint(pUniqueConstraint); } else if (UMLDoc::tagEq(tag, QStringLiteral("ForeignKeyConstraint"))) { UMLForeignKeyConstraint* pForeignKeyConstraint = new UMLForeignKeyConstraint(this); if (!pForeignKeyConstraint->loadFromXMI(tempElement)) { return false; } addConstraint(pForeignKeyConstraint); } else if (UMLDoc::tagEq(tag, QStringLiteral("CheckConstraint"))) { UMLCheckConstraint* pCheckConstraint = new UMLCheckConstraint(this); if (!pCheckConstraint->loadFromXMI(tempElement)) { return false; } addConstraint(pCheckConstraint); } else if (tag == QStringLiteral("stereotype")) { logDebug1("UMLEntity::load1 %1: losing old-format stereotype.", name()); } else { logWarn1("UMLEntity::load1: unknown child type %1", tag); } node = node.nextSibling(); }//end while return true; } /** * Sets the UniqueConstraint passed as the Primary Key of this Entity * If the UniqueConstraint exists, then it is made a primary key * Else the UniqueConstraint is added and set as PrimaryKey * @param uconstr The Unique Constraint that is to be set as Primary Key * @return true if Primary key could be set successfully */ bool UMLEntity::setAsPrimaryKey(UMLUniqueConstraint* uconstr) { if (uconstr == nullptr) { logWarn0("UMLEntity::setAsPrimaryKey: NULL value passed. To unset a Primary Key use " "unsetPrimaryKey()"); return false; } if (uconstr->umlParent()->asUMLEntity() != this) { logDebug1("UMLEntity::setAsPrimaryKey: Parent of %1 does not match with current entity", uconstr->name()); return false; } // check if this constraint already exists as a unique constraint for this entity UMLObject *o = findChildObjectById(uconstr->id()); UMLUniqueConstraint* uuc = o ? o->asUMLUniqueConstraint() : nullptr; if (uuc == nullptr) { addConstraint(uconstr); uuc = uconstr; } UMLUniqueConstraint* oldPrimaryKey = m_PrimaryKey; m_PrimaryKey = uuc; if (oldPrimaryKey != nullptr) oldPrimaryKey->emitModified(); uuc->emitModified(); emitModified(); return true; } /** * Unset a Primary Key Constraint if it exists, else does nothing * This function will make the primary key into just another UniqueConstraint * if it exists */ void UMLEntity::unsetPrimaryKey() { m_PrimaryKey = nullptr; } /** * Checks if This UMLEntity has a primary key set. * @return true if a Primary Key Exists for this UMLEntity */ bool UMLEntity::hasPrimaryKey() const { if (m_PrimaryKey) { return true; } return false; } /** * Adds a Constraint to this UMLEntity. * To set a UMLUniqueConstraint as Primary Key use setAsPrimaryKey. * @param constr The UMLEntityConstraint that is to be added * @return true if the constraint could be added successfully */ bool UMLEntity::addConstraint(UMLEntityConstraint* constr) { if (findChildObjectById(constr->id()) != nullptr) { logDebug1("UMLEntity::addConstraint: Constraint with id %1 already exists", Uml::ID::toString(constr->id())); return false; } subordinates().append(constr); Q_EMIT entityConstraintAdded(constr); UMLObject::emitModified(); connect(constr, SIGNAL(modified()), this, SIGNAL(modified())); return true; } /** * Removes an existing constraint from this UMLEntity. * If the Constraint is a Primary Key, this Entity will no longer have a PrimaryKey. * @param constr the constraint to be removed * @return true if the constraint could be removed successfully */ bool UMLEntity::removeConstraint(UMLEntityConstraint* constr) { if (findChildObjectById(constr->id()) == nullptr) { logDebug1("UMLEntity::removeConstraint: Constraint with id %1 does not exist", Uml::ID::toString(constr->id())); return false; } if (m_PrimaryKey == constr) { unsetPrimaryKey(); } subordinates().removeAll(constr); Q_EMIT entityConstraintRemoved(constr); UMLObject::emitModified(); delete constr; return true; } /** * Slot for entity attribute removed. */ void UMLEntity::slotEntityAttributeRemoved(UMLClassifierListItem* cli) { // this function does some cleanjobs related to this entity when the attribute is // removed, like, removing the attribute from all constraints UMLEntityAttribute* entAtt = cli->asUMLEntityAttribute(); if (cli) { UMLClassifierListItemList ual = this->getFilteredList(UMLObject::ot_UniqueConstraint); for(UMLClassifierListItem *ucli : ual) { UMLUniqueConstraint* uuc = ucli->asUMLUniqueConstraint(); if (uuc->hasEntityAttribute(entAtt)) { uuc->removeEntityAttribute(entAtt); } } } } /** * Reimplementation of getFilteredList to support ot=UMLObject::ot_EntityConstraint. */ UMLClassifierListItemList UMLEntity::getFilteredList(UMLObject::ObjectType ot) const { if (ot == UMLObject::ot_EntityConstraint) { UMLClassifierListItemList ucList, fcList, ccList, rcList; ucList = UMLClassifier::getFilteredList(UMLObject::ot_UniqueConstraint); fcList = UMLClassifier::getFilteredList(UMLObject::ot_ForeignKeyConstraint); ccList = UMLClassifier::getFilteredList(UMLObject::ot_CheckConstraint); // append the lists to rcList // first the Unique Constraints for(UMLClassifierListItem *ucli : ucList) { rcList.append(ucli); } // then the Foreign Key Constraints for(UMLClassifierListItem *ucli : fcList) { rcList.append(ucli); } for(UMLClassifierListItem *ucli : ccList) { rcList.append(ucli); } return rcList; } return UMLClassifier::getFilteredList(ot); } /** * Checks if a given Unique Constraint is primary key of this entity * @param uConstr a Unique Constraint * @return bool true if passed parameter is a primary key of this entity */ bool UMLEntity::isPrimaryKey(const UMLUniqueConstraint* uConstr) const { if (uConstr == m_PrimaryKey) { return true; } return false; } /** * Returns the Entity Attributes. * Same as getFilteredList(UMLObject::ot_EntityAttribute). */ UMLEntityAttributeList UMLEntity::getEntityAttributes() const { UMLEntityAttributeList entityAttributeList; for(UMLObject *listItem : subordinates()) { if (listItem->baseType() == UMLObject::ot_EntityAttribute) { entityAttributeList.append(listItem->asUMLEntityAttribute()); } } return entityAttributeList; } /** * Create a new ClassifierListObject (entityattribute) * according to the given XMI tag. * Returns NULL if the string given does not contain one of the tags * <UML:EntityAttribute> * Used by the clipboard for paste operation. * Reimplemented from UMLClassifier for UMLEntity */ UMLClassifierListItem* UMLEntity::makeChildObject(const QString& xmiTag) { UMLClassifierListItem *pObject = nullptr; if (UMLDoc::tagEq(xmiTag, QStringLiteral("EntityAttribute"))) { pObject = new UMLEntityAttribute(this); } return pObject; }
22,626
C++
.cpp
624
30.616987
125
0.683225
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,460
attribute.cpp
KDE_umbrello/umbrello/umlmodel/attribute.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "attribute.h" // app includes #include "debug_utils.h" #include "classifier.h" #include "operation.h" #include "umlobject.h" #include "umldoc.h" #include "uml.h" #include "folder.h" #include "umlattributedialog.h" #include "object_factory.h" #include "optionstate.h" // qt includes #include <QApplication> DEBUG_REGISTER(UMLAttribute) /** * Sets up an attribute. * * @param parent The parent of this UMLAttribute. * @param name The name of this UMLAttribute. * @param id The unique id given to this UMLAttribute. * @param s The visibility of the UMLAttribute. * @param type The type of this UMLAttribute. * @param iv The initial value of the attribute. */ UMLAttribute::UMLAttribute(UMLObject *parent, const QString& name, Uml::ID::Type id, Uml::Visibility::Enum s, UMLObject *type, const QString& iv) : UMLClassifierListItem(parent, name, id) { m_InitialValue = iv; m_BaseType = UMLObject::ot_Attribute; m_visibility = s; m_ParmKind = Uml::ParameterDirection::In; /* CHECK: Do we need this: if (type == 0) { type = Object_Factory::createUMLObject(Uml::ot_Datatype, "undef"); } */ m_pSecondary = type; } /** * Sets up an attribute. * * @param parent The parent of this UMLAttribute. */ UMLAttribute::UMLAttribute(UMLObject *parent) : UMLClassifierListItem(parent) { m_BaseType = UMLObject::ot_Attribute; m_visibility = Uml::Visibility::Private; m_ParmKind = Uml::ParameterDirection::In; } /** * Destructor. */ UMLAttribute::~UMLAttribute() { } /** * Reimplementation of method from UMLObject is required as * an extra signal, attributeChanged(), is emitted. */ void UMLAttribute::setName(const QString &name) { m_name = name; Q_EMIT attributeChanged(); UMLObject::emitModified(); } /** * Reimplementation of method from UMLObject is required as * an extra signal, attributeChanged(), is emitted. */ void UMLAttribute::setVisibility(Uml::Visibility::Enum s) { m_visibility = s; Q_EMIT attributeChanged(); UMLObject::emitModified(); } /** * Returns The initial value of the UMLAttribute. * * @return The initial value of the Attribute. */ QString UMLAttribute::getInitialValue() const { return m_InitialValue; } /** * Sets the initial value of the UMLAttribute. * * @param iv The initial value of the UMLAttribute. */ void UMLAttribute::setInitialValue(const QString &iv) { if(m_InitialValue != iv) { m_InitialValue = iv; UMLObject::emitModified(); } } void UMLAttribute::setParmKind (Uml::ParameterDirection::Enum pk) { m_ParmKind = pk; } Uml::ParameterDirection::Enum UMLAttribute::getParmKind() const { return m_ParmKind; } /** * Returns a string representation of the UMLAttribute. * * @param sig If true will show the attribute type and initial value. * @param withStereotype If true will show a possible stereotype applied to the attribute. * @return Returns a string representation of the UMLAttribute. */ QString UMLAttribute::toString(Uml::SignatureType::Enum sig, bool withStereotype) const { QString s; if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::NoSig) { s = Uml::Visibility::toString(m_visibility, true) + QLatin1Char(' '); } if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::SigNoVis) { // Determine whether the type name needs to be scoped. UMLObject *owningObject = umlParent(); if (owningObject->baseType() == UMLObject::ot_Operation) { // The immediate parent is the UMLOperation but we want // the UMLClassifier: owningObject = owningObject->umlParent(); } const UMLClassifier *ownParent = owningObject->asUMLClassifier(); if (ownParent == nullptr) { logError2("UMLAttribute::toString(%1): parent %2 is not a UMLClassifier", name(), owningObject->name()); return QString(); } QString typeName; UMLClassifier *type = UMLClassifierListItem::getType(); if (type) { UMLPackage *typeScope = type->umlPackage(); if (typeScope != ownParent && typeScope != ownParent->umlPackage()) typeName = type->fullyQualifiedName(); else typeName = type->name(); } // The default direction, "in", is not mentioned. // Perhaps we should include a pd_Unspecified in // Uml::ParameterDirection::Enum to have better control over this. if (m_ParmKind == Uml::ParameterDirection::InOut) s += QStringLiteral("inout "); else if (m_ParmKind == Uml::ParameterDirection::Out) s += QStringLiteral("out "); // Construct the attribute text. QString string = s + name() + QStringLiteral(" : ") + typeName; if (m_InitialValue.length() > 0) string += QStringLiteral(" = ") + m_InitialValue; if (withStereotype) { QString st = stereotype(true); if (!st.isEmpty()) string += QLatin1Char(' ') + st; } return string; } return s + name(); } /** * Reimplement method from UMLObject. */ QString UMLAttribute::getFullyQualifiedName(const QString& separator, bool includeRoot /* = false */) const { const UMLOperation *op = nullptr; UMLObject *owningObject = umlParent(); if (owningObject->baseType() == UMLObject::ot_Operation) { op = owningObject->asUMLOperation(); owningObject = owningObject->umlParent(); } UMLClassifier *ownParent = owningObject->asUMLClassifier(); if (ownParent == nullptr) { logError2("UMLAttribute::getFullyQualifiedName(%1): parent %2 is not a UMLClassifier", name(), owningObject->name()); return QString(); } QString tempSeparator = separator; if (tempSeparator.isEmpty()) tempSeparator = UMLApp::app()->activeLanguageScopeSeparator(); QString fqn = ownParent->fullyQualifiedName(tempSeparator, includeRoot); if (op) fqn.append(tempSeparator + op->name()); fqn.append(tempSeparator + name()); return fqn; } /** * Overloaded '==' operator */ bool UMLAttribute::operator==(const UMLAttribute &rhs) const { if(this == &rhs) return true; if(!UMLObject::operator==(rhs)) return false; // The type name is the only distinguishing criterion. // (Some programming languages might support more, but others don't.) if (m_pSecondary != rhs.m_pSecondary) return false; return true; } /** * Copy the internal presentation of this object into the UMLAttribute * object. */ void UMLAttribute::copyInto(UMLObject *lhs) const { UMLAttribute *target = lhs->asUMLAttribute(); // call the parent first. UMLClassifierListItem::copyInto(target); // Copy all datamembers target->m_pSecondary = m_pSecondary; target->m_SecondaryId = m_SecondaryId; target->m_InitialValue = m_InitialValue; target->m_ParmKind = m_ParmKind; } /** * Make a clone of the UMLAttribute. */ UMLObject* UMLAttribute::clone() const { //FIXME: The new attribute should be slaved to the NEW parent not the old. UMLAttribute *clone = new UMLAttribute(umlParent()); copyInto(clone); return clone; } /** * Creates the <UML:Attribute> XMI element. */ void UMLAttribute::saveToXMI(QXmlStreamWriter& writer) { if (Settings::optionState().generalState.uml2) { UMLObject::save1(writer, QStringLiteral("Property"), QStringLiteral("ownedAttribute")); } else { UMLObject::save1(writer, QStringLiteral("Attribute")); } if (m_pSecondary == nullptr) { logDebug2("UMLAttribute::saveToXMI(%1) : m_pSecondary is null, m_SecondaryId is '%2'", name(), m_SecondaryId); } else { writer.writeAttribute(QStringLiteral("type"), Uml::ID::toString(m_pSecondary->id())); } if (! m_InitialValue.isEmpty()) writer.writeAttribute(QStringLiteral("initialValue"), m_InitialValue); UMLObject::save1end(writer); } /** * Loads the <UML:Attribute> XMI element. */ bool UMLAttribute::load1(QDomElement & element) { m_SecondaryId = element.attribute(QStringLiteral("type")); // We use the m_SecondaryId as a temporary store for the xmi.id // of the attribute type model object. // It is resolved later on, when all classes have been loaded. // This deferred resolution is required because the xmi.id may // be a forward reference, i.e. it may identify a model object // that has not yet been loaded. if (m_SecondaryId.isEmpty()) { // Perhaps the type is stored in a child node: QDomNode node = element.firstChild(); while (!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("type"))) { node = node.nextSibling(); continue; } m_SecondaryId = Model_Utils::getXmiId(tempElement); if (m_SecondaryId.isEmpty()) m_SecondaryId = tempElement.attribute(QStringLiteral("xmi.idref")); if (!m_SecondaryId.isEmpty()) break; QString href = tempElement.attribute(QStringLiteral("href")); if (href.isEmpty()) { QDomNode inner = node.firstChild(); QDomElement tmpElem = inner.toElement(); m_SecondaryId = Model_Utils::getXmiId(tmpElem); if (m_SecondaryId.isEmpty()) m_SecondaryId = tmpElem.attribute(QStringLiteral("xmi.idref")); } else { QString xmiType = tempElement.attribute(QStringLiteral("xmi:type")); bool isPrimitive = (xmiType.isEmpty() ? href.contains(QStringLiteral("PrimitiveType")) : xmiType.contains(QStringLiteral("PrimitiveType"))); if (isPrimitive && href.contains(QRegularExpression(QStringLiteral("#[A-Za-z][a-z]+$")))) { // Example from OMG XMI: // <type xmi:type="uml:PrimitiveType" href="http://www.omg.org/spec/UML/20090901/UML.xmi#Boolean"/> // Example from MagicDraw: // <type href="http://www.omg.org/spec/UML/20131001/PrimitiveTypes.xmi#String"/> // Examples from PapyrusUML: // <type xmi:type="uml:PrimitiveType" href="pathmap://UML_LIBRARIES/UMLPrimitiveTypes.library.uml#String"/> // <type xmi:type="uml:PrimitiveType" href="pathmap://UML_LIBRARIES/JavaPrimitiveTypes.library.uml#float"/> int hashpos = href.lastIndexOf(QChar(QLatin1Char('#'))); QString typeName = href.mid(hashpos + 1); UMLFolder *dtFolder = UMLApp::app()->document()->datatypeFolder(); UMLObjectList dataTypes = dtFolder->containedObjects(); m_pSecondary = Model_Utils::findUMLObject(dataTypes, typeName, UMLObject::ot_Datatype); if (m_pSecondary) { logDebug3("UMLAttribute::load1(%1) : href type = %2, number of datatypes = %3, " "found existing type.", name(), typeName, dataTypes.size()); } else { UMLDoc *pDoc = UMLApp::app()->document(); pDoc->createDatatype(typeName); /* m_pSecondary = Object_Factory::createUMLObject(UMLObject::ot_Datatype, typeName, dtFolder); */ qApp->processEvents(); m_pSecondary = Model_Utils::findUMLObject(dataTypes, typeName, UMLObject::ot_Datatype); logDebug3("UMLAttribute::load1(%1) : href type = %2, number of datatypes = %3, " "did not find it so created it now.", name(), typeName, dataTypes.size()); } } else { logWarn2("UMLAttribute::load1(%1) : resolving of href is not yet implemented (%2)", name(), href); } } break; } if (m_SecondaryId.isEmpty() && !m_pSecondary) { logDebug1("UMLAttribute::load1(%1): cannot find type.", name()); } } m_InitialValue = element.attribute(QStringLiteral("initialValue")); if (m_InitialValue.isEmpty()) { // for backward compatibility m_InitialValue = element.attribute(QStringLiteral("value")); } return true; } /** * Display the properties configuration dialog for the attribute. */ bool UMLAttribute::showPropertiesDialog(QWidget* parent) { UMLAttributeDialog dialog(parent, this); return dialog.exec(); } /** * Puts in the param templateParamList all the template params that are in templateParam */ void UMLAttribute::setTemplateParams(const QString& templateParam, UMLClassifierList &templateParamList) { if (templateParam.isEmpty()) return; QString type = templateParam.simplified(); int start = type.indexOf(QLatin1Char('<')); if (start >= 0) { int end = start; int count = 1; int len = type.length(); while (count != 0 && ++end < len) { QChar c = type.at(end); if (c == QLatin1Char('<')) { count++; } if (c == QLatin1Char('>')) { count--; } } if (count != 0) { //The template is ill-formed, let's quit return; } setTemplateParams(type.mid(start + 1, end - start - 1), templateParamList); setTemplateParams(type.left(start) + type.right(len - end - 1), templateParamList); } else { QStringList paramsList = type.split(QLatin1Char(',')); for (QStringList::Iterator it = paramsList.begin(); it != paramsList.end(); ++it) { QString param = *it; if (!param.isEmpty()) { UMLDoc *pDoc = UMLApp::app()->document(); UMLObject* obj = pDoc->findUMLObject(param); if (obj == nullptr) { obj = pDoc->findUMLObject(param.remove(QLatin1Char(' '))); } if (obj != nullptr) { //We want to list only the params that already exist in this document //If the param doesn't already exist, we couldn't draw an association anyway UMLClassifier* tmpClassifier = obj->asUMLClassifier(); if (templateParamList.indexOf(tmpClassifier) == -1) { templateParamList.append(tmpClassifier); } } } } } } /** * Returns all the template params (if any) that are in the type of this attribute */ UMLClassifierList UMLAttribute::getTemplateParams() { UMLClassifierList templateParamList; QString type = getType()->name(); QString templateParam; // Handle C++/D/Java template/generic parameters const Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage(); if (pl == Uml::ProgrammingLanguage::Cpp || pl == Uml::ProgrammingLanguage::CSharp || pl == Uml::ProgrammingLanguage::Java || pl == Uml::ProgrammingLanguage::D) { int start = type.indexOf(QLatin1Char('<')); if (start >= 0) { int end = type.lastIndexOf(QLatin1Char('>')); if (end > start) { templateParam = type.mid(start + 1, end - start - 1); setTemplateParams(templateParam, templateParamList); } } } return templateParamList; }
16,500
C++
.cpp
426
30.342723
129
0.605598
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,461
operation.cpp
KDE_umbrello/umbrello/umlmodel/operation.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "operation.h" // app includes #include "attribute.h" #include "classifier.h" #include "model_utils.h" #include "debug_utils.h" #include "uml.h" #include "umldoc.h" #include "uniqueid.h" #include "umloperationdialog.h" #include "codegenerator.h" #include "codedocument.h" #include "codeblock.h" // kde includes #include <KLocalizedString> // qt includes #include <QRegularExpression> DEBUG_REGISTER(UMLOperation) /** * Constructs a UMLOperation. * Not intended for general use: The operation is not tied in with * umbrello's Qt signalling for object creation. * If you want to create an Operation use the method in UMLDoc instead. * * @param parent the parent to this operation * @param name the name of the operation * @param id the id of the operation * @param s the visibility of the operation * @param rt the return type of the operation */ UMLOperation::UMLOperation(UMLClassifier *parent, const QString& name, Uml::ID::Type id, Uml::Visibility::Enum s, UMLObject *rt) : UMLClassifierListItem(parent, name, id), m_bVirtual(false), m_bInline(false) { if (rt) m_returnId = UniqueID::gen(); else m_returnId = Uml::ID::None; m_pSecondary = rt; m_visibility = s; m_BaseType = UMLObject::ot_Operation; m_bConst = false; m_bOverride = false; m_bFinal = false; m_Code.clear(); } /** * Constructs a UMLOperation. * Not intended for general use: The operation is not tied in with * umbrello's Qt signalling for object creation. * If you want to create an Operation use the method in UMLDoc instead. * * @param parent the parent to this operation */ UMLOperation::UMLOperation(UMLClassifier * parent) : UMLClassifierListItem (parent), m_bVirtual(false), m_bInline(false) { m_BaseType = UMLObject::ot_Operation; m_bConst = false; m_bOverride = false; m_bFinal = false; m_Code.clear(); } /** * Destructor. */ UMLOperation::~UMLOperation() { } /** * Reimplement method from UMLClassifierListItem. * * @param type pointer to the type object */ void UMLOperation::setType(UMLObject* type) { UMLClassifierListItem::setType(type); if (m_returnId == Uml::ID::None) m_returnId = UniqueID::gen(); } /** * Move a parameter one position to the left. * * @param a the parameter to move */ void UMLOperation::moveParmLeft(UMLAttribute * a) { if (a == nullptr) { logDebug0("UMLOperation::moveParmLeft called on NULL attribute"); return; } logDebug1("UMLOperation::moveParmLeft called for %1", a->name()); disconnect(a, SIGNAL(modified()), this, SIGNAL(modified())); int idx; if ((idx = m_args.indexOf(a)) == -1) { logDebug1("UMLOperation::moveParmLeftError move parm left %1", a->name()); return; } if (idx == 0) return; m_args.removeAll(a); m_args.insert(idx-1, a); } /** * Move a parameter one position to the right. * * @param a the parameter to move */ void UMLOperation::moveParmRight(UMLAttribute * a) { if (a == nullptr) { logDebug0("UMLOperation::moveParmRight called on NULL attribute"); return; } logDebug1("UMLOperation::moveParmRight called for %1", a->name()); disconnect(a, SIGNAL(modified()), this, SIGNAL(modified())); int idx; if ((idx = m_args.indexOf(a)) == -1) { logDebug1("UMLOperation::moveParmRight: Error move parm right %1", a->name()); return; } int count = m_args.count(); if (idx == count-1) return; m_args.removeAll(a); m_args.insert(idx+1, a); } /** * Remove a parameter from the operation. * * @param a the parameter to remove * @param emitModifiedSignal whether to emit the "modified" signal * which creates an entry in the Undo stack for the * removal, default: true */ void UMLOperation::removeParm(UMLAttribute * a, bool emitModifiedSignal /* =true */) { if (a == nullptr) { logDebug0("UMLOperation::removeParm called on NULL attribute"); return; } logDebug1("UMLOperation::removeParm called for %1", a->name()); disconnect(a, SIGNAL(modified()), this, SIGNAL(modified())); if (!m_args.removeAll(a)) logDebug1("UMLOperation::removeParm: Error removing parm %1", a->name()); if (emitModifiedSignal) Q_EMIT modified(); } /** * Returns a list of parameters. * * @return a list of the parameters in the operation */ UMLAttributeList UMLOperation::getParmList() const { return m_args; } /** * Finds a parameter of the operation. * * @param name the parameter name to search for * @return the found parameter, 0 if not found */ UMLAttribute* UMLOperation::findParm(const QString &name) const { for(UMLAttribute *obj: m_args) { if (obj->name() == name) return obj; } return (UMLAttribute*)nullptr; } /** * Returns a string representation of the operation. * * @param sig what type of operation string to show * @param withStereotype if true will show a possible stereotype applied to the operation * @return the string representation of the operation */ QString UMLOperation::toString(Uml::SignatureType::Enum sig, bool withStereotype) const { QString s; if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::NoSig) s = Uml::Visibility::toString(m_visibility, true) + QLatin1Char(' '); s += name(); Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage(); bool parameterlessOpNeedsParentheses = (pl != Uml::ProgrammingLanguage::Pascal && pl != Uml::ProgrammingLanguage::Ada); if (sig == Uml::SignatureType::NoSig || sig == Uml::SignatureType::NoSigNoVis) { if (parameterlessOpNeedsParentheses) s.append(QStringLiteral("()")); if (withStereotype) { QString st = stereotype(true); if (!st.isEmpty()) s += QLatin1Char(' ') + st; } return s; } int last = m_args.count(); if (last) { s.append(QStringLiteral("(")); int i = 0; for(UMLAttribute *param : m_args) { i++; s.append(param->toString(Uml::SignatureType::SigNoVis, withStereotype)); if (i < last) s.append(QStringLiteral(", ")); } s.append(QStringLiteral(")")); } else if (parameterlessOpNeedsParentheses) { s.append(QStringLiteral("()")); } const UMLClassifier *ownParent = umlParent()->asUMLClassifier(); QString returnType; UMLClassifier *retType = UMLClassifierListItem::getType(); if (retType) { UMLPackage *retVisibility = retType->umlPackage(); if (retVisibility != ownParent && retVisibility != ownParent->umlPackage()) returnType = retType->fullyQualifiedName(); else returnType = retType->name(); } if (returnType.length() > 0 && returnType != QStringLiteral("void")) { s.append(QStringLiteral(" : ")); if (returnType.startsWith(QStringLiteral("virtual "))) { s += returnType.mid(8); } else { s += returnType; } } if (withStereotype) { QString st = stereotype(true); if (!st.isEmpty()) s += QLatin1Char(' ') + st; } return s; } /** * Add a parameter to the operation. * * @param parameter the parameter to add * @param position the position in the parameter list. * If position = -1 the parameter will be * appended to the list. */ void UMLOperation::addParm(UMLAttribute *parameter, int position) { if (position >= 0 && position <= (int)m_args.count()) m_args.insert(position, parameter); else m_args.append(parameter); UMLObject::emitModified(); connect(parameter, SIGNAL(modified()), this, SIGNAL(modified())); } /** * Returns an unused parameter name for a new parameter. */ QString UMLOperation::getUniqueParameterName() const { QString currentName = i18n("new_parameter"); QString name = currentName; for (int number = 1; findParm(name); ++number) { name = currentName + QLatin1Char('_') + QString::number(number); } return name; } /** * Overloaded '==' operator. */ bool UMLOperation::operator==(const UMLOperation & rhs) const { if (this == &rhs) return true; if (!UMLObject::operator==(rhs)) return false; if (getTypeName() != rhs.getTypeName()) return false; if (m_args.count() != rhs.m_args.count()) return false; if (!(m_args == rhs.m_args)) return false; return true; } /** * Copy the internal presentation of this object into the new * object. */ void UMLOperation::copyInto(UMLObject *lhs) const { UMLOperation *target = lhs->asUMLOperation(); UMLClassifierListItem::copyInto(target); m_args.copyInto(&(target->m_args)); } /** * Make a clone of this object. */ UMLObject* UMLOperation::clone() const { //FIXME: The new operation should be slaved to the NEW parent not the old. UMLOperation *clone = new UMLOperation(umlParent()->asUMLClassifier()); copyInto(clone); return clone; } /** * Calls resolveRef() on all parameters. * Needs to be called after all UML objects are loaded from file. * * @return true for success */ bool UMLOperation::resolveRef() { bool overallSuccess = UMLObject::resolveRef(); // See remark on iteration style in UMLClassifier::resolveRef() for(UMLAttribute* pAtt : m_args) { if (! pAtt->resolveRef()) overallSuccess = false; } return overallSuccess; } /** * Returns whether this operation is a constructor. * * @return true if this operation is a constructor */ bool UMLOperation::isConstructorOperation() const { // if an operation has the stereotype constructor // return true if (stereotype() == QStringLiteral("constructor")) return true; const UMLClassifier * c = umlParent()->asUMLClassifier(); if (!c) return false; QString cName = c->name(); QString opName = name(); // It's a constructor operation if the operation name // matches that of the parent classifier. return (cName == opName); } /** * Returns whether this operation is a destructor. * * @return true if this operation is a destructor */ bool UMLOperation::isDestructorOperation() const { if (stereotype() == QStringLiteral("destructor")) return true; const UMLClassifier * c = umlParent()->asUMLClassifier(); if (!c) return false; QString cName = c->name(); QString opName = name(); // Special support for C++ syntax: // It's a destructor operation if the operation name begins // with "~" followed by the name of the parent classifier. if (! opName.startsWith(QLatin1Char('~'))) return false; opName.remove(QRegularExpression(QStringLiteral("^~\\s*"))); return (cName == opName); } /** * Shortcut for (isConstructorOperation() || isDestructorOperation()). * * @return true if this operation is a constructor or destructor */ bool UMLOperation::isLifeOperation() const { return (isConstructorOperation() || isDestructorOperation()); } /** * Sets whether this operation is a query (C++ "const"). */ void UMLOperation::setConst(bool b) { m_bConst = b; } /** * Returns whether this operation is a query (C++ "const"). */ bool UMLOperation::getConst() const { return m_bConst; } /** * Sets whether this operation has override flag. */ void UMLOperation::setOverride(bool b) { m_bOverride = b; } /** * Returns whether this operation has override flag. */ bool UMLOperation::getOverride() const { return m_bOverride; } /** * Sets whether this operation has final flag. */ void UMLOperation::setFinal(bool b) { m_bFinal = b; } /** * Returns whether this operation has final flag. */ bool UMLOperation::getFinal() const { return m_bFinal; } /** * Sets whether this operation is a virtual method. */ void UMLOperation::setVirtual(bool b) { m_bVirtual = b; } /** * Returns whether this operation is a virtual method. */ bool UMLOperation::isVirtual() const { return m_bVirtual; } /** * Sets whether this operation is inlined. */ void UMLOperation::setInline(bool b) { m_bInline = b; } /** * Returns whether this operation is inlined. */ bool UMLOperation::isInline() const { return m_bInline; } /** * Display the properties configuration dialog for the template. * * @param parent the parent for the dialog */ bool UMLOperation::showPropertiesDialog(QWidget* parent) { UMLOperationDialog dialog(parent, this); return dialog.exec(); } /** * Sets the source code for this operation. * * @param code the body of this operation */ void UMLOperation::setSourceCode(const QString& code) { m_Code = code; } /** * Returns the source code for this operation. */ QString UMLOperation::getSourceCode() const { return m_Code; } /** * Saves to the <UML:Operation> XMI element. */ void UMLOperation::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Operation"), QStringLiteral("ownedOperation")); if (m_bConst) writer.writeAttribute(QStringLiteral("isQuery"), QStringLiteral("true")); if (m_bOverride) writer.writeAttribute(QStringLiteral("isOverride"), QStringLiteral("true")); if (m_bFinal) writer.writeAttribute(QStringLiteral("isFinal"), QStringLiteral("true")); if (m_bVirtual) writer.writeAttribute(QStringLiteral("isVirtual"), QStringLiteral("true")); if (m_bInline) writer.writeAttribute(QStringLiteral("isInline"), QStringLiteral("true")); if (m_pSecondary == nullptr && m_args.isEmpty()) { writer.writeEndElement(); // UML:Operation return; } if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:BehavioralFeature.parameter")); } const QString dirAttrName = (Settings::optionState().generalState.uml2 ? QStringLiteral("direction") : QStringLiteral("kind")); if (m_pSecondary) { if (m_returnId == Uml::ID::None) { logDebug1("UMLOperation::saveToXMI %1: m_returnId is not set, setting it now.", name()); m_returnId = UniqueID::gen(); } if (Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("ownedParameter")); writer.writeAttribute(QStringLiteral("xmi:type"), QStringLiteral("uml:Parameter")); writer.writeAttribute(QStringLiteral("xmi:id"), Uml::ID::toString(m_returnId)); } else { writer.writeStartElement(QStringLiteral("UML:Parameter")); writer.writeAttribute(QStringLiteral("xmi.id"), Uml::ID::toString(m_returnId)); } writer.writeAttribute(QStringLiteral("type"), Uml::ID::toString(m_pSecondary->id())); writer.writeAttribute(dirAttrName, QStringLiteral("return")); writer.writeEndElement(); } else { logDebug1("UMLOperation::saveToXMI: m_SecondaryId is %1", m_SecondaryId); } //save each attribute here, type different for(UMLAttribute* pAtt : m_args) { pAtt->UMLObject::save1(writer, QStringLiteral("Parameter"), QStringLiteral("ownedParameter")); UMLClassifier *attrType = pAtt->getType(); if (attrType) { writer.writeAttribute(QStringLiteral("type"), Uml::ID::toString(attrType->id())); } else { writer.writeAttribute(QStringLiteral("type"), pAtt->getTypeName()); } writer.writeAttribute(QStringLiteral("value"), pAtt->getInitialValue()); Uml::ParameterDirection::Enum kind = pAtt->getParmKind(); if (kind == Uml::ParameterDirection::Out) writer.writeAttribute(dirAttrName, QStringLiteral("out")); else if (kind == Uml::ParameterDirection::InOut) writer.writeAttribute(dirAttrName, QStringLiteral("inout")); // The default for the parameter kind is "in". writer.writeEndElement(); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); // UML:BehavioralFeature.parameter } UMLObject::save1end(writer); // UML:Operation } /** * Loads a <UML:Operation> XMI element. */ bool UMLOperation::load1(QDomElement & element) { m_SecondaryId = element.attribute(QStringLiteral("type")); QString isQuery = element.attribute(QStringLiteral("isQuery")); if (!isQuery.isEmpty()) { // We need this extra test for isEmpty() because load() might have been // called again by the processing for BehavioralFeature.parameter (see below) m_bConst = (isQuery == QStringLiteral("true")); } QString isOverride = element.attribute(QStringLiteral("isOverride")); m_bOverride = (isOverride == QStringLiteral("true")); QString isFinal = element.attribute(QStringLiteral("isFinal")); m_bFinal = (isFinal == QStringLiteral("true")); QString isVirtual = element.attribute(QStringLiteral("isVirtual")); m_bVirtual = (isVirtual == QStringLiteral("true")); QString isInline = element.attribute(QStringLiteral("isInline")); m_bInline = (isInline == QStringLiteral("true")); QDomNode node = element.firstChild(); if (node.isComment()) node = node.nextSibling(); QDomElement attElement = node.toElement(); while (!attElement.isNull()) { QString tag = attElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("BehavioralFeature.parameter")) || UMLDoc::tagEq(tag, QStringLiteral("Element.ownedElement"))) { // Embarcadero's Describe if (! load1(attElement)) return false; } else if (UMLDoc::tagEq(tag, QStringLiteral("Parameter")) || UMLDoc::tagEq(tag, QStringLiteral("ownedParameter"))) { QString kind = attElement.attribute(QStringLiteral("kind")); if (kind.isEmpty()) { kind = attElement.attribute(QStringLiteral("direction")); // UML2 if (kind.isEmpty()) { // Perhaps the kind is stored in a child node: for (QDomNode n = attElement.firstChild(); !n.isNull(); n = n.nextSibling()) { if (n.isComment()) continue; QDomElement tempElement = n.toElement(); QString tag = tempElement.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("kind"))) continue; kind = tempElement.attribute(QStringLiteral("xmi.value")); break; } } if (kind.isEmpty()) { kind = QStringLiteral("in"); } } if (kind == QStringLiteral("return") || kind == QStringLiteral("result")) { // Embarcadero's Describe QString returnId = Model_Utils::getXmiId(attElement); if (!returnId.isEmpty()) m_returnId = Uml::ID::fromString(returnId); m_SecondaryId = attElement.attribute(QStringLiteral("type")); if (m_SecondaryId.isEmpty()) { // Perhaps the type is stored in a child node: QDomNode node = attElement.firstChild(); while (!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("type"))) { node = node.nextSibling(); continue; } m_SecondaryId = Model_Utils::getXmiId(tempElement); if (m_SecondaryId.isEmpty()) m_SecondaryId = tempElement.attribute(QStringLiteral("xmi.idref")); if (m_SecondaryId.isEmpty()) { QDomNode inner = node.firstChild(); QDomElement tmpElem = inner.toElement(); m_SecondaryId = Model_Utils::getXmiId(tmpElem); if (m_SecondaryId.isEmpty()) m_SecondaryId = tmpElem.attribute(QStringLiteral("xmi.idref")); } break; } if (m_SecondaryId.isEmpty()) { logError1("UMLOperation::load1(%1) : cannot find return type", name()); } } // Use deferred xmi.id resolution. m_pSecondary = nullptr; } else { UMLAttribute * pAtt = new UMLAttribute(this); if(!pAtt->loadFromXMI(attElement)) { delete pAtt; return false; } if (kind == QStringLiteral("out")) pAtt->setParmKind(Uml::ParameterDirection::Out); else if (kind == QStringLiteral("inout")) pAtt->setParmKind(Uml::ParameterDirection::InOut); else pAtt->setParmKind(Uml::ParameterDirection::In); m_args.append(pAtt); } } node = node.nextSibling(); if (node.isComment()) node = node.nextSibling(); attElement = node.toElement(); // loading the source code which was entered in the 'classpropdlg' dialog is not done // with the following code, because there is no CodeDocument. /* CodeGenerator* codegen = UMLApp::app()->getGenerator(); if (codegen) { logDebug1("UMLOperation::load1: CodeDocument searching with id=%1", Uml::ID::toString(UMLObject::ID()); CodeDocument* codeDoc = codegen->findCodeDocumentByID(Uml::ID::toString(UMLObject::ID())); if (codeDoc) { logDebug0("UMLOperation::load1: CodeDocument was found"); } } */ // it is done in the code generators by calling CodeGenerator::loadFromXMI(...). }//end while return true; }
22,852
C++
.cpp
667
27.691154
102
0.624605
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,462
umlattributelist.cpp
KDE_umbrello/umbrello/umlmodel/umlattributelist.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2004-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlattributelist.h" #include "attribute.h" #include <KLocalizedString> UMLAttributeList::UMLAttributeList() { } UMLAttributeList::~UMLAttributeList() { } /** * Copy the internal presentation of this object into the new * object. */ void UMLAttributeList::copyInto(UMLAttributeList *rhs) const { // Don't copy yourself. if (rhs == this) return; rhs->clear(); // Suffering from const; we shall not modify our object. UMLAttributeList *tmp = new UMLAttributeList(*this); UMLAttribute *item; for (UMLAttributeListIt ait(*tmp); ait.hasNext() ;) { item = ait.next(); rhs->append((UMLAttribute*)item->clone()); } delete tmp; } /** * Make a clone of this object. */ UMLAttributeList* UMLAttributeList::clone() const { UMLAttributeList *clone = new UMLAttributeList(); copyInto(clone); return clone; }
1,031
C++
.cpp
41
21.926829
92
0.711224
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,463
port.cpp
KDE_umbrello/umbrello/umlmodel/port.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2014-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "port.h" #include <KLocalizedString> /** * Sets up a Port. * * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLPort::UMLPort(const QString & name, Uml::ID::Type id) : UMLCanvasObject(name, id) { init(); } /** * Destructor. */ UMLPort::~UMLPort() { } /** * Initializes key variables of the class. */ void UMLPort::init() { m_BaseType = UMLObject::ot_Port; } /** * Make a clone of this object. */ UMLObject* UMLPort::clone() const { UMLPort *clone = new UMLPort(); UMLObject::copyInto(clone); return clone; } /** * Creates the <UML:Port> XMI element. */ void UMLPort::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Port"), QStringLiteral("ownedAttribute")); UMLObject::save1end(writer); } /** * Loads the <UML:Port> XMI element (empty.) */ bool UMLPort::load1(QDomElement&) { return true; }
1,076
C++
.cpp
54
17.703704
92
0.692004
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,464
component.cpp
KDE_umbrello/umbrello/umlmodel/component.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "component.h" // app includes #include "association.h" #include "debug_utils.h" #include "object_factory.h" #include "model_utils.h" #include "clipboard/idchangelog.h" #include "optionstate.h" #include "umldoc.h" #include "uml.h" // kde includes #include <KLocalizedString> /** * Sets up a Component. * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLComponent::UMLComponent(const QString & name, Uml::ID::Type id) : UMLPackage(name, id), m_executable(false) { m_BaseType = UMLObject::ot_Component; } /** * Destructor. */ UMLComponent::~UMLComponent() { } /** * Make a clone of this object. */ UMLObject* UMLComponent::clone() const { UMLComponent *clone = new UMLComponent(); UMLObject::copyInto(clone); return clone; } /** * Creates the UML:Component element including its operations, * attributes and templates */ void UMLComponent::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Component")); writer.writeAttribute(QStringLiteral("executable"), QString::number(m_executable)); // Save contained components if any. if (m_objects.count()) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Namespace.ownedElement")); } for (UMLObjectListIt objectsIt(m_objects); objectsIt.hasNext();) { UMLObject* obj = objectsIt.next(); uIgnoreZeroPointer(obj); obj->saveToXMI (writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); } } UMLObject::save1end(writer); } /** * Loads the UML:Component element including its ports et al. */ bool UMLComponent::load1(QDomElement& element) { QString executable = element.attribute(QStringLiteral("executable"), QStringLiteral("0")); m_executable = (bool)executable.toInt(); for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; QDomElement tempElement = node.toElement(); QString type = tempElement.tagName(); if (Model_Utils::isCommonXMI1Attribute(type)) continue; if (UMLDoc::tagEq(type, QStringLiteral("Namespace.ownedElement")) || UMLDoc::tagEq(type, QStringLiteral("Namespace.contents"))) { //CHECK: Umbrello currently assumes that nested elements // are ownedElements anyway. // Therefore these tags are not further interpreted. if (! load1(tempElement)) return false; continue; } if (UMLDoc::tagEq(type, QStringLiteral("ownedAttribute"))) { type = tempElement.attribute(QStringLiteral("xmi:type")); } UMLObject *pObject = Object_Factory::makeObjectFromXMI(type); if (!pObject) { logWarn1("UMLComponent::load1 unknown type of umlobject to create: %1", type); continue; } pObject->setUMLPackage(this); if (pObject->loadFromXMI(tempElement)) { addObject(pObject); } else { delete pObject; } } return true; } /** * Sets m_executable. */ void UMLComponent::setExecutable(bool executable) { m_executable = executable; } /** * Returns the value of m_executable. */ bool UMLComponent::getExecutable() const { return m_executable; }
3,665
C++
.cpp
122
24.745902
94
0.660158
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,465
instance.cpp
KDE_umbrello/umbrello/umlmodel/instance.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "instance.h" //app includes #include "cmds.h" #include "classifier.h" #include "classpropertiesdialog.h" #include "debug_utils.h" #include "instanceattribute.h" #include "object_factory.h" #include "uml.h" #include "umldoc.h" #include "umlinstanceattributedialog.h" #include "uniqueid.h" //kde includes #include <KLocalizedString> #include <KMessageBox> DEBUG_REGISTER(UMLInstance) /** * Construct UMLInstance * @param instanceName Name of the instance * @param id The unique id to assign * @param c The UMLClassifier that this instance represents, or * nullptr in case of an untyped instance. * The classifier can also be set after construction * by calling setClassifier(). */ UMLInstance::UMLInstance(const QString &instanceName, Uml::ID::Type id, UMLClassifier *c /* = nullptr */) : UMLCanvasObject(instanceName, id) { m_BaseType = UMLObject::ot_Instance; setClassifierCmd(c, false); // Signal shall not be emitted here // because we are stll in the constructor. } /** * Set undoable classifier * @param classifier */ void UMLInstance::setClassifier(UMLClassifier *classifier) { if (m_pSecondary == classifier) return; //UMLApp::app()->executeCommand(new Uml::CmdRenameUMLInstanceType(this, classifier)); m_pSecondary = classifier; emitModified(); } /** * Set classifier * @param classifier the classifier which is the type of this instance * @param emitSignal flag controlling whether to emit a modification signal (default: true) */ void UMLInstance::setClassifierCmd(UMLClassifier *classifier, bool emitSignal /* = true */) { if (m_pSecondary == classifier) return; if (m_pSecondary) { subordinates().clear(); disconnect(m_pSecondary, SIGNAL(attributeAdded(UMLClassifierListItem*)), this, SLOT(attributeAdded(UMLClassifierListItem*))); disconnect(m_pSecondary, SIGNAL(attributeRemoved(UMLClassifierListItem*)), this, SLOT(attributeRemoved(UMLClassifierListItem*))); } m_pSecondary = classifier; if (classifier) { UMLClassifierListItemList attrDefs = classifier->getFilteredList(UMLObject::ot_Attribute); for(UMLClassifierListItem *item : attrDefs) { uIgnoreZeroPointer(item); UMLAttribute *umla = item->asUMLAttribute(); if (umla) { UMLInstanceAttribute *ia = new UMLInstanceAttribute(this, umla, umla->getInitialValue()); subordinates().append(ia); } else { logError1("UMLInstance::setClassifierCmd : item %1 is not an attribute", item->name()); } } connect(classifier, SIGNAL(attributeAdded(UMLClassifierListItem*)), this, SLOT(attributeAdded(UMLClassifierListItem*))); connect(classifier, SIGNAL(attributeRemoved(UMLClassifierListItem*)), this, SLOT(attributeRemoved(UMLClassifierListItem*))); } if (emitSignal) emitModified(); } UMLClassifier *UMLInstance::classifier() const { return (m_pSecondary ? m_pSecondary->asUMLClassifier() : nullptr); } /** * Creates the <UML:Instance> element including its slots. */ void UMLInstance::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Instance")); if (m_pSecondary) { writer.writeAttribute(QStringLiteral("classifier"), Uml::ID::toString(m_pSecondary->id())); //save attributes for(UMLObject *pObject : subordinates()) { pObject->saveToXMI(writer); } } UMLObject::save1end(writer); } /** * Loads the <UML:Instance> element including its instanceAttributes. */ bool UMLInstance::load1(QDomElement &element) { m_SecondaryId = element.attribute(QStringLiteral("classifier")); QDomNode node = element.firstChild(); while (!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("slot"))) { UMLInstanceAttribute *pInstanceAttribute = new UMLInstanceAttribute(this, nullptr); if (!pInstanceAttribute->loadFromXMI(tempElement)) { return false; } subordinates().append(pInstanceAttribute); } node = node.nextSibling(); } // end while return true; } /** * Resolve forward declaration of referenced classifier held in m_secondaryId * after loading object from xmi file. * @return true - resolve was successful * @return false - resolve was not successful */ bool UMLInstance::resolveRef() { if (m_SecondaryId.isEmpty()) { maybeSignalObjectCreated(); return true; } if (m_pSecondary) { m_SecondaryId.clear(); maybeSignalObjectCreated(); return true; } if (!UMLObject::resolveRef()) { return false; } return (m_pSecondary != nullptr); } /** * Display the properties configuration dialog. * @param parent Parent widget * @return true - configuration has been applied * @return false - configuration has not been applied */ bool UMLInstance::showPropertiesDialog(QWidget* parent) { ClassPropertiesDialog dialog(parent, this); return dialog.exec(); } void UMLInstance::attributeAdded(UMLClassifierListItem *item) { for (int i = 0; i < subordinates().count(); i++) { UMLObject *o = subordinates().at(i); if (o->parent() == item) { logDebug2("UMLInstance %1 attributeAdded(%2) : instanceAttribute already present", name(), item->name()); return; } } UMLAttribute *umla = item->asUMLAttribute(); if (umla) { logDebug2("UMLInstance %1 attributeAdded(%2) : creating UMLInstanceAttribute", name(), item->name()); UMLInstanceAttribute *ia = new UMLInstanceAttribute(this, umla, umla->getInitialValue()); subordinates().append(ia); } else { logError2("UMLInstance %1 attributeAdded(%2) : item is not a UMLAttribute", name(), item->name()); } } void UMLInstance::attributeRemoved(UMLClassifierListItem *item) { for (int i = 0; i < subordinates().count(); i++) { UMLObject *o = subordinates().at(i); if (o->parent() == item) { logDebug3("UMLInstance %1 attributeRemoved(%2) : removing instanceAttribute at index %3", name(), item->name(), i); subordinates().removeAt(i); return; } } logWarn1("UMLInstance::attributeRemoved(%1) : instanceAttribute not found", item->name()); }
6,960
C++
.cpp
197
29.253807
105
0.661281
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,466
instanceattribute.cpp
KDE_umbrello/umbrello/umlmodel/instanceattribute.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ //own header #include "instanceattribute.h" //local includes #include "instance.h" #include "attribute.h" #include "debug_utils.h" #include "model_utils.h" #include "umldoc.h" #include "uml.h" #include "umlinstanceattributedialog.h" #include "uniqueid.h" #include "object_factory.h" #include "optionstate.h" //kde includes #include <KLocalizedString> #include <KMessageBox> /** * Constructor * @param parent The UMLInstance to which this instance attribute belongs. * @param umlAttr The UMLAttribute which this instance attribute reifies. * It is expected that umlAttr be a non null pointer. * If umlAttr is passed in as nullptr then the setAttribute * method shall be used for setting a non null pointer * before the instance attribute is used by the application. * @param value The value of the instance attribute. */ UMLInstanceAttribute::UMLInstanceAttribute(UMLInstance *parent, UMLAttribute *umlAttr, const QString& value) : UMLObject(parent) { m_nId = UniqueID::gen(); m_pSecondary = umlAttr; m_value = value; init(); } /** * @brief UMLInstanceAttribute::init * Initialize members of this class */ void UMLInstanceAttribute::init() { m_BaseType = UMLObject::ot_InstanceAttribute; } /** * Sets the UMLInstanceAttribute's UML attribute. * @param umlAttr Non null pointer to UMLAttribute. */ void UMLInstanceAttribute::setAttribute(UMLAttribute *umlAttr) { Q_ASSERT(umlAttr); m_pSecondary = umlAttr; } /** * Returns the UMLInstanceAttribute's UML attribute. * @return The UMLInstanceAttribute's UML attribute. */ UMLAttribute * UMLInstanceAttribute::getAttribute() const { if (m_pSecondary == nullptr) return nullptr; return m_pSecondary->asUMLAttribute(); } /** * Sets the UMLInstanceAttribute's value. * @param value The value to set. */ void UMLInstanceAttribute::setValue(const QString& value) { m_value = value; } /** * Returns the UMLInstanceAttribute's value. * @return The UMLInstanceAttribute's value. */ QString UMLInstanceAttribute::getValue() const { return m_value; } /** * Returns the textual notation for instance attribute. * @return Stringified attribute name and value. */ QString UMLInstanceAttribute::toString() const { QString result(m_pSecondary->name() + QStringLiteral(" = ") + m_value); return result; } /** * Creates the <UML:InstanceAttribute> XMI element. */ void UMLInstanceAttribute::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("slot")); if (Settings::optionState().generalState.uml2) { writer.writeAttribute(QStringLiteral("xmi:id"), Uml::ID::toString(m_nId)); } else { writer.writeAttribute(QStringLiteral("xmi.id"), Uml::ID::toString(m_nId)); } Q_ASSERT(m_pSecondary); writer.writeAttribute(QStringLiteral("attribute"), Uml::ID::toString(m_pSecondary->id())); writer.writeAttribute(QStringLiteral("value"), m_value); writer.writeEndElement(); } /** * Loads the UMLInstance "slot" XMI element. */ bool UMLInstanceAttribute::load1(QDomElement & element) { QString id = Model_Utils::getXmiId(element); if (id.isEmpty() || id == QStringLiteral("-1")) { logWarn0("UMLInstanceAttribute::load1: xmi.id not present, generating a new one"); m_nId = UniqueID::gen(); } else { m_nId = Uml::ID::fromString(id); } m_SecondaryId = element.attribute(QStringLiteral("attribute")); if (m_SecondaryId.isEmpty() || m_SecondaryId == QStringLiteral("-1")) { logError0("UMLInstanceAttribute::load1: element 'attribute' not set or empty"); return false; } UMLDoc *pDoc = UMLApp::app()->document(); m_pSecondary = pDoc->findObjectById(Uml::ID::fromString(m_SecondaryId)); if (m_pSecondary) m_SecondaryId.clear(); m_value = element.attribute(QStringLiteral("value")); return true; } /** * Display the properties configuration dialog for the instanceattribute. */ bool UMLInstanceAttribute::showPropertiesDialog(QWidget* parent) { UMLInstanceAttributeDialog dialog(parent, this); return dialog.exec(); }
4,375
C++
.cpp
139
28.215827
94
0.711985
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,467
actor.cpp
KDE_umbrello/umbrello/umlmodel/actor.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "actor.h" /** * Constructs an Actor. * * @param name The name of the Actor. * @param id The unique id to assign to this Actor. */ UMLActor::UMLActor(const QString & name, Uml::ID::Type id) : UMLCanvasObject(name, id) { init(); } /** * Standard destructor. */ UMLActor::~UMLActor() { } /** * Initializes key variables of the class. */ void UMLActor::init() { m_BaseType = UMLObject::ot_Actor; } /** * Make a clone of this object. */ UMLObject* UMLActor::clone() const { UMLActor *clone = new UMLActor(); UMLObject::copyInto(clone); return clone; } /** * Creates the <UML:Actor> XMI element. */ void UMLActor::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Actor")); UMLObject::save1end(writer); } /** * Loads the <UML:Actor> XMI element (empty). */ bool UMLActor::load1(QDomElement& element) { Q_UNUSED(element); return true; }
1,080
C++
.cpp
54
17.722222
92
0.692534
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,468
datatype.cpp
KDE_umbrello/umbrello/umlmodel/datatype.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "datatype.h" /** * Sets up a Datatype. * @param name The name of the Datatype. * @param id The unique id of the Concept. */ UMLDatatype::UMLDatatype(const QString & name, Uml::ID::Type id) : UMLClassifier(name, id), m_isRef(false), m_isActive(true) { m_BaseType = UMLObject::ot_Datatype; setStereotype(QStringLiteral("dataType")); } /** * Destructor. */ UMLDatatype::~UMLDatatype() { } /** * Set the origin type (in case of e.g. typedef) * @param origType the origin type to set */ void UMLDatatype::setOriginType(UMLClassifier *origType) { m_pSecondary = origType; } /** * Get the origin type (in case of e.g. typedef) * @return the origin type */ UMLClassifier * UMLDatatype::originType() const { return m_pSecondary->asUMLClassifier(); } /** * Set the m_isRef flag (true when dealing with a pointer type) * @param isRef the flag to set */ void UMLDatatype::setIsReference(bool isRef) { m_isRef = isRef; } /** * Get the m_isRef flag. * @return true if is reference, otherwise false */ bool UMLDatatype::isReference() const { return m_isRef; } /** * Set the m_isActive flag (is already set true by constructor). * @param active the flag to set */ void UMLDatatype::setActive(bool active) { m_isActive = active; } /** * Get the m_isActive flag. * @return true if is active, otherwise false */ bool UMLDatatype::isActive() const { return m_isActive; } /** * Loads Datatype specific attributes from QDomElement. * Is invoked by UMLObject::loadFromXMI() which does most of the work. * * @param element A QDomElement which contains xml info for this object. */ bool UMLDatatype::load1(QDomElement & element) { m_SecondaryId = element.attribute(QStringLiteral("elementReference")); if (!m_SecondaryId.isEmpty()) { // @todo We do not currently support composition. m_isRef = true; } QString active = element.attribute(QStringLiteral("isActive")); m_isActive = (active != QStringLiteral("false")); return true; } /** * Creates the UML:Datatype XMI element. * Invokes UMLObject::save1() which does most of the work. * * @param writer the QXmlStreamWriter to save to */ void UMLDatatype::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("DataType")); if (m_pSecondary != nullptr) writer.writeAttribute(QStringLiteral("elementReference"), Uml::ID::toString(m_pSecondary->id())); if (!m_isActive) writer.writeAttribute(QStringLiteral("isActive"), QStringLiteral("false")); UMLObject::save1end(writer); }
2,808
C++
.cpp
105
23.790476
92
0.700743
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,469
enumliteral.cpp
KDE_umbrello/umbrello/umlmodel/enumliteral.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "enumliteral.h" #include "umlenumliteraldialog.h" #include <KLocalizedString> /** * Sets up an enum literal. * @param parent The parent of this UMLEnumLiteral. * @param name The name of this UMLEnumLiteral. * @param id The unique id given to this UMLEnumLiteral. * @param v The numeric representation value of this UMLEnumLiteral. * CAVEAT: 1) This does not conform to the UML standard. * 2) Programming language specific: * Not all languages support enum representations. */ UMLEnumLiteral::UMLEnumLiteral(UMLObject *parent, const QString& name, Uml::ID::Type id, const QString& v) : UMLClassifierListItem(parent, name, id) { m_Value = v; m_BaseType = UMLObject::ot_EnumLiteral; } /** * Sets up an enum literal. * @param parent The parent of this UMLEnumLiteral. */ UMLEnumLiteral::UMLEnumLiteral(UMLObject *parent) : UMLClassifierListItem(parent) { m_BaseType = UMLObject::ot_EnumLiteral; } /** * Destructor. */ UMLEnumLiteral::~UMLEnumLiteral() { } /** * Returns the value of the UMLEnumLiteral. * * @return The value of the Enum Literal. */ QString UMLEnumLiteral::value() const { return m_Value; } /** * Sets the value of the UMLEnumLiteral. * * @param v The value of the Enum Literal. */ void UMLEnumLiteral::setValue(const QString &v) { if(m_Value != v) { m_Value = v; UMLObject::emitModified(); } } /** * Returns a string representation of the UMLEnumLiteral. * * @param sig If true will show the attribute type and value. * @return Returns a string representation of the UMLEnumLiteral. */ QString UMLEnumLiteral::toString(Uml::SignatureType::Enum sig, bool /*withStereotype*/) const { QString s; Q_UNUSED(sig); s = name(); if (m_Value.length() > 0) s += QStringLiteral(" = ") + m_Value; return s; } /** * Overloaded '==' operator */ bool UMLEnumLiteral::operator==(const UMLEnumLiteral& rhs) const { if (this == &rhs) { return true; } if (!UMLObject::operator==(rhs)) { return false; } return true; } /** * Copy the internal presentation of this object into the new * object. */ void UMLEnumLiteral::copyInto(UMLObject *lhs) const { UMLEnumLiteral *target = lhs->asUMLEnumLiteral(); UMLClassifierListItem::copyInto(lhs); target->m_Value = m_Value; } /** * Make a clone of this object. */ UMLObject* UMLEnumLiteral::clone() const { UMLEnumLiteral *clone = new UMLEnumLiteral(umlParent()); copyInto(clone); return clone; } /** * Creates the <UML:EnumLiteral> XMI element. */ void UMLEnumLiteral::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("EnumerationLiteral"), QStringLiteral("ownedLiteral")); if (! m_Value.isEmpty()) writer.writeAttribute(QStringLiteral("value"), m_Value); UMLObject::save1end(writer); } /** * Loads the <UML:EnumLiteral> XMI element (empty.) */ bool UMLEnumLiteral::load1(QDomElement& element) { m_Value = element.attribute(QStringLiteral("value")); return true; } /** * Display the properties configuration dialog for the enum literal. */ bool UMLEnumLiteral::showPropertiesDialog(QWidget* parent) { UMLEnumLiteralDialog dialog(parent, this); return dialog.exec(); }
3,611
C++
.cpp
135
23.311111
99
0.676403
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,470
usecase.cpp
KDE_umbrello/umbrello/umlmodel/usecase.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "usecase.h" /** * Creates a UseCase object * * @param name The name of the object. * @param id The id of the object. */ UMLUseCase::UMLUseCase(const QString & name, Uml::ID::Type id) : UMLCanvasObject(name, id) { init(); } /** * Standard destructor. */ UMLUseCase::~UMLUseCase() { } /** * Initializes key variables of the class. */ void UMLUseCase::init() { m_BaseType = UMLObject::ot_UseCase; } /** * Make a clone of this object. */ UMLObject* UMLUseCase::clone() const { UMLUseCase *clone = new UMLUseCase(); UMLObject::copyInto(clone); return clone; } /** * Creates the <UML:UseCase> element. */ void UMLUseCase::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("UseCase")); UMLObject::save1end(writer); } /** * Loads the <UML:UseCase> element (TODO). */ bool UMLUseCase::load1(QDomElement&) { return true; }
1,059
C++
.cpp
53
17.735849
92
0.7001
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,471
umlobjectlist.cpp
KDE_umbrello/umbrello/umlmodel/umlobjectlist.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlobjectlist.h" #include "umlobject.h" UMLObjectList::UMLObjectList() { } UMLObjectList::~UMLObjectList() { } /** * Copy the internal presentation of this object into the new * object. */ void UMLObjectList::copyInto(UMLObjectList *rhs) const { // Don't copy yourself. if (rhs == this) return; rhs->clear(); // Suffering from const; we shall not modify our object. UMLObjectList *tmp = new UMLObjectList(*this); UMLObject *item = nullptr; for (UMLObjectListIt oit(*tmp); oit.hasNext() ;) { item = oit.next(); rhs->append(item->clone()); } delete tmp; } /** * Make a clone of this object. */ UMLObjectList* UMLObjectList::clone() const { UMLObjectList *clone = new UMLObjectList(); copyInto(clone); return clone; }
952
C++
.cpp
40
20.575
92
0.690265
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,472
umlobject.cpp
KDE_umbrello/umbrello/umlmodel/umlobject.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "umlobject.h" // app includes #include "classpropertiesdialog.h" #include "debug_utils.h" #include "enumliteral.h" #include "uniqueid.h" #include "uml.h" #include "umldoc.h" #include "umllistview.h" #include "umlobjectprivate.h" #include "models/objectsmodel.h" #include "package.h" #include "folder.h" #include "stereotype.h" #include "object_factory.h" #include "model_utils.h" #include "import_utils.h" #include "docwindow.h" #include "optionstate.h" #include "cmds.h" // kde includes #include <KLocalizedString> // qt includes #include <QApplication> #include <QPointer> using namespace Uml; DEBUG_REGISTER_DISABLED(UMLObject) /** * Creates a UMLObject. * @param other object to created from */ UMLObject::UMLObject(const UMLObject &other) : QObject(other.umlParent()), m_d(new UMLObjectPrivate) { other.copyInto(this); UMLApp::app()->document()->objectsModel()->add(this); } /** * Creates a UMLObject. * @param parent The parent of the object. * @param name The name of the object. * @param id The ID of the object (optional.) If omitted * then a new ID will be assigned internally. */ UMLObject::UMLObject(UMLObject* parent, const QString& name, ID::Type id) : QObject(parent), m_nId(id), m_name(name), m_d(new UMLObjectPrivate) { init(); if (id == Uml::ID::None) m_nId = UniqueID::gen(); UMLApp::app()->document()->objectsModel()->add(this); } /** * Creates a UMLObject. * @param name The name of the object. * @param id The ID of the object (optional.) If omitted * then a new ID will be assigned internally. */ UMLObject::UMLObject(const QString& name, ID::Type id) : QObject(nullptr), m_nId(id), m_name(name), m_d(new UMLObjectPrivate) { init(); if (id == Uml::ID::None) m_nId = UniqueID::gen(); UMLApp::app()->document()->objectsModel()->add(this); } /** * Creates a UMLObject. * @param parent The parent of the object. */ UMLObject::UMLObject(UMLObject * parent) : QObject(parent), m_nId(Uml::ID::None), m_name(QString()), m_d(new UMLObjectPrivate) { init(); UMLApp::app()->document()->objectsModel()->add(this); } /** * Standard destructor. */ UMLObject::~UMLObject() { // unref stereotype setUMLStereotype(nullptr); if (m_pSecondary && m_pSecondary->baseType() == ot_Stereotype) { UMLStereotype* stereotype = m_pSecondary->asUMLStereotype(); if (stereotype) stereotype->decrRefCount(); } UMLApp::app()->document()->objectsModel()->remove(this); delete m_d; } /** * Initializes key variables of the class. */ void UMLObject::init() { setObjectName(QStringLiteral("UMLObject")); m_BaseType = ot_UMLObject; m_visibility = Uml::Visibility::Public; m_pStereotype = nullptr; m_Doc.clear(); m_bAbstract = false; m_bStatic = false; m_bCreationWasSignalled = false; m_pSecondary = nullptr; } /** * Display the properties configuration dialog for the object. * * @param parent The parent widget. * @return True for success of this operation. */ bool UMLObject::showPropertiesDialog(QWidget *parent) { DocWindow *docwindow = UMLApp::app()->docWindow(); docwindow->updateDocumentation(false); QPointer<ClassPropertiesDialog> dlg = new ClassPropertiesDialog(parent, this, false); bool modified = false; if (dlg->exec()) { docwindow->showDocumentation(this, true); UMLApp::app()->document()->setModified(true); modified = true; } dlg->close(); delete dlg; return modified; } /** * This should be reimplemented by subclasses if they wish to * accept certain types of associations. Note that this only * tells if this UMLObject can accept the association * type. When creating an association another check is made to * see if the association is valid. For example a UMLClass * (UMLClassifier) can accept generalizations and should * return true. If while creating a generalization the * superclass is already subclassed from this, the association * is not valid and will not be created. The default accepts * nothing (returns false) */ bool UMLObject::acceptAssociationType(Uml::AssociationType::Enum type) const { Q_UNUSED(type); // A UMLObject accepts nothing. This should be reimplemented by the subclasses return false; } /** * Assigns a new Id to the object */ void UMLObject::setID(ID::Type NewID) { m_nId = NewID; emitModified(); } /** * Set the UMLObject's name */ void UMLObject::setName(const QString &strName) { if (name() != strName) { UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(this, strName)); } } /** * Method used by setName: it is called by cmdSetName, Don't use it! */ void UMLObject::setNameCmd(const QString &strName) { m_name = strName; emitModified(); } /** * Returns a copy of m_name */ QString UMLObject::name() const { return m_name; } /** * Returns the fully qualified name, i.e. all package prefixes and then m_name. * * @param separator The separator string to use (optional.) * If not given then the separator is chosen according * to the currently selected active programming language * of import and code generation. * @param includeRoot Whether to prefix the root folder name to the FQN. * See UMLDoc::getRootFolder(). Default: false. * @return The fully qualified name of this UMLObject. */ QString UMLObject::fullyQualifiedName(const QString& separator, bool includeRoot /* = false */) const { QString fqn; UMLPackage *parent = umlPackage(); if (parent && parent != this) { bool skipPackage = false; if (!includeRoot) { UMLDoc *umldoc = UMLApp::app()->document(); if ((umldoc->rootFolderType(parent) != Uml::ModelType::N_MODELTYPES) || (parent == umldoc->datatypeFolder())) skipPackage = true; } if (!skipPackage) { QString tempSeparator = separator; if (tempSeparator.isEmpty()) tempSeparator = UMLApp::app()->activeLanguageScopeSeparator(); fqn = parent->fullyQualifiedName(tempSeparator, includeRoot); fqn.append(tempSeparator); } } fqn.append(m_name); return fqn; } /** * Overloaded '==' operator */ bool UMLObject::operator==(const UMLObject & rhs) const { if (this == &rhs) return true; //don't compare IDs, these are program specific and //don't mean the objects are the same //***** CHECK: Who put in this comment? What was the reason? //***** Currently some operator== in umbrello compare the IDs //***** while others don't. if (m_name != rhs.m_name) return false; // Packages create different namespaces, therefore they should be // part of the equality test. if (umlParent() != rhs.umlParent()) return false; // Making the type part of an object's identity has its problems: // Not all programming languages support declarations of the same // name but different type. // In such cases, the code generator is responsible for generating // the appropriate error message. if (m_BaseType != rhs.m_BaseType) return false; // The documentation should not be part of the equality test. // If two objects are the same but differ only in their documentation, // what does that mean? //if(m_Doc != rhs.m_Doc) // return false; // The visibility should not be part of the equality test. // What does it mean if two objects are the same but differ in their // visibility? - I'm not aware of any programming language that would // support that. //if(m_visibility != rhs.m_visibility) // return false; // See comments above //if(m_pStereotype != rhs.m_pStereotype) // return false; // See comments above //if(m_bAbstract != rhs.m_bAbstract) // return false; // See comments above //if(m_bStatic != rhs.m_bStatic) // return false; return true; } /** * Copy the internal presentation of this object into the new * object. */ void UMLObject::copyInto(UMLObject *lhs) const { // Data members with copy constructor lhs->m_Doc = m_Doc; lhs->m_pStereotype = m_pStereotype; if (lhs->m_pStereotype) lhs->m_pStereotype->incrRefCount(); lhs->m_bAbstract = m_bAbstract; lhs->m_bStatic = m_bStatic; lhs->m_BaseType = m_BaseType; lhs->m_visibility = m_visibility; lhs->setUMLParent(umlParent()); // We don't want the same name existing twice. lhs->m_name = Model_Utils::uniqObjectName(m_BaseType, umlPackage(), m_name); // Create a new ID. lhs->m_nId = UniqueID::gen(); // Hope that the parent from QObject is okay. if (lhs->umlParent() != umlParent()) logDebug0("UMLObject::copyInto: new parent differs from existing"); } UMLObject *UMLObject::clone() const { UMLObject *clone = new UMLObject; UMLObject::copyInto(clone); return clone; } /** * Returns the abstract state of the object. */ bool UMLObject::isAbstract() const { return m_bAbstract; } /** * Sets the paste state of the object. */ void UMLObject::setAbstract(bool bAbstract) { m_bAbstract = bAbstract; emitModified(); } /** * Returns true if this UMLObject has classifier scope, * otherwise false (the default). */ bool UMLObject::isStatic() const { return m_bStatic; } /** * Sets the value for m_bStatic. */ void UMLObject::setStatic(bool bStatic) { m_bStatic = bStatic; emitModified(); } /** * Forces the emission of the modified signal. Useful when * updating several attributes at a time: you can block the * signals, update all atts, and then force the signal. */ void UMLObject::emitModified() { UMLDoc *umldoc = UMLApp::app()->document(); if (!umldoc->loading() && !umldoc->closing()) Q_EMIT modified(); } /** * Returns the type of the object. * * @return Returns the type of the object. */ UMLObject::ObjectType UMLObject::baseType() const { return m_BaseType; } /** * @return The type used for rtti as string. */ QLatin1String UMLObject::baseTypeStr() const { return QLatin1String(ENUM_NAME(UMLObject, ObjectType, m_BaseType)); } /** * Set the type of the object. * * @param ot The ObjectType to set. */ void UMLObject::setBaseType(ObjectType ot) { m_BaseType = ot; } /** * Returns the ID of the object. * * @return Returns the ID of the object. */ ID::Type UMLObject::id() const { return m_nId; } /** * Returns the documentation for the object. * * @return Returns the documentation for the object. */ QString UMLObject::doc() const { return m_Doc; } /** * Returns state of documentation for the object. * * @return false if documentation is empty */ bool UMLObject::hasDoc() const { return !m_Doc.isEmpty(); } /** * Sets the documentation for the object. * * @param d The documentation for the object. */ void UMLObject::setDoc(const QString &d) { m_Doc = d; //emit modified(); No, this is done centrally at DocWindow::updateDocumentation() } /** * Returns the visibility of the object. * * @return Returns the visibility of the object. */ Visibility::Enum UMLObject::visibility() const { return m_visibility; } /** * Sets the visibility of the object. * * @param visibility The visibility of the object. */ void UMLObject::setVisibility(Visibility::Enum visibility) { if (m_visibility != visibility) { UMLApp::app()->executeCommand(new CmdSetVisibility(this, visibility)); } } /** * Method used by setVisibility: it is called by cmdSetVisibility, Don't use it! */ void UMLObject::setVisibilityCmd(Visibility::Enum visibility) { m_visibility = visibility; emitModified(); } /** * Sets the class' UMLStereotype. Adjusts the reference counts * at the previously set stereotype and at the new stereotype. * If the previously set UMLStereotype's reference count drops * to zero then the UMLStereotype is removed at the UMLDoc and * it is then physically deleted. * * @param stereo Sets the classes UMLStereotype. */ void UMLObject::setUMLStereotype(UMLStereotype *stereo) { if (stereo == m_pStereotype) return; if (stereo) { stereo->incrRefCount(); } if (m_pStereotype) { m_pStereotype->decrRefCount(); if (m_pStereotype->refCount() == 0) { UMLDoc *pDoc = UMLApp::app()->document(); pDoc->removeStereotype(m_pStereotype); delete m_pStereotype; } } m_pStereotype = stereo; // TODO: don't emit modified() if predefined folder if (!UMLApp::shuttingDown()) emitModified(); } /** * Sets the classes stereotype name. * Internally uses setUMLStereotype(). * * @param name Sets the classes stereotype name. */ void UMLObject::setStereotype(const QString &name) { if (name != stereotype()) { UMLApp::app()->executeCommand(new CmdSetStereotype(this, name)); } } void UMLObject::setStereotypeCmd(const QString& name) { if (name.isEmpty()) { setUMLStereotype(nullptr); return; } UMLDoc *pDoc = UMLApp::app()->document(); UMLStereotype *s = pDoc->findOrCreateStereotype(name); setUMLStereotype(s); } /** * Returns the classes UMLStereotype object. * * @return Returns the classes UMLStereotype object. */ UMLStereotype * UMLObject::umlStereotype() const { return m_pStereotype; } /** * Returns the stereotype. */ QString UMLObject::stereotype(bool includeAdornments /* = false */) const { if (m_pStereotype == nullptr) return QString(); return m_pStereotype->name(includeAdornments); } /** * Returns the concrete values of stereotype attributes. */ QStringList & UMLObject::tags() { return m_TaggedValues; } /** * Return the package(s) in which this UMLObject is contained * as a text. * * @param separator Separator string for joining together the * individual package prefixes (optional.) * If no separator is given then the separator * of the currently selected language is used. * @param includeRoot Whether to prefix the root folder name. * Default: false. * @return The UMLObject's enclosing package(s) as a text. */ QString UMLObject::package(const QString& separator, bool includeRoot) const { QString tempSeparator = separator; if (tempSeparator.isEmpty()) tempSeparator = UMLApp::app()->activeLanguageScopeSeparator(); QString fqn = fullyQualifiedName(tempSeparator, includeRoot); if (!fqn.contains(tempSeparator)) return QString(); QString scope = fqn.left(fqn.length() - tempSeparator.length() - m_name.length()); return scope; } /** * Return a list of the packages in which this class is embedded. * The outermost package is first in the list. * * @param includeRoot Whether to prefix the root folder name. * Default: false. * @return UMLPackageList of the containing packages. */ UMLPackageList UMLObject::packages(bool includeRoot) const { UMLPackageList pkgList; UMLPackage* pkg = umlPackage(); while (pkg != nullptr) { pkgList.prepend(pkg); pkg = pkg->umlPackage(); } if (!includeRoot) pkgList.removeFirst(); return pkgList; } /** * Sets the UMLPackage in which this class is located. * * @param pPkg Pointer to the class' UMLPackage. */ bool UMLObject::setUMLPackage(UMLPackage *pPkg) { if (pPkg == this) { logDebug0("UMLObject::setUMLPackage: setting parent to myself is not allowed"); return false; } if (pPkg == nullptr) { // Allow setting to NULL for stereotypes setParent(pPkg); return true; } if (pPkg->umlPackage() == this) { logDebug0("UMLObject::setUMLPackage: setting parent to an object of which I'm " "already the parent is not allowed"); return false; } setParent(pPkg); emitModified(); return true; } /** * Returns the UMLPackage that this class is located in. * * This method is a shortcut for calling umlParent()->asUMLPackage(). * * @return Pointer to the UMLPackage of this class. */ UMLPackage* UMLObject::umlPackage() const { return dynamic_cast<UMLPackage *>(parent()); } /** * Set UML model parent. * * @param parent object to set as parent * * TODO prevent setting parent to myself */ void UMLObject::setUMLParent(UMLObject *parent) { setParent(parent); } /** * Return UML model parent. * * Model classes of type UMLClassifierListItem and below * uses QObject::parent to hold the model parent * * @return parent of uml object */ UMLObject *UMLObject::umlParent() const { return dynamic_cast<UMLObject *>(parent()); } /** * Return secondary ID. Required by resolveRef(). */ QString UMLObject::secondaryId() const { return m_SecondaryId; } /** * Set the secondary ID. * Currently only required by petalTree2Uml(); all other setting of the * m_SecondaryID is internal to the UMLObject class hierarchy. */ void UMLObject::setSecondaryId(const QString& id) { m_SecondaryId = id; } /** * Return secondary ID fallback. * Required by resolveRef() for imported model files. */ QString UMLObject::secondaryFallback() const { return m_SecondaryFallback; } /** * Set the secondary ID fallback. * Currently only used by petalTree2Uml(). */ void UMLObject::setSecondaryFallback(const QString& id) { m_SecondaryFallback = id; } /** * Calls UMLDoc::signalUMLObjectCreated() if m_BaseType affords * doing so. */ void UMLObject::maybeSignalObjectCreated() { if (!m_bCreationWasSignalled && m_BaseType != ot_Stereotype && m_BaseType != ot_Association && m_BaseType != ot_Role) { m_bCreationWasSignalled = true; UMLDoc* umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(this); } } /** * Resolve referenced objects (if any.) * Needs to be called after all UML objects are loaded from file. * This needs to be done after all model objects are loaded because * some of the xmi.id's might be forward references, i.e. they may * identify model objects which were not yet loaded at the point of * reference. * The default implementation attempts resolution of the m_SecondaryId. * * @return True for success. */ bool UMLObject::resolveRef() { if (m_pSecondary || (m_SecondaryId.isEmpty() && m_SecondaryFallback.isEmpty())) { maybeSignalObjectCreated(); return true; } #ifdef VERBOSE_DEBUGGING logDebug2("UMLObject %1 resolveRef: m_SecondaryId is %2", m_name, m_SecondaryId); #endif UMLDoc *pDoc = UMLApp::app()->document(); // In the new, XMI standard compliant save format, // the type is the xmi.id of a UMLClassifier. if (! m_SecondaryId.isEmpty()) { m_pSecondary = pDoc->findObjectById(Uml::ID::fromString(m_SecondaryId)); if (m_pSecondary != nullptr) { if (m_pSecondary->baseType() == ot_Stereotype) { if (m_pStereotype) m_pStereotype->decrRefCount(); m_pStereotype = m_pSecondary->asUMLStereotype(); m_pStereotype->incrRefCount(); m_pSecondary = nullptr; } m_SecondaryId = QString(); maybeSignalObjectCreated(); return true; } if (m_SecondaryFallback.isEmpty()) { logDebug2("UMLObject %1 resolveRef: object with xmi.id=%2 not found, setting to undef", m_name, m_SecondaryId); UMLFolder *datatypes = pDoc->datatypeFolder(); m_pSecondary = Object_Factory::createUMLObject(ot_Datatype, QStringLiteral("undef"), datatypes, false); return true; } } if (m_SecondaryFallback.isEmpty()) { logError2("UMLObject::resolveRef(%1) : cannot find type with id %2", m_name, m_SecondaryId); return false; } #ifdef VERBOSE_DEBUGGING logDebug3("UMLObject %1 resolveRef: could not resolve secondary ID %2, using secondary fallback %3", m_name, m_SecondaryId, m_SecondaryFallback); #endif m_SecondaryId = m_SecondaryFallback; // Assume we're dealing with the older Umbrello format where // the type name was saved in the "type" attribute rather // than the xmi.id of the model object of the attribute type. m_pSecondary = pDoc->findUMLObject(m_SecondaryId, ot_UMLObject, this); if (m_pSecondary) { m_SecondaryId = QString(); maybeSignalObjectCreated(); return true; } // Work around Object_Factory::createUMLObject()'s incapability // of on-the-fly scope creation: if (m_SecondaryId.contains(QStringLiteral("::"))) { // TODO: Merge Import_Utils::createUMLObject() into Object_Factory::createUMLObject() m_pSecondary = Import_Utils::createUMLObject(ot_UMLObject, m_SecondaryId, umlPackage()); if (m_pSecondary) { if (Import_Utils::newUMLObjectWasCreated()) { maybeSignalObjectCreated(); qApp->processEvents(); logDebug2("UMLObject %1 resolveRef: Import_Utils::createUMLObject created a new type for id=%2", m_name, m_SecondaryId); } else { logDebug2("UMLObject %1 resolveRef: Import_Utils::createUMLObject returned an existing type for id=%2", m_name, m_SecondaryId); } m_SecondaryId = QString(); return true; } logError2("UMLObject %1 resolveRef: Import_Utils::createUMLObject failed to create type for id=%2", m_name, m_SecondaryId); return false; } logDebug2("UMLObject %1 resolveRef: Creating new type for %2", m_name, m_SecondaryId); // This is very C++ specific - we rely on some '*' or // '&' to decide it's a ref type. Plus, we don't recognize // typedefs of ref types. bool isReferenceType = (m_SecondaryId.contains(QLatin1Char('*')) || m_SecondaryId.contains(QLatin1Char('&'))); ObjectType ot = ot_Class; if (isReferenceType) { ot = ot_Datatype; } else { if (Model_Utils::isCommonDataType(m_SecondaryId)) ot = ot_Datatype; } m_pSecondary = Object_Factory::createUMLObject(ot, m_SecondaryId, nullptr); if (m_pSecondary == nullptr) return false; m_SecondaryId = QString(); maybeSignalObjectCreated(); //qApp->processEvents(); return true; } void UMLObject::saveToXMI(QXmlStreamWriter& writer) { Q_UNUSED(writer); } /** * Auxiliary to saveToXMI. * Create an XML element with the given tag, and save the XMI attributes * that are common to all child classes to the newly created element. * This method does not need to be overridden by child classes. * It is public because UMLOperation::saveToXMI invokes it for its * \<Parameter\>s (cannot be done with protected access). * * @param writer The QXmlStreamWriter into which to write. * @param type In UML1 mode, it is used as the XML tag. * In UML2 mode, it is used as the xmi:type attribute. * @param tag In UML2 mode, it is used as the XML tag. * When given the special value "<use_type_as_tag>", the * @p type is used as the XML tag just as in UML1 mode. * In this case, no xmi:type attribute is generated. */ void UMLObject::save1(QXmlStreamWriter& writer, const QString& type, const QString& tag) { m_d->isSaved = true; /* Call as the first action of saveToXMI() in child class: This creates the XML element with which to work. */ const bool uml2 = Settings::optionState().generalState.uml2; if (type.indexOf(QStringLiteral(":")) >= 0) { logWarn1("UMLObject::save1(%1) should not be called with hard coded UML namespace", m_name); writer.writeStartElement(type); } else if (tag == QStringLiteral("<use_type_as_tag>")) { const QString nmSpc = (uml2 ? QStringLiteral("uml") : QStringLiteral("UML")); writer.writeStartElement(nmSpc + QStringLiteral(":") + type); } else if (uml2) { if (!tag.isEmpty()) { writer.writeStartElement(tag); } else { writer.writeStartElement(QStringLiteral("packagedElement")); } writer.writeAttribute(QStringLiteral("xmi:type"), QStringLiteral("uml:") + type); } else { writer.writeStartElement(QStringLiteral("UML:") + type); } if (!uml2) { writer.writeAttribute(QStringLiteral("isSpecification"), QStringLiteral("false")); if (m_BaseType != ot_Association && m_BaseType != ot_Role && m_BaseType != ot_Attribute && m_BaseType != ot_Instance) { writer.writeAttribute(QStringLiteral("isLeaf"), QStringLiteral("false")); writer.writeAttribute(QStringLiteral("isRoot"), QStringLiteral("false")); const QString isAbstract = (m_bAbstract ? QStringLiteral("true") : QStringLiteral("false")); writer.writeAttribute(QStringLiteral("isAbstract"), isAbstract); } } const QString idAttrName = (uml2 ? QStringLiteral("xmi:id") : QStringLiteral("xmi.id")); writer.writeAttribute(idAttrName, Uml::ID::toString(m_nId)); writer.writeAttribute(QStringLiteral("name"), m_name); if (uml2) { if (m_bAbstract) writer.writeAttribute(QStringLiteral("isAbstract"), QStringLiteral("true")); } else if (m_BaseType != ot_Operation && m_BaseType != ot_Role && m_BaseType != ot_Attribute) { Uml::ID::Type nmSpc; if (umlPackage()) nmSpc = umlPackage()->id(); else nmSpc = UMLApp::app()->document()->modelID(); writer.writeAttribute(QStringLiteral("namespace"), Uml::ID::toString(nmSpc)); } if (! m_Doc.isEmpty()) writer.writeAttribute(QStringLiteral("comment"), m_Doc); //CHECK: uml13.dtd compliance #ifdef XMI_FLAT_PACKAGES if (umlParent()->asUMLPackage()) //FIXME: uml13.dtd compliance writer.writeAttribute(QStringLiteral("package"), umlParent()->asUMLPackage()->ID()); #endif if (!uml2 || m_visibility != Uml::Visibility::Public) { QString visibility = Uml::Visibility::toString(m_visibility, false); writer.writeAttribute(QStringLiteral("visibility"), visibility); } if (m_pStereotype != nullptr) writer.writeAttribute(QStringLiteral("stereotype"), Uml::ID::toString(m_pStereotype->id())); if (m_bStatic) writer.writeAttribute(QStringLiteral("ownerScope"), QStringLiteral("classifier")); /* else writer.writeAttribute("ownerScope", "instance"); *** ownerScope defaults to instance if not set **********/ } /** * Auxiliary to saveToXMI. * Save possible stereotype tagged values stored in m_TaggedValues * and write the XML end element created in save1(). */ void UMLObject::save1end(QXmlStreamWriter& writer) { // Save optional stereotype attributes if (m_TaggedValues.count()) { if (m_pStereotype == nullptr) { logError1("UMLObject::save1end(%1) TaggedValues are set but pStereotype is null : clearing TaggedValues", m_name); m_TaggedValues.clear(); return; } writer.writeStartElement(QStringLiteral("UML:ModelElement.taggedValues")); writer.writeAttribute(QStringLiteral("stereotype"), Uml::ID::toString(m_pStereotype->id())); const UMLStereotype::AttributeDefs& attrDefs = m_pStereotype->getAttributeDefs(); for (int i = 0; i < m_TaggedValues.count(); i++) { if (i >= attrDefs.count()) { logError3("UMLObject::save1end(%1) : stereotype %2 defines %3 attributes; ignoring excess TaggedValues", m_name, m_pStereotype->name(), attrDefs.count()); break; } const QString& tv = m_TaggedValues.at(i); writer.writeStartElement(QStringLiteral("UML:TaggedValue")); writer.writeAttribute(QStringLiteral("tag"), attrDefs[i].name); writer.writeAttribute(QStringLiteral("value"), tv); writer.writeEndElement(); // UML:TaggedValue } writer.writeEndElement(); // UML:ModelElement.taggedValues } writer.writeEndElement(); } /** * Auxiliary to loadFromXMI. * This method is usually overridden by child classes. * It is responsible for loading the specific XMI structure * of the child class. */ bool UMLObject::load1(QDomElement&) { // This body is not usually executed because child classes // overwrite the load method. return true; } /** * Analyzes the given QDomElement for a reference to a stereotype. * * @param element QDomElement to analyze. * @return True if a stereotype reference was found, else false. */ bool UMLObject::loadStereotype(QDomElement & element) { QString tag = element.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("stereotype"))) return false; QString stereo = element.attribute(QStringLiteral("xmi.value")); if (stereo.isEmpty() && element.hasChildNodes()) { /* like so: <UML:ModelElement.stereotype> <UML:Stereotype xmi.idref = '07CD'/> </UML:ModelElement.stereotype> */ QDomNode stereoNode = element.firstChild(); QDomElement stereoElem = stereoNode.toElement(); tag = stereoElem.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("Stereotype"))) { stereo = stereoElem.attribute(QStringLiteral("xmi.idref")); } } if (stereo.isEmpty()) return false; Uml::ID::Type stereoID = Uml::ID::fromString(stereo); UMLDoc *pDoc = UMLApp::app()->document(); if (m_pStereotype) m_pStereotype->decrRefCount(); m_pStereotype = pDoc->findStereotypeById(stereoID); if (m_pStereotype) m_pStereotype->incrRefCount(); else m_SecondaryId = stereo; // leave it to resolveRef() return true; } /** * This method loads the generic parts of the XMI common to most model * classes. It is not usually reimplemented by child classes. * Instead, it invokes the load() method which implements the loading * of the specifics of each child class. * * @param element The QDomElement from which to load. */ bool UMLObject::loadFromXMI(QDomElement & element) { UMLDoc* umldoc = UMLApp::app()->document(); if (umldoc == nullptr) { logError0("UMLObject::loadFromXMI: umldoc is NULL"); return false; } // Read the name first so that if we encounter a problem, the error // message can say the name. m_name = element.attribute(QStringLiteral("name")); QString id = Model_Utils::getXmiId(element); if (id.isEmpty() || id == QStringLiteral("-1")) { // Before version 1.4, Umbrello did not save the xmi.id of UMLRole objects. // Some tools (such as Embarcadero's) do not have an xmi.id on all attributes. m_nId = UniqueID::gen(); logWarn1("UMLObject::loadFromXMI(%1) : xmi.id not present, generating a new one", m_name); } else { Uml::ID::Type nId = Uml::ID::fromString(id); if (m_BaseType == ot_Role) { // Some older Umbrello versions had a problem with xmi.id's // of other objects being reused for the UMLRole, see e.g. // attachment 21179 at https://bugs.kde.org/147988 . // If the xmi.id is already being used then we generate a new one. UMLObject *o = umldoc->findObjectById(nId); if (o) { logError1("UMLObject::loadFromXMI(UMLRole): id %1 is already in use! Please fix your XMI file", id); } } m_nId = nId; } if (element.hasAttribute(QStringLiteral("documentation"))) // for bkwd compat. m_Doc = element.attribute(QStringLiteral("documentation")); else m_Doc = element.attribute(QStringLiteral("comment")); //CHECK: need a UML:Comment? m_visibility = Uml::Visibility::Public; if (element.hasAttribute(QStringLiteral("scope"))) { // for bkwd compat. QString scope = element.attribute(QStringLiteral("scope")); if (scope == QStringLiteral("instance_level")) // nsuml compat. m_bStatic = false; else if (scope == QStringLiteral("classifier_level")) // nsuml compat. m_bStatic = true; else { int nScope = scope.toInt(); switch (nScope) { case 200: m_visibility = Uml::Visibility::Public; break; case 201: m_visibility = Uml::Visibility::Private; break; case 202: m_visibility = Uml::Visibility::Protected; break; default: logError2("UMLObject::loadFromXMI(%1) : illegal scope %2", m_name, nScope); } } } else { QString visibility = element.attribute(QStringLiteral("visibility"), QStringLiteral("public")); if (visibility == QStringLiteral("private") || visibility == QStringLiteral("private_vis")) // for compatibility with other programs m_visibility = Uml::Visibility::Private; else if (visibility == QStringLiteral("protected") || visibility == QStringLiteral("protected_vis")) // for compatibility with other programs m_visibility = Uml::Visibility::Protected; else if (visibility == QStringLiteral("implementation")) m_visibility = Uml::Visibility::Implementation; } QString stereo = element.attribute(QStringLiteral("stereotype")); if (!stereo.isEmpty()) { Uml::ID::Type stereoID = Uml::ID::fromString(stereo); if (m_pStereotype) m_pStereotype->decrRefCount(); m_pStereotype = umldoc->findStereotypeById(stereoID); if (m_pStereotype) { m_pStereotype->incrRefCount(); } else { logDebug2("UMLObject::loadFromXMI(%1) : UMLStereotype %2 not found, creating now.", m_name, Uml::ID::toString(stereoID)); setStereotypeCmd(stereo); } } if (element.hasAttribute(QStringLiteral("abstract"))) { // for bkwd compat. QString abstract = element.attribute(QStringLiteral("abstract"), QStringLiteral("0")); m_bAbstract = (bool)abstract.toInt(); } else { QString isAbstract = element.attribute(QStringLiteral("isAbstract"), QStringLiteral("false")); m_bAbstract = (isAbstract == QStringLiteral("true")); } if (element.hasAttribute(QStringLiteral("static"))) { // for bkwd compat. QString staticScope = element.attribute(QStringLiteral("static"), QStringLiteral("0")); m_bStatic = (bool)staticScope.toInt(); } else { QString ownerScope = element.attribute(QStringLiteral("ownerScope"), QStringLiteral("instance")); m_bStatic = (ownerScope == QStringLiteral("classifier")); } // If the node has child nodes, check whether attributes can be // extracted from them. if (element.hasChildNodes()) { QDomNode node = element.firstChild(); if (node.isComment()) node = node.nextSibling(); QDomElement elem = node.toElement(); while (!elem.isNull()) { QString tag = elem.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("ModelElement.taggedValues"))) { QDomNode tvNode = elem.firstChild(); QDomElement tvElem = tvNode.toElement(); while (!tvElem.isNull()) { tag = tvElem.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("TaggedValue"))) { QString value = tvElem.attribute(QStringLiteral("value")); m_TaggedValues.append(value); logDebug3("UMLObject::loadFromXMI(%1): Loaded %2 value %3", m_name, tag, value); } else { logDebug2("loadFromXMI(%1): Unknown ModelElement.taggedValues child %2", m_name, tag); } tvNode = tvNode.nextSibling(); tvElem = tvNode.toElement(); } } else if (UMLDoc::tagEq(tag, QStringLiteral("name"))) { m_name = elem.attribute(QStringLiteral("xmi.value")); if (m_name.isEmpty()) m_name = elem.text(); } else if (UMLDoc::tagEq(tag, QStringLiteral("visibility"))) { QString vis = elem.attribute(QStringLiteral("xmi.value")); if (vis.isEmpty()) vis = elem.text(); if (vis == QStringLiteral("private") || vis == QStringLiteral("private_vis")) m_visibility = Uml::Visibility::Private; else if (vis == QStringLiteral("protected") || vis == QStringLiteral("protected_vis")) m_visibility = Uml::Visibility::Protected; else if (vis == QStringLiteral("implementation")) m_visibility = Uml::Visibility::Implementation; } else if (UMLDoc::tagEq(tag, QStringLiteral("isAbstract"))) { QString isAbstract = elem.attribute(QStringLiteral("xmi.value")); if (isAbstract.isEmpty()) isAbstract = elem.text(); m_bAbstract = (isAbstract == QStringLiteral("true")); } else if (UMLDoc::tagEq(tag, QStringLiteral("ownerScope"))) { QString ownerScope = elem.attribute(QStringLiteral("xmi.value")); if (ownerScope.isEmpty()) ownerScope = elem.text(); m_bStatic = (ownerScope == QStringLiteral("classifier")); } else if (UMLDoc::tagEq(tag, QStringLiteral("ownedComment"))) { m_Doc = Model_Utils::loadCommentFromXMI(elem); } else { loadStereotype(elem); } node = node.nextSibling(); if (node.isComment()) node = node.nextSibling(); elem = node.toElement(); } } // Operations, attributes, enum literals, templates, stereotypes, // and association role objects get added and signaled elsewhere. if (m_BaseType != ot_Operation && m_BaseType != ot_Attribute && m_BaseType != ot_EnumLiteral && m_BaseType != ot_EntityAttribute && m_BaseType != ot_Template && m_BaseType != ot_Stereotype && m_BaseType != ot_Role && m_BaseType != ot_UniqueConstraint && m_BaseType != ot_ForeignKeyConstraint && m_BaseType != ot_CheckConstraint && m_BaseType != ot_InstanceAttribute ) { if (umlPackage()) { umlPackage()->addObject(this); } else if (umldoc->rootFolderType(this) == Uml::ModelType::N_MODELTYPES) { // umlPackage() is not set on the root folders. logDebug1("UMLObject::loadFromXMI(%1): umlPackage() is not set", m_name); } } return load1(element); } /** * Helper function for debug output. * Returns the given enum value as string. * @param ot ObjectType of which a string representation is wanted * @return the ObjectType as string */ QString UMLObject::toString(ObjectType ot) { return QLatin1String(ENUM_NAME(UMLObject, ObjectType, ot)); } /** * Returns the given object type value as localized string. * @param t ObjectType of which a string representation is wanted * @return the ObjectType as localized string */ QString UMLObject::toI18nString(ObjectType t) { QString name; switch (t) { case UMLObject::ot_Actor: name = i18n("Actor &name:"); break; case UMLObject::ot_Artifact: name = i18n("Artifact &name:"); break; case UMLObject::ot_Association: name = i18n("Association &name:"); break; case UMLObject::ot_Class: name = i18n("Class &name:"); break; case UMLObject::ot_Component: name = i18n("Component &name:"); break; case UMLObject::ot_Datatype: name = i18n("Datatype &name:"); break; case UMLObject::ot_Entity: name = i18n("Entity &name:"); break; case UMLObject::ot_Enum: name = i18n("Enum &name:"); break; case UMLObject::ot_Folder: name = i18n("Folder &name:"); break; case UMLObject::ot_Interface: name = i18n("Interface &name:"); break; case UMLObject::ot_Node: name = i18n("Node &name:"); break; case UMLObject::ot_Package: name = i18n("Package &name:"); break; case UMLObject::ot_Port: name = i18n("Port &name:"); break; case UMLObject::ot_Stereotype: name = i18n("Stereotype &name:"); break; case UMLObject::ot_UseCase: name = i18n("Use case &name:"); break; case UMLObject::ot_Instance: name = i18n("Instance name:"); break; default: name = QStringLiteral("<unknown> &name:"); logWarn1("UMLObject::toI18nString unknown object type %1", toString(t)); break; } return name; } /** * Returns the given object type value as icon type. * @param t ObjectType of which an icon type is wanted * @return the ObjectType as icon type */ Icon_Utils::IconType UMLObject::toIcon(ObjectType t) { Icon_Utils::IconType icon; switch (t) { case UMLObject::ot_Actor: icon = Icon_Utils::it_Actor; break; case UMLObject::ot_Artifact: icon = Icon_Utils::it_Artifact; break; case UMLObject::ot_Association: icon = Icon_Utils::it_Association; break; case UMLObject::ot_Class: icon = Icon_Utils::it_Class; break; case UMLObject::ot_Component: icon = Icon_Utils::it_Component; break; case UMLObject::ot_Datatype: icon = Icon_Utils::it_Datatype; break; case UMLObject::ot_Entity: icon = Icon_Utils::it_Entity; break; case UMLObject::ot_Enum: icon = Icon_Utils::it_Enum; break; case UMLObject::ot_Folder: icon = Icon_Utils::it_Folder; break; case UMLObject::ot_Instance: icon = Icon_Utils::it_Instance; break; case UMLObject::ot_Interface: icon = Icon_Utils::it_Interface; break; case UMLObject::ot_Node: icon = Icon_Utils::it_Node; break; case UMLObject::ot_Package: icon = Icon_Utils::it_Package; break; case UMLObject::ot_Port: icon = Icon_Utils::it_Port; break; case UMLObject::ot_EnumLiteral: icon = Icon_Utils::it_Enum_Literal; break; case UMLObject::ot_Attribute: case UMLObject::ot_InstanceAttribute: icon = Icon_Utils::it_Public_Attribute; break; case UMLObject::ot_Operation: icon = Icon_Utils::it_Public_Method; break; case UMLObject::ot_Template: icon = Icon_Utils::it_Template; break; case UMLObject::ot_Category: icon = Icon_Utils::it_Category; break; case UMLObject::ot_EntityAttribute: icon = Icon_Utils::it_Entity_Attribute; break; case UMLObject::ot_UniqueConstraint: icon = Icon_Utils::it_Unique_Constraint; break; case UMLObject::ot_ForeignKeyConstraint: icon = Icon_Utils::it_ForeignKey_Constraint; break; case UMLObject::ot_CheckConstraint: icon = Icon_Utils::it_Check_Constraint; break; case UMLObject::ot_UseCase: icon = Icon_Utils::it_UseCase; break; default: icon = Icon_Utils::it_Home; logWarn1("UMLObject::toIcon unknown object type %1", toString(t)); break; } return icon; } /** * Print UML Object to debug output stream, so it can be used like * uDebug() << "This object shouldn't be here: " << illegalObject; */ QDebug operator<<(QDebug out, const UMLObject& obj) { out.nospace() << "UMLObject: name= " << obj.name() << ", type= " << UMLObject::toString(obj.m_BaseType); return out.space(); } //only required for getting types #include "actor.h" #include "artifact.h" #include "association.h" #include "attribute.h" #include "umlcanvasobject.h" #include "category.h" #include "checkconstraint.h" #include "classifier.h" #include "component.h" #include "datatype.h" #include "entity.h" #include "entityattribute.h" #include "entityconstraint.h" #include "enum.h" #include "foreignkeyconstraint.h" #include "instance.h" #include "instanceattribute.h" #include "node.h" #include "operation.h" #include "port.h" #include "umlrole.h" #include "template.h" #include "uniqueconstraint.h" #include "usecase.h" UMLActor * UMLObject::asUMLActor() { return dynamic_cast<UMLActor*>(this); } UMLArtifact * UMLObject::asUMLArtifact() { return dynamic_cast<UMLArtifact*>(this); } UMLAssociation * UMLObject::asUMLAssociation() { return dynamic_cast<UMLAssociation*>(this); } UMLAttribute * UMLObject::asUMLAttribute() { return dynamic_cast<UMLAttribute*>(this); } UMLCanvasObject * UMLObject::asUMLCanvasObject() { return dynamic_cast<UMLCanvasObject*>(this); } UMLCategory * UMLObject::asUMLCategory() { return dynamic_cast<UMLCategory*>(this); } UMLCheckConstraint * UMLObject::asUMLCheckConstraint() { return dynamic_cast<UMLCheckConstraint*>(this); } UMLClassifier * UMLObject::asUMLClassifier() { return dynamic_cast<UMLClassifier*>(this); } UMLClassifierListItem * UMLObject::asUMLClassifierListItem() { return dynamic_cast<UMLClassifierListItem*>(this); } UMLComponent * UMLObject::asUMLComponent() { return dynamic_cast<UMLComponent*>(this); } UMLDatatype * UMLObject::asUMLDatatype() { return dynamic_cast<UMLDatatype*>(this); } UMLEntity * UMLObject::asUMLEntity() { return dynamic_cast<UMLEntity*>(this); } UMLEntityAttribute * UMLObject::asUMLEntityAttribute() { return dynamic_cast<UMLEntityAttribute*>(this); } UMLEntityConstraint * UMLObject::asUMLEntityConstraint() { return dynamic_cast<UMLEntityConstraint*>(this); } UMLEnum * UMLObject::asUMLEnum() { return dynamic_cast<UMLEnum*>(this); } UMLEnumLiteral * UMLObject::asUMLEnumLiteral() { return dynamic_cast<UMLEnumLiteral*>(this); } UMLFolder * UMLObject::asUMLFolder() { return dynamic_cast<UMLFolder*>(this); } UMLForeignKeyConstraint * UMLObject::asUMLForeignKeyConstraint() { return dynamic_cast<UMLForeignKeyConstraint*>(this); } UMLInstance * UMLObject::asUMLInstance() { return dynamic_cast<UMLInstance*>(this); } UMLInstanceAttribute * UMLObject::asUMLInstanceAttribute() { return dynamic_cast<UMLInstanceAttribute*>(this); } UMLNode * UMLObject::asUMLNode() { return dynamic_cast<UMLNode*>(this); } UMLObject * UMLObject::asUMLObject() { return dynamic_cast<UMLObject*>(this); } UMLOperation * UMLObject::asUMLOperation() { return dynamic_cast<UMLOperation*>(this); } UMLPackage * UMLObject::asUMLPackage() { return dynamic_cast<UMLPackage*>(this); } UMLPort * UMLObject::asUMLPort() { return dynamic_cast<UMLPort*>(this); } UMLRole * UMLObject::asUMLRole() { return dynamic_cast<UMLRole*>(this); } UMLStereotype * UMLObject::asUMLStereotype() { return dynamic_cast<UMLStereotype*>(this); } UMLTemplate * UMLObject::asUMLTemplate() { return dynamic_cast<UMLTemplate*>(this); } UMLUniqueConstraint * UMLObject::asUMLUniqueConstraint() { return dynamic_cast<UMLUniqueConstraint*>(this); } UMLUseCase * UMLObject::asUMLUseCase() { return dynamic_cast<UMLUseCase*>(this); } const UMLActor * UMLObject::asUMLActor() const { return dynamic_cast<const UMLActor*>(this); } const UMLArtifact * UMLObject::asUMLArtifact() const { return dynamic_cast<const UMLArtifact*>(this); } const UMLAssociation * UMLObject::asUMLAssociation() const { return dynamic_cast<const UMLAssociation*>(this); } const UMLAttribute * UMLObject::asUMLAttribute() const { return dynamic_cast<const UMLAttribute*>(this); } const UMLCanvasObject * UMLObject::asUMLCanvasObject() const { return dynamic_cast<const UMLCanvasObject*>(this); } const UMLCategory * UMLObject::asUMLCategory() const { return dynamic_cast<const UMLCategory*>(this); } const UMLCheckConstraint * UMLObject::asUMLCheckConstraint() const { return dynamic_cast<const UMLCheckConstraint*>(this); } const UMLClassifier * UMLObject::asUMLClassifier() const { return dynamic_cast<const UMLClassifier*>(this); } const UMLClassifierListItem * UMLObject::asUMLClassifierListItem() const { return dynamic_cast<const UMLClassifierListItem*>(this); } const UMLComponent * UMLObject::asUMLComponent() const { return dynamic_cast<const UMLComponent*>(this); } const UMLDatatype * UMLObject::asUMLDatatype() const { return dynamic_cast<const UMLDatatype*>(this); } const UMLEntity * UMLObject::asUMLEntity() const { return dynamic_cast<const UMLEntity*>(this); } const UMLEntityAttribute * UMLObject::asUMLEntityAttribute() const { return dynamic_cast<const UMLEntityAttribute*>(this); } const UMLEntityConstraint * UMLObject::asUMLEntityConstraint() const { return dynamic_cast<const UMLEntityConstraint*>(this); } const UMLEnum * UMLObject::asUMLEnum() const { return dynamic_cast<const UMLEnum*>(this); } const UMLEnumLiteral * UMLObject::asUMLEnumLiteral() const { return dynamic_cast<const UMLEnumLiteral*>(this); } const UMLFolder * UMLObject::asUMLFolder() const { return dynamic_cast<const UMLFolder*>(this); } const UMLForeignKeyConstraint * UMLObject::asUMLForeignKeyConstraint() const { return dynamic_cast<const UMLForeignKeyConstraint*>(this); } const UMLInstance * UMLObject::asUMLInstance() const { return dynamic_cast<const UMLInstance*>(this); } const UMLInstanceAttribute * UMLObject::asUMLInstanceAttribute() const { return dynamic_cast<const UMLInstanceAttribute*>(this); } const UMLNode * UMLObject::asUMLNode() const { return dynamic_cast<const UMLNode*>(this); } const UMLObject * UMLObject::asUMLObject() const { return dynamic_cast<const UMLObject*>(this); } const UMLOperation * UMLObject::asUMLOperation() const { return dynamic_cast<const UMLOperation*>(this); } const UMLPackage * UMLObject::asUMLPackage() const { return dynamic_cast<const UMLPackage*>(this); } const UMLPort * UMLObject::asUMLPort() const { return dynamic_cast<const UMLPort*>(this); } const UMLRole * UMLObject::asUMLRole() const { return dynamic_cast<const UMLRole*>(this); } const UMLStereotype * UMLObject::asUMLStereotype() const { return dynamic_cast<const UMLStereotype*>(this); } const UMLTemplate * UMLObject::asUMLTemplate() const { return dynamic_cast<const UMLTemplate*>(this); } const UMLUniqueConstraint * UMLObject::asUMLUniqueConstraint() const { return dynamic_cast<const UMLUniqueConstraint*>(this); } const UMLUseCase * UMLObject::asUMLUseCase() const { return dynamic_cast<const UMLUseCase*>(this); }
52,788
C++
.cpp
1,380
32.692029
139
0.644586
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,473
association.cpp
KDE_umbrello/umbrello/umlmodel/association.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "association.h" // app includes #include "debug_utils.h" #include "classifier.h" #include "classpropertiesdialog.h" #include "folder.h" #include "uml.h" #include "umldoc.h" #include "umlrole.h" #include "uniqueid.h" #include "model_utils.h" #include "optionstate.h" #include "cmds.h" // kde includes #include <KLocalizedString> // qt includes #include <QPointer> using namespace Uml; DEBUG_REGISTER(UMLAssociation) /** * Sets up an association. * A new unique ID is assigned internally. * @param type The AssociationType::Enum to construct. * @param roleA Pointer to the UMLObject in role A. * @param roleB Pointer to the UMLObject in role B. */ UMLAssociation::UMLAssociation(Uml::AssociationType::Enum type, UMLObject * roleA, UMLObject * roleB) : UMLObject(QString()) { init(type, roleA, roleB); m_pRole[RoleType::A]->setID(UniqueID::gen()); m_pRole[RoleType::B]->setID(UniqueID::gen()); } /** * Constructs an association - for loading only. * This constructor should not normally be used as it constructs * an incomplete association (i.e. the role objects are missing.) * @param type The AssociationType::Enum to construct. * Default: Unknown. */ UMLAssociation::UMLAssociation(Uml::AssociationType::Enum type) : UMLObject(QString(), Uml::ID::Reserved) { init(type, nullptr, nullptr); } /** * Standard destructor. */ UMLAssociation::~UMLAssociation() { if (m_pRole[RoleType::A] == nullptr) { logError0("UMLAssociation destructor: m_pRole[A] is null already"); } else { delete m_pRole[RoleType::A]; m_pRole[RoleType::A] = nullptr; } if (m_pRole[RoleType::B] == nullptr) { logError0("UMLAssociation destructor: m_pRole[B] is null already"); } else { delete m_pRole[RoleType::B]; m_pRole[RoleType::B] = nullptr; } } /** * Overloaded '==' operator */ bool UMLAssociation::operator==(const UMLAssociation &rhs) const { if (this == &rhs) { return true; } return (UMLObject::operator== (rhs) && m_AssocType == rhs.m_AssocType && m_Name == rhs.m_Name && m_pRole[RoleType::A] == rhs.m_pRole[RoleType::A] && m_pRole[RoleType::B] == rhs.m_pRole[RoleType::B]); } /** * Returns the AssociationType::Enum of the UMLAssociation. * @return The AssociationType::Enum of the UMLAssociation. */ Uml::AssociationType::Enum UMLAssociation::getAssocType() const { return m_AssocType; } /** * Returns a String representation of this UMLAssociation. */ QString UMLAssociation::toString() const { QString string = m_pRole[RoleType::A]->toString(); string += QLatin1Char(' ') + Uml::AssociationType::toStringI18n(m_AssocType) + QLatin1Char(' '); string += m_pRole[RoleType::B]->toString(); return string; } /** * Resolve types. Required when dealing with foreign XMI files. * Needs to be called after all UML objects are loaded from file. * Overrides the method from UMLObject. * Calls resolveRef() for each role. * @return True for success. */ bool UMLAssociation::resolveRef() { bool successA = getUMLRole(RoleType::A)->resolveRef(); bool successB = getUMLRole(RoleType::B)->resolveRef(); if (successA && successB) { UMLObject *objA = getUMLRole(RoleType::A)->object(); UMLObject *objB = getUMLRole(RoleType::B)->object(); // Check if need to change the assoc type to Realization if (isRealization(objA, objB)) { m_AssocType = Uml::AssociationType::Realization; } umlPackage()->addAssocToConcepts(this); return true; } return false; } /** * Creates the <UML:Generalization> or <UML:Association> XMI element * including its role objects. */ void UMLAssociation::saveToXMI(QXmlStreamWriter& writer) { if (m_AssocType == Uml::AssociationType::Generalization) { // In UML2 mode, the generalization is saved in UMLClassifier::saveToXMI() if (! Settings::optionState().generalState.uml2) { UMLObject::save1(writer, QStringLiteral("Generalization"), QStringLiteral("generalization")); writer.writeAttribute(QStringLiteral("child"), Uml::ID::toString(getObjectId(RoleType::A))); writer.writeAttribute(QStringLiteral("parent"), Uml::ID::toString(getObjectId(RoleType::B))); writer.writeEndElement(); } return; } if (m_AssocType == Uml::AssociationType::Realization) { if (Settings::optionState().generalState.uml2) { UMLObject::save1(writer, QStringLiteral("InterfaceRealization"), QStringLiteral("interfaceRealization")); } else { UMLObject::save1(writer, QStringLiteral("Abstraction")); } writer.writeAttribute(QStringLiteral("client"), Uml::ID::toString(getObjectId(RoleType::A))); writer.writeAttribute(QStringLiteral("supplier"), Uml::ID::toString(getObjectId(RoleType::B))); writer.writeEndElement(); return; } if (m_AssocType == Uml::AssociationType::Dependency) { UMLObject::save1(writer, QStringLiteral("Dependency")); writer.writeAttribute(QStringLiteral("client"), Uml::ID::toString(getObjectId(RoleType::A))); writer.writeAttribute(QStringLiteral("supplier"), Uml::ID::toString(getObjectId(RoleType::B))); writer.writeEndElement(); return; } if (m_AssocType == Uml::AssociationType::Child2Category) { UMLObject::save1(writer, QStringLiteral("Child2Category")); writer.writeAttribute(QStringLiteral("client"), Uml::ID::toString(getObjectId(RoleType::A))); writer.writeAttribute(QStringLiteral("supplier"), Uml::ID::toString(getObjectId(RoleType::B))); writer.writeEndElement(); return; } if (m_AssocType == Uml::AssociationType::Category2Parent) { UMLObject::save1(writer, QStringLiteral("Category2Parent")); writer.writeAttribute(QStringLiteral("client"), Uml::ID::toString(getObjectId(RoleType::A))); writer.writeAttribute(QStringLiteral("supplier"), Uml::ID::toString(getObjectId(RoleType::B))); writer.writeEndElement(); return; } UMLObject::save1(writer, QStringLiteral("Association")); if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Association.connection")); } // TODO: Adapt to UML2: getUMLRole(RoleType::A)->saveToXMI (writer); // 1) attribute "memberEnd" with two space separated xmiIds getUMLRole(RoleType::B)->saveToXMI (writer); // 2) nested element <ownedEnd xmi:type="uml:Property"> if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); // UML:Association.connection } writer.writeEndElement(); // uml:Association } bool UMLAssociation::showPropertiesDialog(QWidget *parent) { QPointer<ClassPropertiesDialog> dlg = new ClassPropertiesDialog(parent, this, true); bool modified = dlg->exec(); delete dlg; return modified; } /** * Loads the <UML:Generalization> or <UML:Association> XMI element * including its role objects. */ bool UMLAssociation::load1(QDomElement & element) { if (id() == Uml::ID::None) return false; // old style XMI file. No real info in this association. UMLDoc * doc = UMLApp::app()->document(); UMLObject * obj[2] = { nullptr, NULL }; if (m_AssocType == Uml::AssociationType::Generalization || m_AssocType == Uml::AssociationType::Realization || m_AssocType == Uml::AssociationType::Dependency || m_AssocType == Uml::AssociationType::Child2Category || m_AssocType == Uml::AssociationType::Category2Parent) { QString general = element.attribute(QStringLiteral("general")); if (!general.isEmpty()) { UMLClassifier *owningClassifier = umlParent()->asUMLClassifier(); if (owningClassifier == nullptr){ logWarn1("Cannot load UML2 generalization: m_pUMLPackage (%1) is expected " "to be the owning classifier (=client)", umlParent()->name()); return false; } m_pRole[RoleType::A]->setObject(owningClassifier); m_pRole[RoleType::B]->setSecondaryId(general); // defer resolution to resolveRef() owningClassifier->addAssociationEnd(this); setUMLPackage(umlPackage()->umlPackage()); // reparent umlPackage()->addObject(this); return true; } for (unsigned r = RoleType::A; r <= RoleType::B; ++r) { const QString fetch = (m_AssocType == Uml::AssociationType::Generalization ? r == RoleType::A ? QStringLiteral("child") : QStringLiteral("parent") : r == RoleType::A ? QStringLiteral("client") : QStringLiteral("supplier")); QString roleIdStr = element.attribute(fetch); if (roleIdStr.isEmpty()) { // Might be given as a child node instead - see below. continue; } // set umlobject of role if possible (else defer resolution) obj[r] = doc->findObjectById(Uml::ID::fromString(roleIdStr)); Uml::RoleType::Enum role = Uml::RoleType::fromInt(r); if (obj[r] == nullptr) { m_pRole[role]->setSecondaryId(roleIdStr); // defer to resolveRef() } else { m_pRole[role]->setObject(obj[r]); if (umlPackage() == nullptr) { Uml::ModelType::Enum mt = Model_Utils::convert_OT_MT(obj[r]->baseType()); setUMLPackage(doc->rootFolder(mt)); DEBUG() << "assoctype " << m_AssocType << ": setting model type " << Uml::ModelType::toString(mt); } } } if (obj[RoleType::A] == nullptr || obj[RoleType::B] == nullptr) { for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (Model_Utils::isCommonXMI1Attribute(tag)) continue; // Permitted tag names: // roleA: "child" "subtype" "client" // roleB: "parent" "supertype" "supplier" QString idStr = Model_Utils::getXmiId(tempElement); if (idStr.isEmpty()) idStr = tempElement.attribute(QStringLiteral("xmi.idref")); if (idStr.isEmpty()) { QDomNode inner = node.firstChild(); QDomElement tmpElem = inner.toElement(); idStr = Model_Utils::getXmiId(tmpElem); if (idStr.isEmpty()) idStr = tmpElem.attribute(QStringLiteral("xmi.idref")); } if (idStr.isEmpty()) { logError3("UMLAssociation::load1 type %1, id %2 : xmi id not given for %3", m_AssocType, Uml::ID::toString(id()), tag); continue; } // Since we know for sure that we're dealing with a non // umbrello file, use deferred resolution unconditionally. if (UMLDoc::tagEq(tag, QStringLiteral("child")) || UMLDoc::tagEq(tag, QStringLiteral("subtype")) || UMLDoc::tagEq(tag, QStringLiteral("client"))) { getUMLRole(RoleType::A)->setSecondaryId(idStr); } else { getUMLRole(RoleType::B)->setSecondaryId(idStr); } } } // it is a realization if either endpoint is an interface if (isRealization(obj[RoleType::A], obj[RoleType::B])) { m_AssocType = Uml::AssociationType::Realization; } return true; } for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { // uml13.dtd compliant format (new style) if (node.isComment()) continue; QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (Model_Utils::isCommonXMI1Attribute(tag)) continue; QDomNode nodeA = node; if (UMLDoc::tagEq(tag, QStringLiteral("Association.connection")) || UMLDoc::tagEq(tag, QStringLiteral("Association.end")) || // Embarcadero's Describe UMLDoc::tagEq(tag, QStringLiteral("Namespace.ownedElement")) || UMLDoc::tagEq(tag, QStringLiteral("Namespace.contents"))) { nodeA = tempElement.firstChild(); } // Load role A. while (nodeA.isComment()) nodeA = nodeA.nextSibling(); tempElement = nodeA.toElement(); if (tempElement.isNull()) { logWarn0("UMLAssociation::load1 : element (A) is null"); return false; } tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("NavigableEnd"))) { // Embarcadero's Describe m_AssocType = Uml::AssociationType::UniAssociation; } else if (!UMLDoc::tagEq(tag, QStringLiteral("ownedEnd")) && !UMLDoc::tagEq(tag, QStringLiteral("AssociationEnd")) && !UMLDoc::tagEq(tag, QStringLiteral("AssociationEndRole"))) { logWarn1("UMLAssociation::load1: unknown child (A) tag %1", tag); return false; } if (! getUMLRole(RoleType::A)->loadFromXMI(tempElement)) return false; // Load role B. QDomNode nodeB = nodeA.nextSibling(); while (nodeB.isComment()) nodeB = nodeB.nextSibling(); tempElement = nodeB.toElement(); if (tempElement.isNull()) { logWarn0("UMLAssociation::load1 : element (B) is null"); return false; } tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("NavigableEnd"))) { // Embarcadero's Describe m_AssocType = Uml::AssociationType::UniAssociation; } else if (!UMLDoc::tagEq(tag, QStringLiteral("ownedEnd")) && !UMLDoc::tagEq(tag, QStringLiteral("AssociationEnd")) && !UMLDoc::tagEq(tag, QStringLiteral("AssociationEndRole"))) { logWarn1("UMLAssociation::load1: unknown child (B) tag %1", tag); return false; } if (! getUMLRole(RoleType::B)->loadFromXMI(tempElement)) return false; if (umlPackage() == nullptr) { Uml::ModelType::Enum mt = Model_Utils::convert_OT_MT(getObject(RoleType::B)->baseType()); setUMLPackage(doc->rootFolder(mt)); DEBUG() << "setting model type " << Uml::ModelType::toString(mt); } // setting the association type: // // In the old days, we could just record this on the association, // and be done with it. But that's not how the UML13.dtd does things. // As a result, we are checking roleA for information about the // parent association (!) which by this point in the parse, should // be set. However, the information that the roles are allowed to have // is not complete, so we need to finish the analysis here. // find self-associations if (m_AssocType == Uml::AssociationType::Association && getObjectId(RoleType::A) == getObjectId(RoleType::B)) m_AssocType = Uml::AssociationType::Association_Self; // fall-back default type if (m_AssocType == Uml::AssociationType::Unknown) { m_AssocType = Uml::AssociationType::Association; } return true; } // From here on it's old-style stuff. QString assocTypeStr = element.attribute(QStringLiteral("assoctype"), QStringLiteral("-1")); Uml::AssociationType::Enum assocType = Uml::AssociationType::Unknown; if (assocTypeStr[0] >= QLatin1Char('a') && assocTypeStr[0] <= QLatin1Char('z')) { // In an earlier version, the natural assoctype names were saved. const char *assocTypeString[] = { "generalization", // Uml::AssociationType::Generalization "aggregation", // Uml::AssociationType::Aggregation "dependency", // Uml::AssociationType::Dependency "association", // Uml::AssociationType::Association "associationself", // Uml::AssociationType::Association_Self "collmessage", // Uml::AssociationType::Coll_Message "seqmessage", // Uml::AssociationType::Seq_Message "collmessageself", // Uml::AssociationType::Coll_Mesg_Self "seqmessageself", // Uml::AssociationType::Seq_Message_Self "implementation", // Uml::AssociationType::Implementation "composition", // Uml::AssociationType::Composition "realization", // Uml::AssociationType::Realization "uniassociation", // Uml::AssociationType::UniAssociation "anchor", // Uml::AssociationType::Anchor "state", // Uml::AssociationType::State "activity", // Uml::AssociationType::Activity "exception", // Uml::AssociationType::Exception "category2parent", // Uml::AssociationType::Category2Parent "child2category", // Uml::AssociationType::Child2Category "relationship" // Uml::AssociationType::Relationship }; const int arraySize = sizeof(assocTypeString) / sizeof(char*); DEBUG() << "AssociationType string array size = " << arraySize; int index; for (index = 0; index < arraySize; ++index) if (assocTypeStr == QString::fromLatin1(assocTypeString[index])) break; if (index < arraySize) assocType = Uml::AssociationType::fromInt(index); } else { int assocTypeNum = assocTypeStr.toInt(); if (assocTypeNum < (int)Uml::AssociationType::Generalization || // first enum assocTypeNum >= (int)Uml::AssociationType::Reserved) { // last enum logWarn1("UMLAssociation::load1: bad assoctype of UML:AssociationType::Enum %1", Uml::ID::toString(id())); return false; } assocType = Uml::AssociationType::fromInt(assocTypeNum); } setAssociationType(assocType); Uml::ID::Type roleAObjID = Uml::ID::fromString(element.attribute(QStringLiteral("rolea"), QStringLiteral("-1"))); Uml::ID::Type roleBObjID = Uml::ID::fromString(element.attribute(QStringLiteral("roleb"), QStringLiteral("-1"))); if (assocType == Uml::AssociationType::Aggregation || assocType == Uml::AssociationType::Composition) { // Flip roles to compensate for changed diamond logic in AssociationLine. // For further explanations see AssociationWidget::loadFromXMI. Uml::ID::Type tmp = roleAObjID; roleAObjID = roleBObjID; roleBObjID = tmp; } UMLObject * objA = doc->findObjectById(roleAObjID); UMLObject * objB = doc->findObjectById(roleBObjID); if(objA) getUMLRole(RoleType::A)->setObject(objA); else return false; if(objB) getUMLRole(RoleType::B)->setObject(objB); else return false; setMultiplicity(element.attribute(QStringLiteral("multia")), RoleType::A); setMultiplicity(element.attribute(QStringLiteral("multib")), RoleType::B); setRoleName(element.attribute(QStringLiteral("namea")), RoleType::A); setRoleName(element.attribute(QStringLiteral("nameb")), RoleType::B); setRoleDoc(element.attribute(QStringLiteral("doca")), RoleType::A); setRoleDoc(element.attribute(QStringLiteral("docb")), RoleType::B); // Visibility defaults to Public if it cant set it here.. QString visibilityA = element.attribute(QStringLiteral("visibilitya"), QStringLiteral("0")); QString visibilityB = element.attribute(QStringLiteral("visibilityb"), QStringLiteral("0")); int vis = visibilityA.toInt(); if (vis >= 200) // bkwd compat. vis -= 200; setVisibility((Uml::Visibility::Enum)vis, RoleType::A); vis = visibilityB.toInt(); if (vis >= 200) // bkwd compat. vis -= 200; setVisibility((Uml::Visibility::Enum)vis, RoleType::B); // Changeability defaults to Changeable if it cant set it here.. QString changeabilityA = element.attribute(QStringLiteral("changeabilitya"), QStringLiteral("0")); QString changeabilityB = element.attribute(QStringLiteral("changeabilityb"), QStringLiteral("0")); if (changeabilityA.toInt() > 0) setChangeability(Uml::Changeability::fromInt(changeabilityA.toInt()), RoleType::A); if (changeabilityB.toInt() > 0) setChangeability(Uml::Changeability::fromInt(changeabilityB.toInt()), RoleType::B); return true; } /** * Returns the UMLObject assigned to the given role. * @return Pointer to the UMLObject in the given role. */ UMLObject* UMLAssociation::getObject(Uml::RoleType::Enum role) const { if (m_pRole[role] == nullptr) return nullptr; return m_pRole[role]->object(); } /** * Returns the ID of the UMLObject assigned to the given role. * Shorthand for getObject(role)->ID(). * @return ID of the UMLObject in the given role. */ Uml::ID::Type UMLAssociation::getObjectId(Uml::RoleType::Enum role) const { UMLRole *roleObj = m_pRole[role]; if (roleObj == nullptr) return Uml::ID::None; UMLObject *o = roleObj->object(); if (o == nullptr) { QString auxID = roleObj->secondaryId(); if (auxID.isEmpty()) { logError1("UMLAssociation::getObjectId role %1 : getObject returns null", Uml::RoleType::toString(role)); return Uml::ID::None; } else { DEBUG() << "role " << role << ": using secondary ID " << auxID; return Uml::ID::fromString(auxID); } } return o->id(); } /** * Returns the ID of the UMLObject assigned to the given role. * CURRENTLY UNUSED. * @return ID of the UMLObject of the given role. */ Uml::ID::Type UMLAssociation::getRoleId(RoleType::Enum role) const { return m_pRole[role]->id(); } /** * Returns the changeability. */ Uml::Changeability::Enum UMLAssociation::changeability(Uml::RoleType::Enum role) const { return m_pRole[role]->changeability(); } /** * Returns the Visibility of the given role. * @return Visibility of the given role. */ Uml::Visibility::Enum UMLAssociation::visibility(Uml::RoleType::Enum role) const { return m_pRole[role]->visibility(); } /** * Returns the multiplicity assigned to the given role. * @return The multiplicity assigned to the given role. */ QString UMLAssociation::getMultiplicity(Uml::RoleType::Enum role) const { return m_pRole[role]->multiplicity(); } /** * Returns the name assigned to the role A. * @return The name assigned to the given role. */ QString UMLAssociation::getRoleName(Uml::RoleType::Enum role) const { return m_pRole[role]->name(); } /** * Returns the documentation assigned to the given role. * @return Documentation text of given role. */ QString UMLAssociation::getRoleDoc(Uml::RoleType::Enum role) const { return m_pRole[role]->doc(); } /** * Get the underlying UMLRole object for the given role. * @return Pointer to the UMLRole object for the given role. */ UMLRole * UMLAssociation::getUMLRole(Uml::RoleType::Enum role) const { return m_pRole[role]; } /** * Set the attribute m_bOldLoadMode. * @param value the new value to set */ void UMLAssociation::setOldLoadMode(bool value /* = true */) { m_bOldLoadMode = value; } /** * Return the backward compatibility flag for loading files. */ bool UMLAssociation::getOldLoadMode() const { return m_bOldLoadMode; } /** * Sets the assocType of the UMLAssociation. * @param assocType The AssociationType::Enum of the UMLAssociation. */ void UMLAssociation::setAssociationType(Uml::AssociationType::Enum assocType) { m_AssocType = assocType; if (m_AssocType == Uml::AssociationType::UniAssociation) { // In this case we need to auto-set the multiplicity/rolenames // of the roles #ifdef VERBOSE_DEBUGGING DEBUG() << " A new uni-association has been created."; #endif } UMLObject::emitModified(); } /** * Sets the UMLObject playing the given role in the association. * @param obj Pointer to the UMLObject of the given role. * @param role The Uml::RoleType::Enum played by the association */ void UMLAssociation::setObject(UMLObject *obj, Uml::RoleType::Enum role) { m_pRole[role]->setObject(obj); } /** * Sets the visibility of the given role of the UMLAssociation. * @param value Visibility of role. * @param role The Uml::RoleType::Enum to which the visibility is being applied */ void UMLAssociation::setVisibility(Visibility::Enum value, Uml::RoleType::Enum role) { m_pRole[role]->setVisibility(value); } /** * Sets the changeability of the given role of the UMLAssociation. * @param value Changeability_Type of the given role. * @param role The Uml::RoleType::Enum to which the changeability is being set */ void UMLAssociation::setChangeability(Uml::Changeability::Enum value, Uml::RoleType::Enum role) { m_pRole[role]->setChangeability(value); } /** * Sets the multiplicity of the given role of the UMLAssociation. * @param multi The multiplicity of the given role. * @param role The Uml::RoleType::Enum to which the multiplicity is being applied */ void UMLAssociation::setMultiplicity(const QString &multi, Uml::RoleType::Enum role) { if (m_pRole[role]->multiplicity() != multi) { UMLApp::app()->executeCommand(new CmdChangeMultiplicity(m_pRole[role], multi)); } } /** * Sets the name of the given role of the UMLAssociation. * @param roleName The name to set for the given role. * @param role The Uml::RoleType::Enum for which to set the name. */ void UMLAssociation::setRoleName(const QString &roleName, Uml::RoleType::Enum role) { m_pRole[role]->setName(roleName); } /** * Sets the documentation on the given role in the association. * @param doc The string with the documentation. * @param role The Uml::RoleType::Enum to which the documentation is being applied */ void UMLAssociation::setRoleDoc(const QString &doc, Uml::RoleType::Enum role) { m_pRole[role]->setDoc(doc); } /** * When the association type is "Generalization" and at least one of the * given objects an interface, then it is a "Realization". * @param objA UML object as role A * @param objB UML object as role B * @return flag whether association is a realization */ bool UMLAssociation::isRealization(UMLObject* objA, UMLObject* objB) const { bool aIsInterface = false; if (objA && (objA->baseType() == UMLObject::ot_Interface)) { aIsInterface = true; } bool bIsInterface = false; if (objB && (objB->baseType() == UMLObject::ot_Interface)) { bIsInterface = true; } return (m_AssocType == Uml::AssociationType::Generalization) && (aIsInterface || bIsInterface); } /** * Common initializations at construction time. * @param type The AssociationType::Enum to represent. * @param roleAObj Pointer to the role A UMLObject. * @param roleBObj Pointer to the role B UMLObject. */ void UMLAssociation::init(Uml::AssociationType::Enum type, UMLObject *roleAObj, UMLObject *roleBObj) { m_AssocType = type; m_BaseType = ot_Association; m_Name = QString(); m_bOldLoadMode = false; nrof_parent_widgets = -1; if (!UMLApp::app()->document()->loading()) { setUMLPackage(UMLApp::app()->document()->currentRoot()); } m_pRole[RoleType::A] = new UMLRole (this, roleAObj, RoleType::A); m_pRole[RoleType::B] = new UMLRole (this, roleBObj, RoleType::B); }
28,648
C++
.cpp
676
35.054734
117
0.638829
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,474
checkconstraint.cpp
KDE_umbrello/umbrello/umlmodel/checkconstraint.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ //own header #include "checkconstraint.h" // app includes #include "debug_utils.h" #include "umlcheckconstraintdialog.h" /** * Sets up a constraint. * * @param parent The parent of this UMLCheckConstraint. * @param name The name of this UMLCheckConstraint. * @param id The unique id given to this UMLCheckConstraint. */ UMLCheckConstraint::UMLCheckConstraint(UMLObject *parent, const QString& name, Uml::ID::Type id) : UMLEntityConstraint(parent, name, id) { init(); } /** * Sets up a constraint. * * @param parent The parent of this UMLCheckConstraint. */ UMLCheckConstraint::UMLCheckConstraint(UMLObject *parent) : UMLEntityConstraint(parent) { init(); } /** * Overloaded '==' operator. */ bool UMLCheckConstraint::operator==(const UMLCheckConstraint &rhs) const { if (this == &rhs) return true; if (!UMLObject::operator==(rhs)) return false; return true; } /** * Destructor. */ UMLCheckConstraint::~UMLCheckConstraint() { } /** * Copy the internal presentation of this object into the UMLCheckConstraint * object. */ void UMLCheckConstraint::copyInto(UMLObject *lhs) const { UMLCheckConstraint *target = lhs->asUMLCheckConstraint(); // call the parent first. UMLEntityConstraint::copyInto(target); // Copy all datamembers target->m_CheckCondition = m_CheckCondition; } /** * Make a clone of the UMLCheckConstraint. */ UMLObject* UMLCheckConstraint::clone() const { //FIXME: The new attribute should be slaved to the NEW parent not the old. UMLCheckConstraint *clone = new UMLCheckConstraint(umlParent()); copyInto(clone); return clone; } /** * Returns a string representation of the UMLCheckConstraint. * Reimplements function from @ref UMLClassifierListItem. */ QString UMLCheckConstraint::toString(Uml::SignatureType::Enum sig, bool) const { QString s; if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::SigNoVis) { s = name() ; } return s; } QString UMLCheckConstraint::getFullyQualifiedName(const QString& separator, bool includeRoot) const { Q_UNUSED(separator); Q_UNUSED(includeRoot); return this->name(); } /** * Creates the <UML:UniqueConstraint> XMI element. */ void UMLCheckConstraint::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("CheckConstraint")); writer.writeTextElement(QString(), m_CheckCondition); UMLObject::save1end(writer); } /** * Display the properties configuration dialog for the attribute. */ bool UMLCheckConstraint::showPropertiesDialog(QWidget* parent) { UMLCheckConstraintDialog dialog(parent, this); return dialog.exec(); } /** * Loads the <UML:CheckConstraint> XMI element. */ bool UMLCheckConstraint::load1(QDomElement & element) { QDomNode node = element.firstChild(); QDomText checkConstraintText = node.toText(); if (checkConstraintText.isNull()) m_CheckCondition = QString(); else m_CheckCondition = checkConstraintText.data(); return true; } /** * Initialises Check Constraint */ void UMLCheckConstraint::init() { m_BaseType = UMLObject::ot_CheckConstraint; m_CheckCondition.clear(); }
3,450
C++
.cpp
127
23.669291
92
0.716798
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,475
umlcanvasobject.cpp
KDE_umbrello/umbrello/umlmodel/umlcanvasobject.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "umlcanvasobject.h" // local includes #include "debug_utils.h" #include "uml.h" #include "umldoc.h" #include "classifier.h" #include "association.h" #include "attribute.h" #include "operation.h" #include "template.h" #include "stereotype.h" #include "idchangelog.h" // kde includes #include <KLocalizedString> DEBUG_REGISTER_DISABLED(UMLCanvasObject) /** * Sets up a UMLCanvasObject. * * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLCanvasObject::UMLCanvasObject(const QString & name, Uml::ID::Type id) : UMLObject(name, id) { } /** * Standard deconstructor. */ UMLCanvasObject::~UMLCanvasObject() { //removeAllAssociations(); // No! This is way too late to do that. // It should have been called explicitly before destructing the // UMLCanvasObject. if (associations()) { DEBUG() << "UMLCanvasObject destructor: FIXME: there are still associations()"; } } /** * Return the subset of subordinates that matches the given type. * * @param assocType The AssociationType::Enum to match. * @return The list of associations that match assocType. */ UMLAssociationList UMLCanvasObject::getSpecificAssocs(Uml::AssociationType::Enum assocType) const { UMLAssociationList list; for(UMLObject *o : subordinates()) { if (o->baseType() != UMLObject::ot_Association) continue; UMLAssociation *a = o->asUMLAssociation(); if (a->getAssocType() == assocType) list.append(a); } return list; } /** * Adds an association end to subordinates. * * @param assoc The association to add. * @todo change param type to UMLRole */ bool UMLCanvasObject::addAssociationEnd(UMLAssociation* assoc) { Q_ASSERT(assoc); // add association only if not already present in list if (!hasAssociation(assoc)) { subordinates().append(assoc); // Don't emit signals during load from XMI UMLObject::emitModified(); Q_EMIT sigAssociationEndAdded(assoc); return true; } return false; } /** * Determine if this canvasobject has the given association. * * @param assoc The association to check. */ bool UMLCanvasObject::hasAssociation(UMLAssociation* assoc) const { uint cnt = subordinates().count(assoc); DEBUG() << "count is " << cnt; return (cnt > 0); } /** * Remove an association end from the CanvasObject. * * @param assoc The association to remove. * @todo change param type to UMLRole */ int UMLCanvasObject::removeAssociationEnd(UMLAssociation * assoc) { if (!hasAssociation(assoc) || !subordinates().removeAll(assoc)) { DEBUG() << "cannot find given assoc " << assoc << " in list"; return -1; } UMLApp::app()->document()->removeAssociation(assoc, false); UMLObject::emitModified(); Q_EMIT sigAssociationEndRemoved(assoc); return subordinates().count(); } /** * Remove all association ends from the CanvasObject. */ void UMLCanvasObject::removeAllAssociationEnds() { for(UMLObject *o : subordinates()) { if (o->baseType() != UMLObject::ot_Association) { continue; } UMLAssociation *assoc = o->asUMLAssociation(); //umldoc->slotRemoveUMLObject(assoc); UMLObject* objA = assoc->getObject(Uml::RoleType::A); UMLObject* objB = assoc->getObject(Uml::RoleType::B); UMLCanvasObject *roleAObj = objA->asUMLCanvasObject(); if (roleAObj) { roleAObj->removeAssociationEnd(assoc); } else if (objA) { DEBUG() << name() << ": objA " << objA->name() << " is not a UMLCanvasObject"; } else { DEBUG() << name() << "): objA is NULL"; } UMLCanvasObject *roleBObj = objB->asUMLCanvasObject(); if (roleBObj) { roleBObj->removeAssociationEnd(assoc); } else if (objB) { DEBUG() << name() << "): objB " << objB->name() << " is not a UMLCanvasObject"; } else { DEBUG() << name() << "): objB is NULL"; } } } /** * Remove all child objects. * Just clear list, objects must be deleted where they were created * (or we have bad crashes). */ void UMLCanvasObject::removeAllChildObjects() { if (!subordinates().isEmpty()) { removeAllAssociationEnds(); subordinates().clear(); } } /** * Returns a name for the new association, operation, template * or attribute appended with a number if the default name is * taken e.g. new_association, new_association_1 etc. * * @param type The object type for which to make a name. * @param prefix Optional prefix to use for the name. * If not given then uniqChildName() will choose the prefix * internally based on the object type. * @return Unique name string for the ObjectType given. */ QString UMLCanvasObject::uniqChildName(const UMLObject::ObjectType type, const QString &prefix /* = QString() */) const { QString currentName; currentName = prefix; if (currentName.isEmpty()) { switch (type) { case UMLObject::ot_Association: currentName = i18n("new_association"); break; case UMLObject::ot_Attribute: currentName = i18n("new_attribute"); break; case UMLObject::ot_Template: currentName = i18n("new_template"); break; case UMLObject::ot_Operation: currentName = i18n("new_operation"); break; case UMLObject::ot_EnumLiteral: currentName = i18n("new_literal"); break; case UMLObject::ot_EntityAttribute: currentName = i18n("new_field"); break; case UMLObject::ot_UniqueConstraint: currentName = i18n("new_unique_constraint"); break; case UMLObject::ot_ForeignKeyConstraint: currentName = i18n("new_fkey_constraint"); break; case UMLObject::ot_CheckConstraint: currentName = i18n("new_check_constraint"); break; case UMLObject::ot_Instance: currentName = i18n("new_object"); break; default: logWarn1("UMLCanvasObject::uniqChildName() called for unknown child type %1", UMLObject::toString(type)); return QStringLiteral("ERROR_in_UMLCanvasObject_uniqChildName"); } } QString name = currentName; for (int number = 1; findChildObject(name); ++number) { name = currentName + QLatin1Char('_') + QString::number(number); } return name; } /** * Find a child object with the given name. * * @param n The name of the object to find. * @param t The type to find (optional.) If not given then * any object type will match. * @return Pointer to the object found; NULL if none found. */ UMLObject * UMLCanvasObject::findChildObject(const QString &n, UMLObject::ObjectType t) const { const bool caseSensitive = UMLApp::app()->activeLanguageIsCaseSensitive(); for(UMLObject *obj : subordinates()) { if (t != UMLObject::ot_UMLObject && obj->baseType() != t) continue; if (caseSensitive) { if (obj->name() == n) return obj; } else if (obj->name().toLower() == n.toLower()) { return obj; } } return nullptr; } /** * Find an association. * * @param id The id of the object to find. * @param considerAncestors boolean switch to consider ancestors while searching * @return Pointer to the object found (NULL if not found.) */ UMLObject* UMLCanvasObject::findChildObjectById(Uml::ID::Type id, bool considerAncestors) const { Q_UNUSED(considerAncestors); for(UMLObject *o : subordinates()) { if (o->id() == id) return o; } return nullptr; } /** * Overloaded '==' operator */ bool UMLCanvasObject::operator==(const UMLCanvasObject& rhs) const { if (this == &rhs) { return true; } if (!UMLObject::operator==(rhs)) { return false; } if (subordinates().count() != rhs.subordinates().count()) { return false; } for (int i = 0; i < subordinates().count(); i++) { UMLObject *a = subordinates().at(i); UMLObject *b = subordinates().at(i); if (!(*a == *b)) return false; } return true; } /** * Copy the internal presentation of this object into the new * object. */ void UMLCanvasObject::copyInto(UMLObject *lhs) const { UMLObject::copyInto(lhs); // TODO Associations are not copied at the moment. This because // the duplicate function (on umlwidgets) do not copy the associations. // //target->subordinates() = subordinates(); } /** * Returns the number of associations for the CanvasObject. * This is the sum of the aggregations and compositions. * * @return The number of associations for the Concept. */ int UMLCanvasObject::associations() const { int count = 0; for(UMLObject *obj : subordinates()) { if (obj->baseType() == UMLObject::ot_Association) count++; } return count; } /** * Return the list of associations for the CanvasObject. * * @return The list of associations for the CanvasObject. */ UMLAssociationList UMLCanvasObject::getAssociations() const { UMLAssociationList assocs; for(UMLObject *o : subordinates()) { if (o->baseType() != UMLObject::ot_Association) continue; UMLAssociation *assoc = o->asUMLAssociation(); assocs.append(assoc); } return assocs; } /** * Return a list of the superclasses of this classifier. * TODO: This overlaps with UMLClassifier::findSuperClassConcepts(), * see if we can merge the two. * * @param withRealizations include realizations in the returned list (default=yes) * @return The list of superclasses for the classifier. */ UMLClassifierList UMLCanvasObject::getSuperClasses(bool withRealizations) const { UMLClassifierList list; UMLAssociationList assocs = getAssociations(); for(UMLAssociation* a : assocs) { uIgnoreZeroPointer(a); if ((a->getAssocType() != Uml::AssociationType::Generalization && a->getAssocType() != Uml::AssociationType::Realization) || (!withRealizations && a->getAssocType() == Uml::AssociationType::Realization) || a->getObjectId(Uml::RoleType::A) != id()) continue; UMLClassifier *c = a->getObject(Uml::RoleType::B)->asUMLClassifier(); if (c) { list.append(c); } else { DEBUG() << name() << ": generalization's other end is not a " << "UMLClassifier (id= " << Uml::ID::toString(a->getObjectId(Uml::RoleType::B)) << ")"; } } return list; } /** * Return a list of the classes that inherit from this classifier. * TODO: This overlaps with UMLClassifier::findSubClassConcepts(), * see if we can merge the two. * * @return The list of classes inheriting from the classifier. */ UMLClassifierList UMLCanvasObject::getSubClasses() const { UMLClassifierList list; UMLAssociationList assocs = getAssociations(); for(UMLAssociation* a : assocs) { uIgnoreZeroPointer(a); if ((a->getAssocType() != Uml::AssociationType::Generalization && a->getAssocType() != Uml::AssociationType::Realization) || a->getObjectId(Uml::RoleType::B) != id()) continue; UMLClassifier *c = a->getObject(Uml::RoleType::A)->asUMLClassifier(); if (c) { list.append(c); } else { DEBUG() << "specialization's other end is not a UMLClassifier" << " (id=" << Uml::ID::toString(a->getObjectId(Uml::RoleType::A)) << ")"; } } return list; } /** * Shorthand for getSpecificAssocs(Uml::at_Realization) * * @return The list of realizations for the Concept. */ UMLAssociationList UMLCanvasObject::getRealizations() const { return getSpecificAssocs(Uml::AssociationType::Realization); } /** * Shorthand for getSpecificAssocs(Uml::at_Aggregation) * * @return The list of aggregations for the Concept. */ UMLAssociationList UMLCanvasObject::getAggregations() const { return getSpecificAssocs(Uml::AssociationType::Aggregation); } /** * Shorthand for getSpecificAssocs(Uml::at_Composition) const * * @return The list of compositions for the Concept. */ UMLAssociationList UMLCanvasObject::getCompositions() const { return getSpecificAssocs(Uml::AssociationType::Composition); } /** * Shorthand for getSpecificAssocs(Uml::at_Relationship) * * @return The list of relationships for the entity. */ UMLAssociationList UMLCanvasObject::getRelationships() const { return getSpecificAssocs(Uml::AssociationType::Relationship); } /** * Reimplementation of UMLObject method. */ bool UMLCanvasObject::resolveRef() { bool overallSuccess = UMLObject::resolveRef(); for(UMLObject *obj : subordinates()) { if (! obj->resolveRef()) { subordinates().removeAll(obj); overallSuccess = false; } } return overallSuccess; }
13,620
C++
.cpp
422
26.727488
103
0.642087
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,476
foreignkeyconstraint.cpp
KDE_umbrello/umbrello/umlmodel/foreignkeyconstraint.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ //own header #include "foreignkeyconstraint.h" // app includes #include "debug_utils.h" #include "entity.h" #include "entityattribute.h" #include "umlobject.h" #include "umldoc.h" #include "uml.h" #include "umlforeignkeyconstraintdialog.h" #include "object_factory.h" DEBUG_REGISTER(UMLForeignKeyConstraint) /** * Sets up a constraint. * @param parent The parent of this UMLForeignKeyConstraint. * @param name The name of this UMLForeignKeyConstraint. * @param id The unique id given to this UMLForeignKeyConstraint. */ UMLForeignKeyConstraint::UMLForeignKeyConstraint(UMLObject *parent, const QString& name, Uml::ID::Type id) : UMLEntityConstraint(parent, name, id) { init(); } /** * Sets up a constraint. * @param parent The parent of this UMLForeignKeyConstraint. */ UMLForeignKeyConstraint::UMLForeignKeyConstraint(UMLObject *parent) : UMLEntityConstraint(parent) { init(); } /** * Initialisation of common variables */ void UMLForeignKeyConstraint::init() { // initialise attributes m_BaseType = UMLObject::ot_ForeignKeyConstraint; // should be NULL actually // self referencing assigned to protect default behaviour m_ReferencedEntity = umlParent()->asUMLEntity(); m_UpdateAction = uda_NoAction; m_DeleteAction = uda_NoAction; // connect signals and slots connect(this, SIGNAL(sigReferencedEntityChanged()), this, SLOT(slotReferencedEntityChanged())); } /** * Overloaded '==' operator */ bool UMLForeignKeyConstraint::operator==(const UMLForeignKeyConstraint &rhs) const { if(this == &rhs) return true; if(!UMLObject::operator==(rhs)) return false; return true; } /** * Destructor. */ UMLForeignKeyConstraint::~UMLForeignKeyConstraint() { } /** * Copy the internal presentation of this object into the UMLForeignKeyConstraint * object. */ void UMLForeignKeyConstraint::copyInto(UMLObject *lhs) const { UMLForeignKeyConstraint *target = lhs->asUMLForeignKeyConstraint(); // call the parent first. UMLEntityConstraint::copyInto(target); // Copy all datamembers target->m_ReferencedEntity = m_ReferencedEntity; target->m_AttributeMap = m_AttributeMap; target->m_DeleteAction = m_DeleteAction; target->m_UpdateAction = m_UpdateAction; } /** * Make a clone of the UMLForeignKeyConstraint. */ UMLObject* UMLForeignKeyConstraint::clone() const { //FIXME: The new attribute should be slaved to the NEW parent not the old. UMLForeignKeyConstraint *clone = new UMLForeignKeyConstraint(umlParent()); copyInto(clone); return clone; } /** * Returns a string representation of the UMLForeignKeyConstraint. * @param sig If true will show the attribute type and initial value. * @return Returns a string representation of the UMLAttribute. */ QString UMLForeignKeyConstraint::toString(Uml::SignatureType::Enum sig, bool /*withStereotype*/) const { QString s; if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::SigNoVis) { s = name() + QLatin1Char(':'); s += QStringLiteral(" Foreign Key ("); QList<UMLEntityAttribute*> keys = m_AttributeMap.keys(); bool first = true; for(UMLEntityAttribute* key : keys) { if (first) { first = false; } else s += QLatin1Char(','); s += key->name(); } s += QLatin1Char(')'); } return s; } /** * Creates the <UML:ForeignKeyConstraint> XMI element. */ void UMLForeignKeyConstraint::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("ForeignKeyConstraint")); writer.writeAttribute(QStringLiteral("referencedEntity"), Uml::ID::toString(m_ReferencedEntity->id())); int updateAction = (int)m_UpdateAction; int deleteAction = (int)m_DeleteAction; writer.writeAttribute(QStringLiteral("updateAction"), QString::number(updateAction)); writer.writeAttribute(QStringLiteral("deleteAction"), QString::number(deleteAction)); QMap<UMLEntityAttribute*, UMLEntityAttribute*>::iterator i; for (i = m_AttributeMap.begin(); i!= m_AttributeMap.end() ; ++i) { writer.writeStartElement(QStringLiteral("AttributeMap")); writer.writeAttribute(QStringLiteral("key"), Uml::ID::toString((i.key())->id())); writer.writeAttribute(QStringLiteral("value"), Uml::ID::toString((i.value())->id())); writer.writeEndElement(); } UMLObject::save1end(writer); } /** * Display the properties configuration dialog for the attribute. */ bool UMLForeignKeyConstraint::showPropertiesDialog(QWidget* parent) { UMLForeignKeyConstraintDialog dialog(parent, this); return dialog.exec(); } /** * Adds the attribute pair to the attributeMap * @param pAttr The Attribute of the Parent Entity * @param rAttr The Attribute of the Referenced Entity * @return true if the attribute pair could be added successfully */ bool UMLForeignKeyConstraint::addEntityAttributePair(UMLEntityAttribute* pAttr, UMLEntityAttribute* rAttr) { UMLEntity *owningParent = umlParent()->asUMLEntity(); if (pAttr == nullptr || rAttr == nullptr) { logError0("UMLForeignKeyConstraint::addEntityAttributePair: null value passed to function"); return false; } // check for sanity of pAttr (parent entity attribute) if (owningParent == nullptr) { logError1("UMLForeignKeyConstraint::addEntityAttributePair(%1) : parent is not a UMLEntity", name()); return false; } if (owningParent->findChildObjectById(pAttr->id()) == nullptr) { logError2("UMLForeignKeyConstraint::addEntityAttributePair: parent %1 does not contain attribute %2", owningParent->name(), pAttr->name()); return false; } //check for sanity of rAttr (referenced entity attribute) if (m_ReferencedEntity != nullptr) { if(m_ReferencedEntity->findChildObjectById(rAttr->id()) == nullptr) { logError2("UMLForeignKeyConstraint::addEntityAttributePair parent %1 does not contain attribute %2", m_ReferencedEntity->name(), rAttr->name()); return false; } } else { logError0("UMLForeignKeyConstraint::addEntityAttributePair: Referenced Table Not set. Not Adding Pair"); return false; } // check if key takes part in some mapping if (m_AttributeMap.contains(pAttr) == true) return false; // check if value takes part in some mapping (no direct function) for(UMLEntityAttribute* attr : m_AttributeMap.values()) { if (rAttr == attr) return false; } // passed all checks, insert now m_AttributeMap.insert(pAttr, rAttr); QMap<UMLEntityAttribute*, UMLEntityAttribute*>::iterator i; logDebug0("UMLForeignKeyConstraint::addEntityAttributePair: AttributeMap after insertion " "(keyName keyType valueName valueType)"); for (i = m_AttributeMap.begin(); i != m_AttributeMap.end(); ++i) logDebug4("- %1 %2 %3 %4", i.key()->name(), i.key()->baseType(), i.value()->name(), i.value()->baseType()); return true; } /** * Removes an Attribute pair * @param pAttr The Attribute of the Parent Entity in the map. This attribute is the key of the map. * @return true of the attribute pair could be removed successfully */ bool UMLForeignKeyConstraint::removeEntityAttributePair(UMLEntityAttribute* /*key*/ pAttr) { bool state = m_AttributeMap.remove(pAttr); return state; } /** * Check if an attribute pair already exists * @param pAttr The Attribute of the Parent Entity * @param rAttr The Attribute of the Referenced Entity * @return true if the attribute pair could be found. */ bool UMLForeignKeyConstraint::hasEntityAttributePair(UMLEntityAttribute* pAttr, UMLEntityAttribute* rAttr) const { if (m_AttributeMap.contains(pAttr)) { if (m_AttributeMap.value(pAttr) == rAttr) { return true; } } return false; } /** * Loads the <UML:ForeignKeyConstraint> XMI element. */ bool UMLForeignKeyConstraint::load1(QDomElement & element) { UMLDoc* doc = UMLApp::app()->document(); Uml::ID::Type referencedEntityId = Uml::ID::fromString(element.attribute(QStringLiteral("referencedEntity"))); UMLObject* obj = doc->findObjectById(referencedEntityId); m_ReferencedEntity = obj->asUMLEntity(); if (m_ReferencedEntity == nullptr) { // save for resolving later m_pReferencedEntityID = referencedEntityId; } m_UpdateAction = (UpdateDeleteAction)element.attribute(QStringLiteral("updateAction")).toInt(); m_DeleteAction = (UpdateDeleteAction)element.attribute(QStringLiteral("deleteAction")).toInt(); QDomNode node = element.firstChild(); while (!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("AttributeMap"))) { QString xmiKey = tempElement.attribute(QStringLiteral("key")); QString xmiValue = tempElement.attribute(QStringLiteral("value")); Uml::ID::Type keyId = Uml::ID::fromString(xmiKey); Uml::ID::Type valueId = Uml::ID::fromString(xmiValue); const UMLEntity* parentEntity = umlParent()->asUMLEntity(); UMLObject* keyObj = parentEntity->findChildObjectById(keyId); UMLEntityAttribute* key = keyObj->asUMLEntityAttribute(); if (keyObj == nullptr) { logWarn1("UMLForeignKeyConstraint::load1 unable to resolve foreign key referencing attribute %1", xmiKey); } else if (m_ReferencedEntity == nullptr) { // if referenced entity is null, then we won't find its attributes even // save for resolving later m_pEntityAttributeIDMap.insert(key, valueId); } else { UMLObject* valueObj = m_ReferencedEntity->findChildObjectById(valueId); if (valueObj == nullptr) { logWarn1("UMLForeignKeyConstraint::load1 unable to resolve foreign key referenced attribute %1", xmiValue); } else { m_AttributeMap[key] = valueObj->asUMLEntityAttribute(); } } } else { logWarn1("UMLForeignKeyConstraint::load1: unknown child type %1", tag); } node = node.nextSibling(); } return true; } /** * Set the Referenced Entity. * @param ent The Entity to Reference */ void UMLForeignKeyConstraint::setReferencedEntity(UMLEntity* ent) { if (ent == m_ReferencedEntity) return; m_ReferencedEntity = ent; Q_EMIT sigReferencedEntityChanged(); } /** * Get the Referenced Entity. * @return the UML entity object */ UMLEntity* UMLForeignKeyConstraint::getReferencedEntity() const { return m_ReferencedEntity; } /** * Slot for referenced entity changed. */ void UMLForeignKeyConstraint::slotReferencedEntityChanged() { // clear all mappings m_AttributeMap.clear(); } /** * Clears all mappings between local and referenced attributes */ void UMLForeignKeyConstraint::clearMappings() { m_AttributeMap.clear(); } /** * Remimplementation from base classes * Used to resolve forward references to referenced entities in xmi */ bool UMLForeignKeyConstraint::resolveRef() { // resolve referenced entity first UMLDoc* doc = UMLApp::app()->document(); bool success = true; //resolve the referenced entity if (!Uml::ID::toString(m_pReferencedEntityID).isEmpty()) { UMLObject* obj = doc->findObjectById(m_pReferencedEntityID); m_ReferencedEntity = obj->asUMLEntity(); if (m_ReferencedEntity == nullptr) { success = false; } } QMap<UMLEntityAttribute*, Uml::ID::Type>::iterator i; for (i = m_pEntityAttributeIDMap.begin(); i!= m_pEntityAttributeIDMap.end() ; ++i) { if (!Uml::ID::toString(i.value()).isEmpty()) { UMLObject* obj = doc->findObjectById(i.value()); m_AttributeMap[i.key()] = obj->asUMLEntityAttribute(); if (m_AttributeMap[i.key()] == nullptr) { success = false; } } } return success; } /** * Retrieve all Pairs of Attributes. */ QMap<UMLEntityAttribute*, UMLEntityAttribute*> UMLForeignKeyConstraint::getEntityAttributePairs() { return m_AttributeMap; } /** * Get the Delete Action. */ UMLForeignKeyConstraint::UpdateDeleteAction UMLForeignKeyConstraint::getDeleteAction() const { return m_DeleteAction; } /** * Get the Update Action. */ UMLForeignKeyConstraint::UpdateDeleteAction UMLForeignKeyConstraint::getUpdateAction() const { return m_UpdateAction; } /** * Set the Delete Action to the specified UpdateDeleteAction. */ void UMLForeignKeyConstraint::setDeleteAction(UpdateDeleteAction uda) { m_DeleteAction = uda; } /** * Set the Update Action to the specified UpdateDeleteAction */ void UMLForeignKeyConstraint::setUpdateAction(UpdateDeleteAction uda) { m_UpdateAction = uda; }
13,473
C++
.cpp
376
30.553191
116
0.691151
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,477
enum.cpp
KDE_umbrello/umbrello/umlmodel/enum.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "enum.h" // app includes #include "debug_utils.h" #include "enumliteral.h" #include "optionstate.h" #include "umldoc.h" #include "uml.h" #include "uniqueid.h" #include "idchangelog.h" // kde includes #include <KLocalizedString> #include <KMessageBox> DEBUG_REGISTER(UMLEnum) /** * Sets up an enum. * @param name The name of the Enum. * @param id The unique id of the Enum. */ UMLEnum::UMLEnum(const QString& name, Uml::ID::Type id) : UMLClassifier(name, id) { init(); } /** * Standard destructor. */ UMLEnum::~UMLEnum() { subordinates().clear(); } /** * Overloaded '==' operator. */ bool UMLEnum::operator==(const UMLEnum & rhs) const { return UMLClassifier::operator==(rhs); } /** * Copy the internal presentation of this object into the new * object. */ void UMLEnum::copyInto(UMLObject *lhs) const { UMLClassifier::copyInto(lhs); } /** * Make a clone of this object. */ UMLObject* UMLEnum::clone() const { UMLEnum *clone = new UMLEnum(); copyInto(clone); return clone; } /** * Initializes key variables of the class. */ void UMLEnum::init() { m_BaseType = UMLObject::ot_Enum; setStereotypeCmd(QStringLiteral("enum")); } /** * Creates a literal for the enum. * @return The UMLEnum created */ UMLObject* UMLEnum::createEnumLiteral(const QString& name) { Uml::ID::Type id = UniqueID::gen(); QString currentName; if (name.isNull()) { currentName = uniqChildName(UMLObject::ot_EnumLiteral); } else { currentName = name; } UMLEnumLiteral* newEnumLiteral = new UMLEnumLiteral(this, currentName); bool ok = true; bool goodName = false; //check for name.isNull() stops dialog being shown //when creating enum literal via list view while (ok && !goodName && name.isNull()) { ok = newEnumLiteral->showPropertiesDialog(UMLApp::app()); QString name = newEnumLiteral->name(); if(name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else { goodName = true; } } if (!ok) { delete newEnumLiteral; return nullptr; } addEnumLiteral(newEnumLiteral); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newEnumLiteral); return newEnumLiteral; } /** * Adds an enumliteral to the enum. * @param name The name of the enumliteral. * @param id The id of the enumliteral (optional.) * If omitted a new ID is assigned internally. * @param value Optional numeric representation of the enumliteral. * @return Pointer to the UMLEnumliteral created. */ UMLObject* UMLEnum::addEnumLiteral(const QString &name, Uml::ID::Type id, const QString& value) { UMLObject *el = UMLCanvasObject::findChildObject(name); if (el != nullptr) { logDebug1("UMLEnum::addEnumLiteral: %1 is already present", name); return el; } UMLEnumLiteral* literal = new UMLEnumLiteral(this, name, id, value); subordinates().append(literal); UMLObject::emitModified(); Q_EMIT enumLiteralAdded(literal); connect(literal, SIGNAL(modified()), this, SIGNAL(modified())); return literal; } /** * Adds an already created enumliteral. * The enumliteral object must not belong to any other classifier. * @param literal Pointer to the UMLEnumLiteral. * @param Log Pointer to the IDChangeLog. * @return True if the enumliteral was successfully added. */ bool UMLEnum::addEnumLiteral(UMLEnumLiteral* literal, IDChangeLog* Log /* = nullptr*/) { QString name = (QString)literal->name(); if (findChildObject(name) == nullptr) { literal->setParent(this); subordinates().append(literal); UMLObject::emitModified(); Q_EMIT enumLiteralAdded(literal); connect(literal, SIGNAL(modified()), this, SIGNAL(modified())); return true; } else if (Log) { Log->removeChangeByNewID(literal->id()); delete literal; } return false; } /** * Adds an enumliteral to the enum, at the given position. * If position is negative or too large, the enumliteral is added * to the end of the list. * TODO: give default value -1 to position (append) - now it conflicts with the method above.. * @param literal Pointer to the UMLEnumLiteral. * @param position Position index for the insertion. * @return True if the enumliteral was successfully added. */ bool UMLEnum::addEnumLiteral(UMLEnumLiteral* literal, int position) { Q_ASSERT(literal); QString name = (QString)literal->name(); if (findChildObject(name) == nullptr) { literal->setParent(this); if (position >= 0 && position <= (int)subordinates().count()) { subordinates().insert(position, literal); } else { subordinates().append(literal); } UMLObject::emitModified(); Q_EMIT enumLiteralAdded(literal); connect(literal, SIGNAL(modified()), this, SIGNAL(modified())); return true; } return false; } /** * Removes an enumliteral from the class. * @param literal The enumliteral to remove. * @return Count of the remaining enumliterals after removal. * Returns -1 if the given enumliteral was not found. */ int UMLEnum::removeEnumLiteral(UMLEnumLiteral* literal) { if (!subordinates().removeAll(literal)) { logDebug0("UMLEnum::removeEnumLiteral: cannot find att given in list"); return -1; } Q_EMIT enumLiteralRemoved(literal); UMLObject::emitModified(); // If we are deleting the object, then we don't need to disconnect..this is done auto-magically // for us by QObject. -b.t. // disconnect(a, SIGNAL(modified()), this, SIGNAL(modified())); delete literal; return subordinates().count(); } /** * Returns the number of enumliterals for the class. * @return The number of enumliterals for the class. */ int UMLEnum::enumLiterals() const { return subordinates().count(); } /** * Emit the enumLiteralRemoved signal. */ void UMLEnum::signalEnumLiteralRemoved(UMLClassifierListItem *elit) { Q_EMIT enumLiteralRemoved(elit); } /** * Creates the <UML:Enum> element including its enumliterals. */ void UMLEnum::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Enumeration")); // save enum literals if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Enumeration.literal")); } UMLClassifierListItemList enumLiterals = getFilteredList(UMLObject::ot_EnumLiteral); for(UMLClassifierListItem *pEnumLiteral : enumLiterals) { pEnumLiteral->saveToXMI(writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); // UML:Enumeration.literal } UMLObject::save1end(writer); // UML:Enumeration } /** * Loads the <UML:Enum> element including its enumliterals. */ bool UMLEnum::load1(QDomElement& element) { QDomNode node = element.firstChild(); while(!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("EnumerationLiteral")) || UMLDoc::tagEq(tag, QStringLiteral("ownedLiteral")) || UMLDoc::tagEq(tag, QStringLiteral("EnumLiteral"))) { // for backward compatibility UMLEnumLiteral* pEnumLiteral = new UMLEnumLiteral(this); if(!pEnumLiteral->loadFromXMI(tempElement)) { return false; } subordinates().append(pEnumLiteral); } else if (UMLDoc::tagEq(tag, QStringLiteral("Enumeration.literal"))) { // UML 1.4 if (! load1(tempElement)) return false; } else if (tag == QStringLiteral("stereotype")) { logDebug1("UMLEnum::load1 %1: losing old-format stereotype.", name()); } else { logWarn1("UMLEnum::load1: unknown child type %1", tag); } node = node.nextSibling(); }//end while return true; } /** * Create a new ClassifierListObject (enumLiteral) * according to the given XMI tag. * Returns NULL if the string given does not contain one of the tags * <UML:EnumLiteral> * Used by the clipboard for paste operation. * Reimplemented from UMLClassifier for UMLEnum */ UMLClassifierListItem* UMLEnum::makeChildObject(const QString& xmiTag) { UMLClassifierListItem *pObject = nullptr; if (UMLDoc::tagEq(xmiTag, QStringLiteral("EnumerationLiteral")) || UMLDoc::tagEq(xmiTag, QStringLiteral("EnumLiteral"))) { pObject = new UMLEnumLiteral(this); } return pObject; }
8,999
C++
.cpp
278
27.874101
100
0.678785
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,478
umlrole.cpp
KDE_umbrello/umbrello/umlmodel/umlrole.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "umlrole.h" // local includes #include "association.h" #include "debug_utils.h" #include "model_utils.h" #include "optionstate.h" #include "umldoc.h" #include "umlroledialog.h" #include "uml.h" // qt includes #include <QPointer> DEBUG_REGISTER(UMLRole) /** * Sets up an association. * * @param parent The parent (association) of this UMLRole. * @param parentObj The Parent UML Object of this UMLRole * @param role The Uml::RoleType::Enum of this UMLRole */ UMLRole::UMLRole(UMLAssociation * parent, UMLObject * parentObj, Uml::RoleType::Enum role) : UMLObject(const_cast<UMLAssociation*>(parent)), m_pAssoc(parent), m_role(role), m_Multi(QString()), m_Changeability(Uml::Changeability::Changeable) { m_BaseType = UMLObject::ot_Role; m_name.clear(); m_pSecondary = parentObj; // connect this up to parent connect(this, SIGNAL(modified()), parent, SIGNAL(modified())); } /** * Standard destructor. */ UMLRole::~UMLRole() { } /** * Overloaded '==' operator. */ bool UMLRole::operator==(const UMLRole &rhs) const { if (this == &rhs) { return true; } return (UMLObject::operator==(rhs) && m_Changeability == rhs.m_Changeability && m_Multi == rhs.m_Multi && m_name == rhs.m_name ); } /** * Returns a String representation of this UMLRole instance. */ QString UMLRole::toString() const { QString result; if (object()) { result = object()->name(); result += QLatin1Char(':'); result += name(); } else result = QStringLiteral("null"); return result; } UMLAssociation * UMLRole::parentAssociation() const { return m_pAssoc; } /** * Returns the UMLObject assigned to the role. * @return Pointer to the UMLObject in role. */ UMLObject* UMLRole::object() const { return m_pSecondary; } /** * Returns the Changeablity of the role. * * @return Changeability of role. */ Uml::Changeability::Enum UMLRole::changeability() const { return m_Changeability; } /** * Returns the multiplicity assigned to the role. * * @return The multiplicity assigned to the role. */ QString UMLRole::multiplicity() const { return m_Multi; } /** * Sets the UMLObject playing the role in the association. * * @param obj Pointer to the UMLObject of role. */ void UMLRole::setObject(UMLObject *obj) { // because we will get the id of this role from the parent // object, we CANT allow UMLRoles to take other UMLRoles as // parent objects. In fact, there is probably good reason // to only take UMLClassifiers here, but I'll leave it more open // for the time being. -b.t. if (obj && obj->asUMLRole()) { logError2("UMLRole(%1) cannot setObject() to another UMLRole(%2)", Uml::ID::toString(m_nId), Uml::ID::toString(obj->id())); return; } m_pSecondary = obj; UMLObject::emitModified(); } /** * Sets the changeability of the role. * * @param value Changeability::Enum of role. */ void UMLRole::setChangeability(Uml::Changeability::Enum value) { m_Changeability = value; UMLObject::emitModified(); } /** * Sets the multiplicity of the role. * * @param multi The multiplicity of role. */ void UMLRole::setMultiplicity(const QString &multi) { m_Multi = multi; UMLObject::emitModified(); } /** * Get the 'id' of the role (NOT the parent object). This could be * either Uml::RoleType::A or Uml::RoleType::B. Yes, it would be better if we * could get along without this, but we need it to distinguish saved * umlrole objects in the XMI for 'self' associations where both roles * will point to the same underlying UMLObject. */ Uml::RoleType::Enum UMLRole::role() const { return m_role; } /** * Creates the <UML:AssociationEnd> XMI element. */ void UMLRole::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("AssociationEnd"), QStringLiteral("ownedEnd")); if (m_pSecondary) writer.writeAttribute(QStringLiteral("type"), Uml::ID::toString(m_pSecondary->id())); else logError1("UMLRole::saveToXMI(id %1) : m_pSecondary is null", Uml::ID::toString(m_nId)); if (!m_Multi.isEmpty()) writer.writeAttribute(QStringLiteral("multiplicity"), m_Multi); if (m_role == Uml::RoleType::A) { // role aggregation based on parent type // role A switch (m_pAssoc->getAssocType()) { case Uml::AssociationType::Composition: writer.writeAttribute(QStringLiteral("aggregation"), QStringLiteral("composite")); break; case Uml::AssociationType::Aggregation: writer.writeAttribute(QStringLiteral("aggregation"), QStringLiteral("aggregate")); break; default: writer.writeAttribute(QStringLiteral("aggregation"), QStringLiteral("none")); break; } if (m_pAssoc->getAssocType() == Uml::AssociationType::UniAssociation) { // Normally the isNavigable attribute is "true". // We set it to false on role A to indicate that // role B gets an explicit arrowhead. writer.writeAttribute(QStringLiteral("isNavigable"), QStringLiteral("false")); } else { writer.writeAttribute(QStringLiteral("isNavigable"), QStringLiteral("true")); } } else { writer.writeAttribute(QStringLiteral("aggregation"), QStringLiteral("none")); writer.writeAttribute(QStringLiteral("isNavigable"), QStringLiteral("true")); //FIXME obviously this isn't standard XMI if (m_pAssoc->getAssocType() == Uml::AssociationType::Relationship) { writer.writeAttribute(QStringLiteral("relationship"), QStringLiteral("true")); } } switch (m_Changeability) { case Uml::Changeability::Frozen: writer.writeAttribute(QStringLiteral("changeability"), QStringLiteral("frozen")); break; case Uml::Changeability::AddOnly: writer.writeAttribute(QStringLiteral("changeability"), QStringLiteral("addOnly")); break; case Uml::Changeability::Changeable: writer.writeAttribute(QStringLiteral("changeability"), QStringLiteral("changeable")); break; } writer.writeEndElement(); } /** * Display the properties configuration dialog for the object. * * @param parent The parent widget. * @return True for success of this operation. */ bool UMLRole::showPropertiesDialog(QWidget *parent) { QPointer<UMLRoleDialog> dlg = new UMLRoleDialog(parent, this); bool modified = dlg->exec() == QDialog::Accepted; delete dlg; return modified; } /** * Loads the <UML:AssociationEnd> XMI element. * Auxiliary to UMLObject::loadFromXMI. */ bool UMLRole::load1(QDomElement & element) { UMLDoc * doc = UMLApp::app()->document(); QString type = element.attribute(QStringLiteral("type")); if (!type.isEmpty()) { if (!m_SecondaryId.isEmpty()) logWarn2("UMLRole::load1 overwriting old m_SecondaryId %1 with new value %2", m_SecondaryId, type); m_SecondaryId = type; } // Inspect child nodes - for multiplicity (and type if not set above.) for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("name"))) { m_name = tempElement.text(); } else if (UMLDoc::tagEq(tag, QStringLiteral("AssociationEnd.multiplicity"))) { /* * There are different ways in which the multiplicity might be given: * - direct value in the <AssociationEnd.multiplicity> tag, * - attributes "lower" and "upper" of a subordinate <MultiplicityRange>, * - direct value in subordinate <MultiplicityRange.lower> and * <MultiplicityRange.upper> tags */ QDomNode n = tempElement.firstChild(); if (node.isNull() || tempElement.isNull() || n.isNull() || n.toElement().isNull()) { m_Multi = tempElement.text().trimmed(); continue; } tempElement = n.toElement(); tag = tempElement.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("Multiplicity"))) { m_Multi = tempElement.text().trimmed(); continue; } n = tempElement.firstChild(); tempElement = n.toElement(); tag = tempElement.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("Multiplicity.range"))) { m_Multi = tempElement.text().trimmed(); continue; } n = tempElement.firstChild(); tempElement = n.toElement(); tag = tempElement.tagName(); if (!UMLDoc::tagEq(tag, QStringLiteral("MultiplicityRange"))) { m_Multi = tempElement.text().trimmed(); continue; } QString multiUpper; if (tempElement.hasAttribute(QStringLiteral("lower"))) { m_Multi = tempElement.attribute(QStringLiteral("lower")); multiUpper = tempElement.attribute(QStringLiteral("upper")); if (!multiUpper.isEmpty()) { if (!m_Multi.isEmpty()) m_Multi.append(QStringLiteral("..")); m_Multi.append(multiUpper); } continue; } n = tempElement.firstChild(); while (!n.isNull()) { tempElement = n.toElement(); tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("MultiplicityRange.lower"))) { m_Multi = tempElement.text(); } else if (UMLDoc::tagEq(tag, QStringLiteral("MultiplicityRange.upper"))) { multiUpper = tempElement.text(); } n = n.nextSibling(); } if (!multiUpper.isEmpty()) { if (!m_Multi.isEmpty()) m_Multi.append(QStringLiteral("..")); m_Multi.append(multiUpper); } } else if (m_SecondaryId.isEmpty() && (UMLDoc::tagEq(tag, QStringLiteral("type")) || UMLDoc::tagEq(tag, QStringLiteral("participant")))) { m_SecondaryId = Model_Utils::getXmiId(tempElement); if (m_SecondaryId.isEmpty()) m_SecondaryId = tempElement.attribute(QStringLiteral("xmi.idref")); if (m_SecondaryId.isEmpty()) { QDomNode inner = tempElement.firstChild(); QDomElement innerElem = inner.toElement(); m_SecondaryId = Model_Utils::getXmiId(innerElem); if (m_SecondaryId.isEmpty()) m_SecondaryId = innerElem.attribute(QStringLiteral("xmi.idref")); } } } if (!m_Multi.isEmpty()) logDebug2("UMLRole::load1 %1: m_Multi is %2", name(), m_Multi); if (m_SecondaryId.isEmpty()) { logError1("UMLRole::load1(%1) : type not given or illegal", name()); return false; } UMLObject * obj; obj = doc->findObjectById(Uml::ID::fromString(m_SecondaryId)); if (obj) { m_pSecondary = obj; m_SecondaryId = QString(); } // block signals to prevent needless updating blockSignals(true); // Here comes the handling of the association type. // This is open for discussion - I'm pretty sure there are better ways.. // Yeah, for one, setting the *parent* object parameters from here is sucky // as hell. Why are we using roleA to store what is essentially a parent (association) // parameter, eh? The UML13.dtd is pretty silly, but since that is what // is driving us to that point, we have to go with it. Some analysis of // the component roles/linked items needs to be done in order to get things // right. *sigh* -b.t. // Setting association type from the role (A) // Determination of the "aggregation" attribute used to be done only // when (m_role == Uml::RoleType::A) but some XMI writers (e.g. StarUML) place // the aggregation attribute at role B. // The role end with the aggregation unequal to "none" wins. QString aggregation = element.attribute(QStringLiteral("aggregation"), QStringLiteral("none")); if (aggregation == QStringLiteral("composite")) m_pAssoc->setAssociationType(Uml::AssociationType::Composition); else if (aggregation == QStringLiteral("shared") // UML1.3 || aggregation == QStringLiteral("aggregate")) // UML1.4 m_pAssoc->setAssociationType(Uml::AssociationType::Aggregation); if (!element.hasAttribute(QStringLiteral("isNavigable"))) { // Backward compatibility mode: In Umbrello version 1.3.x the // logic for saving the isNavigable flag was wrong. // May happen on loading role A. m_pAssoc->setOldLoadMode(true); } else if (m_pAssoc->getOldLoadMode() == true) { // Here is the original logic: // "Role B: // If isNavigable is not given, we make no change to the // association type. // If isNavigable is given, and is "true", then we assume that // the association's other end (role A) is not navigable, and // therefore we change the association type to UniAssociation. // The case that isNavigable is given as "false" is ignored. // Combined with the association type logic for role A, this // allows us to support at_Association and at_UniAssociation." if (element.attribute(QStringLiteral("isNavigable")) == QStringLiteral("true")) m_pAssoc->setAssociationType(Uml::AssociationType::UniAssociation); } else if (element.attribute(QStringLiteral("isNavigable")) == QStringLiteral("false")) { m_pAssoc->setAssociationType(Uml::AssociationType::UniAssociation); } //FIXME not standard XMI if (element.hasAttribute(QStringLiteral("relationship"))) { if (element.attribute(QStringLiteral("relationship")) == QStringLiteral("true")) { m_pAssoc->setAssociationType(Uml::AssociationType::Relationship); } } if (m_Multi.isEmpty()) m_Multi = element.attribute(QStringLiteral("multiplicity")); // Changeability defaults to Changeable if it cant set it here.. m_Changeability = Uml::Changeability::Changeable; QString changeability = element.attribute(QStringLiteral("changeability")); if (changeability.isEmpty()) element.attribute(QStringLiteral("changeable")); // for backward compatibility if (changeability == QStringLiteral("frozen")) m_Changeability = Uml::Changeability::Frozen; else if (changeability == QStringLiteral("addOnly")) m_Changeability = Uml::Changeability::AddOnly; // finished config, now unblock blockSignals(false); return true; }
15,402
C++
.cpp
392
32.089286
99
0.63569
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,479
folder.cpp
KDE_umbrello/umbrello/umlmodel/folder.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "folder.h" // app includes #include "debug_utils.h" #include "dialog_utils.h" #include "model_utils.h" #include "object_factory.h" #include "optionstate.h" #include "uml.h" #include "umldoc.h" #include "umlscene.h" #include "umlview.h" #include "datatype.h" // kde includes #include <KLocalizedString> #include <KMessageBox> // qt includes #include <QFile> #include <QXmlStreamWriter> DEBUG_REGISTER(UMLFolder) /** * Sets up a Folder. * @param name The name of the Folder. * @param id The unique id of the Folder. A new ID will be generated * if this argument is left away. */ UMLFolder::UMLFolder(const QString & name, Uml::ID::Type id) : UMLPackage(name, id) { m_BaseType = UMLObject::ot_Folder; UMLObject::setStereotypeCmd(QStringLiteral("folder")); } /** * Empty destructor. */ UMLFolder::~UMLFolder() { qDeleteAll(m_diagrams); m_diagrams.clear(); } /** * Make a clone of this object. */ UMLObject* UMLFolder::clone() const { UMLFolder *clone = new UMLFolder(); UMLObject::copyInto(clone); return clone; } /** * Set the localized name of this folder. * This is set for the predefined root views (Logical, * UseCase, Component, Deployment, EntityRelationship, * and the Datatypes folder inside the Logical View.) */ void UMLFolder::setLocalName(const QString& localName) { m_localName = localName; } /** * Return the localized name of this folder. * Only useful for the predefined root folders. */ QString UMLFolder::localName() const { return m_localName; } /** * Add a view to the diagram list. */ void UMLFolder::addView(UMLView *view) { m_diagrams.append(view); } /** * Remove a view from the diagram list. */ void UMLFolder::removeView(UMLView *view) { m_diagrams.removeAll(view); } /** * Append the views in this folder to the given diagram list. * @param viewList The UMLViewList to which to append the diagrams. * @param includeNested Whether to include diagrams from nested folders * (default: true.) */ void UMLFolder::appendViews(UMLViewList& viewList, bool includeNested) { if (includeNested) { for(UMLObject* o : m_objects) { uIgnoreZeroPointer(o); if (o->baseType() == UMLObject::ot_Folder) { UMLFolder *f = o->asUMLFolder(); f->appendViews(viewList); } } } for(UMLView* v : m_diagrams) { viewList.append(v); } } /** * Activate the views in this folder. * "Activation": Some widgets require adjustments after loading from file, * those are done here. */ void UMLFolder::activateViews() { for(UMLObject* o : m_objects) { uIgnoreZeroPointer(o); if (o->baseType() == UMLObject::ot_Folder) { UMLFolder *f = o->asUMLFolder(); f->activateViews(); } } for(UMLView* v : m_diagrams) { UMLScene *scene = v->umlScene(); scene->activateAfterLoad(); uDebug() << "UMLFolder::activateViews: " << scene->name() << " sceneRect = " << scene->sceneRect(); } // Make sure we have a treeview item for each diagram. // It may happen that we are missing them after switching off tabbed widgets. Settings::OptionState optionState = Settings::optionState(); if (optionState.generalState.tabdiagrams) { return; } Model_Utils::treeViewAddViews(m_diagrams); } /** * Seek a view of the given ID in this folder. * @param id ID of the view to find. * @return Pointer to the view if found, NULL if no view found. */ UMLView *UMLFolder::findView(Uml::ID::Type id) { for(UMLView* v : m_diagrams) { if (v && v->umlScene() && v->umlScene()->ID() == id) { return v; } } UMLView *v = nullptr; UMLPackageList packages; appendPackages(packages); for(UMLPackage *o : packages) { if (o->baseType() != UMLObject::ot_Folder) { continue; } UMLFolder *f = o->asUMLFolder(); v = f->findView(id); if (v) { break; } } return v; } /** * Seek a view by the type and name given. * @param type The type of view to find. * @param name The name of the view to find. * @param searchAllScopes Search in all subfolders (default: true.) * @return Pointer to the view found, or NULL if not found. */ UMLView *UMLFolder::findView(Uml::DiagramType::Enum type, const QString &name, bool searchAllScopes) { for(UMLView *v : m_diagrams) { if (v->umlScene()->type() == type && v->umlScene()->name() == name) { return v; } } UMLView *v = nullptr; if (searchAllScopes) { for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); if (o->baseType() != UMLObject::ot_Folder) { continue; } UMLFolder *f = o->asUMLFolder(); v = f->findView(type, name, searchAllScopes); if (v) { break; } } } return v; } /** * Set the options for the views in this folder. */ void UMLFolder::setViewOptions(const Settings::OptionState& optionState) { // for each view update settings for(UMLView *v : m_diagrams) { v->umlScene()->setOptionState(optionState); } } /** * Remove all views in this folder. */ void UMLFolder::removeAllViews() { for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); if (o->baseType() != UMLObject::ot_Folder) continue; UMLFolder *f = o->asUMLFolder(); f->removeAllViews(); } for(UMLView *v : m_diagrams) { // TODO ------------------ check this code - bad: calling back to UMLDoc::removeView() v->umlScene()->removeAllAssociations(); // note : It may not be apparent, but when we remove all associations // from a view, it also causes any UMLAssociations that lack parent // association widgets (but once had them) to remove themselves from // this document. logDebug1("UMLFolder::removeAllViews: removing %1", v->umlScene()->name()); UMLApp::app()->document()->removeView(v, false); } qDeleteAll(m_diagrams); m_diagrams.clear(); } /** * Set the folder file name for a separate submodel. */ void UMLFolder::setFolderFile(const QString& fileName) { m_folderFile = fileName; } /** * Get the folder file name for a separate submodel. */ QString UMLFolder::folderFile() const { return m_folderFile; } /** * Auxiliary to saveToXMI(): Save the contained objects and diagrams. * Can be used regardless of whether saving to the main model file * or to an external folder file (see m_folderFile.) */ void UMLFolder::saveContents(QXmlStreamWriter& writer) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Namespace.ownedElement")); } // Save contained objects if any. for(UMLObject *obj : m_objects) { uIgnoreZeroPointer(obj); obj->saveToXMI (writer); } // Save associations if any. for(UMLObject *obj : subordinates()) { obj->saveToXMI (writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); } // Save diagrams to `extension'. if (m_diagrams.count()) { if (Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("xmi:Extension")); writer.writeAttribute(QStringLiteral("extender"), QStringLiteral("umbrello")); } else { writer.writeStartElement(QStringLiteral("XMI.extension")); writer.writeAttribute(QStringLiteral("xmi.extender"), QStringLiteral("umbrello")); } writer.writeStartElement(QStringLiteral("diagrams")); if (!qFuzzyIsNull(UMLApp::app()->document()->resolution())) { writer.writeAttribute(QStringLiteral("resolution"), QString::number(UMLApp::app()->document()->resolution())); } for(UMLView *pView : m_diagrams) { pView->umlScene()->saveToXMI(writer); } writer.writeEndElement(); // diagrams writer.writeEndElement(); // XMI.extension } } /** * Auxiliary to saveToXMI(): * - In UML1 mode it creates a <UML:Model> element when saving a predefined * modelview, or a <UML:Package> element when saving a user created folder. * - In UML2 mode it creates a \<packagedElement xmi:type="uml:Model"> when * saving a predefined view, or a \<packagedElement xmi:type="uml:Package"> * when saving a user created folder. * Invokes saveContents() with the newly created element. */ void UMLFolder::save1(QXmlStreamWriter& writer) { UMLDoc *umldoc = UMLApp::app()->document(); QString elementName(QStringLiteral("Package")); QString elementTag (QStringLiteral("<use_type_as_tag>")); const Uml::ModelType::Enum mt = umldoc->rootFolderType(this); if (mt != Uml::ModelType::N_MODELTYPES) { elementName = QStringLiteral("Model"); if (Settings::optionState().generalState.uml2) elementTag = QStringLiteral("packagedElement"); } UMLObject::save1(writer, elementName, elementTag); saveContents(writer); writer.writeEndElement(); } /** * Saves the folder in XMI representation: * If m_folderFile is empty then calls save1(). * If m_folderFile is non empty then * - creates an XMI Extension stub for the folder in the main XMI file; * - creates the external file for the submodel and writes its XMI. */ void UMLFolder::saveToXMI(QXmlStreamWriter& writer) { if (m_folderFile.isEmpty()) { save1(writer); return; } // See if we can create the external file. // If not then internalize the folder. UMLDoc *umldoc = UMLApp::app()->document(); QString fileName = umldoc->url().adjusted(QUrl::RemoveFilename).path() + m_folderFile; QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { logError1("UMLFolder::saveToXMI(%1) : cannot create file. Content will be saved in main model file", m_folderFile); m_folderFile.clear(); save1(writer); return; } // External file is writable. Create XMI.extension stub in main file. UMLObject::save1(writer, QStringLiteral("Package")); if (Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("xmi:Extension")); writer.writeAttribute(QStringLiteral("extender"), QStringLiteral("umbrello")); } else { writer.writeStartElement(QStringLiteral("XMI.extension")); writer.writeAttribute(QStringLiteral("xmi.extender"), QStringLiteral("umbrello")); } writer.writeStartElement(QStringLiteral("external_file")); writer.writeAttribute(QStringLiteral("name"), m_folderFile); writer.writeEndElement(); // external_file writer.writeEndElement(); // XMI.extension writer.writeEndElement(); // UML:Package // Write the external file. QXmlStreamWriter xfWriter(&file); xfWriter.setCodec("UTF-8"); xfWriter.setAutoFormatting(true); xfWriter.setAutoFormattingIndent(2); xfWriter.writeStartDocument(); xfWriter.writeStartElement(QStringLiteral("external_file")); xfWriter.writeAttribute(QStringLiteral("name"), name()); xfWriter.writeAttribute(QStringLiteral("filename"), m_folderFile); xfWriter.writeAttribute(QStringLiteral("mainModel"), umldoc->url().fileName()); xfWriter.writeAttribute(QStringLiteral("parentId"), Uml::ID::toString(umlPackage()->id())); xfWriter.writeAttribute(QStringLiteral("parent"), umlPackage()->fullyQualifiedName(QStringLiteral("::"), true)); saveContents(xfWriter); xfWriter.writeEndElement(); file.close(); } /** * Auxiliary to load(): * Load the diagrams from the "diagrams" in the <XMI.extension> */ bool UMLFolder::loadDiagramsFromXMI1(QDomNode& node) { qreal resolution = 0.0; QString res = node.toElement().attribute(QStringLiteral("resolution"), QStringLiteral("")); if (!res.isEmpty()) { resolution = res.toDouble(); } if (!qFuzzyIsNull(resolution)) { UMLApp::app()->document()->setResolution(resolution); } else { /* FIXME how to get dpi ? * 1. from user -> will open a dialog box for any old file * 2. after loading from user changeable document settings * 3. estimated from contained widgets */ UMLApp::app()->document()->setResolution(0.0); } QDomNode diagrams = node.firstChild(); const Settings::OptionState optionState = Settings::optionState(); UMLDoc *umldoc = UMLApp::app()->document(); bool totalSuccess = true; for (QDomElement diagram = diagrams.toElement(); !diagram.isNull(); diagrams = diagrams.nextSibling(), diagram = diagrams.toElement()) { QString tag = diagram.tagName(); if (tag != QStringLiteral("diagram")) { logDebug1("UMLFolder::loadDiagramsFromXMI1: ignoring %1 in <diagrams>", tag); continue; } UMLView * pView = new UMLView(this); pView->umlScene()->setOptionState(optionState); if (pView->umlScene()->loadFromXMI(diagram)) { pView->hide(); umldoc->addView(pView); } else { delete pView; totalSuccess = false; } } return totalSuccess; } /** * Folders in the listview can be marked such that their contents * are saved to a separate file. * This method loads the separate folder file. * CAVEAT: This is not XMI standard compliant. * If standard compliance is an issue then avoid folder files. * @param path Fully qualified file name, i.e. absolute directory * plus file name. * @return True for success. */ bool UMLFolder::loadFolderFile(const QString& path) { QFile file(path); if (!file.exists()) { KMessageBox::error(nullptr, i18n("The folderfile %1 does not exist.", path), i18n("Load Error")); return false; } if (!file.open(QIODevice::ReadOnly)) { KMessageBox::error(nullptr, i18n("The folderfile %1 cannot be opened.", path), i18n("Load Error")); return false; } QTextStream stream(&file); QString data = stream.readAll(); file.close(); QDomDocument doc; QString error; int line; if (!doc.setContent(data, false, &error, &line)) { logError2("UMLFolder::loadFolderFile cannot set content: error %1 line %2", error, line); return false; } QDomNode rootNode = doc.firstChild(); while (rootNode.isComment() || rootNode.isProcessingInstruction()) { rootNode = rootNode.nextSibling(); } if (rootNode.isNull()) { logError0("UMLFolder::loadFolderFile: Root node is null"); return false; } QDomElement element = rootNode.toElement(); QString type = element.tagName(); if (type != QStringLiteral("external_file")) { logError1("UMLFolder::loadFolderFile: Root node has unknown type %1", type); return false; } return load1(element); } /** * Loads the owned elements of the \<packagedElement xmi:type="uml:Model"> * (in UML2 mode) or <UML:Model> (in UML1 mode). */ bool UMLFolder::load1(QDomElement& element) { UMLDoc *umldoc = UMLApp::app()->document(); bool totalSuccess = true; for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; QDomElement tempElement = node.toElement(); QString type = tempElement.tagName(); if (Model_Utils::isCommonXMI1Attribute(type)) continue; if (UMLDoc::tagEq(type, QStringLiteral("Namespace.ownedElement")) || UMLDoc::tagEq(type, QStringLiteral("Namespace.contents"))) { //CHECK: Umbrello currently assumes that nested elements // are ownedElements anyway. // Therefore these tags are not further interpreted. if (! load1(tempElement)) { logDebug2("UMLFolder::load1 %1: An error happened while loading %2", name(), type); totalSuccess = false; } continue; } else if (type == QStringLiteral("packagedElement") || type == QStringLiteral("ownedElement")) { type = tempElement.attribute(QStringLiteral("xmi:type")); } else if (type == QStringLiteral("XMI.extension") || type == QStringLiteral("xmi:Extension")) { for (QDomNode xtnode = node.firstChild(); !xtnode.isNull(); xtnode = xtnode.nextSibling()) { QDomElement el = xtnode.toElement(); const QString xtag = el.tagName(); if (xtag == QStringLiteral("diagrams")) { umldoc->addDiagramToLoad(this, xtnode); } else if (xtag == QStringLiteral("external_file")) { const QString rootDir(umldoc->url().adjusted(QUrl::RemoveFilename).path()); QString fileName = el.attribute(QStringLiteral("name")); const QString path(rootDir + QLatin1Char('/') + fileName); if (loadFolderFile(path)) m_folderFile = fileName; } else { logDebug2("UMLFolder::load1 %1: ignoring XMI.extension %2", name(), xtag); continue; } } continue; } // Do not re-create the predefined Datatypes folder in the Logical View, // it already exists. UMLFolder *logicalView = umldoc->rootFolder(Uml::ModelType::Logical); if (this == logicalView && UMLDoc::tagEq(type, QStringLiteral("Package"))) { QString thisName = tempElement.attribute(QStringLiteral("name")); if (thisName == QStringLiteral("Datatypes")) { UMLFolder *datatypeFolder = umldoc->datatypeFolder(); if (!datatypeFolder->loadFromXMI(tempElement)) totalSuccess = false; continue; } } UMLObject *pObject = nullptr; // Avoid duplicate creation of forward declared object QString idStr = Model_Utils::getXmiId(tempElement); if (!idStr.isEmpty()) { Uml::ID::Type id = Uml::ID::fromString(idStr); pObject = umldoc->findObjectById(id); if (pObject) { logDebug1("UMLFolder::load1: object %1 already exists", idStr); } } // Avoid duplicate creation of datatype if (pObject == nullptr && this == umldoc->datatypeFolder()) { QString name = tempElement.attribute(QStringLiteral("name")); for(UMLObject *o : m_objects) { uIgnoreZeroPointer(o); if (o->name() == name) { UMLDatatype *dt = o->asUMLDatatype(); if (dt) { QString isActive = tempElement.attribute(QStringLiteral("isActive")); dt->setActive(isActive != QStringLiteral("false")); pObject = dt; break; } } } } if (pObject == nullptr) { QString stereoID = tempElement.attribute(QStringLiteral("stereotype")); pObject = Object_Factory::makeObjectFromXMI(type, stereoID); if (!pObject) { logWarn1("UMLFolder::load1 unknown type of umlobject to create: %1", type); continue; } } pObject->setUMLPackage(this); if (!pObject->loadFromXMI(tempElement)) { removeObject(pObject); delete pObject; totalSuccess = false; } } return totalSuccess; } bool UMLFolder::showPropertiesDialog(QWidget *parent) { Q_UNUSED(parent); QString folderName = this->name(); bool ok = Dialog_Utils::askRenameName(UMLObject::ot_Folder, folderName); if (ok) { setName(folderName); } return ok; } /** * Overloading operator for debugging output. */ QDebug operator<<(QDebug out, const UMLFolder& item) { out.nospace() << "UMLFolder: localName=" << item.m_localName << ", folderFile=" << item.m_folderFile << ", diagrams=" << item.m_diagrams.count(); return out.space(); }
20,757
C++
.cpp
576
29.407986
117
0.629188
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,480
classifier.cpp
KDE_umbrello/umbrello/umlmodel/classifier.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "classifier.h" // app includes #include "association.h" #include "debug_utils.h" #include "umlassociationlist.h" #include "operation.h" #include "attribute.h" #include "template.h" #include "enumliteral.h" #include "entityattribute.h" #include "enum.h" #include "entity.h" #include "stereotype.h" #include "umldoc.h" #include "uml.h" #include "uniqueid.h" #include "object_factory.h" #include "model_utils.h" #include "idchangelog.h" #include "umloperationdialog.h" #include "umlattributedialog.h" #include "umltemplatedialog.h" #include "optionstate.h" #include "icon_utils.h" #include "instance.h" #include "instanceattribute.h" #include "optionstate.h" // kde includes #include <KLocalizedString> #include <KMessageBox> // qt includes #include <QPointer> using namespace Uml; DEBUG_REGISTER(UMLClassifier) /** * @brief holds set of classifiers for recursive loop detection */ class UMLClassifierSet: public QSet<const UMLClassifier *> { public: UMLClassifierSet() : level(0) { } int level; }; /** * Sets up a Classifier. * * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLClassifier::UMLClassifier(const QString & name, Uml::ID::Type id) : UMLPackage(name, id) { m_BaseType = UMLObject::ot_Class; // default value m_pClassAssoc = nullptr; } /** * Standard deconstructor. */ UMLClassifier::~UMLClassifier() { } /** * Reimplementation of method from class UMLObject for controlling the * exact type of this classifier: class, interface, or datatype. * @param ot the base type to set */ void UMLClassifier::setBaseType(UMLObject::ObjectType ot) { m_BaseType = ot; Icon_Utils::IconType newIcon; switch (ot) { case ot_Interface: UMLObject::setStereotypeCmd(QStringLiteral("interface")); UMLObject::m_bAbstract = true; newIcon = Icon_Utils::it_Interface; break; case ot_Class: UMLObject::setStereotypeCmd(QString()); UMLObject::m_bAbstract = false; newIcon = Icon_Utils::it_Class; break; case ot_Datatype: UMLObject::setStereotypeCmd(QStringLiteral("datatype")); UMLObject::m_bAbstract = false; newIcon = Icon_Utils::it_Datatype; break; case ot_Package: UMLObject::setStereotypeCmd(QString()); UMLObject::m_bAbstract = false; newIcon = Icon_Utils::it_Package; break; default: logError2("UMLClassifier %1 setBaseType : cannot set to type %2", name(), ot); return; } Model_Utils::treeViewChangeIcon(this, newIcon); } /** * Returns true if this classifier represents an interface. */ bool UMLClassifier::isInterface() const { return (m_BaseType == ot_Interface); } /** * Checks whether an operation is valid based on its signature - * An operation is "valid" if the operation's name and parameter list * are unique in the classifier. * * @param name Name of the operation to check. * @param opParams The operation's argument list. * @param exemptOp Pointer to the exempt method (optional.) * @return NULL if the signature is valid (ok), else return a pointer * to the existing UMLOperation that causes the conflict. */ UMLOperation * UMLClassifier::checkOperationSignature( const QString& name, UMLAttributeList opParams, UMLOperation *exemptOp) const { UMLOperationList list = findOperations(name); if (list.count() == 0) { return nullptr; } const int inputParmCount = opParams.count(); // there is at least one operation with the same name... compare the parameter list for(UMLOperation* test : list) { if (test == exemptOp) { continue; } UMLAttributeList testParams = test->getParmList(); const int pCount = testParams.count(); if (pCount != inputParmCount) { continue; } int i = 0; while (i < pCount) { // The only criterion for equivalence is the parameter types. // (Default values are not considered.) if(testParams.at(i)->getTypeName() != opParams.at(i)->getTypeName()) break; i++; } if (i == pCount) { // all parameters matched->the signature is not unique return test; } } // we did not find an exact match, so the signature is unique (acceptable) return nullptr; } /** * Find an operation of the given name and parameter signature. * * @param name The name of the operation to find. * @param params The parameter descriptors of the operation to find. * * @return The operation found. Will return 0 if none found. */ UMLOperation* UMLClassifier::findOperation(const QString& name, Model_Utils::NameAndType_List params) const { UMLOperationList list = findOperations(name); if (list.count() == 0) { return nullptr; } // if there are operation(s) with the same name then compare the parameter list const int inputParmCount = params.count(); for(UMLOperation* test : list) { UMLAttributeList testParams = test->getParmList(); const int pCount = testParams.count(); if (inputParmCount == 0 && pCount == 0) return test; if (inputParmCount != pCount) continue; int i = 0; for (; i < pCount; ++i) { Model_Utils::NameAndType_ListIt nt(params.begin() + i); UMLClassifier *type = (*nt).m_type->asUMLClassifier(); UMLClassifier *testType = testParams.at(i)->getType(); if (type == nullptr && testType == nullptr) { //no parameter type continue; } else if (type == nullptr) { //template parameter if (testType->name() != QStringLiteral("class")) break; } else if (type != testType) break; } if (i == pCount) return test; // all parameters matched } return nullptr; } /** * Creates an operation in the current document. * The new operation is initialized with name, id, etc. * If a method with the given profile already exists in the classifier, * no new method is created and the existing operation is returned. * If no name is provided, or if the params are 0, an Operation * Dialog is shown to ask the user for a name and parameters. * The operation's signature is checked for validity within the parent * classifier. * * @param name The operation name (will be chosen internally if * none given.) * @param isExistingOp Optional pointer to bool. If supplied, the bool is * set to true if an existing operation is returned. * @param params Optional list of parameter names and types. * If supplied, new operation parameters are * constructed using this list. * @return The new operation, or NULL if the operation could not be * created because for example, the user canceled the dialog * or no appropriate name can be found. */ UMLOperation* UMLClassifier::createOperation( const QString &name /*=QString()*/, bool *isExistingOp /*= nullptr*/, Model_Utils::NameAndType_List *params /*= nullptr*/) { bool nameNotSet = (name.isNull() || name.isEmpty()); if (! nameNotSet) { Model_Utils::NameAndType_List parList; if (params) parList = *params; UMLOperation* existingOp = findOperation(name, parList); if (existingOp != nullptr) { if (isExistingOp != nullptr) *isExistingOp = true; return existingOp; } } // we did not find an exact match, so the signature is unique UMLOperation *op = new UMLOperation(this, name); if (params) { for (Model_Utils::NameAndType_ListIt it = params->begin(); it != params->end(); ++it) { const Model_Utils::NameAndType &nt = *it; UMLAttribute *par = new UMLAttribute(op, nt.m_name, Uml::ID::None, Uml::Visibility::Private, nt.m_type, nt.m_initialValue); par->setParmKind(nt.m_direction); op->addParm(par); } } if (isInterface()) { op->setAbstract(true); op->setVirtual(true); } // Only show the operation dialog if no name was provided (allows quick-create // from listview) if (nameNotSet) { op->setName(uniqChildName(UMLObject::ot_Operation)); while (true) { QPointer<UMLOperationDialog> operationDialog = new UMLOperationDialog(nullptr, op); if(operationDialog->exec() != QDialog::Accepted) { delete op; delete operationDialog; return nullptr; } else if (checkOperationSignature(op->name(), op->getParmList())) { KMessageBox::information(nullptr, i18n("An operation with the same name and signature already exists. You cannot add it again.")); } else { break; } delete operationDialog; } } // operation name is ok, formally add it to the classifier if (! addOperation(op)) { delete op; return nullptr; } UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(op); return op; } /** * Appends an operation to the classifier. * This function is mainly intended for the clipboard. * * @param op Pointer to the UMLOperation to add. * @param position Inserted at the given position. * @return True if the operation was added successfully. */ bool UMLClassifier::addOperation(UMLOperation* op, int position) { Q_ASSERT(op); if (subordinates().indexOf(op) != -1) { logDebug1("UMLClassifier::addOperation: findRef(%1) finds op (bad)", op->name()); return false; } if (checkOperationSignature(op->name(), op->getParmList())) { logDebug1("UMLClassifier::addOperation: checkOperationSignature(%1) op is non-unique", op->name()); return false; } if (position >= 0 && position <= subordinates().count()) { logDebug2("UMLClassifier::addOperation(%1): inserting at position %2", op->name(), position); subordinates().insert(position, op); UMLClassifierListItemList itemList = getFilteredList(UMLObject::ot_Operation); QString buf; for(UMLClassifierListItem* currentAtt : itemList) { buf.append(QLatin1Char(' ') + currentAtt->name()); } logDebug1("UMLClassifier::addOperation list after change:%1", buf); } else { subordinates().append(op); } Q_EMIT operationAdded(op); UMLObject::emitModified(); connect(op, SIGNAL(modified()), this, SIGNAL(modified())); return true; } /** * Appends an operation to the classifier. * @see bool addOperation(UMLOperation* Op, int position = -1) * This function is mainly intended for the clipboard. * * @param op Pointer to the UMLOperation to add. * @param log Pointer to the IDChangeLog. * @return True if the operation was added successfully. */ bool UMLClassifier::addOperation(UMLOperation* op, IDChangeLog* log) { if (addOperation(op, -1)) { return true; } else if (log) { log->removeChangeByNewID(op->id()); } return false; } /** * Remove an operation from the Classifier. * The operation is not deleted so the caller is responsible for what * happens to it after this. * * @param op The operation to remove. * @return Count of the remaining operations after removal, or * -1 if the given operation was not found. */ int UMLClassifier::removeOperation(UMLOperation *op) { if (op == nullptr) { logDebug0("UMLClassifier::removeOperation called on NULL op"); return -1; } if (!subordinates().removeAll(op)) { logDebug1("UMLClassifier::removeOperation cannot find op %1 in list", op->name()); return -1; } // disconnection needed. // note that we don't delete the operation, just remove it from the Classifier disconnect(op, SIGNAL(modified()), this, SIGNAL(modified())); Q_EMIT operationRemoved(op); UMLObject::emitModified(); return subordinates().count(); } /** * Create and add a just created template. * @param currentName the name of the template * @return the template or NULL */ UMLObject* UMLClassifier::createTemplate(const QString& currentName /*= QString()*/) { QString name = currentName; bool goodName = !name.isEmpty(); if (!goodName) { name = uniqChildName(UMLObject::ot_Template); } UMLTemplate* newTemplate = new UMLTemplate(this, name); int button = QDialog::Accepted; while (button == QDialog::Accepted && !goodName) { QPointer<UMLTemplateDialog> templateDialog = new UMLTemplateDialog(nullptr, newTemplate); button = templateDialog->exec(); name = newTemplate->name(); if (name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else if (findChildObject(name) != nullptr) { KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name")); } else { goodName = true; } delete templateDialog; } if (button != QDialog::Accepted) { return nullptr; } addTemplate(newTemplate); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newTemplate); return newTemplate; } /** * Returns the attributes for the specified scope. * @return List of true attributes for the class. */ UMLAttributeList UMLClassifier::getAttributeList() const { UMLAttributeList attributeList; for(UMLObject* listItem : subordinates()) { if (listItem->baseType() == UMLObject::ot_Attribute) { attributeList.append(listItem->asUMLAttribute()); } } return attributeList; } /** * Returns the attributes for the specified scope. * @param scope The scope of the attribute. * @return List of true attributes for the class. */ UMLAttributeList UMLClassifier::getAttributeList(Visibility::Enum scope) const { UMLAttributeList list; if (!isInterface()) { UMLAttributeList atl = getAttributeList(); for(UMLAttribute* at : atl) { uIgnoreZeroPointer(at); if (! at->isStatic()) { if (scope == Uml::Visibility::Private) { if ((at->visibility() == Uml::Visibility::Private) || (at->visibility() == Uml::Visibility::Implementation)) { list.append(at); } } else if (scope == at->visibility()) { list.append(at); } } } } return list; } /** * Returns the static attributes for the specified scope. * * @param scope The scope of the attribute. * @return List of true attributes for the class. */ UMLAttributeList UMLClassifier::getAttributeListStatic(Visibility::Enum scope) const { UMLAttributeList list; if (!isInterface()) { UMLAttributeList atl = getAttributeList(); for(UMLAttribute* at : atl) { uIgnoreZeroPointer(at); if (at->isStatic()) { if (scope == Uml::Visibility::Private) { if ((at->visibility() == Uml::Visibility::Private) || (at->visibility() == Uml::Visibility::Implementation)) { list.append(at); } } else if (scope == at->visibility()) { list.append(at); } } } } return list; } /** * Find a list of operations with the given name. * * @param n The name of the operation to find. * @return The list of objects found; will be empty if none found. */ UMLOperationList UMLClassifier::findOperations(const QString &n) const { const bool caseSensitive = UMLApp::app()->activeLanguageIsCaseSensitive(); UMLOperationList list; for(UMLObject* obj : subordinates()) { if (obj->baseType() != UMLObject::ot_Operation) continue; UMLOperation *op = obj->asUMLOperation(); if (caseSensitive) { if (obj->name() == n) list.append(op); } else if (obj->name().toLower() == n.toLower()) { list.append(op); } } return list; } /** * Find the child object by the given id. * @param id the id of the child object * @param considerAncestors flag whether the ancestors should be considered during search * @return the found child object or NULL */ UMLObject* UMLClassifier::findChildObjectById(Uml::ID::Type id, bool considerAncestors /* =false */) const { UMLObject *o = UMLCanvasObject::findChildObjectById(id); if (o) { return o; } if (considerAncestors) { UMLClassifierList ancestors = findSuperClassConcepts(); for(UMLClassifier *anc : ancestors) { UMLObject *o = anc->findChildObjectById(id); if (o) { return o; } } } return nullptr; } /** * Returns a list of concepts which inherit from this classifier. * * @param type The ClassifierType to seek. * @return List of UMLClassifiers that inherit from us. */ UMLClassifierList UMLClassifier::findSubClassConcepts (ClassifierType type) const { UMLClassifierList list = getSubClasses(); UMLAssociationList rlist = getRealizations(); UMLClassifierList inheritingConcepts; Uml::ID::Type myID = id(); for(UMLClassifier *c : list) { uIgnoreZeroPointer(c); if (type == ALL || (!c->isInterface() && type == CLASS) || (c->isInterface() && type == INTERFACE)) { inheritingConcepts.append(c); } } for(UMLAssociation *a : rlist) { uIgnoreZeroPointer(a); if (a->getObjectId(RoleType::A) != myID) { UMLObject* obj = a->getObject(RoleType::A); UMLClassifier *classifier = obj->asUMLClassifier(); if (classifier && (type == ALL || (!classifier->isInterface() && type == CLASS) || (classifier->isInterface() && type == INTERFACE)) && (inheritingConcepts.indexOf(classifier) == -1)) { inheritingConcepts.append(classifier); } } } return inheritingConcepts; } /** * Returns a list of concepts which this classifier inherits from. * * @param type The ClassifierType to seek. * @return List of UMLClassifiers we inherit from. */ UMLClassifierList UMLClassifier::findSuperClassConcepts (ClassifierType type) const { UMLClassifierList list = getSuperClasses(); UMLAssociationList rlist = getRealizations(); UMLClassifierList parentConcepts; Uml::ID::Type myID = id(); for (UMLClassifier *classifier : list) { uIgnoreZeroPointer(classifier); if (type == ALL || (!classifier->isInterface() && type == CLASS) || (classifier->isInterface() && type == INTERFACE)) parentConcepts.append(classifier); } for(UMLAssociation *a : rlist) { if (a->getObjectId(RoleType::A) == myID) { UMLObject* obj = a->getObject(RoleType::B); UMLClassifier *classifier = obj->asUMLClassifier(); if (classifier && (type == ALL || (!classifier->isInterface() && type == CLASS) || (classifier->isInterface() && type == INTERFACE)) && (parentConcepts.indexOf(classifier) == -1)) parentConcepts.append(classifier); } } return parentConcepts; } /** * Copy the internal presentation of this object into the new * object. */ void UMLClassifier::copyInto(UMLObject *lhs) const { UMLClassifier *target = lhs->asUMLClassifier(); UMLCanvasObject::copyInto(target); target->setBaseType(m_BaseType); // CHECK: association property m_pClassAssoc is not copied subordinates().copyInto(&(target->subordinates())); for(UMLObject *o : target->subordinates()) { o->setUMLParent(target); } } /** * Make a clone of this object. */ UMLObject* UMLClassifier::clone() const { UMLClassifier *clone = new UMLClassifier(); copyInto(clone); return clone; } /** * override setting name of classifier * @param strName name to set */ void UMLClassifier::setNameCmd(const QString &strName) { if (UMLApp::app()->activeLanguage() == Uml::ProgrammingLanguage::Cpp || UMLApp::app()->activeLanguage() == Uml::ProgrammingLanguage::CSharp || UMLApp::app()->activeLanguage() == Uml::ProgrammingLanguage::Java) { for(UMLOperation *op : getOpList()) { if (op->isConstructorOperation()) op->setNameCmd(strName); if (op->isDestructorOperation()) op->setNameCmd(QStringLiteral("~") + strName); } } UMLObject::setNameCmd(strName); } /** * Needs to be called after all UML objects are loaded from file. * Calls the parent resolveRef(), and calls resolveRef() on all * UMLClassifierListItems. * Overrides the method from UMLObject. * * @return true for success. */ bool UMLClassifier::resolveRef() { bool success = UMLPackage::resolveRef(); // Using reentrant iteration is a bare necessity here: for(UMLObject* obj : subordinates()) { /**** For reference, here is the non-reentrant iteration scheme - DO NOT USE THIS ! for (UMLObject *obj = subordinates().first(); obj; obj = subordinates().next()) { .... } ****/ if (obj->resolveRef()) { UMLClassifierListItem *cli = obj->asUMLClassifierListItem(); if (!cli) continue; switch (cli->baseType()) { case UMLObject::ot_Attribute: Q_EMIT attributeAdded(cli); break; case UMLObject::ot_Operation: Q_EMIT operationAdded(cli); break; case UMLObject::ot_Template: Q_EMIT templateAdded(cli); break; default: break; } } } return success; } /** * Reimplemented from UMLObject. */ bool UMLClassifier::acceptAssociationType(AssociationType::Enum type) const { switch(type) { case AssociationType::Generalization: case AssociationType::Aggregation: case AssociationType::Relationship: case AssociationType::Dependency: case AssociationType::Association: case AssociationType::Association_Self: case AssociationType::Containment: case AssociationType::Composition: case AssociationType::Realization: case AssociationType::UniAssociation: return true; default: return false; } return false; //shutup compiler warning } /** * Creates an attribute for the class. * * @param name An optional name, used by when creating through UMLListView * @param type An optional type, used by when creating through UMLListView * @param vis An optional visibility, used by when creating through UMLListView * @param init An optional initial value, used by when creating through UMLListView * @return The UMLAttribute created */ UMLAttribute* UMLClassifier::createAttribute(const QString &name, UMLObject *type, Visibility::Enum vis, const QString &init) { Uml::ID::Type id = UniqueID::gen(); QString currentName; if (name.isNull()) { currentName = uniqChildName(UMLObject::ot_Attribute); } else { currentName = name; } UMLAttribute* newAttribute = new UMLAttribute(this, currentName, id, vis, type, init); int button = QDialog::Accepted; bool goodName = false; //check for name.isNull() stops dialog being shown //when creating attribute via list view while (button == QDialog::Accepted && !goodName && name.isNull()) { QPointer<UMLAttributeDialog> attributeDialog = new UMLAttributeDialog(nullptr, newAttribute); button = attributeDialog->exec(); QString name = newAttribute->name(); if(name.length() == 0) { KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name")); } else if (findChildObject(name) != nullptr) { KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name")); } else { goodName = true; } delete attributeDialog; } if (button != QDialog::Accepted) { delete newAttribute; return nullptr; } addAttribute(newAttribute); UMLDoc *umldoc = UMLApp::app()->document(); umldoc->signalUMLObjectCreated(newAttribute); return newAttribute; } /** * Creates and adds an attribute for the class. * * @param name an optional name, used by when creating through UMLListView * @param id an optional id * @return the UMLAttribute created and added */ UMLAttribute* UMLClassifier::addAttribute(const QString &name, Uml::ID::Type id /* = Uml::id_None */) { for(UMLObject* obj : subordinates()) { uIgnoreZeroPointer(obj); if (obj->baseType() == UMLObject::ot_Attribute && obj->name() == name) return obj->asUMLAttribute(); } Uml::Visibility::Enum scope = Settings::optionState().classState.defaultAttributeScope; UMLAttribute *a = new UMLAttribute(this, name, id, scope); subordinates().append(a); Q_EMIT attributeAdded(a); UMLObject::emitModified(); connect(a, SIGNAL(modified()), this, SIGNAL(modified())); return a; } /** * Adds an already created attribute. * The attribute object must not belong to any other classifier. * * @param name the name of the attribute * @param type the type of the attribute * @param scope the visibility of the attribute * @return the just created and added attribute */ UMLAttribute* UMLClassifier::addAttribute(const QString &name, UMLObject *type, Visibility::Enum scope) { UMLAttribute *a = new UMLAttribute(this); a->setName(name); a->setVisibility(scope); a->setID(UniqueID::gen()); if (type) { a->setType(type); } subordinates().append(a); Q_EMIT attributeAdded(a); UMLObject::emitModified(); connect(a, SIGNAL(modified()), this, SIGNAL(modified())); return a; } /** * Adds an already created attribute. * The attribute object must not belong to any other classifier. * * @param att Pointer to the UMLAttribute. * @param log Pointer to the IDChangeLog (optional.) * @param position Position index for the insertion (optional.) * If the position is omitted, or if it is * negative or too large, the attribute is added * to the end of the list. * @return True if the attribute was successfully added. */ bool UMLClassifier::addAttribute(UMLAttribute *att, IDChangeLog* log /* = nullptr */, int position /* = -1 */) { Q_ASSERT(att); if (findChildObject(att->name()) == nullptr) { att->setParent(this); if (position >= 0 && position < (int)subordinates().count()) { subordinates().insert(position, att); } else { subordinates().append(att); } Q_EMIT attributeAdded(att); UMLObject::emitModified(); connect(att, SIGNAL(modified()), this, SIGNAL(modified())); return true; } else if (log) { log->removeChangeByNewID(att->id()); delete att; } return false; } /** * Removes an attribute from the class. * * @param att The attribute to remove. * @return Count of the remaining attributes after removal. * Returns -1 if the given attribute was not found. */ int UMLClassifier::removeAttribute(UMLAttribute* att) { if (!subordinates().removeAll(att)) { logDebug0("UMLClassifier::removeAttribute cannot find att given in list"); return -1; } // note that we don't delete the attribute, just remove it from the Classifier disconnect(att, SIGNAL(modified()), this, SIGNAL(modified())); Q_EMIT attributeRemoved(att); UMLObject::emitModified(); return subordinates().count(); } /** * Return true if this classifier has abstract operations. */ bool UMLClassifier::hasAbstractOps () const { UMLOperationList opl(getOpList()); for(UMLOperation *op : opl) { uIgnoreZeroPointer(op); if (op->isAbstract()) { return true; } } return false; } /** * Counts the number of operations in the Classifier. * * @return The number of operations for the Classifier. */ int UMLClassifier::operations() const { return getOpList().count(); } /** * Return a list of operations for the Classifier. * * @param includeInherited Includes operations from superclasses. * @param alreadyTraversed internal used object to avoid recursive loops * @return The list of operations for the Classifier. */ UMLOperationList UMLClassifier::getOpList(bool includeInherited, UMLClassifierSet *alreadyTraversed) const { UMLOperationList ops; for(UMLObject *li : subordinates()) { uIgnoreZeroPointer(li); if (li->baseType() == ot_Operation) { ops.append(li->asUMLOperation()); } } if (includeInherited) { if (!alreadyTraversed) { alreadyTraversed = new UMLClassifierSet; } else alreadyTraversed->level++; if (!alreadyTraversed->contains(this)) *alreadyTraversed << this; // get a list of parents of this class UMLClassifierList parents = findSuperClassConcepts(); for(UMLClassifier *c : parents) { if (alreadyTraversed->contains(c)) { logError2("UMLClassifier::getOpList(%1) : class %2 is starting a dependency loop!", name(), c->name()); continue; } // get operations for each parent by recursive call UMLOperationList pops = c->getOpList(true, alreadyTraversed); // add these operations to operation list, but only if unique. for(UMLOperation *po : pops) { QString po_as_string(po->toString(Uml::SignatureType::SigNoVis)); bool breakFlag = false; for(UMLOperation *o : ops) { if (o->toString(Uml::SignatureType::SigNoVis) == po_as_string) { breakFlag = true; break; } } if (breakFlag == false) ops.append(po); } // remember this node *alreadyTraversed << c; } if (alreadyTraversed->level-- == 0) { delete alreadyTraversed; alreadyTraversed = nullptr; } } return ops; } /** * Returns the entries in subordinates that are of the requested type. * If the requested type is UMLObject::ot_UMLObject then all entries * are returned. * @param ot the requested object type * @return The list of true operations for the Concept. */ UMLClassifierListItemList UMLClassifier::getFilteredList(UMLObject::ObjectType ot) const { UMLClassifierListItemList resultList; for(UMLObject *o : subordinates()) { uIgnoreZeroPointer(o); if (!o || o->baseType() == UMLObject::ot_Association) { continue; } UMLClassifierListItem *listItem = o->asUMLClassifierListItem(); if (!listItem) continue; if (ot == UMLObject::ot_UMLObject || listItem->baseType() == ot) { resultList.append(listItem); } } return resultList; } /** * Adds an already created template. * The template object must not belong to any other classifier. * * @param name the name of the template * @param id the id of the template * @return the added template */ UMLTemplate* UMLClassifier::addTemplate(const QString &name, Uml::ID::Type id) { UMLTemplate *templt = findTemplate(name); if (templt) { return templt; } templt = new UMLTemplate(this, name, id); subordinates().append(templt); Q_EMIT templateAdded(templt); UMLObject::emitModified(); connect(templt, SIGNAL(modified()), this, SIGNAL(modified())); return templt; } /** * Adds an already created template. * The template object must not belong to any other classifier. * * @param newTemplate Pointer to the UMLTemplate object to add. * @param log Pointer to the IDChangeLog. * @return True if the template was successfully added. */ bool UMLClassifier::addTemplate(UMLTemplate* newTemplate, IDChangeLog* log /* = nullptr*/) { QString name = newTemplate->name(); if (findChildObject(name) == nullptr) { newTemplate->setParent(this); subordinates().append(newTemplate); Q_EMIT templateAdded(newTemplate); UMLObject::emitModified(); connect(newTemplate, SIGNAL(modified()), this, SIGNAL(modified())); return true; } else if (log) { log->removeChangeByNewID(newTemplate->id()); delete newTemplate; } return false; } /** * Adds an template to the class. * The template object must not belong to any other class. * TODO: If the param IDChangeLog from the method above is not being used, * give position a default value of -1 and the method can replace the above one. * @param templt Pointer to the UMLTemplate to add. * @param position The position of the template in the list. * A value of -1 will add the template at the end. * @return True if the template was successfully added. */ bool UMLClassifier::addTemplate(UMLTemplate* templt, int position) { Q_ASSERT(templt); QString name = templt->name(); if (findChildObject(name) == nullptr) { templt->setParent(this); if (position >= 0 && position <= (int)subordinates().count()) { subordinates().insert(position, templt); } else { subordinates().append(templt); } Q_EMIT templateAdded(templt); UMLObject::emitModified(); connect(templt, SIGNAL(modified()), this, SIGNAL(modified())); return true; } //else return false; } /** * Removes a template from the class. * * @param umltemplate The template to remove. * @return Count of the remaining templates after removal. * Returns -1 if the given template was not found. */ int UMLClassifier::removeTemplate(UMLTemplate* umltemplate) { if (!subordinates().removeAll(umltemplate)) { logWarn1("UMLClassifier::removeTemplate(%1) : cannot find att given in list", name()); return -1; } Q_EMIT templateRemoved(umltemplate); UMLObject::emitModified(); disconnect(umltemplate, SIGNAL(modified()), this, SIGNAL(modified())); return subordinates().count(); } /** * Seeks the template parameter of the given name. * @param name the template name * @return the found template or 0 */ UMLTemplate *UMLClassifier::findTemplate(const QString& name) const { UMLTemplateList templParams = getTemplateList(); for(UMLTemplate *templt : templParams) { if (templt->name() == name) { return templt; } } return nullptr; } /** * Returns the number of templates for the class. * * @return The number of templates for the class. */ int UMLClassifier::templates() const { UMLClassifierListItemList tempList = getFilteredList(UMLObject::ot_Template); return tempList.count(); } /** * Returns the templates. * Same as UMLClassifier::getFilteredList(ot_Template) but * return type is a true UMLTemplateList. * * @return Pointer to the list of true templates for the class. */ UMLTemplateList UMLClassifier::getTemplateList() const { UMLTemplateList templateList; for(UMLObject *listItem : subordinates()) { uIgnoreZeroPointer(listItem); if (listItem->baseType() == UMLObject::ot_Template) { templateList.append(listItem->asUMLTemplate()); } } return templateList; } /** * Take and return a subordinate item from this classifier. * Ownership of the item is passed to the caller. * * @param item Subordinate item to take. * @return Index in subordinates of the item taken. * Return -1 if the item is not found in subordinates. */ int UMLClassifier::takeItem(UMLClassifierListItem *item) { QString buf; for(UMLObject *currentAtt : subordinates()) { uIgnoreZeroPointer(currentAtt); #if 0 QString txt = currentAtt->name(); if (txt.isEmpty()) { txt = QStringLiteral("Type-") + QString::number((int) currentAtt->baseType()); } #endif buf.append(QLatin1Char(' ') + currentAtt->name()); } logDebug1("UMLClassifier::takeItem (before): subordinates() is %1", buf); int index = subordinates().indexOf(item); if (index == -1) { return -1; } switch (item->baseType()) { case UMLObject::ot_Operation: { if (removeOperation(item->asUMLOperation()) < 0) { index = -1; } break; } case UMLObject::ot_Attribute: { UMLAttribute *retval = subordinates().takeAt(index)->asUMLAttribute(); if (retval) { Q_EMIT attributeRemoved(retval); UMLObject::emitModified(); } else { index = -1; } break; } case UMLObject::ot_Template: { UMLTemplate *templt = subordinates().takeAt(index)->asUMLTemplate(); if (templt) { Q_EMIT templateRemoved(templt); UMLObject::emitModified(); } else { index = -1; } break; } case UMLObject::ot_EnumLiteral: { UMLEnumLiteral *el = subordinates().takeAt(index)->asUMLEnumLiteral(); if (el) { UMLEnum *e = this->asUMLEnum(); e->signalEnumLiteralRemoved(el); UMLObject::emitModified(); } else { index = -1; } break; } case UMLObject::ot_EntityAttribute: { UMLEntityAttribute* el = subordinates().takeAt(index)->asUMLEntityAttribute(); if (el) { UMLEntity *e = this->asUMLEntity(); e->signalEntityAttributeRemoved(el); UMLObject::emitModified(); } else { index = -1; } break; } default: index = -1; break; } return index; } /** * Return true if this classifier has associations. * @return true if classifier has associations */ bool UMLClassifier::hasAssociations() const { return getSpecificAssocs(AssociationType::Association).count() > 0 || getAggregations().count() > 0 || getCompositions().count() > 0 || getUniAssociationToBeImplemented().count() > 0; } /** * Return true if this classifier has attributes. */ bool UMLClassifier::hasAttributes() const { return getAttributeList(Uml::Visibility::Public).count() > 0 || getAttributeList(Uml::Visibility::Protected).count() > 0 || getAttributeList(Uml::Visibility::Private).count() > 0 || getAttributeListStatic(Uml::Visibility::Public).count() > 0 || getAttributeListStatic(Uml::Visibility::Protected).count() > 0 || getAttributeListStatic(Uml::Visibility::Private).count() > 0; } /** * Return true if this classifier has static attributes. */ bool UMLClassifier::hasStaticAttributes() const { return getAttributeListStatic(Uml::Visibility::Public).count() > 0 || getAttributeListStatic(Uml::Visibility::Protected).count() > 0 || getAttributeListStatic(Uml::Visibility::Private).count() > 0; } /** * Return true if this classifier has accessor methods. */ bool UMLClassifier::hasAccessorMethods() const { return hasAttributes() || hasAssociations(); } /** * Return true if this classifier has operation methods. */ bool UMLClassifier::hasOperationMethods() const { return getOpList().count() > 0 ? true : false; } /** * Return true if this classifier has methods. */ bool UMLClassifier::hasMethods() const { return hasOperationMethods() || hasAccessorMethods(); } // this is a bit too simplistic..some associations are for // SINGLE objects, and WONT be declared as Vectors, so this // is a bit overly inclusive (I guess that's better than the other way around) /** * Return true if this classifier has vector fields. */ bool UMLClassifier::hasVectorFields() const { return hasAssociations(); } /** * Return the list of unidirectional association that should show up in the code */ UMLAssociationList UMLClassifier::getUniAssociationToBeImplemented() const { UMLAssociationList associations = getSpecificAssocs(AssociationType::UniAssociation); UMLAssociationList uniAssocListToBeImplemented; for(UMLAssociation *a : associations) { uIgnoreZeroPointer(a); if (a->getObjectId(RoleType::B) == id()) { continue; // we need to be at the A side } QString roleNameB = a->getRoleName(RoleType::B); if (!roleNameB.isEmpty()) { UMLAttributeList atl = getAttributeList(); bool found = false; //make sure that an attribute with the same name doesn't already exist for(UMLAttribute *at : atl) { uIgnoreZeroPointer(at); if (at->name() == roleNameB) { found = true; break; } } if (!found) { uniAssocListToBeImplemented.append(a); } } } return uniAssocListToBeImplemented; } /** * Creates XML tag <UML:Class>, <UML:Interface>, or <UML:DataType> * depending on m_BaseType. * Saves possible template parameters, generalizations, attributes, * operations, and contained objects to the given QDomElement. */ void UMLClassifier::saveToXMI(QXmlStreamWriter& writer) { QString tag; switch (m_BaseType) { case UMLObject::ot_Class: tag = QStringLiteral("Class"); break; case UMLObject::ot_Interface: tag = QStringLiteral("Interface"); break; case UMLObject::ot_Package: UMLPackage::saveToXMI(writer); return; break; default: logError2("UMLClassifier::saveToXMI(%1) internal error: basetype is %2", name(), m_BaseType); return; } UMLObject::save1(writer, tag); //save templates UMLClassifierListItemList list = getFilteredList(UMLObject::ot_Template); if (list.count()) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:ModelElement.templateParameter")); } for(UMLClassifierListItem *tmpl : list) { tmpl->saveToXMI(writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); } } //save generalizations (we are the subclass, the other end is the superclass) UMLAssociationList generalizations = getSpecificAssocs(AssociationType::Generalization); if (generalizations.count()) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:GeneralizableElement.generalization")); } for(UMLAssociation *asso : generalizations) { // We are the subclass if we are at the role A end. if (m_nId != asso->getObjectId(RoleType::A)) { continue; } if (Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("generalization")); writer.writeAttribute(QStringLiteral("xmi:type"), QStringLiteral("uml:Generalization")); writer.writeAttribute(QStringLiteral("xmi:id"), Uml::ID::toString(asso->id())); Uml::ID::Type superId = asso->getObjectId(RoleType::B); writer.writeAttribute(QStringLiteral("general"), Uml::ID::toString(superId)); } else { writer.writeStartElement(QStringLiteral("UML:Generalization")); // CHECK - This looks wrong, we should be saving the role B ID (superclass) writer.writeAttribute(QStringLiteral("xmi.idref"), Uml::ID::toString(asso->id())); } writer.writeEndElement(); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); } } UMLClassifierListItemList attList = getFilteredList(UMLObject::ot_Attribute); UMLOperationList opList = getOpList(); if (attList.count() || opList.count()) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Classifier.feature")); } // save attributes for(UMLClassifierListItem *pAtt : attList) { pAtt->saveToXMI(writer); } // save operations for(UMLOperation *pOp : opList) { pOp->saveToXMI(writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); } } // save contained objects if (m_objects.count()) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Namespace.ownedElement")); } for(UMLObject* obj : m_objects) { uIgnoreZeroPointer(obj); obj->saveToXMI (writer); } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); } } UMLObject::save1end(writer); // from UMLObject::save1(tag) } /** * Creates a new classifier list object (attribute, operation, template) * according to the given XMI tag. * Returns NULL if the string given does not contain one of the tags * <UML:Attribute>, <UML:Operation>, or <UML:TemplateParameter>. * Used by the clipboard for paste operation. */ UMLClassifierListItem* UMLClassifier::makeChildObject(const QString& xmiTag) { UMLClassifierListItem *pObject = nullptr; if (UMLDoc::tagEq(xmiTag, QStringLiteral("Operation")) || UMLDoc::tagEq(xmiTag, QStringLiteral("ownedOperation"))) { pObject = new UMLOperation(this); } else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Attribute")) || UMLDoc::tagEq(xmiTag, QStringLiteral("ownedAttribute"))) { if (baseType() != UMLObject::ot_Class) return nullptr; pObject = new UMLAttribute(this); } else if (UMLDoc::tagEq(xmiTag, QStringLiteral("TemplateParameter")) || UMLDoc::tagEq(xmiTag, QStringLiteral("ClassifierTemplateParameter"))) { pObject = new UMLTemplate(this); } return pObject; } /** * Reimplements method from UMLPackage. * Removes a classifier list object from this classifier. * Does not physically delete the object. * Does not emit signals. * * @param pObject Pointer to UMLObject to be removed is expected to be * convertible to UMLClassifierListItem*. */ void UMLClassifier::removeObject(UMLObject *pObject) { if (!pObject) { logError1("UMLClassifier %1 removeObject is called with null argument", name()); return; } UMLClassifierListItem *cli = pObject->asUMLClassifierListItem(); if (!cli) { logError2("UMLClassifier %1 removeObject %2 object cannot be cast to UMLClassifierListItem", name(), pObject->name()); return; } if (!subordinates().removeAll(cli)) { logWarn2("UMLClassifier %1 removeObject %2 : cannot find object in list", name(), pObject->name()); } } /** * Auxiliary to loadFromXMI: * The loading of operations is implemented here. * Calls loadFromXMI() for any other tag. * Child classes can override the loadFromXMI() method * to load its additional tags. */ bool UMLClassifier::load1(QDomElement& element) { UMLClassifierListItem *child = nullptr; bool totalSuccess = true; for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; element = node.toElement(); QString tag = element.tagName(); QString stereotype = element.attribute(QStringLiteral("stereotype")); if (UMLDoc::tagEq(tag, QStringLiteral("ModelElement.templateParameter")) || UMLDoc::tagEq(tag, QStringLiteral("Classifier.feature")) || UMLDoc::tagEq(tag, QStringLiteral("Namespace.ownedElement")) || UMLDoc::tagEq(tag, QStringLiteral("Element.ownedElement")) || // Embarcadero's Describe UMLDoc::tagEq(tag, QStringLiteral("Namespace.contents"))) { load1(element); // Not evaluating the return value from load() // because we want a best effort. } else if ((child = makeChildObject(tag)) != nullptr) { if (child->loadFromXMI(element)) { switch (child->baseType()) { case UMLObject::ot_Template: addTemplate(child->asUMLTemplate()); break; case UMLObject::ot_Operation: if (! addOperation(child->asUMLOperation())) { logError1("UMLClassifier::load1(%1) : error from addOperation(op)", name()); delete child; totalSuccess = false; } break; case UMLObject::ot_Attribute: case UMLObject::ot_InstanceAttribute: addAttribute(child->asUMLAttribute()); break; default: break; } } else { logWarn2("UMLClassifier::load1(%1): failed to load %2", name(), tag); delete child; totalSuccess = false; } } else if (!Model_Utils::isCommonXMI1Attribute(tag)) { UMLObject *pObject = Object_Factory::makeObjectFromXMI(tag, stereotype); if (pObject == nullptr) { // Not setting totalSuccess to false // because we want a best effort. continue; } pObject->setUMLPackage(this); if (! pObject->loadFromXMI(element)) { removeObject(pObject); delete pObject; totalSuccess = false; } } } return totalSuccess; } /* UMLClassifierList UMLClassifier::getPlainAssocChildClassifierList() { UMLAssociationList plainAssociations = getSpecificAssocs(Uml::AssociationType::Association); return findAssocClassifierObjsInRoles(&plainAssociations); } UMLClassifierList UMLClassifier::getAggregateChildClassifierList() { UMLAssociationList aggregations = getAggregations(); return findAssocClassifierObjsInRoles(&aggregations); } UMLClassifierList UMLClassifier::getCompositionChildClassifierList() { UMLAssociationList compositions = getCompositions(); return findAssocClassifierObjsInRoles(&compositions); } UMLClassifierList UMLClassifier::findAssocClassifierObjsInRoles (UMLAssociationList * list) { UMLClassifierList classifiers; for (UMLAssociationListIt alit(*list); alit.hasNext(); ) { UMLAssociation* a = alit.next(); // DON'T accept a classifier IF the association role is empty, by // convention, that means to ignore the classifier on that end of // the association. // We also ignore classifiers which are the same as the current one // (e.g. id matches), we only want the "other" classifiers if (a->getObjectId(RoleType::A) == id() && !a->getRoleName(RoleType::B).isEmpty()) { UMLClassifier *c = a->getObject(RoleType::B)->asUMLClassifier(); if(c) classifiers.append(c); } else if (a->getObjectId(RoleType::B) == id() && !a->getRoleName(RoleType::A).isEmpty()) { UMLClassifier *c = a->getObject(RoleType::A)->asUMLClassifier(); if(c) classifiers.append(c); } } return classifiers; } */
54,151
C++
.cpp
1,516
28.525066
137
0.623396
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,481
umlentityattributelist.cpp
KDE_umbrello/umbrello/umlmodel/umlentityattributelist.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2004-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlentityattributelist.h" #include "entityattribute.h" #include <KLocalizedString> UMLEntityAttributeList::UMLEntityAttributeList() { } UMLEntityAttributeList::UMLEntityAttributeList(const UMLEntityAttributeList& other) : QList<UMLEntityAttribute*>(other) { } UMLEntityAttributeList::~UMLEntityAttributeList() { } /** * Copy the internal presentation of this object into the new * object. */ void UMLEntityAttributeList::copyInto(UMLEntityAttributeList* rhs) const { // Don't copy yourself. if (rhs == this) return; rhs->clear(); // Suffering from const; we shall not modify our object. UMLEntityAttributeList* tmp = new UMLEntityAttributeList(*this); UMLEntityAttribute* item; for (UMLEntityAttributeListIt eait(*tmp); eait.hasNext() ;) { item = eait.next(); rhs->append((UMLEntityAttribute*)item->clone()); } delete tmp; } /** * Make a clone of this object. */ UMLEntityAttributeList* UMLEntityAttributeList::clone() const { UMLEntityAttributeList *clone = new UMLEntityAttributeList(); copyInto(clone); return clone; }
1,259
C++
.cpp
44
25.568182
92
0.752492
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
749,482
artifact.cpp
KDE_umbrello/umbrello/umlmodel/artifact.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "artifact.h" #include "association.h" #include "clipboard/idchangelog.h" #include <KLocalizedString> #include <QDir> /** * Sets up an Artifact. * @param name The name of the Concept. * @param id The unique id of the Concept. */ UMLArtifact::UMLArtifact(const QString & name, Uml::ID::Type id) : UMLPackage(name, id), m_drawAsType(defaultDraw) { m_BaseType = UMLObject::ot_Artifact; } /** * Standard deconstructor. */ UMLArtifact::~UMLArtifact() { } /** * Make a clone of this object. * @return the cloned object */ UMLObject* UMLArtifact::clone() const { UMLArtifact *clone = new UMLArtifact(); UMLObject::copyInto(clone); return clone; } /** * Creates the UML:Artifact element including its operations, * attributes and templates * @param writer the QXmlStreamWriter serialization target */ void UMLArtifact::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Artifact")); writer.writeAttribute(QStringLiteral("drawas"), QString::number(m_drawAsType)); UMLObject::save1end(writer); } /** * Loads the UML:Artifact element including its operations, * attributes and templates. * @param element the xml element to load * @return the success status of the operation */ bool UMLArtifact::load1(QDomElement& element) { QString drawAs = element.attribute(QStringLiteral("drawas"), QStringLiteral("0")); m_drawAsType = (Draw_Type)drawAs.toInt(); return true; } /** * Sets m_drawAsType for which method to draw the artifact as. * @param type the draw type */ void UMLArtifact::setDrawAsType(Draw_Type type) { m_drawAsType = type; } /** * Returns the value of m_drawAsType. * @return the value of the draw type attribute */ UMLArtifact::Draw_Type UMLArtifact::getDrawAsType() const { return m_drawAsType; } /** * Return full path of this artifact including its parent * @return full path */ QString UMLArtifact::fullPath() const { QString path = name(); for(UMLPackage *p = umlPackage(); p != nullptr && p->umlPackage() != nullptr; p = p->umlPackage()) { path.insert(0, p->name() + QLatin1Char('/')); } return QDir::toNativeSeparators(path); }
2,347
C++
.cpp
87
24.528736
104
0.72331
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,483
template.cpp
KDE_umbrello/umbrello/umlmodel/template.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "template.h" // app includes #include "debug_utils.h" #include "optionstate.h" #include "uml.h" #include "umldoc.h" #include "umltemplatedialog.h" /** * Sets up a template. * * @param parent The parent of this UMLTemplate (i.e. its classifier). * @param name The name of this UMLTemplate. * @param id The unique id given to this UMLTemplate. * @param type The type of this UMLTemplate. */ UMLTemplate::UMLTemplate(UMLObject *parent, const QString& name, Uml::ID::Type id, const QString& type) : UMLClassifierListItem(parent, name, id) { setTypeName(type); m_BaseType = UMLObject::ot_Template; } /** * Sets up a template. * * @param parent The parent of this UMLTemplate (i.e. its classifier). */ UMLTemplate::UMLTemplate(UMLObject *parent) : UMLClassifierListItem(parent) { m_BaseType = UMLObject::ot_Template; } /** * Destructor. */ UMLTemplate::~UMLTemplate() { } QString UMLTemplate::toString(Uml::SignatureType::Enum sig, bool withStereotype) const { Q_UNUSED(sig); QString s; if (m_pSecondary == nullptr || m_pSecondary->name() == QStringLiteral("class")) { s = name(); } else { s = name() + QStringLiteral(" : ") + m_pSecondary->name(); } if (withStereotype) { QString st = stereotype(true); if (!st.isEmpty()) s += QStringLiteral(" ") + st; } return s; } /** * Overrides method from UMLClassifierListItem. * Returns the type name of the UMLTemplate. * If the template parameter is a class, there is no separate * type object. In this case, getTypeName() returns "class". * * @return The type name of the UMLClassifierListItem. */ QString UMLTemplate::getTypeName() const { if (m_pSecondary == nullptr) return QStringLiteral("class"); return m_pSecondary->name(); } /** * Overloaded '==' operator. */ bool UMLTemplate::operator==(const UMLTemplate &rhs) const { if (this == &rhs) { return true; } if (!UMLObject::operator==(rhs)) { return false; } if (m_pSecondary != rhs.m_pSecondary) { return false; } return true; } /** * Copy the internal presentation of this object into the new * object. */ void UMLTemplate::copyInto(UMLObject *lhs) const { UMLClassifierListItem::copyInto(lhs); } /** * Make a clone of this object. */ UMLObject* UMLTemplate::clone() const { UMLTemplate *clone = new UMLTemplate(umlParent()->asUMLTemplate()); copyInto(clone); return clone; } /** * Writes the <UML:TemplateParameter> XMI element. */ void UMLTemplate::saveToXMI(QXmlStreamWriter& writer) { //FIXME: uml13.dtd compliance const QString xmiType = (Settings::optionState().generalState.uml2 ? QStringLiteral("ClassifierTemplateParameter") : QStringLiteral("TemplateParameter")); UMLObject::save1(writer, xmiType, QStringLiteral("ownedParameter")); if (m_pSecondary) writer.writeAttribute(QStringLiteral("type"), Uml::ID::toString(m_pSecondary->id())); writer.writeEndElement(); } /** * Loads the <UML:TemplateParameter> XMI element. */ bool UMLTemplate::load1(QDomElement& element) { m_SecondaryId = element.attribute(QStringLiteral("type")); return true; } /** * Display the properties configuration dialog for the template. * * @return Success status. */ bool UMLTemplate::showPropertiesDialog(QWidget* parent) { UMLTemplateDialog dialog(parent, this); return dialog.exec(); }
3,765
C++
.cpp
139
23.115108
93
0.671836
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,484
umlclassifierlistitemlist.cpp
KDE_umbrello/umbrello/umlmodel/umlclassifierlistitemlist.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2004-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlclassifierlistitemlist.h" #include "classifierlistitem.h" #include <KLocalizedString> UMLClassifierListItemList::UMLClassifierListItemList() { } UMLClassifierListItemList::~UMLClassifierListItemList() { } /** * Copy the internal presentation of this object into the new * object. */ void UMLClassifierListItemList::copyInto(UMLClassifierListItemList *rhs) const { // Prevent copying to yourself. (Can cause serious injuries) if (rhs == this) return; rhs->clear(); // Suffering from const; we shall not modify our object. UMLClassifierListItemList *tmp = new UMLClassifierListItemList(*this); UMLClassifierListItem *item; for (UMLClassifierListItemListIt clit(*tmp); clit.hasNext() ;) { item = clit.next(); rhs->append((UMLClassifierListItem*)item->clone()); } delete tmp; } /** * Make a clone of this object. */ UMLClassifierListItemList* UMLClassifierListItemList::clone() const { UMLClassifierListItemList *clone = new UMLClassifierListItemList(); copyInto(clone); return clone; }
1,220
C++
.cpp
40
27.325
92
0.755556
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,485
entityconstraint.cpp
KDE_umbrello/umbrello/umlmodel/entityconstraint.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ //own header #include "entityconstraint.h" // app includes #include "umlobject.h" #include "umldoc.h" #include "uml.h" // qt includes /** * Sets up a constraint. * @param parent The parent of this UMLEntityConstraint. * @param name The name of this UMLEntityConstraint. * @param id The unique id given to this UMLEntityConstraint. */ UMLEntityConstraint::UMLEntityConstraint(UMLObject *parent, const QString& name, Uml::ID::Type id) : UMLClassifierListItem(parent, name, id) { m_BaseType = UMLObject::ot_EntityConstraint; } /** * Sets up a constraint. * @param parent The parent of this UMLEntityConstraint. */ UMLEntityConstraint::UMLEntityConstraint(UMLObject *parent) : UMLClassifierListItem(parent) { m_BaseType = UMLObject::ot_EntityConstraint; } /** * Overloaded '==' operator */ bool UMLEntityConstraint::operator==(const UMLEntityConstraint &rhs) const { if(this == &rhs) return true; if(!UMLObject::operator==(rhs)) return false; return true; } /** * destructor. */ UMLEntityConstraint::~UMLEntityConstraint() { } /** * Copy the internal presentation of this object into the UMLEntityConstraint * object. */ void UMLEntityConstraint::copyInto(UMLObject *lhs) const { // call the parent first. UMLClassifierListItem::copyInto(lhs); }
1,484
C++
.cpp
58
23.086207
92
0.736209
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,486
stereotype.cpp
KDE_umbrello/umbrello/umlmodel/stereotype.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "stereotype.h" // local includes #include "debug_utils.h" #include "dialog_utils.h" #include "optionstate.h" #include "umldoc.h" #include "uml.h" // kde includes #include <KLocalizedString> DEBUG_REGISTER(UMLStereotype) /** * Sets up a stereotype. * * @param name The name of this UMLStereotype. * @param id The unique id given to this UMLStereotype. */ UMLStereotype::UMLStereotype(const QString &name, Uml::ID::Type id /* = Uml::id_None */) : UMLObject(name, id) { m_BaseType = UMLObject::ot_Stereotype; UMLStereotype * existing = UMLApp::app()->document()->findStereotype(name); if (existing) { logError1("UMLStereotype constructor: %1 already exists", name); } m_refCount = 0; } /** * Sets up a stereotype. */ UMLStereotype::UMLStereotype() : UMLObject() { m_BaseType = UMLObject::ot_Stereotype; m_refCount = 0; } /** * Destructor. */ UMLStereotype::~UMLStereotype() { //Q_ASSERT(m_refCount == 0); } /** * Overloaded '==' operator. */ bool UMLStereotype::operator==(const UMLStereotype &rhs) const { if (this == &rhs) { return true; } if (!UMLObject::operator==(rhs)) { return false; } return true; } /** * Copy the internal presentation of this object into the new * object. */ void UMLStereotype::copyInto(UMLObject *lhs) const { UMLObject::copyInto(lhs); } /** * Make a clone of this object. */ UMLObject* UMLStereotype::clone() const { UMLStereotype *clone = new UMLStereotype(); copyInto(clone); return clone; } /** * Reset stereotype attribute definitions to none. */ void UMLStereotype::clearAttributeDefs() { m_attrDefs.clear(); } /** * Setter for stereotype attribute definitions. */ void UMLStereotype::setAttributeDefs(const AttributeDefs& adefs) { m_attrDefs = adefs; } /** * Const getter for stereotype attribute definitions. */ const UMLStereotype::AttributeDefs& UMLStereotype::getAttributeDefs() const { return m_attrDefs; } /** * Getter for stereotype attribute definitions returning writable data. */ UMLStereotype::AttributeDefs& UMLStereotype::getAttributeDefs() { return m_attrDefs; } /** * Saves to the <UML:StereoType> XMI element. */ void UMLStereotype::saveToXMI(QXmlStreamWriter& writer) { //FIXME: uml13.dtd compliance UMLObject::save1(writer, QStringLiteral("Stereotype")); if (!m_attrDefs.isEmpty()) { if (! Settings::optionState().generalState.uml2) { writer.writeStartElement(QStringLiteral("UML:Stereotype.feature")); } for(AttributeDef ad : m_attrDefs) { const QString tag = (Settings::optionState().generalState.uml2 ? QStringLiteral("ownedAttribute") : QStringLiteral("UML:Attribute")); writer.writeStartElement(tag); writer.writeAttribute(QStringLiteral("name"), ad.name); writer.writeAttribute(QStringLiteral("type"), Uml::PrimitiveTypes::toString(ad.type)); if (!ad.defaultVal.isEmpty()) writer.writeAttribute(QStringLiteral("initialValue"), ad.defaultVal); writer.writeEndElement(); // UML:Attribute } if (! Settings::optionState().generalState.uml2) { writer.writeEndElement(); // UML:Stereotype.feature } } writer.writeEndElement(); } /** * Auxiliary to loadFromXMI: * The loading of stereotype attributes is implemented here. */ bool UMLStereotype::load1(QDomElement& element) { if (!element.hasChildNodes()) { return true; } for (QDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { if (node.isComment()) continue; element = node.toElement(); QString tag = element.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("Stereotype.feature"))) { QDomNode attNode = element.firstChild(); QDomElement attElem = attNode.toElement(); while (!attElem.isNull()) { tag = attElem.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("Attribute"))) { QString name = attElem.attribute(QStringLiteral("name")); QString typeStr = attElem.attribute(QStringLiteral("type")); Uml::PrimitiveTypes::Enum type = Uml::PrimitiveTypes::fromString(typeStr); QString dfltVal = attElem.attribute(QStringLiteral("initialValue")); AttributeDef ad(name, type, dfltVal); m_attrDefs.append(ad); } else { logDebug2("UMLStereotype::load1(%1): Unknown Stereotype.feature child %2", m_name, tag); } attNode = attNode.nextSibling(); attElem = attNode.toElement(); } } } return true; } /** * Display the properties configuration dialog for the stereotype * (just a line edit). */ bool UMLStereotype::showPropertiesDialog(QWidget* parent) { Q_UNUSED(parent); QString stereoTypeName = name(); bool ok = Dialog_Utils::askRenameName(baseType(), stereoTypeName); if (ok) { setName(stereoTypeName); } return ok; } /** * Increments the reference count for this stereotype. */ void UMLStereotype::incrRefCount() { m_refCount++; } /** * Decrements the reference count for this stereotype. */ void UMLStereotype::decrRefCount() { m_refCount--; } /** * Returns the reference count for this stereotype. */ int UMLStereotype::refCount() const { return m_refCount; } /** * Returns the name as string */ QString UMLStereotype::name(bool includeAdornments) const { if (includeAdornments) { return QString::fromUtf8("«") + UMLObject::name() + QString::fromUtf8("»"); } return UMLObject::name(); }
6,057
C++
.cpp
214
23.299065
101
0.653773
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,487
umlentityconstraintlist.cpp
KDE_umbrello/umbrello/umlmodel/umlentityconstraintlist.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2004-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "umlentityconstraintlist.h" #include "entityconstraint.h" #include <KLocalizedString> UMLEntityConstraintList::UMLEntityConstraintList() { } UMLEntityConstraintList::~UMLEntityConstraintList() { } /** * Copy the internal presentation of this object into the new * object. */ void UMLEntityConstraintList::copyInto(UMLEntityConstraintList* rhs) const { // Don't copy yourself. if (rhs == this) return; rhs->clear(); // Suffering from const; we shall not modify our object. UMLEntityConstraintList* tmp = new UMLEntityConstraintList(*this); UMLEntityConstraint* item; for (UMLEntityConstraintListIt ecit(*tmp); ecit.hasNext() ;) { item = ecit.next(); rhs->append((UMLEntityConstraint*)item->clone()); } delete tmp; } /** * Make a clone of this object. */ UMLEntityConstraintList* UMLEntityConstraintList::clone() const { UMLEntityConstraintList *clone = new UMLEntityConstraintList(); copyInto(clone); return clone; }
1,149
C++
.cpp
40
25.55
92
0.745223
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,488
uniqueconstraint.cpp
KDE_umbrello/umbrello/umlmodel/uniqueconstraint.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ //own header #include "uniqueconstraint.h" // app includes #include "debug_utils.h" #include "entity.h" #include "entityattribute.h" #include "umldoc.h" #include "uml.h" // Only needed for log{Warn,Error} #include "umlattributedialog.h" #include "umluniqueconstraintdialog.h" #include "object_factory.h" DEBUG_REGISTER(UMLUniqueConstraint) /** * Sets up a constraint. * * @param parent The parent of this UMLUniqueConstraint. * @param name The name of this UMLUniqueConstraint. * @param id The unique id given to this UMLUniqueConstraint. */ UMLUniqueConstraint::UMLUniqueConstraint(UMLObject *parent, const QString& name, Uml::ID::Type id) : UMLEntityConstraint(parent, name, id) { init(); } /** * Sets up a constraint. * * @param parent The parent of this UMLUniqueConstraint. */ UMLUniqueConstraint::UMLUniqueConstraint(UMLObject *parent) : UMLEntityConstraint(parent) { init(); } /** * Overloaded '==' operator */ bool UMLUniqueConstraint::operator==(const UMLUniqueConstraint &rhs) const { if(this == &rhs) return true; if(!UMLObject::operator==(rhs)) return false; return true; } /** * Destructor. */ UMLUniqueConstraint::~UMLUniqueConstraint() { } /** * Copy the internal presentation of this object into the UMLUniqueConstraint * object. */ void UMLUniqueConstraint::copyInto(UMLObject *lhs) const { UMLUniqueConstraint *target = lhs->asUMLUniqueConstraint(); // call the parent first. UMLEntityConstraint::copyInto(target); // Copy all datamembers target->m_EntityAttributeList.clear(); bool valid = true; for(UMLEntityAttribute* attr : m_EntityAttributeList) { if (!valid) break; valid = target->addEntityAttribute(attr); } if (!valid) { logDebug0("UMLUniqueConstraint::copyInto: Copying Attributes failed. " "Clearing target list."); target->m_EntityAttributeList.clear(); } } /** * Make a clone of the UMLUniqueConstraint. */ UMLObject* UMLUniqueConstraint::clone() const { //FIXME: The new attribute should be slaved to the NEW parent not the old. UMLUniqueConstraint *clone = new UMLUniqueConstraint(umlParent()); copyInto(clone); return clone; } /** * Returns a string representation of the UMLUniqueConstraint. * * @param sig If true will show the attribute type and initial value. * @return Returns a string representation of the UMLAttribute. */ QString UMLUniqueConstraint::toString(Uml::SignatureType::Enum sig, bool withStereotype) const { Q_UNUSED(withStereotype); QString s; if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::SigNoVis) { s = name() + QLatin1Char(':'); const UMLEntity *e = umlParent()->asUMLEntity(); if (e && e->isPrimaryKey(this)) { s += QStringLiteral("Primary Key ("); } else { s += QStringLiteral("Unique ("); } bool first = true; for(UMLEntityAttribute* att : m_EntityAttributeList) { if (first) { first = false; } else s += QLatin1Char(','); s += att->name(); } s += QLatin1Char(')') ; } return s; } QString UMLUniqueConstraint::getFullyQualifiedName(const QString& separator, bool includeRoot) const { Q_UNUSED(separator); Q_UNUSED(includeRoot); return this->name(); } /** * Creates the <UML:UniqueConstraint> XMI element. */ void UMLUniqueConstraint::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("UniqueConstraint")); const UMLEntity* parentEnt = umlParent()->asUMLEntity(); if (parentEnt && parentEnt->isPrimaryKey(this)) { writer.writeAttribute(QStringLiteral("isPrimary"), QStringLiteral("1")); } else { writer.writeAttribute(QStringLiteral("isPrimary"), QStringLiteral("0")); } for(UMLEntityAttribute* att : m_EntityAttributeList) { att->saveToXMI(writer); } writer.writeEndElement(); } /** * Display the properties configuration dialog for the attribute. */ bool UMLUniqueConstraint::showPropertiesDialog(QWidget* parent) { UMLUniqueConstraintDialog dialog(parent, this); return dialog.exec(); } /** * Loads the <UML:UniqueConstraint> XMI element. */ bool UMLUniqueConstraint::load1(QDomElement & element) { int isPrimary = element.attribute(QStringLiteral("isPrimary"), QStringLiteral("0")).toInt(); UMLEntity* parentEnt = umlParent()->asUMLEntity(); if (isPrimary == 1) { parentEnt->setAsPrimaryKey(this); } QDomNode node = element.firstChild(); while (!node.isNull()) { if (node.isComment()) { node = node.nextSibling(); continue; } QDomElement tempElement = node.toElement(); QString tag = tempElement.tagName(); if (UMLDoc::tagEq(tag, QStringLiteral("ownedAttribute"))) { tag = tempElement.attribute(QStringLiteral("xmi:type")); } if (UMLDoc::tagEq(tag, QStringLiteral("EntityAttribute"))) { QString attName = tempElement.attribute(QStringLiteral("name")); UMLObject* obj = parentEnt->findChildObject(attName); UMLEntityAttribute* entAtt = obj->asUMLEntityAttribute(); if (entAtt == nullptr) continue; m_EntityAttributeList.append(entAtt); } else { logWarn1("UMLUniqueConstraint::load: unknown child type %1", tag); } node = node.nextSibling(); } return true; } /** * Check if a entity attribute is present in m_entityAttributeList * * @param attr The Entity Attribute to check for existence in list * @return true if it exists in the list, else false */ bool UMLUniqueConstraint::hasEntityAttribute(UMLEntityAttribute* attr) const { if (m_EntityAttributeList.indexOf(attr) == -1) { //not present return false; } // else present return true; } /** * Adds a UMLEntityAttribute to the list. * The UMLEntityAttribute should already exist and should * belong to the parent UMLEntity. * * @param attr The UMLEntityAttribute to add * @return false if it failed to add, else true */ bool UMLUniqueConstraint::addEntityAttribute(UMLEntityAttribute* attr) { const UMLEntity *owningParent = umlParent()->asUMLEntity(); if (hasEntityAttribute(attr)) { logDebug1("UMLUniqueConstraint::addEntityAttribute: Constraint already contains %2", attr->name()); return false; } if (owningParent == nullptr) { logError1("UMLUniqueConstraint::addEntityAttribute(%1) : parent is not a UMLEntity", name()); return false; } if (owningParent->findChildObjectById(attr->id()) == nullptr) { logError3("UMLUniqueConstraint::addEntityAttribute(%1) parent %2 does not contain attribute %3", name(), owningParent->name(), attr->name()); return false; } //else add the attribute to the Entity Attribute List m_EntityAttributeList.append(attr); return true; } /** * Removes a UMLEntityAttribute from the list * * @param attr The UMLEntityAttribute to remove from list * @return false if it failed to remove the attribute from the list */ bool UMLUniqueConstraint::removeEntityAttribute(UMLEntityAttribute* attr) { const UMLEntity *owningParent = umlParent()->asUMLEntity(); if (owningParent == nullptr) { logError1("UMLUniqueConstraint::removeEntityAttribute(%1) : parent is not a UMLEntity", name()); return false; } /* * The attribute may already be removed from the Entity when this function * is called. So checking this is not right * * if (owningParent->findChildObjectById(attr->ID()) == 0) { * uError() * << " parent " << owningParent->getName() * << " does not contain attribute " << attr->getName(); * return false; * } */ //else remove the attribute from the Entity Attribute List if (m_EntityAttributeList.removeAll(attr)) { return true; } return false; } /** * Get the Entity Attributes List. */ UMLEntityAttributeList UMLUniqueConstraint::getEntityAttributeList() const { return m_EntityAttributeList; } void UMLUniqueConstraint::init() { m_BaseType = UMLObject::ot_UniqueConstraint; } /** * Clear the list of attributes contained in this UniqueConstraint */ void UMLUniqueConstraint::clearAttributeList() { m_EntityAttributeList.clear(); }
8,854
C++
.cpp
278
26.733813
104
0.674683
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,489
classifierlistitem.cpp
KDE_umbrello/umbrello/umlmodel/classifierlistitem.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "classifierlistitem.h" // local includes #include "debug_utils.h" #include "classifier.h" #include "model_utils.h" #include "object_factory.h" #include "uml.h" #include "umldoc.h" // kde includes #include <KLocalizedString> DEBUG_REGISTER(UMLClassifierListItem) /** * Constructor. * * @param parent The parent to this operation. * At first sight it would appear that the type of the * parent should be UMLClassifier. However, the class * UMLAttribute is also used for the parameters of * operations, and in this case the UMLOperation is the * parent. * @param name The name of the operation. * @param id The id of the operation. */ UMLClassifierListItem::UMLClassifierListItem(UMLObject *parent, const QString& name, Uml::ID::Type id) : UMLObject(parent, name, id) { UMLClassifier *pc = parent->asUMLClassifier(); if (pc) UMLObject::setUMLPackage(pc); } /** * Constructor. * * @param parent The parent to this operation. * At first sight it would appear that the type of the * parent should be UMLClassifier. However, the class * UMLAttribute is also used for the parameters of * operations, and in this case the UMLOperation is the * parent. */ UMLClassifierListItem::UMLClassifierListItem(UMLObject *parent) : UMLObject(parent) { UMLClassifier *pc = parent->asUMLClassifier(); if (pc) UMLObject::setUMLPackage(pc); } /** * Destructor. Empty. */ UMLClassifierListItem::~UMLClassifierListItem() { } /** * Copy the internal presentation of this object into the new * object. */ void UMLClassifierListItem::copyInto(UMLObject *lhs) const { // Call the parent. UMLObject::copyInto(lhs); UMLClassifierListItem *o = lhs->asUMLClassifierListItem(); if (o) o->setType(getType()); } /** * Returns a string representation of the list item. * * @param sig What type of operation string to show. * @return The string representation of the operation. */ QString UMLClassifierListItem::toString(Uml::SignatureType::Enum sig, bool) const { Q_UNUSED(sig); return name(); } /** * Returns the type of the UMLClassifierListItem. * * @return The type of the UMLClassifierListItem. */ UMLClassifier * UMLClassifierListItem::getType() const { return m_pSecondary ? m_pSecondary->asUMLClassifier() : nullptr; } /** * Returns the type name of the UMLClassifierListItem. * * @return The type name of the UMLClassifierListItem. */ QString UMLClassifierListItem::getTypeName() const { if (m_pSecondary == nullptr) return m_SecondaryId; const UMLPackage *typePkg = m_pSecondary->umlPackage(); if (typePkg != nullptr && typePkg != umlPackage()) return m_pSecondary->fullyQualifiedName(); return m_pSecondary->name(); } /** * Sets the type of the UMLAttribute. * * @param type Pointer to the UMLObject of the type. */ void UMLClassifierListItem::setType(UMLObject *type) { if (m_pSecondary != type) { m_pSecondary = type; UMLObject::emitModified(); } } /** * Sets the type name of the UMLClassifierListItem. * DEPRECATED - use setType() instead. * * @param type The type name of the UMLClassifierListItem. */ void UMLClassifierListItem::setTypeName(const QString &type) { if (type.isEmpty() || type == QStringLiteral("void")) { m_pSecondary = nullptr; m_SecondaryId.clear(); return; } UMLDoc *pDoc = UMLApp::app()->document(); m_pSecondary = pDoc->findUMLObject(type); if (m_pSecondary == nullptr) { // Make data type for easily identified cases if (Model_Utils::isCommonDataType(type) || type.contains(QLatin1Char('*'))) { m_pSecondary = Object_Factory::createUMLObject(UMLObject::ot_Datatype, type); logDebug1("UMLClassifierListItem::setTypeName: created datatype for %1", type); } else { m_SecondaryId = type; } } UMLObject::emitModified(); }
4,258
C++
.cpp
143
26.244755
92
0.685686
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,490
entityattribute.cpp
KDE_umbrello/umbrello/umlmodel/entityattribute.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "entityattribute.h" // app includes #include "debug_utils.h" //#include "umlcanvasobject.h" #include "umldoc.h" #include "uml.h" #include "umlentityattributedialog.h" #include "object_factory.h" // qt includes DEBUG_REGISTER(UMLEntityAttribute) /** * Sets up an entityattribute. * @param parent The parent of this UMLEntityAttribute. * @param name The name of this UMLEntityAttribute. * @param id The unique id given to this UMLEntityAttribute. * @param s The visibility of the UMLEntityAttribute. * @param type The type of this UMLEntityAttribute. * @param iv The initial value of the entityattribute. */ UMLEntityAttribute::UMLEntityAttribute(UMLObject *parent, const QString& name, Uml::ID::Type id, Uml::Visibility::Enum s, UMLObject *type, const QString& iv) : UMLAttribute(parent, name, id, s, type, iv) { init(); } /** * Sets up an entityattribute. * @param parent The parent of this UMLEntityAttribute. */ UMLEntityAttribute::UMLEntityAttribute(UMLObject *parent) : UMLAttribute(parent) { init(); } /** * Destructor. */ UMLEntityAttribute::~UMLEntityAttribute() { } /** * Initialize members of this class. * Auxiliary method used by constructors. */ void UMLEntityAttribute::init() { m_BaseType = UMLObject::ot_EntityAttribute; m_indexType = UMLEntityAttribute::None; m_autoIncrement = false; m_null = false; } /** * Returns the value of the UMLEntityAttribute's attributes property. * @return The value of the UMLEntityAttribute's attributes property. */ QString UMLEntityAttribute::getAttributes() const { return m_attributes; } /** * Sets the UMLEntityAttribute's attributes property. * @param attributes The new value for the attributes property. */ void UMLEntityAttribute::setAttributes(const QString& attributes) { m_attributes = attributes; } /** * Returns the UMLEntityAttribute's length/values property. * @return The new value of the length/values property. */ QString UMLEntityAttribute::getValues() const { return m_values; } /** * Sets the UMLEntityAttribute's length/values property. * @param values The new value of the length/values property. */ void UMLEntityAttribute::setValues(const QString& values) { m_values = values; } /** * Returns the UMLEntityAttribute's auto_increment boolean * @return The UMLEntityAttribute's auto_increment boolean */ bool UMLEntityAttribute::getAutoIncrement() const { return m_autoIncrement; } /** * Sets the UMLEntityAttribute's auto_increment boolean * @param autoIncrement The UMLEntityAttribute's auto_increment boolean */ void UMLEntityAttribute::setAutoIncrement(const bool autoIncrement) { m_autoIncrement = autoIncrement; } /** * Returns the UMLEntityAttribute's index type property. * @return The value of the UMLEntityAttribute's index type property. */ UMLEntityAttribute::DBIndex_Type UMLEntityAttribute::indexType() const { return m_indexType; } /** * Sets the initial value of the UMLEntityAttribute's index type property. * @param indexType The initial value of the UMLEntityAttribute's index type property. */ void UMLEntityAttribute::setIndexType(const UMLEntityAttribute::DBIndex_Type indexType) { m_indexType = indexType; } /** * Returns the UMLEntityAttribute's allow null value. * @return The UMLEntityAttribute's allow null value. */ bool UMLEntityAttribute::getNull() const { return m_null; } /** * Sets the initial value of the UMLEntityAttribute's allow null value. * @param nullIn The initial value of the UMLEntityAttribute's allow null value. */ void UMLEntityAttribute::setNull(const bool nullIn) { m_null = nullIn; } /** * Returns a string representation of the UMLEntityAttribute. * @param sig If true will show the entityattribute type and initial value. * @return Returns a string representation of the UMLEntityAttribute. */ QString UMLEntityAttribute::toString(Uml::SignatureType::Enum sig, bool /*withStereotype*/) const { QString s; //FIXME if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::NoSig) { s = Uml::Visibility::toString(m_visibility, true) + QLatin1Char(' '); } if (sig == Uml::SignatureType::ShowSig || sig == Uml::SignatureType::SigNoVis) { QString string = s + name() + QStringLiteral(" : ") + getTypeName(); if(m_InitialValue.length() > 0) string += QStringLiteral(" = ") + m_InitialValue; return string; } else return s + name(); } /** * Overloaded '==' operator */ bool UMLEntityAttribute::operator==(const UMLEntityAttribute &rhs) const { if(this == &rhs) return true; if(!UMLObject::operator==(rhs)) return false; // The type name is the only distinguishing criterion. // (Some programming languages might support more, but others don't.) if (m_pSecondary != rhs.m_pSecondary) return false; return true; } /** * Copy the internal presentation of this object into the UMLEntityAttribute * object. */ void UMLEntityAttribute::copyInto(UMLObject *lhs) const { UMLEntityAttribute *target = lhs->asUMLEntityAttribute(); // call the parent first. UMLClassifierListItem::copyInto(target); // Copy all datamembers target->m_pSecondary = m_pSecondary; target->m_SecondaryId = m_SecondaryId; target->m_InitialValue = m_InitialValue; target->m_ParmKind = m_ParmKind; } /** * Make a clone of the UMLEntityAttribute. */ UMLObject* UMLEntityAttribute::clone() const { UMLEntityAttribute* clone = new UMLEntityAttribute(umlParent()->asUMLEntityAttribute()); copyInto(clone); return clone; } /** * Creates the <UML:EntityAttribute> XMI element. */ void UMLEntityAttribute::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("EntityAttribute"), QStringLiteral("ownedAttribute")); if (m_pSecondary == nullptr) { logDebug2("UMLEntityAttribute::saveToXMI %1: m_pSecondary is null, using local name %2", name(), m_SecondaryId); writer.writeAttribute(QStringLiteral("type"), m_SecondaryId); } else { writer.writeAttribute(QStringLiteral("type"), Uml::ID::toString(m_pSecondary->id())); } writer.writeAttribute(QStringLiteral("initialValue"), m_InitialValue); writer.writeAttribute(QStringLiteral("dbindex_type"), QString::number(m_indexType)); writer.writeAttribute(QStringLiteral("values"), m_values); writer.writeAttribute(QStringLiteral("attributes"), m_attributes); writer.writeAttribute(QStringLiteral("auto_increment"), QString::number(m_autoIncrement)); writer.writeAttribute(QStringLiteral("allow_null"), QString::number(m_null)); UMLObject::save1end(writer); } /** * Loads the <UML:EntityAttribute> XMI element. */ bool UMLEntityAttribute::load1(QDomElement & element) { if (! UMLAttribute::load1(element)) return false; int indexType = element.attribute(QStringLiteral("dbindex_type"), QStringLiteral("1100")).toInt(); m_indexType = (UMLEntityAttribute::DBIndex_Type)indexType; m_values = element.attribute(QStringLiteral("values")); m_attributes = element.attribute(QStringLiteral("attributes")); m_autoIncrement = (bool)element.attribute(QStringLiteral("auto_increment")).toInt(); m_null = (bool)element.attribute(QStringLiteral("allow_null")).toInt(); return true; } /** * Display the properties configuration dialog for the entityattribute. */ bool UMLEntityAttribute::showPropertiesDialog(QWidget* parent) { UMLEntityAttributeDialog dialog(parent, this); return dialog.exec(); }
7,937
C++
.cpp
241
29.481328
102
0.726312
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,491
category.cpp
KDE_umbrello/umbrello/umlmodel/category.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "category.h" /** * Constructs a Category. * * @param name The name of the Category. * @param id The unique id to assign to this Category. */ UMLCategory::UMLCategory(const QString & name, Uml::ID::Type id) : UMLCanvasObject(name, id) { init(); } /** * Standard destructor. */ UMLCategory::~UMLCategory() { } /** * Initializes key variables of the class. */ void UMLCategory::init() { m_BaseType = UMLObject::ot_Category; m_CategoryType = ct_Disjoint_Specialisation; } /** * Copy the internal presentation of this object into the new * object. */ void UMLCategory::copyInto(UMLObject *lhs) const { UMLCategory *target = lhs->asUMLCategory(); // call the parent first UMLCanvasObject::copyInto(target); target->m_CategoryType = m_CategoryType; } /** * Make a clone of this object. */ UMLObject* UMLCategory::clone() const { UMLCategory *clone = new UMLCategory(); copyInto(clone); return clone; } /** * Creates the <UML:Category> XMI element. */ void UMLCategory::saveToXMI(QXmlStreamWriter& writer) { UMLObject::save1(writer, QStringLiteral("Category")); writer.writeAttribute(QStringLiteral("categoryType"), QString::number(m_CategoryType)); UMLObject::save1end(writer); } /** * Loads the <UML:Category> XMI element (empty.) */ bool UMLCategory::load1(QDomElement& element) { m_CategoryType = (Category_Type)element.attribute(QStringLiteral("categoryType"), QStringLiteral("0")).toInt(); return true; } /** * Get the category type */ UMLCategory::Category_Type UMLCategory::getType() { return m_CategoryType; } /** * Set the category type */ void UMLCategory::setType(Category_Type type) { m_CategoryType = type; emitModified(); }
1,957
C++
.cpp
83
20.481928
92
0.699087
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,492
debug_utils.cpp
KDE_umbrello/umbrello/debug/debug_utils.cpp
/* SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch> SPDX-FileCopyrightText: 2012 Ralf Habacker <ralf.habacker@freenet.de> SPDX-FileCopyrightText: 2022 Oliver Kellogg <okellogg@users.sourceforge.net> SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "debug_utils.h" #include <KLocalizedString> #include <QFileInfo> Q_LOGGING_CATEGORY(UMBRELLO, "umbrello") Tracer* Tracer::s_instance = nullptr; Tracer::MapType* Tracer::s_classes; Tracer::StateMap* Tracer::s_states; bool Tracer::s_logToConsole; #define MAX_TRACERCLIENTS 500 /** * The client info filled by registerClass() needs to be Plain Old Data * (not requiring a constructor) as opposed to C++ class with complex * constructor because registerClass() is called very early in program * execution, in the "static initialization". * The static initialization is done before the main program starts * executing. * The compiler/linker determines the order in which static data are * initialized, and the compiler/linker chosen order may not coincide * with the programmer's expectation. * If a global or static object of a class has a constructor in which * methods of other global/static class objects are called then these * calls can easily result in crash. It cannot be naively assumed that * the other objects have already been constructed at the time of the * call because the compiler/linker may have chosen a contrary ordering * whereby their static initialization is done afterwards. * Concrete examples of such crashes are given in the source. */ struct ClientInfo_POD { /* First example of problem mentioned in doxygen documentation: Controlled termination via fatal message from Qt, "QWidget: Must construct a QApplication before a QWidget" in this case happening on CodeEditorTracer but happens on other classes as well, #5 QMessageLogger::fatal (this=this@entry=0x7fffffffd2e0, msg=msg@entry=0x7ffff63cebc8 "QWidget: Must construct a QApplication before a QWidget") at global/qlogging.cpp:893 #6 0x00007ffff600c8d1 in QWidgetPrivate::QWidgetPrivate (this=<optimized out>, this@entry=0xb1b070, version=<optimized out>, version@entry=331522) at kernel/qwidget.cpp:191 #7 0x00007ffff61069ae in QFramePrivate::QFramePrivate (this=this@entry=0xb1b070) at widgets/qframe.cpp:60 #8 0x00007ffff6107989 in QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate (this=this@entry=0xb1b070) at widgets/qabstractscrollarea.cpp:167 #9 0x00007ffff6286179 in QAbstractItemViewPrivate::QAbstractItemViewPrivate (this=this@entry=0xb1b070) at itemviews/qabstractitemview.cpp:119 #10 0x00007ffff6313e2b in QTreeViewPrivate::QTreeViewPrivate (this=0xb1b070) at ../../include/QtWidgets/5.15.2/QtWidgets/private/../../../../../src/widgets/itemviews/qtreeview_p.h:88 #11 QTreeWidgetPrivate::QTreeWidgetPrivate (this=0xb1b070) at ../../include/QtWidgets/5.15.2/QtWidgets/private/../../../../../src/widgets/itemviews/qtreewidget_p.h:225 #12 QTreeWidget::QTreeWidget (this=0xb17bd0, parent=0x0) at itemviews/qtreewidget.cpp:2662 #13 0x000000000048ff02 in Tracer::Tracer (this=0xb17bd0, parent=0x0) at /umbrello-master/umbrello/debug/debug_utils.cpp:33 #14 0x000000000048fec7 in Tracer::instance () at /umbrello-master/umbrello/debug/debug_utils.cpp:23 #15 0x0000000000490237 in Tracer::registerClass (name="CodeEditor", state=true, filePath="/umbrello-master/umbrello/dialogs/codeeditor.cpp") at /umbrello-master/umbrello/debug/debug_utils.cpp:109 #16 0x000000000049ef7f in CodeEditorTracer::CodeEditorTracer (this=0xadd6c0 <CodeEditorTracerGlobal>) at /umbrello-master/umbrello/dialogs/codeeditor.cpp:54 #17 0x000000000049e742 in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at /umbrello-master/umbrello/dialogs/codeeditor.cpp:54 #18 0x000000000049e758 in _GLOBAL__sub_I_codeeditor.cpp(void) () at /umbrello-master/umbrello/dialogs/codeeditor.cpp:1534 #19 0x00007ffff4bf46fd in call_init (env=<optimized out>, argv=0x7fffffffd578, argc=1) at ../csu/libc-start.c:145 #20 __libc_start_main_impl (main=0x46f255 <main(int, char**)>, argc=1, argv=0x7fffffffd578, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffd568) at ../csu/libc-start.c:379 #21 0x000000000046ea75 in _start () at ../sysdeps/x86_64/start.S:116 Second example of problem: Crash in different client classes of Tracer, in this example running unittests/testoptionstate the SEGV happens on Tracer::registerClass call from UMLApp but also happens from other classes, (gdb) bt #0 std::__atomic_base<int>::load (__m=std::memory_order_relaxed, this=0x0) at /usr/include/c++/11/bits/atomic_base.h:481 #1 QAtomicOps<int>::loadRelaxed<int> (_q_value=...) at /usr/include/qt5/QtCore/qatomic_cxx11.h:239 #2 0x00000000004721c8 in QBasicAtomicInteger<int>::loadRelaxed (this=0x0) at /usr/include/qt5/QtCore/qbasicatomic.h:107 #3 0x000000000047162c in QtPrivate::RefCount::isShared (this=0x0) at /usr/include/qt5/QtCore/qrefcount.h:101 #4 0x000000000051c2b3 in QMap<QString, MapEntry>::detach (this=0xac5c30 <s_classes>) at /usr/include/qt5/QtCore/qmap.h:361 #5 0x000000000051bf27 in QMap<QString, MapEntry>::operator[] (this=0xac5c30 <s_classes>, akey="UMLApp") at /usr/include/qt5/QtCore/qmap.h:680 #6 0x000000000051b325 in Tracer::registerClass (name="UMLApp", state=true, filePath="/umbrello-master/umbrello/uml.cpp") at /umbrello-master/umbrello/debug/debug_utils.cpp:123 #7 0x0000000000497cd9 in UMLAppTracer::UMLAppTracer (this=0xac5640 <UMLAppTracerGlobal>) at /umbrello-master/umbrello/uml.cpp:127 #8 0x0000000000496240 in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at /umbrello-master/umbrello/uml.cpp:127 #9 0x0000000000496256 in _GLOBAL__sub_I_uml.cpp(void) () at /umbrello-master/umbrello/uml.cpp:3590 #10 0x00007ffff4b9a6fd in call_init (env=<optimized out>, argv=0x7fffffffd568, argc=1) at ../csu/libc-start.c:145 #11 __libc_start_main_impl (main=0x4754fe <main(int, char**)>, argc=1, argv=0x7fffffffd568, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffd558) at ../csu/libc-start.c:379 #12 0x000000000046e9e5 in _start () at ../sysdeps/x86_64/start.S:116 */ const char * name; bool state; const char * filePath; }; static ClientInfo_POD g_clientInfo[MAX_TRACERCLIENTS]; static int n_clients = 0; Tracer* Tracer::instance() { if (s_instance == nullptr) { s_instance = new Tracer(); s_classes = new MapType(); s_states = new StateMap(); // Transfer g_clientInfo (C plain old data) to s_classes (C++) for (int i = 0; i < n_clients; i++) { ClientInfo_POD & cli = g_clientInfo[i]; QFileInfo fi(QLatin1String(cli.filePath)); QString dirName = fi.absolutePath(); QFileInfo f(dirName); QString path = f.fileName(); uDebug() << "Tracer::registerClass(" << cli.name << ") : " << path; QString name = QString::fromLatin1(cli.name); (*s_classes)[name] = MapEntry(path, cli.state); } QString umbrello_logToConsole = QString::fromLatin1(qgetenv("UMBRELLO_LOG_TO_CONSOLE")); s_logToConsole = (umbrello_logToConsole == QStringLiteral("1")); } return s_instance; } /** * Constructor. * @param parent the parent widget */ Tracer::Tracer(QWidget *parent) : QTreeWidget(parent) { setRootIsDecorated(true); setAlternatingRowColors(true); setHeaderLabel(i18n("Class Name")); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotItemClicked(QTreeWidgetItem*,int))); } /** * Destructor. */ Tracer::~Tracer() { clear(); } /** * Return debugging state for a given class * @param name the class name to check */ bool Tracer::isEnabled(const QString& name) const { if (!s_classes->contains(name)) { // Classes that are not registered are enabled by default. // The intent is that classes which produce few debug messages, or whose // debug messages for some reason shall not be suppressible, shall not // require registration. // Furthermore, returning false here would prevent a class from ever // producing debug messages. return true; } return (*s_classes)[name].state; } /** * Enable debug output for the given class. * @param name class name */ void Tracer::enable(const QString& name) { (*s_classes)[name].state = true; update(name); } /** * Disable debug output for the given class. * @param name class name */ void Tracer::disable(const QString& name) { (*s_classes)[name].state = false; update(name); } void Tracer::enableAll() { //:TODO: } void Tracer::disableAll() { //:TODO: } bool Tracer::logToConsole() { return s_logToConsole; } /** * Register class for debug output * @param name class name * @param state initial enabled state * @param filePath path qualified source filename of class */ void Tracer::registerClass(const char *name, bool state, const char * filePath /* = nullptr */) { if (n_clients >= MAX_TRACERCLIENTS) { uError() << "Tracer::registerClass : MAX_TRACERCLIENTS is exceeded"; return; } ClientInfo_POD & client = g_clientInfo[n_clients]; client.name = strdup(name); client.state = state; if (filePath) client.filePath = strdup(filePath); else client.filePath = nullptr; n_clients++; } /** * Transfer class state into tree widget. * @param name class name */ void Tracer::update(const QString &name) { if (!isVisible()) return; QList<QTreeWidgetItem*> items = findItems(name, Qt::MatchFixedString); for(QTreeWidgetItem *item : items) { item->setCheckState(0, (*s_classes)[name].state ? Qt::Checked : Qt::Unchecked); } } /** * Update check box of parent items. * * @param parent parent widget item */ void Tracer::updateParentItemCheckBox(QTreeWidgetItem* parent) { int selectedCount = 0; for(int i = 0; i < parent->childCount(); i++) { if (parent->child(i)->checkState(0) == Qt::Checked) selectedCount++; } if (selectedCount == parent->childCount()) parent->setCheckState(0, Qt::Checked); else if (selectedCount == 0) parent->setCheckState(0, Qt::Unchecked); else parent->setCheckState(0, Qt::PartiallyChecked); (*s_states)[parent->text(0)] = parent->checkState(0); } /** * Fill tree widget with collected classes. */ void Tracer::showEvent(QShowEvent* e) { Q_UNUSED(e); clear(); MapType::const_iterator i = s_classes->constBegin(); for(; i != s_classes->constEnd(); i++) { QList<QTreeWidgetItem*> items = findItems(i.value().filePath, Qt::MatchFixedString); QTreeWidgetItem *topLevel = nullptr; if (items.size() == 0) { topLevel = new QTreeWidgetItem(QStringList(i.value().filePath)); topLevel->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); updateParentItemCheckBox(topLevel); addTopLevelItem(topLevel); } else topLevel = items.first(); QTreeWidgetItem* item = new QTreeWidgetItem(topLevel, QStringList(i.key())); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setCheckState(0, i.value().state ? Qt::Checked : Qt::Unchecked); } for(int i = 0; i < topLevelItemCount(); i++) updateParentItemCheckBox(topLevelItem(i)); } /** */ void Tracer::slotParentItemClicked(QTreeWidgetItem* parent) { // @TODO parent->checkState(0) do not return the correct state // Qt::CheckState state = parent->checkState(0); Qt::CheckState state = (*s_states)[parent->text(0)]; if (state == Qt::PartiallyChecked || state == Qt::Unchecked) { for(int i = 0; i < parent->childCount(); i++) { QString text = parent->child(i)->text(0); (*s_classes)[text].state = true; parent->child(i)->setCheckState(0, (*s_classes)[text].state ? Qt::Checked : Qt::Unchecked); } } else if (state == Qt::Checked) { for(int i = 0; i < parent->childCount(); i++) { QString text = parent->child(i)->text(0); (*s_classes)[text].state = false; parent->child(i)->setCheckState(0, (*s_classes)[text].state ? Qt::Checked : Qt::Unchecked); } } updateParentItemCheckBox(parent); } /** * handle tree widget item selection signal * @param item tree widget item * @param column selected column */ void Tracer::slotItemClicked(QTreeWidgetItem* item, int column) { Q_UNUSED(column); if (item->parent()) { (*s_classes)[item->text(0)].state = !(*s_classes)[item->text(0)].state; item->setCheckState(0, (*s_classes)[item->text(0)].state ? Qt::Checked : Qt::Unchecked); updateParentItemCheckBox(item->parent()); return; } slotParentItemClicked(item); }
13,324
C++
.cpp
304
39.082237
126
0.701948
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,493
codegenerator.cpp
KDE_umbrello/umbrello/codegenerators/codegenerator.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codegenerator.h" // app includes #include "debug_utils.h" #include "overwritedialog.h" #include "codeviewerdialog.h" #include "simplecodegenerator.h" #include "attribute.h" #include "association.h" #include "classifier.h" #include "classifiercodedocument.h" #include "codedocument.h" #include "codegenerationpolicy.h" #include "operation.h" #include "uml.h" #include "umldoc.h" #include "umlobject.h" #include "umlattributelist.h" #include "umloperationlist.h" #include <KLocalizedString> #include <KMessageBox> // qt includes #include <QApplication> #include <QDateTime> #include <QDir> #include <QDomDocument> #include <QDomElement> #include <QPointer> #include <QRegularExpression> #include <QTextStream> #include <QXmlStreamWriter> // system includes #include <cstdlib> // to get the user name DEBUG_REGISTER(CodeGenerator) /** * Constructor for a code generator. */ CodeGenerator::CodeGenerator() : m_applyToAllRemaining(true), m_document(UMLApp::app()->document()), m_lastIDIndex(0) { // initial population of our project generator // CANNOT Be done here because we would call pure virtual method // of newClassifierDocument (bad!). // We should only call from the child // initFromParentDocument(); } /** * Destructor. */ CodeGenerator::~CodeGenerator() { // destroy all owned codedocuments qDeleteAll(m_codedocumentVector); m_codedocumentVector.clear(); } /** * Get a unique id for this codedocument. * @return id for the codedocument */ QString CodeGenerator::getUniqueID(CodeDocument * codeDoc) { QString id = codeDoc->ID(); // does this document already exist? then just return its present id if (!id.isEmpty() && findCodeDocumentByID(id)) { return id; } // approach now differs by whether or not it is a classifier code document ClassifierCodeDocument * classDoc = dynamic_cast<ClassifierCodeDocument*>(codeDoc); if (classDoc) { UMLClassifier *c = classDoc->getParentClassifier(); id = Uml::ID::toString(c->id()); // this is supposed to be unique already.. } else { QString prefix = QStringLiteral("doc"); QString id = prefix + QStringLiteral("_0"); int number = m_lastIDIndex; for (; findCodeDocumentByID(id); ++number) { id = prefix + QLatin1Char('_') + QString::number(number); } m_lastIDIndex = number; } return id; } /** * Find a code document by the given id string. * @return CodeDocument */ CodeDocument * CodeGenerator::findCodeDocumentByID(const QString &tag) { CodeDocument* doc = m_codeDocumentDictionary.value(tag); if (doc) { return doc; } else { return nullptr; } } /** * Add a CodeDocument object to the m_codedocumentVector List. * @return boolean - will return false if it couldnt add a document */ bool CodeGenerator::addCodeDocument(CodeDocument * doc) { QString tag = doc->ID(); // assign a tag if one doesn't already exist if (tag.isEmpty()) { tag = getUniqueID(doc); doc->setID(tag); } if (m_codeDocumentDictionary.contains(tag)) { return false; // return false, we already have some object with this tag in the list } else { m_codeDocumentDictionary.insert(tag, doc); } m_codedocumentVector.append(doc); return true; } /** * Remove a CodeDocument object from m_codedocumentVector List. * @return boolean - will return false if it couldnt remove a document */ bool CodeGenerator::removeCodeDocument(CodeDocument * remove_object) { QString tag = remove_object->ID(); if (!(tag.isEmpty())) { m_codeDocumentDictionary.remove(tag); } else { return false; } m_codedocumentVector.removeAll(remove_object); return true; } /** * Get the list of CodeDocument objects held by m_codedocumentVector. * @return CodeDocumentList list of CodeDocument objects held by * m_codedocumentVector */ CodeDocumentList * CodeGenerator::getCodeDocumentList() { return &m_codedocumentVector; } /** * Load codegenerator data from xmi. * @param qElement the element from which to load */ void CodeGenerator::loadFromXMI(QDomElement & qElement) { // look for our particular child element QDomNode node = qElement.firstChild(); QDomElement element = node.toElement(); QString langType = Uml::ProgrammingLanguage::toString(language()); if (qElement.tagName() != QStringLiteral("codegenerator") || qElement.attribute(QStringLiteral("language"), QStringLiteral("UNKNOWN")) != langType) { return; } // got our code generator element, now load // codedocuments QDomNode codeDocNode = qElement.firstChild(); QDomElement codeDocElement = codeDocNode.toElement(); while (!codeDocElement.isNull()) { QString docTag = codeDocElement.tagName(); QString id = codeDocElement.attribute(QStringLiteral("id"), QStringLiteral("-1")); if (docTag == QStringLiteral("sourcecode")) { loadCodeForOperation(id, codeDocElement); } else if (docTag == QStringLiteral("codedocument") || docTag == QStringLiteral("classifiercodedocument")) { CodeDocument * codeDoc = findCodeDocumentByID(id); if (codeDoc) { codeDoc->loadFromXMI(codeDocElement); } else { logWarn1("missing code document for id %1", id); } } else { logWarn1("got strange codegenerator child node %1, ignoring.", docTag); } codeDocNode = codeDocElement.nextSibling(); codeDocElement = codeDocNode.toElement(); } } /** * Extract and load code for operations from xmi section. * Probably we have code which was entered in classpropdlg for an operation. */ void CodeGenerator::loadCodeForOperation(const QString& idStr, const QDomElement& codeDocElement) { Uml::ID::Type id = Uml::ID::fromString(idStr); UMLObject *obj = m_document->findObjectById(id); if (obj) { logDebug1("CodeGenerator::loadCodeForOperation found UMLObject for id: %1", idStr); QString value = codeDocElement.attribute(QStringLiteral("value")); UMLObject::ObjectType t = obj->baseType(); if (t == UMLObject::ot_Operation) { UMLOperation *op = obj->asUMLOperation(); op->setSourceCode(value); } else { logError2("sourcecode id %1 has unexpected type %2", idStr, UMLObject::toString(t)); } } else { logError1("unknown sourcecode id %1", idStr); } } /** * Save the XMI representation of this object */ void CodeGenerator::saveToXMI(QXmlStreamWriter& writer) { QString langType = Uml::ProgrammingLanguage::toString(language()); writer.writeStartElement(QStringLiteral("codegenerator")); writer.writeAttribute(QStringLiteral("language"), langType); if (dynamic_cast<SimpleCodeGenerator*>(this)) { UMLClassifierList concepts = m_document->classesAndInterfaces(); for(UMLClassifier *c : concepts) { uIgnoreZeroPointer(c); UMLOperationList operations = c->getOpList(); for(UMLOperation *op : operations) { // save the source code QString code = op->getSourceCode(); if (code.isEmpty()) { continue; } writer.writeStartElement(QStringLiteral("sourcecode")); writer.writeAttribute(QStringLiteral("id"), Uml::ID::toString(op->id())); writer.writeAttribute(QStringLiteral("value"), code); writer.writeEndElement(); } } } else { const CodeDocumentList * docList = getCodeDocumentList(); CodeDocumentList::const_iterator it = docList->begin(); CodeDocumentList::const_iterator end = docList->end(); for (; it != end; ++it) { (*it)->saveToXMI(writer); } } writer.writeEndElement(); } /** * Force a synchronize of this code generator, and its present contents, to that of the parent UMLDocument. * "UserGenerated" code will be preserved, but Autogenerated contents will be updated/replaced * or removed as is apppropriate. */ void CodeGenerator::syncCodeToDocument() { CodeDocumentList::iterator it = m_codedocumentVector.begin(); CodeDocumentList::iterator end = m_codedocumentVector.end(); for (; it != end; ++it) { (*it)->synchronize(); } } /** * Find a code document by the given classifier. * NOTE: FIX, this should be 'protected' or we could have problems with CPP code generator * @return CodeDocument * @param classifier */ CodeDocument * CodeGenerator::findCodeDocumentByClassifier(UMLClassifier * classifier) { return findCodeDocumentByID(Uml::ID::toString(classifier->id())); } /** * This method is here to provide class wizard the * ability to write out only those classes which * are selected by the user. */ void CodeGenerator::writeCodeToFile() { writeListedCodeDocsToFile(&m_codedocumentVector); finalizeRun(); } /** * This method is here to provide class wizard the * ability to write out only those classes which * are selected by the user. */ void CodeGenerator::writeCodeToFile(UMLClassifierList & concepts) { CodeDocumentList docs; for(UMLClassifier *classifier : concepts) { CodeDocument * doc = findCodeDocumentByClassifier(classifier); if (doc) { docs.append(doc); } } writeListedCodeDocsToFile(&docs); finalizeRun(); } // Main method. Will write out passed code documents to file as appropriate. /** * The actual internal routine which writes code documents. */ void CodeGenerator::writeListedCodeDocsToFile(CodeDocumentList * docs) { // iterate thru all code documents CodeDocumentList::iterator it = docs->begin(); CodeDocumentList::iterator end = docs->end(); for (; it != end; ++it) { // we need this so we know when to emit a 'codeGenerated' signal ClassifierCodeDocument * cdoc = dynamic_cast<ClassifierCodeDocument *>(*it); bool codeGenSuccess = false; // we only write the document, if so requested if ((*it)->getWriteOutCode()) { QString filename = findFileName(*it); // check that we may open that file for writing QFile file; if (openFile(file, filename)) { QTextStream stream(&file); stream << (*it)->toString() << '\n'; file.close(); codeGenSuccess = true; // we wrote the code - OK Q_EMIT showGeneratedFile(file.fileName()); } else { logWarn1("Cannot open file %1 for writing", file.fileName()); codeGenSuccess = false; } } if (cdoc) { Q_EMIT codeGenerated(cdoc->getParentClassifier(), codeGenSuccess); } } } /** * A single call to writeCodeToFile() usually entails processing many * items (e.g. as classifiers) for which code is generated. * This method is called after all code of one call to writeCodeToFile() * has been generated. * It can be reimplemented by concrete code generators to perform additional * cleanups or other actions that can only be performed once all code has * been written. */ void CodeGenerator::finalizeRun() { } /** * Gets the heading file (as a string) to be inserted at the * beginning of the generated file. you give the file type as * parameter and get the string. if fileName starts with a * period (.) then fileName is the extension (.cpp, .h, * .java) if fileName starts with another character you are * requesting a specific file (mylicensefile.txt). The files * can have parameters which are denoted by %parameter%. * * current parameters are * %author% * %date% * %time% * %filepath% * * @return QString * @param file */ QString CodeGenerator::getHeadingFile(const QString &file) { return UMLApp::app()->commonPolicy()->getHeadingFile(file); } /** * Returns a name that can be written to in the output directory, * respecting the overwrite policy. * If a file of the given name and extension does not exist, * then just returns the name. * If a file of the given name and extension does exist, * then opens an overwrite dialog. In this case the name returned * may be a modification of the input name. * This method is invoked by findFileName(). * * @param name the proposed output file name * @param extension the extension to use * @return the real file name that should be used (including extension) or * QString() if none to be used */ QString CodeGenerator::overwritableName(const QString& name, const QString &extension) { CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy(); QDir outputDirectory = pol->getOutputDirectory(); QString filename = name + extension; if (!outputDirectory.exists(filename)) { return filename; } int suffix; QPointer<OverwriteDialog> overwriteDialog = new OverwriteDialog(name, outputDirectory.absolutePath(), m_applyToAllRemaining, qApp->activeWindow()); switch (pol->getOverwritePolicy()) { //if it exists, check the OverwritePolicy we should use case CodeGenerationPolicy::Ok: //ok to overwrite file filename = name + extension; break; case CodeGenerationPolicy::Ask: //ask if we can overwrite switch(overwriteDialog->exec()) { case OverwriteDialog::Ok: //overwrite file if (overwriteDialog->applyToAllRemaining()) { pol->setOverwritePolicy(CodeGenerationPolicy::Ok); filename = name + extension; } else { m_applyToAllRemaining = false; } break; case OverwriteDialog::No: //generate similar name suffix = 1; while (1) { filename = name + QStringLiteral("__") + QString::number(suffix) + extension; if (!outputDirectory.exists(filename)) break; suffix++; } if (overwriteDialog->applyToAllRemaining()) { pol->setOverwritePolicy(CodeGenerationPolicy::Never); } else { m_applyToAllRemaining = false; } break; case OverwriteDialog::Cancel: //don't output anything if (overwriteDialog->applyToAllRemaining()) { pol->setOverwritePolicy(CodeGenerationPolicy::Cancel); } else { m_applyToAllRemaining = false; } delete overwriteDialog; return QString(); break; } break; case CodeGenerationPolicy::Never: //generate similar name suffix = 1; while (1) { filename = name + QStringLiteral("__") + QString::number(suffix) + extension; if (!outputDirectory.exists(filename)) { break; } suffix++; } break; case CodeGenerationPolicy::Cancel: //don't output anything delete overwriteDialog; return QString(); break; } delete overwriteDialog; return filename; } /** * Opens a file named "name" for writing in the outputDirectory. * If something goes wrong, it informs the user * if this function returns true, you know you can write to the file. * @param file file descriptor * @param fileName the name of the file * @return success state */ bool CodeGenerator::openFile(QFile & file, const QString &fileName) { //open files for writing. if (fileName.isEmpty()) { logWarn0("cannot find a file name"); return false; } else { QDir outputDirectory = UMLApp::app()->commonPolicy()->getOutputDirectory(); if (!outputDirectory.exists()) outputDirectory.mkpath(outputDirectory.absolutePath()); file.setFileName(outputDirectory.absoluteFilePath(fileName)); if(!file.open(QIODevice::WriteOnly)) { KMessageBox::information(nullptr, i18n("Cannot open file %1 for writing. Please make sure the folder exists and you have permissions to write to it.", file.fileName()), i18n("Cannot Open File")); return false; } return true; } } /** * Replaces spaces with underscores and capitalises as defined in m_modname * @return QString * @param name */ QString CodeGenerator::cleanName(const QString &name) { QString retval = name; retval.replace(QRegularExpression(QStringLiteral("\\W+")), QStringLiteral("_")); return retval; } /** * Finds an appropriate file name for the given CodeDocument, taking into * account the Overwrite Policy and asking the user what to do if need be * (if policy == Ask). * * @param codeDocument the CodeDocument for which an output file name is desired. * @return the file name that should be used. (with extension) or * NULL if none to be used */ QString CodeGenerator::findFileName(CodeDocument * codeDocument) { // Get the path name QString path = codeDocument->getPath(); // if path is given add this as a directory to the file name QString name; if (!path.isEmpty()) { path.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/")); // Simple hack! name = path + QLatin1Char('/') + codeDocument->getFileName(); path = QLatin1Char('/') + path; } else { // determine the "natural" file name name = codeDocument->getFileName(); } // Convert all "::" to "/" : Platform-specific path separator name.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/")); // Simple hack! // if a path name exists check the existence of the path directory if (!path.isEmpty()) { QDir outputDirectory = UMLApp::app()->commonPolicy()->getOutputDirectory(); QDir pathDir(outputDirectory.absolutePath() + path); // does our complete output directory exist yet? if not, try to create it if (!pathDir.exists()) { // ugh. dir separator here is UNIX specific.. const QStringList dirs = pathDir.absolutePath().split(QLatin1Char('/')); QString currentDir; QStringList::const_iterator end(dirs.end()); for (QStringList::const_iterator dir(dirs.begin()); dir != end; ++dir) { currentDir += QLatin1Char('/') + *dir; if (! (pathDir.exists(currentDir) || pathDir.mkdir(currentDir))) { KMessageBox::error(nullptr, i18n("Cannot create the folder:\n") + pathDir.absolutePath() + i18n("\nPlease check the access rights"), i18n("Cannot Create Folder")); return QString(); } } } } name = name.simplified(); name.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_")); return overwritableName(name, codeDocument->getFileExtension()); } /** * Finds all classes in the current document to which objects of class c * are in some way related. Possible relations are Associations (generalization, * composition, etc) as well as parameters to methods and return values * this is useful in deciding which classes/files to import/include in code generation * @param c the class for which relations are to be found * @param cList a reference to the list into which return the result */ void CodeGenerator::findObjectsRelated(UMLClassifier *c, UMLPackageList &cList) { UMLPackage *temp; UMLAssociationList associations = c->getAssociations(); for(UMLAssociation *a : associations) { temp = nullptr; switch (a->getAssocType()) { case Uml::AssociationType::Generalization: case Uml::AssociationType::Realization: // only the "b" end is seen by the "a" end, not other way around { UMLObject *objB = a->getObject(Uml::RoleType::B); if (objB != c) { temp = (UMLPackage*)objB; } } break; case Uml::AssociationType::Dependency: case Uml::AssociationType::UniAssociation: { UMLObject *objA = a->getObject(Uml::RoleType::A); UMLObject *objB = a->getObject(Uml::RoleType::B); if (objA == c) { temp = objB->asUMLPackage(); } } break; case Uml::AssociationType::Aggregation: case Uml::AssociationType::Composition: case Uml::AssociationType::Association: { UMLObject *objA = a->getObject(Uml::RoleType::A); UMLObject *objB = a->getObject(Uml::RoleType::B); if (objA == c && !objB->isUMLDatatype()) { temp = objB->asUMLPackage(); } } break; default: // all others.. like for state diagrams..we currently don't use break; } // now add in list ONLY if it is not already there if (temp && !cList.count(temp)) { cList.append(temp); } } //operations UMLOperationList opl(c->getOpList()); for(UMLOperation *op : opl) { temp = nullptr; //check return value temp = (UMLClassifier*) op->getType(); if (temp && !temp->isUMLDatatype() && !cList.count(temp)) { cList.append(temp); } //check parameters UMLAttributeList atl = op->getParmList(); for(UMLAttribute *at : atl) { temp = (UMLClassifier*)at->getType(); if (temp && !temp->isUMLDatatype() && !cList.count(temp)) { cList.append(temp); } } } //attributes if (!c->isInterface()) { UMLAttributeList atl = c->getAttributeList(); for(UMLAttribute *at : atl) { temp=nullptr; temp = (UMLClassifier*) at->getType(); if (temp && !temp->isUMLDatatype() && !cList.count(temp)) { cList.append(temp); } } } } /** * Format documentation for output in source files * * @param text the documentation which has to be formatted * @param linePrefix the prefix which has to be added in the beginnig of each line * @param lineWidth the line width used for word-wrapping the documentation * * @return the formatted documentation text */ QString CodeGenerator::formatDoc(const QString &text, const QString &linePrefix, int lineWidth) { const QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); QString output; QStringList lines = text.split(endLine); for (QStringList::ConstIterator lit = lines.constBegin(); lit != lines.constEnd(); ++lit) { QString input = *lit; input.remove(QRegularExpression(QStringLiteral("\\s+$"))); if (input.length() < lineWidth) { output += linePrefix + input + endLine; continue; } int index; while ((index = input.lastIndexOf(QStringLiteral(" "), lineWidth)) >= 0) { output += linePrefix + input.left(index) + endLine; // add line input.remove(0, index + 1); // remove processed string, including white space } if (!input.isEmpty()) { output += linePrefix + input + endLine; } } return output; } /** * Format full documentation block for output in source files * * @param text the documentation which has to be formatted * @param blockHeader the prefix which has to be added in the beginning of each line (instead of the first) * @param blockFooter the prefix which has to be added in the beginning of each line (instead of the first) * @param linePrefix the prefix which has to be added in the beginning of each line (instead of the first) * @param lineWidth the line width used for word-wrapping the documentation * * @return the formatted documentation text */ QString CodeGenerator::formatFullDocBlock(const QString &text, const QString &blockHeader, const QString &blockFooter, const QString &linePrefix, int lineWidth) { const QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); QString output; QStringList lines = text.split(endLine); int lineIndex = 0; for (QStringList::ConstIterator lit = lines.constBegin(); lit != lines.constEnd(); ++lit) { QString input = *lit; input.remove(QRegularExpression(QStringLiteral("\\s+$"))); if (input.length() < lineWidth) { if (lineIndex == 0) { output += blockHeader; } else { output += linePrefix; } output += input; if (lineIndex == lines.count()-1) { output += blockFooter; } output += endLine; lineIndex++; continue; } int index; while ((index = input.lastIndexOf(QStringLiteral(" "), lineWidth)) >= 0) { if (lineIndex == 0) { output += blockHeader; } else { output += linePrefix; } output += input.left(index); // add line if (lineIndex == lines.count() - 1) { output += blockFooter; } output += endLine; lineIndex++; input.remove(0, index + 1); // remove processed string, including white space } if (!input.isEmpty()) { if (lineIndex == 0) { output += blockHeader; } else { output += linePrefix; } output += input; if (lineIndex == lines.count() - 1) { output += blockFooter; } output += endLine; lineIndex++; } } return output; } /** * Format source code for output in source files by * adding the correct indentation to every line of code. * * @param code the source code block which has to be formatted * @param indentation the blanks to indent */ QString CodeGenerator::formatSourceCode(const QString& code, const QString& indentation) { const QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); QString output; if (! code.isEmpty()) { QStringList lines = code.split(endLine); for (int i = 0; i < lines.size(); ++i) { output += indentation + lines.at(i) + endLine; } } return output; } // these are utility methods for accessing the default // code gen policy object and should go away when we // finally implement the CodeGenDialog class -b.t. void CodeGenerator::setForceDoc(bool f) { UMLApp::app()->commonPolicy()->setCodeVerboseDocumentComments(f); } bool CodeGenerator::forceDoc() const { return UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments(); } void CodeGenerator::setSectionCommentPolicy(CodeGenerationPolicy::WriteSectionCommentsPolicy f) { UMLApp::app()->commonPolicy()->setSectionCommentsPolicy(f); } bool CodeGenerator::forceSections() const // TODO change to CodeGenerationPolicy::WriteSectionCommentsPolicy { return UMLApp::app()->commonPolicy()->getSectionCommentsPolicy() == CodeGenerationPolicy::Always; } /** * Return the default datatypes for your language (bool, int etc). * Default implementation returns empty list. */ QStringList CodeGenerator::defaultDatatypes() const { return QStringList(); //empty by default, override in your code generator } /** * Check whether the given string is a reserved word for the * language of this code generator. * * @param keyword string to check * */ bool CodeGenerator::isReservedKeyword(const QString & keyword) { const QStringList keywords = reservedKeywords(); return keywords.contains(keyword); } /** * Get list of reserved keywords. */ QStringList CodeGenerator::reservedKeywords() const { static QStringList emptyList; return emptyList; } /** * Create the default stereotypes for your language (constructor, int etc). */ void CodeGenerator::createDefaultStereotypes() { //empty by default, override in your code generator //e.g. m_document->createDefaultStereotypes("constructor"); }
28,979
C++
.cpp
802
29.55985
207
0.644453
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,494
textblock.cpp
KDE_umbrello/umbrello/codegenerators/textblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "textblock.h" // local includes #include "codedocument.h" #include "codegenerationpolicy.h" #include "debug_utils.h" #include "uml.h" // qt includes #include <QRegularExpression> #include <QTextStream> /** * Constructor. */ TextBlock::TextBlock(CodeDocument * parent, const QString & text) : m_text(QString()), m_tag(QString()), m_canDelete(true), m_writeOutText(true), m_indentationLevel(0), m_parentDocument(parent) { setText(text); } /** * Destructor. */ TextBlock::~TextBlock() { } /** * Set the attribute m_canDelete. * @param canDelete the new value to set */ void TextBlock::setCanDelete(bool canDelete) { m_canDelete = canDelete; } /** * Determine if its OK to delete this textblock from the document. * Used by the text editor to know if deletion could cause a crash of * the program. * @return the value of m_canDelete */ bool TextBlock::canDelete() const { return m_canDelete; } /** * Get the value of m_parentDoc * @return the value of m_parentDoc */ CodeDocument * TextBlock::getParentDocument() const { return m_parentDocument; } /** * Set the value of m_text * The actual text of this code block. * @param text the new value of m_text */ void TextBlock::setText(const QString & text) { m_text = text; } /** * Add text to this object. * @param text the text to add */ void TextBlock::appendText(const QString & text) { m_text = m_text + text; } /** * Get the value of m_text * The actual text of this code block. * @return the value of m_text */ QString TextBlock::getText() const { return m_text; } /** * Get the tag of this text block. This tag * may be used to find this text block in the code document * to which it belongs. * @return the tag */ QString TextBlock::getTag() const { return m_tag; } /** * Set the tag of this text block. This tag * may be used to find this text block in the code document * to which it belongs. * @param value the new value for the tag */ void TextBlock::setTag(const QString & value) { m_tag = value; } /** * Set the value of m_writeOutText * Whether or not to include the text of this TextBlock into a file. * @param write the new value of m_writeOutText */ void TextBlock::setWriteOutText(bool write) { m_writeOutText = write; } /** * Get the value of m_writeOutText * Whether or not to include the text of this TextBlock into a file. * @return the value of m_writeOutText */ bool TextBlock::getWriteOutText() const { return m_writeOutText; } /** * Set how many times to indent this text block. * The amount of each indentation is determined from the parent * codedocument codegeneration policy. * @param level the new value for the indentation level */ void TextBlock::setIndentationLevel(int level) { m_indentationLevel = level; } /** * Get how many times to indent this text block. * The amount of each indentation is determined from the parent * codedocument codegeneration policy. * @return the indentation level */ int TextBlock::getIndentationLevel() const { return m_indentationLevel; } /** * Get the new line chars which ends the line. * @return the ending chars for new line */ QString TextBlock::getNewLineEndingChars() { CodeGenerationPolicy* policy = UMLApp::app()->commonPolicy(); return policy->getNewLineEndingChars(); } /** * Get how much a single "level" of indentation will actually indent. * @return the unit of indentation (for one level) */ QString TextBlock::getIndentation() { CodeGenerationPolicy* policy = UMLApp::app()->commonPolicy(); return policy->getIndentation(); } /** * Get the actual amount of indentation for a given level of indentation. * @param level the level of interest * @return the indentation string */ QString TextBlock::getIndentationString(int level) const { if (!level) { level = m_indentationLevel; } QString indentAmount = getIndentation(); QString indentation; for (int i=0; i<level; ++i) { indentation.append(indentAmount); } return indentation; } /** * TODO: Ush. These are terrifically bad and must one day go away. * Both methods indicate the range of lines in this textblock * which may be edited by the codeeditor (assuming that any are * actually editable). The default case is no lines are editable. * The line numbering starts with '0' and a '-1' means no line * qualifies. * @return line number */ int TextBlock::firstEditableLine() { return 0; } /** * @see firstEditableLine */ int TextBlock::lastEditableLine() { return 0; } /** * Used by the CodeEditor. It provides it with an appropriate * starting string for a new line of text within the given textblock * (for example a string with the proper indentation). * If the indentation amount is '0' the current indentation string will * be used. * <p> * TODO: Can be refactored away and replaced with * <a href="#getIndentationString">getIndentationString</a>. * @param amount the number of indent steps to use * @return the new line */ QString TextBlock::getNewEditorLine(int amount) { return getIndentationString(amount); } /** * UnFormat a long text string. Typically, this means removing * the indentation (linePrefix) and/or newline chars from each line. * If an indentation is not specified, then the current indentation is used. * @param text the original text for unformatting * @param indent the indentation * @return the unformatted text */ QString TextBlock::unformatText(const QString & text, const QString & indent) { QString output = text; QString myIndent = indent; if (myIndent.isEmpty()) { myIndent = getIndentationString(); } if (!output.isEmpty()) { // remove indentation from this text block. output.remove(QRegularExpression(QLatin1Char('^') + myIndent)); } return output; } /** * Causes the text block to release all of its connections * and any other text blocks that it 'owns'. * Needed to be called prior to deletion of the textblock. * TODO: Does nothing. */ void TextBlock::release() { } /** * Format a long text string to be more readable. * @param work the original text for formatting * @param linePrefix a line prefix * @param breakStr a break string * @param addBreak control to add always a break string * @param lastLineHasBreak control to add a break string to the last line * @return the new formatted text */ QString TextBlock::formatMultiLineText(const QString & work, const QString & linePrefix, const QString & breakStr, bool addBreak, bool lastLineHasBreak) { QString output; QString text = work; QString endLine = getNewLineEndingChars(); int matches = text.indexOf(QRegularExpression(breakStr)); if (matches >= 0) { // check that last part of string matches, if not, then // we have to tack on extra match if (!text.contains(QRegularExpression(breakStr + QStringLiteral("\\$")))) matches++; for (int i=0; i < matches; ++i) { QString line = text.section(QRegularExpression(breakStr), i, i); output += linePrefix + line; if ((i != matches-1) || lastLineHasBreak) output += endLine; // add break to line } } else { output = linePrefix + text; if (addBreak) output += breakStr; } return output; } /** * Set attributes of the node that represents this class * in the XMI document. * @param writer the QXmlStreamWriter serialization target */ void TextBlock::setAttributesOnNode(QXmlStreamWriter& writer) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); writer.writeAttribute(QStringLiteral("tag"), getTag()); // only write these if different from defaults const QString trueStr = QStringLiteral("true"); const QString falseStr = QStringLiteral("false"); if (getIndentationLevel()) writer.writeAttribute(QStringLiteral("indentLevel"), QString::number(getIndentationLevel())); if (!m_text.isEmpty()) writer.writeAttribute(QStringLiteral("text"), encodeText(m_text, endLine)); if (!getWriteOutText()) writer.writeAttribute(QStringLiteral("writeOutText"), getWriteOutText() ? trueStr : falseStr); if (!canDelete()) writer.writeAttribute(QStringLiteral("canDelete"), canDelete() ? trueStr : falseStr); } /** * Set the class attributes from a passed object. * @param obj text block from which the attributes are taken */ void TextBlock::setAttributesFromObject(TextBlock * obj) { // DON'T set tag here. setIndentationLevel(obj->getIndentationLevel()); setText(obj->getText()); setWriteOutText(obj->getWriteOutText()); m_canDelete = obj->canDelete(); } /** * Set the class attributes of this object from * the passed element node. * @param root the xmi element from which to load */ void TextBlock::setAttributesFromNode(QDomElement & root) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); setIndentationLevel(root.attribute(QStringLiteral("indentLevel"), QStringLiteral("0")).toInt()); setTag(root.attribute(QStringLiteral("tag"))); setText(decodeText(root.attribute(QStringLiteral("text")), endLine)); const QString trueStr = QStringLiteral("true"); setWriteOutText(root.attribute(QStringLiteral("writeOutText"), trueStr) == trueStr); m_canDelete = root.attribute(QStringLiteral("canDelete"), trueStr) == trueStr; } /** * Encode text for XML storage. * We simply convert all types of newLines to the "\n" or &#010; * entity. * @param text the not yet encoded text * @param endLine the chars at the end of each line * @return the encoded text */ QString TextBlock::encodeText(const QString & text, const QString & endLine) { QString encoded = text; encoded.replace(QRegularExpression(endLine), QStringLiteral("&#010;")); return encoded; } /** * Decode text from XML storage. * We simply convert all newLine entity &#010; to chosen line ending. * @param text the not yet decoded text * @param endLine the chars at the end of each line * @return the decoded text */ QString TextBlock::decodeText(const QString & text, const QString & endLine) { QString decoded = text; decoded.replace(QRegularExpression(QStringLiteral("&#010;")), endLine); return decoded; } /** * Return the text in the right format. Returned string is empty * if m_writeOutText is false. * @return QString */ QString TextBlock::toString() const { // simple output method if (m_writeOutText && !m_text.isEmpty()) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); return formatMultiLineText(m_text, getIndentationString(), endLine); } else { return QString(); } } /** * Operator '<<' for TextBlock. */ QDebug operator<<(QDebug os, const TextBlock& obj) { os.nospace() << "TextBlock: tag=" << obj.getTag() << ", writeOutText=" << (obj.getWriteOutText() ? "true" : "false") << ", canDelete=" << (obj.canDelete() ? "true" : "false") << ", indentationLevel=" << obj.getIndentationLevel() << ", parentDocument id=" << (obj.getParentDocument() ? obj.getParentDocument()->ID() : QStringLiteral("null")) << ", text=" << obj.getText(); return os.space(); }
11,828
C++
.cpp
384
27.598958
102
0.699114
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,495
codeclassfield.cpp
KDE_umbrello/umbrello/codegenerators/codeclassfield.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codeclassfield.h" // app includes #include "attribute.h" #include "association.h" #include "classifiercodedocument.h" #include "codegenerator.h" #include "codegenerators/codegenfactory.h" #include "debug_utils.h" #include "umlobject.h" #include "umlrole.h" #include "uml.h" // qt includes #include <QRegularExpression> #include <QXmlStreamWriter> /** * Constructor. */ CodeClassField::CodeClassField (ClassifierCodeDocument * doc, UMLRole * role) : CodeParameter (doc, (UMLObject*) role) { setParentUMLObject(role); initFields(true); } /** * Constructor. */ CodeClassField::CodeClassField (ClassifierCodeDocument * doc, UMLAttribute * attrib) : CodeParameter (doc, (UMLObject*) attrib) { setParentUMLObject(attrib); initFields(true); } /** * Empty Destructor. */ CodeClassField::~CodeClassField () { // remove methods from parent document for(CodeAccessorMethod *m : m_methodVector) { getParentDocument()->removeTextBlock(m); m->forceRelease(); } // clear the decl block from parent text block list too if(m_declCodeBlock) { getParentDocument()->removeTextBlock(m_declCodeBlock); m_declCodeBlock->forceRelease(); delete m_declCodeBlock; } } /** * Set the parent UMLobject appropriately. */ void CodeClassField::setParentUMLObject (UMLObject * obj) { const UMLRole *role = obj->asUMLRole(); if(role) { const UMLAssociation * parentAssoc = role->parentAssociation(); Uml::AssociationType::Enum atype = parentAssoc->getAssocType(); m_parentIsAttribute = false; if (atype == Uml::AssociationType::Association || atype == Uml::AssociationType::Association_Self) m_classFieldType = PlainAssociation; // Plain == Self + untyped associations else if (atype == Uml::AssociationType::Aggregation) m_classFieldType = Aggregation; else if (atype == Uml::AssociationType::Composition) m_classFieldType = Composition; } else { m_classFieldType = Attribute; m_parentIsAttribute = true; } } QString CodeClassField::getTypeName () { if (parentIsAttribute()) { UMLAttribute * at = (UMLAttribute*) getParentObject(); return at->getTypeName(); } else { UMLRole * role = (UMLRole*) getParentObject(); if(fieldIsSingleValue()) { return getUMLObjectName(role->object()); } else { return role->name(); } } } // get the type of object that will be added/removed from lists // of objects (as per specification of associations) QString CodeClassField::getListObjectType() { if (!parentIsAttribute()) { const UMLRole * role = getParentObject()->asUMLRole(); if (role) return getUMLObjectName(role->object()); } return QString(); } /** * Get the value of m_isAbstract. * @return the value of m_isAbstract */ bool CodeClassField::parentIsAttribute () const { return m_parentIsAttribute; // return (m_classFieldType == Attribute) ? true : false; } /** * Get the type of classfield this is. */ CodeClassField::ClassFieldType CodeClassField::getClassFieldType() const { return m_classFieldType; } /* CodeClassFieldDialog * CodeClassField::getDialog () { return m_dialog; } */ // methods like this _shouldn't_ be needed IF we properly did things thruought the code. QString CodeClassField::getUMLObjectName(UMLObject *obj) { return (obj ? obj->name() : QStringLiteral("NULL")); } /** * Add a Method object to the m_methodVector List. */ bool CodeClassField::addMethod (CodeAccessorMethod * add_object) { CodeAccessorMethod::AccessorType type = add_object->getType(); if(findMethodByType(type)) return false; /* // this wont work as the key for QMap needs to inherit from QObject if(m_methodMap->contains(type)) return false; // return false, we already have some object with this tag in the list else m_methodMap->insert(type, add_object); */ m_methodVector.append(add_object); return true; } /** * Remove a Method object from m_methodVector List. */ bool CodeClassField::removeMethod (CodeAccessorMethod * remove_object) { // m_methodMap->erase(remove_object->getType()); m_methodVector.removeAll(remove_object); getParentDocument()->removeTextBlock(remove_object); return true; } /** * Get the list of Method objects held by m_methodVector. * @return QPtrList<CodeMethodBlock *> list of Method objects held by * m_methodVector */ CodeAccessorMethodList CodeClassField::getMethodList() const { return m_methodVector; } /** * Determine if we will *allow* methods to be viewable. * this flag is often used to toggle autogeneration of accessor * methods in the code class field. */ bool CodeClassField::getWriteOutMethods () const { return m_writeOutMethods; } /** * Determine if we will *allow* methods to be viewable. * this flag is often used to toggle autogeneration of accessor * methods in the code class field. */ void CodeClassField::setWriteOutMethods (bool val) { m_writeOutMethods = val; updateContent(); } /** * Return the declaration statement for this class field object. * will be empty until this (abstract) class is inherited in elsewhere. */ CodeClassFieldDeclarationBlock * CodeClassField::getDeclarationCodeBlock() { return m_declCodeBlock; } /** * Load params from the appropriate XMI element node. */ void CodeClassField::loadFromXMI (QDomElement & root) { setAttributesFromNode(root); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeClassField::setAttributesOnNode (QXmlStreamWriter& writer) { // super class CodeParameter::setAttributesOnNode(writer); // now set local attributes/fields writer.writeAttribute(QStringLiteral("field_type"), QString::number(m_classFieldType)); writer.writeAttribute(QStringLiteral("listClassName"), m_listClassName); writer.writeAttribute(QStringLiteral("writeOutMethods"), getWriteOutMethods() ? QStringLiteral("true") : QStringLiteral("false")); // record tag on declaration codeblock // which we will store in its own separate child node block m_declCodeBlock->saveToXMI(writer); // now record the tags on our accessormethods for(CodeAccessorMethod *method : m_methodVector) { method->saveToXMI(writer); } } /** * Set the class attributes of this object from * the passed element node. */ void CodeClassField::setAttributesFromNode (QDomElement & root) { // always disconnect getParentObject()->disconnect(this); // superclass call.. may reset the parent object CodeParameter::setAttributesFromNode(root); // make AFTER super-class call. This will reconnect to the parent // and re-check we have all needed child accessor methods and decl blocks initFields(); const QString trueStr = QStringLiteral("true"); const QString wrOutMeth = root.attribute(QStringLiteral("writeOutMethods"), trueStr); setWriteOutMethods(wrOutMeth == trueStr); m_listClassName = root.attribute(QStringLiteral("listClassName")); const QString fieldType = root.attribute(QStringLiteral("field_type"), QStringLiteral("0")); m_classFieldType = (ClassFieldType)fieldType.toInt(); // load accessor methods now // by looking for our particular child element QDomNode node = root.firstChild(); QDomElement element = node.toElement(); while (!element.isNull()) { QString tag = element.tagName(); if (tag == QStringLiteral("ccfdeclarationcodeblock")) { m_declCodeBlock->loadFromXMI(element); } else if (tag == QStringLiteral("codeaccessormethod")) { int type = element.attribute(QStringLiteral("accessType"), QStringLiteral("0")).toInt(); int role_id = element.attribute(QStringLiteral("role_id"), QStringLiteral("-1")).toInt(); CodeAccessorMethod * method = findMethodByType((CodeAccessorMethod::AccessorType) type, role_id); if (method) method->loadFromXMI(element); else logError1("Cannot load code accessor method for type %1 which does not exist in this codeclassfield. Is XMI out-dated or corrupt?", type); } else if (tag == QStringLiteral("header")) { // this is treated in parent.. skip over here } else logWarn1("bad savefile? code classfield loadFromXMI got child element with unknown tag %1, ignoring node.", tag); node = element.nextSibling(); element = node.toElement(); } } /** * Save the XMI representation of this object. */ void CodeClassField::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codeclassfield")); setAttributesOnNode(writer); writer.writeEndElement(); } /** * Find the minimum number of things that can occur in an association * If mistakenly called on attribute CF's the default value of is "0" * is returned. Similarly, if the association (role) CF doesn't have a multiplicity * 0 is returned. */ int CodeClassField::minimumListOccurances() { if (!parentIsAttribute()) { const UMLRole * role = getParentObject()->asUMLRole(); if (!role) { logError0("no valid parent object"); return -1; } QString multi = role->multiplicity(); // ush. IF we had a multiplicity object, this would be much easier. if (!multi.isEmpty()) { QString lowerBoundString = multi.remove(QRegularExpression(QStringLiteral("\\.\\.\\d+$"))); if(!lowerBoundString.isEmpty() &&lowerBoundString.contains(QRegularExpression(QStringLiteral("^\\d+$")))) return lowerBoundString.toInt(); } } return 0; } /** * Find the maximum number of things that can occur in an association * If mistakenly called on attribute CF's the default value of is "1" * is returned. If the association (role) CF doesn't have a multiplicity * or has a "*" specified then '-1' (unbounded) is returned. */ int CodeClassField::maximumListOccurances() { if (!parentIsAttribute()) { const UMLRole * role = getParentObject()->asUMLRole(); if (!role) { logError0("no valid parent object"); return -1; } QString multi = role->multiplicity(); // ush. IF we had a multiplicity object, this would be much easier. if (!multi.isEmpty()) { QString upperBoundString = multi.section(QRegularExpression(QStringLiteral("(\\.\\.)")), 1); if (!upperBoundString.isEmpty() && upperBoundString.contains(QRegularExpression(QStringLiteral("^\\d+$")))) return upperBoundString.toInt(); else return -1; // unbounded } else return -1; // unbounded } return 1; } /** * A little utility method to make life easier for code document programmers */ QString CodeClassField::cleanName (const QString &name) { return getParentDocument()->cleanName(name); } /** * Another utility method to make life easier for code document programmers * this one fixes the initial declared value of string attributes so that if * it is empty or lacking quotations, it comes out as "" */ QString CodeClassField::fixInitialStringDeclValue(const QString& val, const QString &type) { QString value = val; // check for strings only<F2>String value = val; if (!value.isEmpty() && type == QStringLiteral("String")) { if (!value.startsWith(QLatin1Char('"'))) value.prepend(QLatin1Char('"')); if (!value.endsWith(QLatin1Char('"'))) value.append(QLatin1Char('"')); } return value; } /** * Force the synchronization of the content (methods and declarations) * of this class field. */ void CodeClassField::synchronize () { updateContent(); for(CodeAccessorMethod *method : m_methodVector) { method->syncToParent(); } if(m_declCodeBlock) m_declCodeBlock->syncToParent(); } /** * Utility method to allow finding particular accessor method of this * code class field by its type identifier. */ CodeAccessorMethod * CodeClassField::findMethodByType (CodeAccessorMethod::AccessorType type, int role_id) { //if we already know to which file this class was written/should be written, just return it. /* // argh. this wont work because "accessorType' doesn't inherit from QObject. if(m_methodMap->contains(type)) return ((*m_methodMap)[type]); CodeAccessorMethod *obj = nullptr; */ if(role_id > 1 || role_id < 0) { for(CodeAccessorMethod *m : m_methodVector) if(m->getType() == type) return m; } else { // ugh. forced into this underperforming algorithm because of bad association // design. for(CodeAccessorMethod *m : m_methodVector) { const UMLRole * role = m->getParentObject()->asUMLRole(); if(!role) logError1("FindMethodByType() cant create role for method type %1", m->getType()); if(role && m->getType() == type && role->role() == role_id) return m; } } return (CodeAccessorMethod *) 0; } void CodeClassField::initAccessorMethods() { // everything gets potential get/set method //if(!m_methodMap->contains(CodeAccessorMethod::GET)) if(!findMethodByType(CodeAccessorMethod::GET)) { CodeAccessorMethod * method = CodeGenFactory::newCodeAccessorMethod (getParentDocument(), this, CodeAccessorMethod::GET); if(method) { method->setType(CodeAccessorMethod::GET); addMethod(method); } } if(!findMethodByType(CodeAccessorMethod::SET)) { CodeAccessorMethod * method = CodeGenFactory::newCodeAccessorMethod (getParentDocument(), this, CodeAccessorMethod::SET); if(method) { method->setType(CodeAccessorMethod::SET); addMethod(method); } } // add in the add, remove and list methods for things which are role based. // (and only used if the role specifies a 'list' type object if (!parentIsAttribute()) { if(!findMethodByType(CodeAccessorMethod::ADD)) { CodeAccessorMethod * method = CodeGenFactory::newCodeAccessorMethod (getParentDocument(), this, CodeAccessorMethod::ADD); if(method) { method->setType(CodeAccessorMethod::ADD); addMethod(method); } } if(!findMethodByType(CodeAccessorMethod::REMOVE)) { CodeAccessorMethod * method = CodeGenFactory::newCodeAccessorMethod (getParentDocument(), this, CodeAccessorMethod::REMOVE); if(method) { method->setType(CodeAccessorMethod::REMOVE); addMethod(method); } } if(!findMethodByType(CodeAccessorMethod::LIST)) { CodeAccessorMethod * method = CodeGenFactory::newCodeAccessorMethod (getParentDocument(), this, CodeAccessorMethod::LIST); if(method) { method->setType(CodeAccessorMethod::LIST); addMethod(method); } } } } /** * Updates the status of the accessor methods * as to whether or not they should be written out. */ void CodeClassField::updateContent() { // Set properties for writing out the various methods derived from UMLRoles. // I suppose this could be supported under individual accessor method synctoparent // calls, but it is going to happen again and again for many languages. Why not a catch // all here? -b.t. if (parentIsAttribute()) { for(CodeAccessorMethod *method : m_methodVector) { method->setWriteOutText(m_writeOutMethods); } return; } const UMLRole * role = getParentObject()->asUMLRole(); if (!role) return; Uml::Changeability::Enum changeType = role->changeability(); bool isSingleValue = fieldIsSingleValue(); bool isEmptyRole = role->name().isEmpty() ? true : false; for(CodeAccessorMethod *method : m_methodVector) { CodeAccessorMethod::AccessorType type = method->getType(); // for role-based accessors, we DON'T write ourselves out when // the name of the role is not defined OR when the global flag // to not show ANY methods is set. if(!m_writeOutMethods || isEmptyRole) { method->setWriteOutText(false); continue; } // not to change if no tag (don't know what it is, OR it is not an AutoGenerated method if(method->contentType() != CodeBlock::AutoGenerated) continue; // first off, some accessor methods wont appear if it is a singleValue // role and vice-versa if(isSingleValue) { switch(type) { case CodeAccessorMethod::SET: // SET method true ONLY IF changeability is NOT Frozen if (changeType != Uml::Changeability::Frozen) method->setWriteOutText(true); else method->setWriteOutText(false); break; case CodeAccessorMethod::GET: method->setWriteOutText(true); break; case CodeAccessorMethod::ADD: case CodeAccessorMethod::REMOVE: case CodeAccessorMethod::LIST: default: // list/add/remove always false method->setWriteOutText(false); break; } } else { switch(type) { // get/set always false case CodeAccessorMethod::GET: case CodeAccessorMethod::SET: method->setWriteOutText(false); break; case CodeAccessorMethod::ADD: // ADD method true ONLY IF changeability is NOT Frozen if (changeType != Uml::Changeability::Frozen) method->setWriteOutText(true); else method->setWriteOutText(false); break; case CodeAccessorMethod::REMOVE: // Remove methods ONLY IF changeability is Changeable if (changeType == Uml::Changeability::Changeable) method->setWriteOutText(true); else method->setWriteOutText(false); break; case CodeAccessorMethod::LIST: default: method->setWriteOutText(true); break; } } } } // determine whether the parent object in this classfield indicates that it is // a single variable or a List (Vector). One day this will be done correctly with special // multiplicity object that we don't have to figure out what it means via regex. /** * Determine whether the parent object in this classfield indicates that it is * a single variable or a List (Vector). One day this will be done correctly with special * multiplicity object. */ bool CodeClassField::fieldIsSingleValue () { // For the time being, all attributes ARE single values (yes, // I know this isnt always true, but we have to start somewhere.) if(parentIsAttribute()) return true; const UMLRole * role = getParentObject()->asUMLRole(); if(!role) return true; // it is really an attribute QString multi = role->multiplicity(); if(multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^(0|1)$"))) || multi.contains(QRegularExpression(QStringLiteral("^0\\.\\.1$")))) return true; return false; } /** * Init class fields. */ void CodeClassField::initFields(bool inConstructor) { m_writeOutMethods = false; m_listClassName.clear(); m_declCodeBlock = nullptr; // m_methodMap = new QMap<CodeAccessorMethod::AccessorType, CodeAccessorMethod *>; if (!inConstructor) finishInitialization(); } /** * Finish off initializations of the object. * This is necessary as a separate method because we cannot call * virtual methods that are reimplemented in a language specific class * during our own construction (the own object is not finished being * constructed and therefore the C++ dispatch mechanism does not yet * work as expected.) */ void CodeClassField::finishInitialization() { m_declCodeBlock = CodeGenFactory::newDeclarationCodeBlock(getParentDocument(), this); initAccessorMethods(); updateContent(); connect(getParentObject(), SIGNAL(modified()), this, SIGNAL(modified())); // child objects will trigger off this signal }
21,367
C++
.cpp
593
29.521079
158
0.662158
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,496
ownedhierarchicalcodeblock.cpp
KDE_umbrello/umbrello/codegenerators/ownedhierarchicalcodeblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "ownedhierarchicalcodeblock.h" // local includes #include "association.h" #include "umldoc.h" #include "umlobject.h" #include "umlrole.h" #include "codedocument.h" #include "codegenerator.h" OwnedHierarchicalCodeBlock::OwnedHierarchicalCodeBlock(UMLObject *parent, CodeDocument * doc, const QString &start, const QString &end, const QString &comment) : OwnedCodeBlock(parent), HierarchicalCodeBlock(doc, start, end, comment) { } OwnedHierarchicalCodeBlock::~OwnedHierarchicalCodeBlock() { } /** * causes the text block to release all of its connections * and any other text blocks that it 'owns'. * needed to be called prior to deletion of the textblock. */ void OwnedHierarchicalCodeBlock::release() { OwnedCodeBlock::release(); HierarchicalCodeBlock::release(); } /** * set the class attributes from a passed object */ void OwnedHierarchicalCodeBlock::setAttributesFromObject(TextBlock * obj) { HierarchicalCodeBlock::setAttributesFromObject(obj); OwnedCodeBlock::setAttributesFromObject(obj); } /** * set attributes of the node that represents this class * in the XMI document. */ void OwnedHierarchicalCodeBlock::setAttributesOnNode(QXmlStreamWriter& writer) { // set super-class attributes HierarchicalCodeBlock::setAttributesOnNode(writer); OwnedCodeBlock::setAttributesOnNode(writer); // set local class attributes writer.writeAttribute(QStringLiteral("parent_id"), Uml::ID::toString(getParentObject()->id())); // setting ID's takes special treatment // as UMLRoles arent properly stored in the XMI right now. // (change would break the XMI format..save for big version change) const UMLRole * role = getParentObject()->asUMLRole(); if(role) { // see comment on role_id at OwnedCodeBlock::setAttributesOnNode() writer.writeAttribute(QStringLiteral("role_id"), QString::number((role->role() == Uml::RoleType::A))); } /* else elem.setAttribute("role_id","-1"); */ } /** * set the class attributes of this object from * the passed element node. */ void OwnedHierarchicalCodeBlock::setAttributesFromNode(QDomElement & root) { // set attributes from the XMI HierarchicalCodeBlock::setAttributesFromNode(root); // superclass load OwnedCodeBlock::setAttributesFromNode(root); // superclass load } /** * Return the parent code document */ CodeDocument * OwnedHierarchicalCodeBlock::getParentDocument() { return TextBlock::getParentDocument(); } void OwnedHierarchicalCodeBlock::syncToParent() { if (contentType() != CodeBlock::AutoGenerated) return; updateContent(); }
2,876
C++
.cpp
86
30.406977
159
0.757117
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,497
simplecodegenerator.cpp
KDE_umbrello/umbrello/codegenerators/simplecodegenerator.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2024 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "simplecodegenerator.h" // app includes #include "overwritedialog.h" #include "model_utils.h" #include "attribute.h" #include "umloperationlist.h" #include "umlattributelist.h" #include "classifier.h" #include "codedocument.h" #include "codegenerationpolicy.h" #include "operation.h" #include "umldoc.h" #include "uml.h" // kde includes #include <KLocalizedString> #include <KMessageBox> // qt includes #include <QApplication> #include <QDateTime> #include <QDir> #include <QPointer> #include <QRegularExpression> // system includes #include <cstdlib> //to get the user name /** * Constructor. */ SimpleCodeGenerator::SimpleCodeGenerator(bool createDirHierarchyForPackages) : CodeGenerator(), m_createDirHierarchyForPackages(createDirHierarchyForPackages), m_indentLevel(0) { m_document->disconnect(this); // disconnect from UMLDoc.. we arent planning to be synced at all // load Classifier documents from parent document // initFromParentDocument(); m_fileMap.clear(); // this really is just being used to sync the internal params // to the codegenpolicy as there are no code documents to really sync. syncCodeToDocument(); } /** * Destructor. */ SimpleCodeGenerator::~SimpleCodeGenerator() { } /** * Returns the current indent string based on m_indentLevel and m_indentation. * @return indentation string */ QString SimpleCodeGenerator::indent() { QString myIndent; for (int i = 0 ; i < m_indentLevel; ++i) { myIndent.append(m_indentation); } return myIndent; } /** * Determine the file name. * @param classifier the package * @param ext the file extension * @return the valid file name */ QString SimpleCodeGenerator::findFileName(UMLPackage* classifier, const QString &ext) { //if we already know to which file this class was written/should be written, just return it. if (m_fileMap.contains(classifier)) return m_fileMap[classifier]; //else, determine the "natural" file name QString name; // Get the package name QString package = classifier->package(QStringLiteral(".")); // Replace sequences of white spaces with single blanks package = package.simplified(); // Replace all blanks with underscore package.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_")); // Convert all "::" to "/" : Platform-specific path separator // package.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/")); // if package is given add this as a directory to the file name if (!package.isEmpty() && m_createDirHierarchyForPackages) { name = package + QLatin1Char('.') + classifier->name(); name.replace(QRegularExpression(QStringLiteral("\\.")), QStringLiteral("/")); package.replace(QRegularExpression(QStringLiteral("\\.")), QStringLiteral("/")); package = QLatin1Char('/') + package; } else { name = classifier->fullyQualifiedName(QStringLiteral("-")); } if (! UMLApp::app()->activeLanguageIsCaseSensitive()) { package = package.toLower(); name = name.toLower(); } // if a package name exists check the existence of the package directory if (!package.isEmpty() && m_createDirHierarchyForPackages) { QDir pathDir(UMLApp::app()->commonPolicy()->getOutputDirectory().absolutePath() + package); // does our complete output directory exist yet? if not, try to create it if (!pathDir.exists()) { const QStringList dirs = pathDir.absolutePath().split(QLatin1Char('/')); QString currentDir; QStringList::const_iterator end(dirs.end()); for (QStringList::const_iterator dir(dirs.begin()); dir != end; ++dir) { currentDir += QLatin1Char('/') + *dir; if (! (pathDir.exists(currentDir) || pathDir.mkdir(currentDir))) { KMessageBox::error(nullptr, i18n("Cannot create the folder:\n") + pathDir.absolutePath() + i18n("\nPlease check the access rights"), i18n("Cannot Create Folder")); return QString(); } } } } name = name.simplified(); name.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_")); QString extension = ext.simplified(); extension.replace(QLatin1Char(' '), QLatin1Char('_')); return overwritableName(classifier, name, extension); } /** * Check if a file named "name" with extension "ext" already exists. * @param classifier the package * @param name the name of the file * @param ext the extension of the file * @return the valid filename or null */ QString SimpleCodeGenerator::overwritableName(UMLPackage* classifier, const QString &name, const QString &ext) { CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy(); QDir outputDir = commonPolicy->getOutputDirectory(); QString filename = name + ext; if (!outputDir.exists(filename)) { m_fileMap.insert(classifier, filename); return filename; //if not, "name" is OK and we have not much to to } int suffix; QPointer<OverwriteDialog> overwriteDialog = new OverwriteDialog(filename, outputDir.absolutePath(), m_applyToAllRemaining, qApp->activeWindow()); switch(commonPolicy->getOverwritePolicy()) { //if it exists, check the OverwritePolicy we should use case CodeGenerationPolicy::Ok: //ok to overwrite file break; case CodeGenerationPolicy::Ask: //ask if we can overwrite switch(overwriteDialog->exec()) { case OverwriteDialog::Ok: //overwrite file if (overwriteDialog->applyToAllRemaining()) { commonPolicy->setOverwritePolicy(CodeGenerationPolicy::Ok); } else { m_applyToAllRemaining = false; } break; case OverwriteDialog::No: //generate similar name suffix = 1; while (1) { filename = name + QStringLiteral("__") + QString::number(suffix) + ext; if (!outputDir.exists(filename)) break; suffix++; } if (overwriteDialog->applyToAllRemaining()) { commonPolicy->setOverwritePolicy(CodeGenerationPolicy::Never); } else { m_applyToAllRemaining = false; } break; case OverwriteDialog::Cancel: //don't output anything if (overwriteDialog->applyToAllRemaining()) { commonPolicy->setOverwritePolicy(CodeGenerationPolicy::Cancel); } else { m_applyToAllRemaining = false; } delete overwriteDialog; return QString(); break; } break; case CodeGenerationPolicy::Never: //generate similar name suffix = 1; while (1) { filename = name + QStringLiteral("__") + QString::number(suffix) + ext; if (!outputDir.exists(filename)) break; suffix++; } break; case CodeGenerationPolicy::Cancel: //don't output anything delete overwriteDialog; return QString(); break; } m_fileMap.insert(classifier, filename); delete overwriteDialog; return filename; } /** * Check whether classifier has default values for attributes. * @param c the classifier to check * @return true when classifier attributes has default values */ bool SimpleCodeGenerator::hasDefaultValueAttr(UMLClassifier *c) { UMLAttributeList atl = c->getAttributeList(); for(UMLAttribute* at : atl) { if (!at->getInitialValue().isEmpty()) return true; } return false; } /** * Check whether classifier has abstract operations. * @param c the classifier to check * @return true when classifier has abstract operations */ bool SimpleCodeGenerator::hasAbstractOps(UMLClassifier *c) { UMLOperationList opl(c->getOpList()); for(UMLOperation* op : opl) { if (op->isAbstract()) return true; } return false; } /** * Write all concepts in project to file. */ void SimpleCodeGenerator::writeCodeToFile() { UMLClassifierList concepts = m_document->classesAndInterfaces(); writeCodeToFile(concepts); } /** * Write only selected concepts to file. * @param concepts the selected concepts */ void SimpleCodeGenerator::writeCodeToFile(UMLClassifierList & concepts) { m_fileMap.clear(); // ?? for(UMLClassifier* c : concepts) { if (! Model_Utils::isCommonDataType(c->name())) this->writeClass(c); // call the writer for each class. } finalizeRun(); } /** * A little method to provide some compatibility between * the newer codegenpolicy object and the older class fields. */ void SimpleCodeGenerator::syncCodeToDocument() { CodeGenerationPolicy *policy = UMLApp::app()->commonPolicy(); m_indentation = policy->getIndentation(); m_endl = policy->getNewLineEndingChars(); } /** * Override parent method. */ void SimpleCodeGenerator::initFromParentDocument() { // do nothing }
9,600
C++
.cpp
268
29.548507
110
0.658384
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,498
codeblock.cpp
KDE_umbrello/umbrello/codegenerators/codeblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "codeblock.h" #include "codedocument.h" #include "debug_utils.h" #include <QTextStream> /** * Constructor. * @param doc the documentation text * @param body the body text * */ CodeBlock::CodeBlock(CodeDocument * doc, const QString & body) : TextBlock(doc, body), m_contentType(AutoGenerated) { } /** * Empty Destructor. */ CodeBlock::~CodeBlock() { } /** * Set the value of m_contentType * specifies whether the content (text) of this object was generated by the code * generator or was supplied by the user. * @param new_var the new value of m_contentType */ void CodeBlock::setContentType(ContentType new_var) { m_contentType = new_var; } /** * Get the value of m_contentType * specifies whether the content (text) of this object was generated by the code * generator or was supplied by the user. * @return the value of m_contentType */ CodeBlock::ContentType CodeBlock::contentType() const { return m_contentType; } /** * Save the XMI representation of this object. * @param writer QXmlStreamWriter serialization target */ void CodeBlock::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codeblock")); // set attributes setAttributesOnNode(writer); writer.writeEndElement(); } /** * Set attributes of the node that represents this class * in the XMI document. * @param writer QXmlStreamWriter serialization target */ void CodeBlock::setAttributesOnNode(QXmlStreamWriter& writer) { // call super-class TextBlock::setAttributesOnNode(writer); // local attributes if (m_contentType != AutoGenerated) writer.writeAttribute(QStringLiteral("contentType"), QString::number(contentType())); } /** * Load params from the appropriate XMI element node. * @param root the starting point to load from */ void CodeBlock::loadFromXMI(QDomElement & root) { setAttributesFromNode(root); } /** * Set the class attributes of this object from * the passed element node. * @param elem the xmi element from which to load */ void CodeBlock::setAttributesFromNode(QDomElement & elem) { // set attributes from the XMI in super-class TextBlock::setAttributesFromNode(elem); // set local fields now setContentType(((ContentType) elem.attribute(QStringLiteral("contentType"), QStringLiteral("0")).toInt())); } /** * Set the class attributes from a passed object. * @param obj text block from which the attributes are taken */ void CodeBlock::setAttributesFromObject(TextBlock * obj) { TextBlock::setAttributesFromObject(obj); CodeBlock * cb = dynamic_cast<CodeBlock*>(obj); if (cb) setContentType(cb->contentType()); } /** * Return a string representation of ContentType. * * @param val the enum value of the ContentType * @return the string representation of the enum */ QString CodeBlock::enumToString(const ContentType& val) { if (val == AutoGenerated) { return QStringLiteral("AutoGenerated"); } else { return QStringLiteral("UserGenerated"); } } QDebug operator<<(QDebug str, const CodeBlock& obj) { str.nospace() << "CodeBlock: " << CodeBlock::enumToString(obj.contentType()) << ", ..." << static_cast<TextBlock*>(const_cast<CodeBlock*>(&obj)); return str.space(); }
3,522
C++
.cpp
121
26.396694
111
0.733314
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,499
codeclassfielddeclarationblock.cpp
KDE_umbrello/umbrello/codegenerators/codeclassfielddeclarationblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "codeclassfielddeclarationblock.h" #include "codeclassfield.h" #include "umlrole.h" #include <QXmlStreamWriter> /** * Constructor. */ CodeClassFieldDeclarationBlock::CodeClassFieldDeclarationBlock(CodeClassField * parentCF) : OwnedCodeBlock((UMLObject*) parentCF->getParentObject()), CodeBlockWithComments((CodeDocument*) parentCF->getParentDocument()) { init(parentCF); } /** * Empty Destructor */ CodeClassFieldDeclarationBlock::~CodeClassFieldDeclarationBlock() { // Q: is this needed?? // m_parentclassfield->getParentObject()->disconnect(this); } /** * Get the value of m_parentclassfield. * @return the value of m_parentclassfield */ CodeClassField * CodeClassFieldDeclarationBlock::getParentClassField() { return m_parentclassfield; } /** * A utility method to get the parent object of the parentCodeClassfield. */ UMLObject * CodeClassFieldDeclarationBlock::getParentObject() { return m_parentclassfield->getParentObject(); } // this type of textblock is special // we DON'T release it when resetTextBlocks is // called because we re-use it over and over // until the codeclassfield is released. void CodeClassFieldDeclarationBlock::release() { // do nothing } /** * So parent can actually release this block. */ void CodeClassFieldDeclarationBlock::forceRelease() { if (m_parentclassfield) { // m_parentclassfield->getParentObject()->disconnect(this); m_parentclassfield->disconnect(this); } m_parentclassfield = nullptr; OwnedCodeBlock::release(); TextBlock::release(); } /** * Save the XMI representation of this object. */ void CodeClassFieldDeclarationBlock::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("ccfdeclarationcodeblock")); setAttributesOnNode(writer); writer.writeEndElement(); } /** * Load params from the appropriate XMI element node. */ void CodeClassFieldDeclarationBlock::loadFromXMI (QDomElement & root) { setAttributesFromNode(root); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeClassFieldDeclarationBlock::setAttributesOnNode (QXmlStreamWriter& writer) { // set super-class attributes CodeBlockWithComments::setAttributesOnNode(writer); OwnedCodeBlock::setAttributesOnNode(writer); } /** * Set the class attributes of this object from * the passed element node. */ void CodeClassFieldDeclarationBlock::setAttributesFromNode(QDomElement & root) { // set attributes from the XMI CodeBlockWithComments::setAttributesFromNode(root); // superclass load OwnedCodeBlock::setAttributesFromNode(root); // superclass load syncToParent(); } /** * Set the class attributes from a passed object. */ void CodeClassFieldDeclarationBlock::setAttributesFromObject (TextBlock * obj) { CodeBlockWithComments::setAttributesFromObject(obj); CodeClassFieldDeclarationBlock * ccb = dynamic_cast<CodeClassFieldDeclarationBlock*>(obj); if (ccb) { m_parentclassfield->disconnect(this); init(ccb->getParentClassField()); syncToParent(); } } void CodeClassFieldDeclarationBlock::syncToParent () { // for role-based accessors, we DON'T write ourselves out when // the name of the role is not defined. if (!(getParentClassField()->parentIsAttribute())) { const UMLRole * parent = getParentObject()->asUMLRole(); if (parent == nullptr) return; if (parent->name().isEmpty()) { getComment()->setWriteOutText(false); setWriteOutText(false); } else { getComment()->setWriteOutText(true); setWriteOutText(true); } } // only update IF we are NOT AutoGenerated if (contentType() != AutoGenerated) return; updateContent(); } void CodeClassFieldDeclarationBlock::init (CodeClassField * parentCF) { m_parentclassfield = parentCF; setCanDelete(false); connect(m_parentclassfield, SIGNAL(modified()), this, SLOT(syncToParent())); }
4,317
C++
.cpp
143
26.475524
94
0.738376
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,500
codeaccessormethod.cpp
KDE_umbrello/umbrello/codegenerators/codeaccessormethod.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codeaccessormethod.h" // qt/kde includes #include <QXmlStreamWriter> // local includes #include "codeclassfield.h" /** * Constructors */ CodeAccessorMethod::CodeAccessorMethod(CodeClassField * parentCF) : CodeMethodBlock (parentCF->getParentDocument(), parentCF->getParentObject()) { initFields(parentCF); } /** * Empty Destructor */ CodeAccessorMethod::~CodeAccessorMethod() { } /** * Get the value of m_parentclassfield * @return the value of m_parentclassfield */ CodeClassField * CodeAccessorMethod::getParentClassField() { return m_parentclassfield; } bool CodeAccessorMethod::parentIsAttribute() { return getParentClassField()->parentIsAttribute(); } /** * Utility method to get the value of the parent object of the parent classifield. * @return the value of the parent of the parent classfield */ /* UMLObject * CodeAccessorMethod::getParentObject() { return getParentClassField()->getParentObject(); } */ /** * Return the type of accessor method this is. */ CodeAccessorMethod::AccessorType CodeAccessorMethod::getType() { return m_accessorType; } /** * Set the type of accessor method this is. */ void CodeAccessorMethod::setType(CodeAccessorMethod::AccessorType atype) { m_accessorType = atype; } /** * This type of textblock is special * we DON'T release it when resetTextBlocks is * called because we re-use it over and over * until the codeclassfield is released. */ void CodeAccessorMethod::release() { // do nothing } /** * A method so the parent code classfield can force code block to release. */ void CodeAccessorMethod::forceRelease() { if (m_parentclassfield) { m_parentclassfield->disconnect(this); } CodeMethodBlock::release(); } /** * Load params from the appropriate XMI element node. */ void CodeAccessorMethod::loadFromXMI(QDomElement & root) { setAttributesFromNode(root); } /** * Save the XMI representation of this object. */ void CodeAccessorMethod::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codeaccessormethod")); setAttributesOnNode(writer); writer.writeEndElement(); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeAccessorMethod::setAttributesOnNode(QXmlStreamWriter& writer) { // set super-class attributes CodeMethodBlock::setAttributesOnNode(writer); // set local class attributes writer.writeAttribute(QStringLiteral("accessType"), QString::number(getType())); writer.writeAttribute(QStringLiteral("classfield_id"), getParentClassField()->ID()); } /** * Set the class attributes of this object from * the passed element node. */ void CodeAccessorMethod::setAttributesFromNode(QDomElement & root) { // set attributes from the XMI CodeMethodBlock::setAttributesFromNode(root); // superclass load /* // I don't believe this is needed for a load from XMI. We never delete // accessor methods from the parent classfield.. they are essentially // in composition with the parent class and are arent meant to be out // on their own. Well, this is fine for now, but IF we start allowing // clipping and pasting of these methods between classes/ classfields // then we may have problems (ugh.. I cant imagine allowing this, but // perhaps someone will see a need to allow it. -b.t.) QString id = root.attribute("classfield_id","-1"); CodeClassField *newCF = nullptr; ClassifierCodeDocument * cdoc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument()); if (cdoc) newCF = cdoc->findCodeClassFieldFromParentID (Uml::ID::fromString(id)); m_parentclassfield->disconnect(this); // always disconnect if (newCF) initFields(newCF); else logError0("code accessor method cant load parent codeclassfield, corrupt file?"); */ // now load/set other local attributes setType((AccessorType)root.attribute(QStringLiteral("accessType"),QStringLiteral("0")).toInt()); } /** * Set the class attributes from a passed object. */ void CodeAccessorMethod::setAttributesFromObject(TextBlock * obj) { CodeMethodBlock::setAttributesFromObject(obj); CodeAccessorMethod * mb = dynamic_cast<CodeAccessorMethod*>(obj); if (mb) { m_parentclassfield->disconnect(this); // always disconnect initFields(mb->getParentClassField()); setType(mb->getType()); } } void CodeAccessorMethod::initFields(CodeClassField * parentClassField) { m_parentclassfield = parentClassField; m_accessorType = GET; setCanDelete(false); // we cant delete these with the codeeditor, delete the UML operation instead. connect(m_parentclassfield, SIGNAL(modified()), this, SLOT(syncToParent())); }
5,096
C++
.cpp
159
28.528302
104
0.736295
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,501
classifiercodedocument.cpp
KDE_umbrello/umbrello/codegenerators/classifiercodedocument.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "classifiercodedocument.h" // local includes #include "association.h" #include "attribute.h" #include "operation.h" #include "classifierlistitem.h" #include "classifier.h" #include "codegenerator.h" #include "uml.h" #include "umldoc.h" #include "umlrole.h" #include "umlattributelist.h" #include "umloperationlist.h" #include "codegenfactory.h" // qt includes #include <QList> #include <QRegularExpression> #include <QXmlStreamWriter> /** * Constructor. */ ClassifierCodeDocument::ClassifierCodeDocument(UMLClassifier * parent) { init (parent); } /** * Destructor. */ ClassifierCodeDocument::~ClassifierCodeDocument() { qDeleteAll(m_classfieldVector); m_classfieldVector.clear(); } /** * Get a list of codeclassifier objects held by this classifiercodedocument that meet the passed criteria. */ CodeClassFieldList ClassifierCodeDocument::getSpecificClassFields(CodeClassField::ClassFieldType cfType) const { CodeClassFieldList list; CodeClassFieldList::ConstIterator it = m_classfieldVector.constBegin(); CodeClassFieldList::ConstIterator end = m_classfieldVector.constEnd(); for (; it != end; ++it) { if ((*it)->getClassFieldType() == cfType) list.append(*it); } return list; } /** * Get a list of codeclassifier objects held by this classifiercodedocument that meet the passed criteria. */ CodeClassFieldList ClassifierCodeDocument::getSpecificClassFields(CodeClassField::ClassFieldType cfType, bool isStatic) const { CodeClassFieldList list; CodeClassFieldList::ConstIterator it = m_classfieldVector.constBegin(); CodeClassFieldList::ConstIterator end = m_classfieldVector.constEnd(); for (; it != end; ++it) { CodeClassField *cf = *it; if (cf->getClassFieldType() == cfType && cf->getStatic() == isStatic) list.append(cf); } return list; } /** * Get a list of codeclassifier objects held by this classifiercodedocument that meet the passed criteria. */ CodeClassFieldList ClassifierCodeDocument::getSpecificClassFields (CodeClassField::ClassFieldType cfType, Uml::Visibility::Enum visibility) const { CodeClassFieldList list; CodeClassFieldList::ConstIterator it = m_classfieldVector.constBegin(); CodeClassFieldList::ConstIterator end = m_classfieldVector.constEnd(); for (; it != end; ++it) { CodeClassField * cf = *it; if (cf->getClassFieldType() == cfType && cf->getVisibility() == visibility) list.append(cf); } return list; } /** * Get a list of codeclassifier objects held by this classifiercodedocument that meet the passed criteria. */ CodeClassFieldList ClassifierCodeDocument::getSpecificClassFields (CodeClassField::ClassFieldType cfType, bool isStatic, Uml::Visibility::Enum visibility) const { CodeClassFieldList list; CodeClassFieldList::ConstIterator it = m_classfieldVector.constBegin(); CodeClassFieldList::ConstIterator end = m_classfieldVector.constEnd(); for (; it != end; ++it) { CodeClassField *cf = *it; if (cf->getClassFieldType() == cfType && cf->getVisibility() == visibility && cf->getStatic() == isStatic) list.append(cf); } return list; } // do we have accessor methods for lists of objects? // (as opposed to lists of primitive types like 'int' or 'float', etc) /** * Tell if any of the accessor classfields will be of lists of objects. */ bool ClassifierCodeDocument::hasObjectVectorClassFields() const { CodeClassFieldList::const_iterator it = m_classfieldVector.begin(); CodeClassFieldList::const_iterator end = m_classfieldVector.end(); for (; it != end; ++it) { if((*it)->getClassFieldType() != CodeClassField::Attribute) { const UMLRole * role = (*it)->getParentObject()->asUMLRole(); if (!role) { logError0("invalid parent object type"); return false; } QString multi = role->multiplicity(); if ( multi.contains(QRegularExpression(QStringLiteral("[23456789\\*]"))) || multi.contains(QRegularExpression(QStringLiteral("1\\d"))) ) return true; } } return false; } /** * Does this object have any classfields declared? */ bool ClassifierCodeDocument::hasClassFields() const { if(m_classfieldVector.count() > 0) return true; return false; } /** * Tell if one or more codeclassfields are derived from associations. */ bool ClassifierCodeDocument::hasAssociationClassFields() const { CodeClassFieldList list = getSpecificClassFields(CodeClassField::Attribute); return (m_classfieldVector.count() - list.count()) > 0 ? true : false; } /** * Tell if one or more codeclassfields are derived from attributes. */ bool ClassifierCodeDocument::hasAttributeClassFields() const { CodeClassFieldList list = getSpecificClassFields(CodeClassField::Attribute); return list.count() > 0 ? true : false; } /** * Add a CodeClassField object to the m_classfieldVector List * We DON'T add methods of the code classfield here because we need to allow * the codegenerator writer the liberty to organize their document as they desire. * @return boolean true if successful in adding */ bool ClassifierCodeDocument::addCodeClassField (CodeClassField * add_object) { UMLObject * umlobj = add_object->getParentObject(); if(!(m_classFieldMap.contains(umlobj))) { m_classfieldVector.append(add_object); m_classFieldMap.insert(umlobj, add_object); return true; } return false; } /** * Synchronize this document to the attributes/associations of the parent classifier. * This is a slot..should only be called from a signal. */ void ClassifierCodeDocument::addAttributeClassField (UMLClassifierListItem *obj, bool syncToParentIfAdded) { UMLAttribute *at = (UMLAttribute*)obj; // This can be signalled multiple times: after creation and after calling resolveRef, // skip creation if the attribute is already there. if (m_classFieldMap.contains(at)) { return; } CodeClassField * cf = CodeGenFactory::newCodeClassField(this, at); if (cf) { if (!addCodeClassField(cf)) { // If cf was not added to m_classFieldMap, it must be deleted to // ensure correct cleanup when closing umbrello. delete cf; } else if (syncToParentIfAdded) { updateContent(); } } } /** * Remove a CodeClassField object from m_classfieldVector List */ bool ClassifierCodeDocument::removeCodeClassField (CodeClassField * remove_object) { UMLObject * umlobj = remove_object->getParentObject(); if(m_classFieldMap.contains(umlobj)) { if (m_classfieldVector.removeAll(remove_object)) { // remove from our classfield map m_classFieldMap.remove(umlobj); delete remove_object; return true; } } return false; } void ClassifierCodeDocument::removeAttributeClassField(UMLClassifierListItem *obj) { CodeClassField * remove_object = m_classFieldMap[obj]; if(remove_object) removeCodeClassField(remove_object); } void ClassifierCodeDocument::removeAssociationClassField (UMLAssociation *assoc) { // the object could be either (or both!) role a or b. We should check // both parts of the association. CodeClassField * remove_object = m_classFieldMap[assoc->getUMLRole(Uml::RoleType::A)]; if(remove_object) removeCodeClassField(remove_object); // check role b remove_object = m_classFieldMap[assoc->getUMLRole(Uml::RoleType::B)]; if(remove_object) removeCodeClassField(remove_object); } /** * Get the list of CodeClassField objects held by m_classfieldVector * @return CodeClassFieldList list of CodeClassField objects held by * m_classfieldVector */ CodeClassFieldList * ClassifierCodeDocument::getCodeClassFieldList () { return &m_classfieldVector; } /** * Get the value of m_parentclassifier * @return the value of m_parentclassifier */ UMLClassifier * ClassifierCodeDocument::getParentClassifier () const { return m_parentclassifier; } /** * Get a list of codeoperation objects held by this classifiercodedocument. * @return QList<CodeOperation> */ QList<const CodeOperation*> ClassifierCodeDocument::getCodeOperations () const { QList<const CodeOperation*> list; TextBlockList * tlist = getTextBlockList(); for (TextBlock* tb : *tlist) { const CodeOperation * cop = dynamic_cast<const CodeOperation*>(tb); if (cop) { list.append(cop); } } return list; } /** * @param o The Operation to add */ void ClassifierCodeDocument::addOperation (UMLClassifierListItem * o) { UMLOperation *op = o->asUMLOperation(); if (op == nullptr) { logError0("arg is not a UMLOperation"); return; } QString tag = CodeOperation::findTag(op); CodeOperation * codeOp = dynamic_cast<CodeOperation*>(findTextBlockByTag(tag, true)); bool createdNew = false; // create the block, if it doesn't already exist if(!codeOp) { codeOp = CodeGenFactory::newCodeOperation(this, op); createdNew = true; } // now try to add it. This may fail because it (or a block with // the same tag) is already in the document somewhere. IF we // created this new, then we need to delete our object. if(!addCodeOperation(codeOp)) // wont add if already present if(createdNew) delete codeOp; } /** * @param op */ void ClassifierCodeDocument::removeOperation (UMLClassifierListItem * op) { QString tag = CodeOperation::findTag((UMLOperation*)op); TextBlock *tb = findTextBlockByTag(tag, true); if(tb) { if(removeTextBlock(tb)) // wont add if already present delete tb; // delete unused operations else logError0("Cant remove CodeOperation from ClassCodeDocument!"); } else logError0("Cant Find codeOperation for deleted operation!"); } // Other methods // /** * A utility method that allows user to easily add classfield methods to this document. */ void ClassifierCodeDocument::addCodeClassFieldMethods(CodeClassFieldList &list) { CodeClassFieldList::Iterator it = list.begin(); CodeClassFieldList::Iterator end = list.end(); for (; it!= end; ++it) { CodeClassField * field = *it; CodeAccessorMethodList list = field->getMethodList(); for(CodeAccessorMethod *method : list) { /* QString tag = method->getTag(); if(tag.isEmpty()) { tag = getUniqueTag(); method->setTag(tag); } */ addTextBlock(method); // wont add if already exists in document, will add a tag if missing; } } } /** * Add declaration blocks for the passed classfields. */ void ClassifierCodeDocument::declareClassFields (CodeClassFieldList & list, CodeGenObjectWithTextBlocks * parent) { CodeClassFieldList::Iterator it = list.begin(); CodeClassFieldList::Iterator end = list.end(); for (; it!= end; ++it) { CodeClassField * field = *it; CodeClassFieldDeclarationBlock * declBlock = field->getDeclarationCodeBlock(); /* // if it has a tag, check if(!declBlock->getTag().isEmpty()) { // In C++, because we may shift the declaration to a different parent // block for a change in scope, we need to track down any pre-existing // location, and remove FIRST before adding to new parent CodeGenObjectWithTextBlocks * oldParent = findParentObjectForTaggedTextBlock (declBlock->getTag()); if(oldParent) { if(oldParent != parent) oldParent->removeTextBlock(declBlock); } } */ parent->addTextBlock(declBlock); // wont add it IF its already present. Will give it a tag if missing } } /** * Return if the parent classifier is a class */ bool ClassifierCodeDocument::parentIsClass() const { return (m_parentclassifier->baseType() == UMLObject::ot_Class); } /** * Return if the parent classifier is an interface */ bool ClassifierCodeDocument::parentIsInterface() const { return (m_parentclassifier->baseType() == UMLObject::ot_Interface); } /** * Initialize from a UMLClassifier object. * @param c Classifier from which to initialize this CodeDocument */ void ClassifierCodeDocument::init (UMLClassifier * c) { m_parentclassifier = c; updateHeader(); syncNamesToParent(); // initCodeClassFields(); // cant call here?..newCodeClassField is pure virtual // slots if (parentIsClass()) { connect(c, SIGNAL(attributeAdded(UMLClassifierListItem*)), this, SLOT(addAttributeClassField(UMLClassifierListItem*))); connect(c, SIGNAL(attributeRemoved(UMLClassifierListItem*)), this, SLOT(removeAttributeClassField(UMLClassifierListItem*))); } connect(c, SIGNAL(sigAssociationEndAdded(UMLAssociation*)), this, SLOT(addAssociationClassField(UMLAssociation*))); connect(c, SIGNAL(sigAssociationEndRemoved(UMLAssociation*)), this, SLOT(removeAssociationClassField(UMLAssociation*))); connect(c, SIGNAL(operationAdded(UMLClassifierListItem*)), this, SLOT(addOperation(UMLClassifierListItem*))); connect(c, SIGNAL(operationRemoved(UMLClassifierListItem*)), this, SLOT(removeOperation(UMLClassifierListItem*))); connect(c, SIGNAL(modified()), this, SLOT(syncToParent())); } /** * IF the classifier object is modified, this will get called. * @todo we cannot make this virtual as long as the * ClassifierCodeDocument constructor calls it because that gives * a call-before-construction error. * Example of the problem: CPPSourceCodeDocument reimplementing syncNamesToParent() * CPPCodeGenerator::initFromParentDocument() * CodeDocument * codeDoc = new CPPSourceCodeDocument(c); * CPPSourceCodeDocument::CPPSourceCodeDocument(UMLClassifier * classifier) * : ClassifierCodeDocument(classifier) * ClassifierCodeDocument::ClassifierCodeDocument(classifier) * init(classifier); * syncNamesToParent(); * dispatches to CPPSourceCodeDocument::syncNamesToParent() * but that object is not yet constructed. */ void ClassifierCodeDocument::syncNamesToParent() { QString fileName = CodeGenerator::cleanName(getParentClassifier()->name()); if (!UMLApp::app()->activeLanguageIsCaseSensitive()) { // @todo let the user decide about mixed case file names (codegen setup menu) fileName = fileName.toLower(); } setFileName(fileName); setPackage(m_parentclassifier->umlPackage()); } /** * Cause this classifier code document to synchronize to current policy. */ void ClassifierCodeDocument::synchronize() { updateHeader(); // doing this insures time/date stamp is at the time of this call syncNamesToParent(); updateContent(); syncClassFields(); updateOperations(); } /** * Force synchronization of child classfields to their parent objects. */ void ClassifierCodeDocument::syncClassFields() { CodeClassFieldList::Iterator it = m_classfieldVector.begin(); CodeClassFieldList::Iterator end = m_classfieldVector.end(); for (; it!= end; ++it) (*it)->synchronize(); } /** * Update code operations in this document using the parent classifier. */ void ClassifierCodeDocument::updateOperations() { UMLOperationList opList(getParentClassifier()->getOpList()); for (UMLOperation *op : opList) { QString tag = CodeOperation::findTag(op); CodeOperation * codeOp = dynamic_cast<CodeOperation*>(findTextBlockByTag(tag, true)); bool createdNew = false; if(!codeOp) { codeOp = CodeGenFactory::newCodeOperation(this, op); createdNew = true; } // now try to add it. This may fail because it (or a block with // the same tag) is already in the document somewhere. IF we // created this new, then we need to delete our object. if(!addCodeOperation(codeOp)) // wont add if already present if(createdNew) delete codeOp; // synchronize all non-new operations if(!createdNew) codeOp->syncToParent(); } } void ClassifierCodeDocument::syncToParent() { synchronize(); } /** * Add codeclassfields to this classifiercodedocument. If a codeclassfield * already exists, it is not added. */ void ClassifierCodeDocument::initCodeClassFields() { UMLClassifier * c = getParentClassifier(); // first, do the code classifields that arise from attributes if (parentIsClass()) { UMLAttributeList alist = c->getAttributeList(); for(UMLAttribute * at : alist) { CodeClassField * field = CodeGenFactory::newCodeClassField(this, at); addCodeClassField(field); } } // now, do the code classifields that arise from associations UMLAssociationList ap = c->getSpecificAssocs(Uml::AssociationType::Association); UMLAssociationList ag = c->getAggregations(); UMLAssociationList ac = c->getCompositions(); UMLAssociationList selfAssoc = c->getSpecificAssocs(Uml::AssociationType::Association_Self); updateAssociationClassFields(ap); updateAssociationClassFields(ag); updateAssociationClassFields(ac); updateAssociationClassFields(selfAssoc); } /** * Using the passed list, update our inventory of CodeClassFields which are * based on UMLRoles (e.g. derived from associations with other classifiers). */ void ClassifierCodeDocument::updateAssociationClassFields (UMLAssociationList &assocList) { for(UMLAssociation * a : assocList) addAssociationClassField(a, false); // syncToParent later } void ClassifierCodeDocument::addAssociationClassField (UMLAssociation * a, bool syncToParentIfAdded) { Uml::ID::Type cid = getParentClassifier()->id(); // so we know who 'we' are bool printRoleA = false, printRoleB = false, shouldSync = false; // it may seem counter intuitive, but you want to insert the role of the // *other* class into *this* class. if (a->getObjectId(Uml::RoleType::A) == cid) printRoleB = true; if (a->getObjectId(Uml::RoleType::B) == cid) printRoleA = true; // grab RoleB decl if (printRoleB) { UMLRole * role = a->getUMLRole(Uml::RoleType::B); if(!m_classFieldMap.contains((UMLObject*)role)) { CodeClassField * classfield = CodeGenFactory::newCodeClassField(this, role); if(addCodeClassField(classfield)) shouldSync = true; } } // print RoleA decl if (printRoleA) { UMLRole * role = a->getUMLRole(Uml::RoleType::A); if(!m_classFieldMap.contains((UMLObject*)role)) { CodeClassField * classfield = CodeGenFactory::newCodeClassField(this, role); if(addCodeClassField(classfield)) shouldSync = true; } } if (shouldSync && syncToParentIfAdded) syncToParent(); // needed for a slot add } /** * Set the class attributes of this object from * the passed element node. */ void ClassifierCodeDocument::setAttributesFromNode (QDomElement & elem) { // NOTE: we DON'T set the parent here as we ONLY get to this point // IF the parent codegenerator could find a matching parent classifier // that already has a code document. // We FIRST set code class field stuff..check re-linnking with // accessor methods by looking for our particular child element QDomNode node = elem.firstChild(); QDomElement childElem = node.toElement(); while(!childElem.isNull()) { QString tag = childElem.tagName(); if(tag == QStringLiteral("classfields")) { // load classfields loadClassFieldsFromXMI(childElem); break; } node = childElem.nextSibling(); childElem= node.toElement(); } // call super-class after. THis will populate the text blocks (incl // the code accessor methods above) as is appropriate CodeDocument::setAttributesFromNode(elem); } // look at all classfields currently in document.. match up // by parent object ID and Role ID (needed for self-association CF's) CodeClassField * ClassifierCodeDocument::findCodeClassFieldFromParentID (Uml::ID::Type id, int role_id) { CodeClassFieldList::Iterator it = m_classfieldVector.begin(); CodeClassFieldList::Iterator end = m_classfieldVector.end(); for (; it != end; ++it) { CodeClassField * cf = *it; if(role_id == -1) { // attribute-based if (Uml::ID::fromString(cf->ID()) == id) return cf; } else { // association(role)-based const Uml::RoleType::Enum r = Uml::RoleType::fromInt(role_id); UMLRole * role = cf->getParentObject()->asUMLRole(); if(role && Uml::ID::fromString(cf->ID()) == id && role->role() == r) return cf; } } // shouldn't happen.. logError2( "Failed to find codeclassfield for parent uml id %1 (role id %2) Do you have a corrupt classifier code document?", Uml::ID::toString(id), role_id); return nullptr; // not found } /** * Load CodeClassFields from XMI element node. */ void ClassifierCodeDocument::loadClassFieldsFromXMI(QDomElement & elem) { QDomNode node = elem.firstChild(); QDomElement childElem = node.toElement(); while(!childElem.isNull()) { QString nodeName = childElem.tagName(); if(nodeName == QStringLiteral("codeclassfield")) { QString id = childElem.attribute(QStringLiteral("parent_id"), QStringLiteral("-1")); int role_id = childElem.attribute(QStringLiteral("role_id"), QStringLiteral("-1")).toInt(); CodeClassField * cf = findCodeClassFieldFromParentID(Uml::ID::fromString(id), role_id); if(cf) { // Because we just may change the parent object here, // we need to yank it from the map of umlobjects m_classFieldMap.remove(cf->getParentObject()); // configure from XMI cf->loadFromXMI(childElem); // now add back in m_classFieldMap.insert(cf->getParentObject(), cf); } else logError1("LoadFromXMI: cannot load classfield parent_id %1, do you have a corrupt savefile?", id); } node = childElem.nextSibling(); childElem= node.toElement(); } } /** * Save the XMI representation of this object. */ void ClassifierCodeDocument::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("classifiercodedocument")); setAttributesOnNode(writer); writer.writeEndElement(); } /** * Load params from the appropriate XMI element node. */ void ClassifierCodeDocument::loadFromXMI (QDomElement & root) { // set attributes/fields setAttributesFromNode(root); // now sync our doc, needed? // synchronize(); } /** * Set attributes of the node that represents this class * in the XMI document. */ void ClassifierCodeDocument::setAttributesOnNode (QXmlStreamWriter& writer) { // do super-class first CodeDocument::setAttributesOnNode(writer); // cache local attributes/fields writer.writeAttribute(QStringLiteral("parent_class"), Uml::ID::toString(getParentClassifier()->id())); // (code) class fields // which we will store in its own separate child node block writer.writeStartElement(QStringLiteral("classfields")); CodeClassFieldList::Iterator it = m_classfieldVector.begin(); CodeClassFieldList::Iterator end = m_classfieldVector.end(); for (; it!= end; ++it) (*it)->saveToXMI(writer); writer.writeEndElement(); } /** * Find a specific textblock held by any code class field in this document * by its tag. */ TextBlock * ClassifierCodeDocument::findCodeClassFieldTextBlockByTag (const QString &tag) { CodeClassFieldList::Iterator it = m_classfieldVector.begin(); CodeClassFieldList::Iterator end = m_classfieldVector.end(); for (; it!= end; ++it) { CodeClassField * cf = *it; CodeClassFieldDeclarationBlock * decl = cf->getDeclarationCodeBlock(); if(decl && decl->getTag() == tag) return decl; // well, if not in the decl block, then in the methods perhaps? CodeAccessorMethodList mlist = cf->getMethodList(); for(CodeAccessorMethod *m : mlist) { if(m->getTag() == tag) { return m; } } } // if we get here, we failed. return nullptr; }
25,521
C++
.cpp
697
30.875179
132
0.682649
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,502
hierarchicalcodeblock.cpp
KDE_umbrello/umbrello/codegenerators/hierarchicalcodeblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "hierarchicalcodeblock.h" // local includes #include "codedocument.h" #include "classifiercodedocument.h" #include "codeclassfield.h" #include "codegenerationpolicy.h" #include "codegenerators/codegenfactory.h" #include "debug_utils.h" #include "uml.h" // qt/kde includes #include <QXmlStreamWriter> /** * Constructor */ HierarchicalCodeBlock::HierarchicalCodeBlock(CodeDocument * doc, const QString &start, const QString &endString, const QString &comment) : CodeBlockWithComments (doc, start, comment), CodeGenObjectWithTextBlocks(doc) { setEndText(endString); initAttributes(); } HierarchicalCodeBlock::~HierarchicalCodeBlock() { } /** * Set the value of m_endText * @param new_var the new value of m_endText */ void HierarchicalCodeBlock::setEndText (const QString &new_var) { m_endText = new_var; } /** * Get the value of m_endText * @return the value of m_endText */ QString HierarchicalCodeBlock::getEndText () const { return m_endText; } /** * return a unique, and currently unallocated, text block tag for this hblock */ QString HierarchicalCodeBlock::getUniqueTag() { return getUniqueTag(QStringLiteral("hblock_tag")); } /** * return a unique, and currently unallocated, text block tag for this hblock */ QString HierarchicalCodeBlock::getUniqueTag(const QString& prefix) { return getParentDocument()->getUniqueTag(prefix); } CodeBlock * HierarchicalCodeBlock::newCodeBlock() { return getParentDocument()->newCodeBlock(); } CodeBlockWithComments * HierarchicalCodeBlock::newCodeBlockWithComments() { return getParentDocument()->newCodeBlockWithComments(); } HierarchicalCodeBlock * HierarchicalCodeBlock::newHierarchicalCodeBlock() { HierarchicalCodeBlock *hb = new HierarchicalCodeBlock(getParentDocument()); //hb->update(); return hb; } /** * Add a TextBlock object to the m_textblockVector List */ bool HierarchicalCodeBlock::addTextBlock(TextBlock* add_object) { if (CodeGenObjectWithTextBlocks::addTextBlock(add_object)) { getParentDocument()->addChildTagToMap(add_object->getTag(), add_object); return true; } return false; } /** * Insert a new text block before/after the existing text block. Returns * false if it cannot insert the textblock. */ bool HierarchicalCodeBlock::insertTextBlock(TextBlock * newBlock, TextBlock * existingBlock, bool after) { if (!newBlock || !existingBlock) return false; QString tag = existingBlock->getTag(); // FIX: just do a quick check if the parent DOCUMENT has this. // IF it does, then the lack of an index will force us into // a search of any child hierarchical codeblocks we may have // Its not efficient, but works. I don't think speed is a problem // right now for the current implementation, but in the future // when code import/roundtripping is done, it *may* be. -b.t. if (!getParentDocument()->findTextBlockByTag(tag, true)) return false; int index = m_textblockVector.indexOf(existingBlock); if (index < 0) { // may be hiding in child hierarchical codeblock for(TextBlock* tb : m_textblockVector) { HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(tb); if (hb && hb->insertTextBlock(newBlock, existingBlock, after)) return true; // found, and inserted, otherwise keep going } logWarn2("couldnt insert text block (tag %1). Reference text block (tag %2) not found.", newBlock->getTag(), existingBlock->getTag()); return false; } // if we get here.. it was in this object so insert // check for tag FIRST QString new_tag = newBlock->getTag(); // assign a tag if one doesn't already exist if (new_tag.isEmpty()) { new_tag = getUniqueTag(); newBlock->setTag(new_tag); } if (m_textBlockTagMap.contains(new_tag)) { return false; // return false, we already have some object with this tag in the list } else { m_textBlockTagMap.insert(new_tag, newBlock); getParentDocument()->addChildTagToMap(new_tag, newBlock); } if(after) index++; m_textblockVector.insert(index, newBlock); return true; } /** * Remove a TextBlock object from m_textblockVector List * returns boolean - true if successful */ bool HierarchicalCodeBlock::removeTextBlock (TextBlock * remove_object) { // try to remove from the list in this object int indx = m_textblockVector.indexOf(remove_object); if (indx > -1) { m_textblockVector.removeAt(indx); } else { // may be hiding in child hierarchical codeblock for(TextBlock* tb : m_textblockVector) { HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(tb); if (hb && hb->removeTextBlock(remove_object)) return true; // because we got in child hb; } return false; } // IF we get here, the text block was in THIS object (and not a child).. QString tag = remove_object->getTag(); if (!(tag.isEmpty())) { m_textBlockTagMap.remove(tag); getParentDocument()->removeChildTagFromMap(tag); } return true; } /** * @param text */ void HierarchicalCodeBlock::setStartText (const QString &text) { m_startText = text; } /** * @return QString */ QString HierarchicalCodeBlock::getStartText () const { return m_startText; } /** * Utility method to add accessormethods in this object */ void HierarchicalCodeBlock::addCodeClassFieldMethods(CodeClassFieldList &list) { CodeClassFieldList::Iterator it = list.begin(); CodeClassFieldList::Iterator end = list.end(); for (; it != end; ++it) { CodeClassField * field = *it; CodeAccessorMethodList list = field->getMethodList(); for(CodeAccessorMethod *method : list) { QString tag = method->getTag(); if (tag.isEmpty()) { tag = getUniqueTag(); method->setTag(tag); } addTextBlock(method); // wont add if already exists in object; } } } /** * Save the XMI representation of this object */ void HierarchicalCodeBlock::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("hierarchicalcodeblock")); setAttributesOnNode(writer); writer.writeEndElement(); } /** * set attributes of the node that represents this class * in the XMI document. */ void HierarchicalCodeBlock::setAttributesOnNode (QXmlStreamWriter& writer) { // set super-class attributes CodeBlockWithComments::setAttributesOnNode(writer); CodeGenObjectWithTextBlocks::setAttributesOnNode(writer); // set local class attributes if (contentType() != CodeBlock::AutoGenerated) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); writer.writeAttribute(QStringLiteral("startText"), encodeText(getStartText(), endLine)); writer.writeAttribute(QStringLiteral("endText"), encodeText(getEndText(), endLine)); } } /** * load params from the appropriate XMI element node. */ void HierarchicalCodeBlock::loadFromXMI (QDomElement & root) { setAttributesFromNode(root); } /** * set the class attributes of this object from * the passed element node. */ void HierarchicalCodeBlock::setAttributesFromNode (QDomElement & root) { // set attributes from the XMI CodeBlockWithComments::setAttributesFromNode(root); // superclass load if (contentType() != CodeBlock::AutoGenerated) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); setStartText(decodeText(root.attribute(QStringLiteral("startText")), endLine)); setEndText(decodeText(root.attribute(QStringLiteral("endText")), endLine)); } // do this *after* all other attributes saved CodeGenObjectWithTextBlocks::setAttributesFromNode(root); } /** * set the class attributes from a passed object */ void HierarchicalCodeBlock::setAttributesFromObject (TextBlock * obj) { CodeBlockWithComments::setAttributesFromObject(obj); HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(obj); if (hb) { setStartText(hb->getStartText()); setEndText(hb->getEndText()); CodeGenObjectWithTextBlocks *cgowtb = dynamic_cast<CodeGenObjectWithTextBlocks*>(obj); CodeGenObjectWithTextBlocks::setAttributesFromObject(cgowtb); } } /** * @return QString */ QString HierarchicalCodeBlock::toString() const { QString string; if (getWriteOutText()) { QString indent = getIndentationString(); QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); QString startText; QString endText; if (!getStartText().isEmpty()) startText = formatMultiLineText (getStartText(), indent, endLine); if (!getEndText().isEmpty()) endText = formatMultiLineText (getEndText(), indent, endLine); QString body = childTextBlocksToString(); QString comment = getComment()->toString(); // tack in text, if there is something there.. if (!comment.isEmpty() && getComment()->getWriteOutText()) string.append(comment); if (!startText.isEmpty()) string.append(startText); if (!body.isEmpty()) string.append(body); if (!endText.isEmpty()) string.append(endText); } return string; } QString HierarchicalCodeBlock::childTextBlocksToString() const { TextBlockList* list = getTextBlockList(); QString retString; for (TextBlock* block : *list) { QString blockValue = block->toString(); if (!blockValue.isEmpty()) retString.append(blockValue); } return retString; } /** * look for specific text blocks which belong to code classfields */ TextBlock * HierarchicalCodeBlock::findCodeClassFieldTextBlockByTag (const QString &tag) { ClassifierCodeDocument * cdoc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument()); if(cdoc) { return cdoc->findCodeClassFieldTextBlockByTag(tag); } logError0("HierarchicalCodeBlock: findCodeClassFieldTextBlockByTag() finds NO parent document! Badly constructed textblock?"); // if we get here, we failed. return nullptr; } void HierarchicalCodeBlock::initAttributes() { setCanDelete(false); m_startText.clear(); m_endText.clear(); } /** * causes the text block to release all of its connections * and any other text blocks that it 'owns'. * needed to be called prior to deletion of the textblock. */ void HierarchicalCodeBlock::release() { resetTextBlocks(); TextBlock::release(); }
11,050
C++
.cpp
337
28.15727
142
0.704249
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,503
codeblockwithcomments.cpp
KDE_umbrello/umbrello/codegenerators/codeblockwithcomments.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codeblockwithcomments.h" // local includes #include "codedocument.h" #include "codegenfactory.h" #include "uml.h" // qt/kde includes #include <QXmlStreamWriter> /** * Basic Constructor */ CodeBlockWithComments::CodeBlockWithComments (CodeDocument * parent, const QString & body, const QString & comment) : CodeBlock (parent, body) { CodeComment * codecomment = CodeGenFactory::newCodeComment(parent); codecomment->setText(comment); m_comment = codecomment; } CodeBlockWithComments::~CodeBlockWithComments () { delete m_comment; } /** * Set the Comment object. */ void CodeBlockWithComments::setComment (CodeComment * object) { m_comment = object; } /** * Get the Comment object. */ CodeComment * CodeBlockWithComments::getComment () const { return m_comment; } /** * Save the XMI representation of this object */ void CodeBlockWithComments::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codeblockwithcomments")); // set attributes setAttributesOnNode(writer); writer.writeEndElement(); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeBlockWithComments::setAttributesOnNode (QXmlStreamWriter& writer) { // set super-class attributes CodeBlock::setAttributesOnNode(writer); // set local attributes now..e.g. a comment // which we will store in its own separate child node block writer.writeStartElement(QStringLiteral("header")); getComment()->saveToXMI(writer); // comment writer.writeEndElement(); } /** * Set the class attributes from a passed object. */ void CodeBlockWithComments::setAttributesFromObject(TextBlock * obj) { CodeBlock::setAttributesFromObject(obj); CodeBlockWithComments * cb = dynamic_cast<CodeBlockWithComments*>(obj); if (cb) { getComment()->setAttributesFromObject((TextBlock*)cb->getComment()); } } /** * Load params from the appropriate XMI element node. */ void CodeBlockWithComments::loadFromXMI (QDomElement & root) { setAttributesFromNode(root); } /** * Set the class attributes of this object from * the passed element node. */ void CodeBlockWithComments::setAttributesFromNode(QDomElement & root) { // set attributes from superclass method the XMI CodeBlock::setAttributesFromNode(root); // load comment now // by looking for our particular child element QDomNode node = root.firstChild(); QDomElement element = node.toElement(); bool gotComment = false; while (!element.isNull()) { QString tag = element.tagName(); if (tag == QStringLiteral("header")) { QDomNode cnode = element.firstChild(); QDomElement celem = cnode.toElement(); getComment()->loadFromXMI(celem); gotComment = true; break; } node = element.nextSibling(); element = node.toElement(); } if (!gotComment) { logWarn1("CodeBlockWithComments::loadFromXMI : unable to initialize CodeComment in block %1", getTag()); } } /** * @return QString */ QString CodeBlockWithComments::toString () const { QString string; if (getWriteOutText()) { QString indent = getIndentationString(); QString endLine = getNewLineEndingChars(); QString body = formatMultiLineText (getText(), indent, endLine); CodeComment* codeComment = getComment(); QString comment = codeComment->toString(); if (!comment.isEmpty() && codeComment->getWriteOutText()) { string.append(comment); } if (!body.isEmpty()) { string.append(body); } } return string; } // slave indentation level for both the header and text body /** * A utility method that causes the comment and body of the code block * to have the same indentation level. */ void CodeBlockWithComments::setOverallIndentationLevel (int level) { setIndentationLevel(level); getComment()->setIndentationLevel(level); }
4,284
C++
.cpp
143
25.916084
115
0.713141
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,504
codegenobjectwithtextblocks.cpp
KDE_umbrello/umbrello/codegenerators/codegenobjectwithtextblocks.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codegenobjectwithtextblocks.h" // local includes #include "codedocument.h" #include "codeoperation.h" #include "codegenerators/codegenfactory.h" #include "classifiercodedocument.h" #include "debug_utils.h" #include "hierarchicalcodeblock.h" #include "uml.h" #include "umldoc.h" // qt/kde includes #include <QXmlStreamWriter> /** * Constructor * @param parent parent code document */ CodeGenObjectWithTextBlocks::CodeGenObjectWithTextBlocks (CodeDocument *parent) : m_pCodeDoc(parent) { } /** * Destructor */ CodeGenObjectWithTextBlocks::~CodeGenObjectWithTextBlocks () { resetTextBlocks(); } /** * Get the list of TextBlock objects held by m_textblockVector * @return list of TextBlock objects held by m_textblockVector */ TextBlockList * CodeGenObjectWithTextBlocks::getTextBlockList () const { return const_cast<TextBlockList*>(&m_textblockVector); } /** * Add a TextBlock object to the m_textblockVector List. * @param add_object text block to add * @return boolean value where false means not added because an TextBlock * object with that tag already exists in this document. */ bool CodeGenObjectWithTextBlocks::addTextBlock(TextBlock* add_object) { QString tag = add_object->getTag(); // assign a tag if one doesn't already exist if (tag.isEmpty()) { tag = getUniqueTag(); add_object->setTag(tag); } else { // if it has a tag, check to see that it is not in some other parent object // IF it is then we will need to remove it FIRST before adding to new parent CodeDocument * parentDoc = add_object->getParentDocument(); if (parentDoc) { CodeGenObjectWithTextBlocks * oldParent = parentDoc->findParentObjectForTaggedTextBlock (tag); if (oldParent && oldParent != this) oldParent->removeTextBlock(add_object); } } if (m_textBlockTagMap.contains(tag)) return false; // return false, we already have some object with this tag in the list // if we get here, then the object is a "fresh" one, we havent // added before. Add it now and return true. m_textBlockTagMap.insert(tag, add_object); m_textblockVector.append(add_object); return true; } /** * Remove a TextBlock object from m_textblockVector list. * @param remove_object the text block to be removed * @return success status */ bool CodeGenObjectWithTextBlocks::removeTextBlock (TextBlock * remove_object) { // check if we can remove it from our local list int indx = m_textblockVector.indexOf(remove_object); if (indx > -1) { m_textblockVector.removeAt(indx); } else { // may be hiding in child hierarchical codeblock for (TextBlock* tb: m_textblockVector) { HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(tb); if (hb && hb->removeTextBlock(remove_object)) return true; } return false; } // if we get here.. it was in this object so remove from our map QString tag = remove_object->getTag(); if (!tag.isEmpty()) { m_textBlockTagMap.remove(tag); } return true; } /** * Find the text block with a given tag. * @param tag the tag to search with * @return the found TextBlock object */ TextBlock * CodeGenObjectWithTextBlocks::findTextBlockByTag(const QString &tag) { //if we already know to which file this class was written/should be written, just return it. if (m_textBlockTagMap.contains(tag)) { return m_textBlockTagMap[tag]; } return nullptr; } /** * Find the direct parent for a given textblock. This * may be any object which holds text blocks, e.g. a CodeGenObjectWithTextBlocks. * IMPORTANT: this will only search for a parent from the viewpoint of this object * and down into its Hierarchical codeblocks. This means you should start any * search from the parent document of the text block. This method NOT meant for * casual usage. * @param tag tag to find the text block * @return parent object. Could return null if the textblock is missing from the * branch of the document tree being examined. */ CodeGenObjectWithTextBlocks * CodeGenObjectWithTextBlocks::findParentObjectForTaggedTextBlock (const QString & tag) { // what??!? no tag, then CANT be here if (tag.isEmpty()) return (CodeGenObjectWithTextBlocks*) 0; if (!findTextBlockByTag(tag)) { // may be hiding in child hierarchical codeblock for (TextBlock* tb: m_textblockVector) { HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(tb); if (hb) { CodeGenObjectWithTextBlocks* cgowtb = dynamic_cast<CodeGenObjectWithTextBlocks*>(hb); CodeGenObjectWithTextBlocks * obj = cgowtb->findParentObjectForTaggedTextBlock(tag); if (obj) return obj; } } } else return this; // shouldn't happen unless the textblock doesn't exist in this object // or its children at all return (CodeGenObjectWithTextBlocks*) 0; } /** * Will get a hierarchicalcodeblock from the document with given tag. IF the codeblock * doesn't exist, then it will create it at the end of the document textBlock * list and pass back a reference. * @param tag tag to find the text block * @param comment comment * @param indentLevel indentation level * @return HierarchicalCodeBlock object */ HierarchicalCodeBlock * CodeGenObjectWithTextBlocks::getHierarchicalCodeBlock (const QString &tag, const QString &comment, int indentLevel) { // now actually declare the fields HierarchicalCodeBlock * codeBlock = dynamic_cast<HierarchicalCodeBlock*>(findTextBlockByTag(tag)); if (!codeBlock) { codeBlock = newHierarchicalCodeBlock(); codeBlock->setTag(tag); codeBlock->setComment(CodeGenFactory::newCodeComment(m_pCodeDoc)); // don't write empty comments out if (comment.isEmpty()) codeBlock->getComment()->setWriteOutText(false); if (!addTextBlock(codeBlock)) { delete codeBlock; return (HierarchicalCodeBlock*) 0; } } codeBlock->setOverallIndentationLevel (indentLevel); codeBlock->getComment()->setText(comment); return codeBlock; } /** * Will get a codeblockwithcomments from the document with given tag. If the codeblock * doesn't exist, then it will create it at the end of the document textBlock * list and pass back a reference. * @param tag tag to find the text block * @param comment comment * @param indentLevel indentation level * @return CodeBlockWithComments object */ CodeBlockWithComments * CodeGenObjectWithTextBlocks::getCodeBlockWithComments (const QString &tag, const QString &comment, int indentLevel) { // now actually declare the fields CodeBlockWithComments * codeBlock = dynamic_cast<CodeBlockWithComments*>(findTextBlockByTag(tag)); if (!codeBlock) { codeBlock = newCodeBlockWithComments(); codeBlock->setTag(tag); codeBlock->setComment(CodeGenFactory::newCodeComment(m_pCodeDoc)); // don't write empty comments out if (comment.isEmpty()) codeBlock->getComment()->setWriteOutText(false); if (!addTextBlock(codeBlock)) { delete codeBlock; return (CodeBlockWithComments*) 0; } } codeBlock->setOverallIndentationLevel (indentLevel); codeBlock->getComment()->setText(comment); return codeBlock; } /** * Allows the user to add a code comment to the end of the list * of text blocks in this document OR, if a text block already exists * with that tag, it will update it with the passed text as appropriate. * @param tag tag to find the text block * @param text code comment to set * @param indentationLevel indentation level * @return codeblock/comment pointer to the object which was created/updated. */ CodeComment * CodeGenObjectWithTextBlocks::addOrUpdateTaggedCodeComment (const QString &tag, const QString &text, int indentationLevel) { TextBlock * tBlock = findTextBlockByTag(tag); CodeComment * codeComment = dynamic_cast<CodeComment*>(tBlock); bool createdCodeComment = false; if (!codeComment) { createdCodeComment = true; codeComment = CodeGenFactory::newCodeComment(m_pCodeDoc); codeComment->setTag(tag); if (!addTextBlock(codeComment)) { delete codeComment; return nullptr; // hmm. total failure.., was there a preexisting comment with this tag?? lets return null } } codeComment->setText(text); if (createdCodeComment) { if (!text.isEmpty()) codeComment->setWriteOutText(true); // set to visible, if we created else codeComment->setWriteOutText(false); // set to not visible, if we created } codeComment->setIndentationLevel(indentationLevel); return codeComment; } /** * Allows the user to either add a code block with comments to the end of the list * of text blocks in this document OR, if a text block already exists * with that tag, it will update it with the passed text as appropriate. * @param tag tag to find the text block * @param text text to set * @param ctext comment to set * @param indentLevel indentation level * @param forceUserBlockUpdate ... * @return codeblock/comment pointer to the object which was created/updated */ CodeBlockWithComments * CodeGenObjectWithTextBlocks::addOrUpdateTaggedCodeBlockWithComments (const QString &tag, const QString &text, const QString &ctext, int indentLevel, bool forceUserBlockUpdate) { TextBlock * tBlock = findTextBlockByTag(tag); CodeBlockWithComments * codeBlock = dynamic_cast<CodeBlockWithComments*>(tBlock); bool createdCodeBlock = false; if (!codeBlock) { createdCodeBlock = true; codeBlock = newCodeBlockWithComments(); codeBlock->setTag(tag); if (!addTextBlock(codeBlock)) { delete codeBlock; return nullptr; // hmm. total failure.., was there a preexisting codeblock with this tag?? lets return null } } // ONLY update IF we are forcing the update of user blocks OR it is an "AutoGenerated" Block if (forceUserBlockUpdate || codeBlock->contentType() == CodeBlock::AutoGenerated) { codeBlock->setText(text); codeBlock->getComment()->setText(ctext); // if we created this from scratch, make it write out only when the block isnt empty if (createdCodeBlock) { if (!ctext.isEmpty()) codeBlock->getComment()->setWriteOutText(true); else codeBlock->getComment()->setWriteOutText(false); if (!text.isEmpty()) codeBlock->setWriteOutText(true); else codeBlock->setWriteOutText(false); } codeBlock->setOverallIndentationLevel(indentLevel); } return codeBlock; } /** * Reset/clear the inventory text blocks held by this object. */ void CodeGenObjectWithTextBlocks::resetTextBlocks() { /************** @todo I had to deactivate this code: TextBlock *tb; for (TextBlockListIt it(m_textblockVector); (tb = it.current()) != 0; ++it) delete tb; ************** else crash happens on loading an XMI file *************/ m_textBlockTagMap.clear(); m_textblockVector.clear(); } /** * Empty method. */ void CodeGenObjectWithTextBlocks::setAttributesFromObject (CodeGenObjectWithTextBlocks * obj) { Q_UNUSED(obj); /* TextBlockList * list = obj->getTextBlockList(); for (TextBlock* tb : *list) { // FIX : we need some functionality like // loadChildTextBlocksFromObject(obj) here } */ } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeGenObjectWithTextBlocks::setAttributesOnNode (QXmlStreamWriter& writer) { // set a section to hold document content writer.writeStartElement(QStringLiteral("textblocks")); // only concrete calls to textblocks are saved TextBlockList * tbList = getTextBlockList(); for (TextBlock* block: *tbList) { block->saveToXMI(writer); } writer.writeEndElement(); } /** * Set the class attributes of this object from * the passed element node. * @param root node from which to load the child text blocks */ void CodeGenObjectWithTextBlocks::setAttributesFromNode (QDomElement & root) { // clear existing codeblocks resetTextBlocks(); // now load em back in loadChildTextBlocksFromNode(root); } /** * Load text blocks. * In this vanilla version, we only load comments and codeblocks * as they are the only instanciatable (vanilla) things * this method should be overridden if this class is inherited * by some other class that is concrete and takes children * derived from codeblock/codecomment/hierarchicalcb/ownedhiercodeblock. * @param root node from which to load the child text blocks */ void CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode (QDomElement & root) { QDomNode tnode = root.firstChild(); QDomElement telement = tnode.toElement(); bool loadCheckForChildrenOK = false; while (!telement.isNull()) { QString nodeName = telement.tagName(); if (nodeName != QStringLiteral("textblocks")) { tnode = telement.nextSibling(); telement = tnode.toElement(); continue; } QDomNode node = telement.firstChild(); QDomElement element = node.toElement(); // if there is nothing to begin with, then we don't worry about it loadCheckForChildrenOK = element.isNull() ? true : false; while (!element.isNull()) { QString name = element.tagName(); if (name == QStringLiteral("codecomment")) { CodeComment * block = CodeGenFactory::newCodeComment(m_pCodeDoc); block->loadFromXMI(element); if (!addTextBlock(block)) { logError0("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to add codeComment"); delete block; } else loadCheckForChildrenOK = true; } else if (name == QStringLiteral("codeaccessormethod") || name == QStringLiteral("ccfdeclarationcodeblock")) { QString acctag = element.attribute(QStringLiteral("tag")); // search for our method in the TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag); if (!tb || !addTextBlock(tb)) { logError1("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to " "add code accessor/decl method block (tag: %1)", acctag); // DON'T delete } else loadCheckForChildrenOK = true; } else if (name == QStringLiteral("codeblock")) { CodeBlock * block = newCodeBlock(); block->loadFromXMI(element); if (!addTextBlock(block)) { logError0("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to add codeBlock"); delete block; } else loadCheckForChildrenOK = true; } else if (name == QStringLiteral("codeblockwithcomments")) { CodeBlockWithComments * block = newCodeBlockWithComments(); block->loadFromXMI(element); if (!addTextBlock(block)) { logError0("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to add codeBlockwithcomments"); delete block; } else loadCheckForChildrenOK = true; } else if (name == QStringLiteral("header")) { // do nothing.. this is treated elsewhere } else if (name == QStringLiteral("hierarchicalcodeblock")) { HierarchicalCodeBlock * block = new HierarchicalCodeBlock(m_pCodeDoc); block->loadFromXMI(element); if (!addTextBlock(block)) { logError0("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to add hierarchicalcodeBlock"); delete block; } else loadCheckForChildrenOK = true; } else if (name == QStringLiteral("codeoperation")) { // find the code operation by id QString id = element.attribute(QStringLiteral("parent_id"), QStringLiteral("-1")); UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id)); UMLOperation * op = obj->asUMLOperation(); if (op) { CodeOperation * block = CodeGenFactory::newCodeOperation(dynamic_cast<ClassifierCodeDocument*>(m_pCodeDoc), op); block->loadFromXMI(element); if (addTextBlock(block)) loadCheckForChildrenOK = true; else { logError0("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to add codeoperation"); delete block; } } else logError1("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to create " "codeoperation for obj id: %1", id); } else logWarn1("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: Got strange tag in text block stack: " "name=%1, ignoring", name); node = element.nextSibling(); element = node.toElement(); } break; } if (!loadCheckForChildrenOK) { CodeDocument * test = dynamic_cast<CodeDocument*>(this); if (test) { logWarn1("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to initialize any child blocks " "in doc: %1", test->getFileName()); } else { HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(this); if (hb) logWarn1("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode: unable to initialize any child " "blocks in Hblock: %1", hb->getTag()); else logWarn0("CodeGenObjectWithTextBlocks::loadChildTextBlocksFromNode unable to initialize any child " "blocks in UNKNOWN OBJ"); } } }
19,120
C++
.cpp
449
35.057906
199
0.661992
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,505
codecomment.cpp
KDE_umbrello/umbrello/codegenerators/codecomment.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "codecomment.h" #include "codedocument.h" CodeComment::CodeComment(CodeDocument * doc, const QString & comment) : TextBlock(doc, comment) { } /** * Empty Destructor. */ CodeComment::~CodeComment() { } /** * Save the XMI representation of this object. */ void CodeComment::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codecomment")); setAttributesOnNode(writer); // as we added no additional fields to this class we may // just use parent TextBlock method writer.writeEndElement(); } /** * Load params from the appropriate XMI element node. */ void CodeComment::loadFromXMI(QDomElement & root) { setAttributesFromNode(root); }
926
C++
.cpp
34
24.852941
92
0.760452
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,506
codeoperation.cpp
KDE_umbrello/umbrello/codegenerators/codeoperation.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codeoperation.h" // local includes #include "classifiercodedocument.h" #include "debug_utils.h" #include "uml.h" #include "umldoc.h" #include "umlobject.h" // qt/kde includes #include <QXmlStreamWriter> CodeOperation::CodeOperation (ClassifierCodeDocument * doc, UMLOperation * parentOp, const QString & body, const QString & comment) : CodeMethodBlock (doc, parentOp, body, comment) { init(parentOp); } CodeOperation::~CodeOperation () { } /** * Add a Parameter object to the m_parameterVector List */ /* void CodeOperation::addParameter (CodeParameter * add_object) { m_parameterVector.append(add_object); } */ /** * Remove a Parameter object from m_parameterVector List */ /* void CodeOperation::removeParameter (CodeParameter * remove_object) { m_parameterVector.remove(remove_object); } */ /** * Get the list of Parameter objects held by m_parameterVector * @return QList<CodeParameter*> list of Parameter objects held by * m_parameterVector */ /* QList<CodeParameter*> CodeOperation::getParameterList () { return m_parameterVector; } */ UMLOperation * CodeOperation::getParentOperation() { return getParentObject()->asUMLOperation(); } /** * Save the XMI representation of this object. */ void CodeOperation::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codeoperation")); // set attributes setAttributesOnNode(writer); writer.writeEndElement(); } /** * Load params from the appropriate XMI element node. */ void CodeOperation::loadFromXMI (QDomElement & root) { setAttributesFromNode(root); } /** * Find the value of the tag that this operation would have. */ QString CodeOperation::findTag (UMLOperation * op) { return QString(QStringLiteral("operation_") + Uml::ID::toString(op->id())); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeOperation::setAttributesOnNode (QXmlStreamWriter& writer) { CodeMethodBlock::setAttributesOnNode(writer); // superclass } /** * Set the class attributes of this object from * the passed element node. */ void CodeOperation::setAttributesFromNode (QDomElement & element) { CodeMethodBlock::setAttributesFromNode(element); // superclass // now set local attributes // oops..this is done in the parent class "ownedcodeblock". // we simply need to record the parent operation here // m_parentOperation->disconnect(this); // always disconnect from current parent QString idStr = element.attribute(QStringLiteral("parent_id"), QStringLiteral("-1")); Uml::ID::Type id = Uml::ID::fromString(idStr); UMLObject * obj = UMLApp::app()->document()->findObjectById(id); UMLOperation * op = obj->asUMLOperation(); if (op) init(op); else logError0("could not load code operation because of missing UMLoperation, corrupt savefile?"); } /** * Set the class attributes from a passed object. */ void CodeOperation::setAttributesFromObject(TextBlock * obj) { CodeMethodBlock::setAttributesFromObject(obj); CodeOperation * op = dynamic_cast<CodeOperation*>(obj); if (op) init((UMLOperation*) op->getParentObject()); } void CodeOperation::init (UMLOperation * parentOp) { setCanDelete(false); // we cant delete these with the codeeditor, delete the UML operation instead. setTag(CodeOperation::findTag(parentOp)); // not needed.. done by parent "ownedcodeblock" class // connect(parentOp, SIGNAL(modified()), this, SLOT(syncToParent())); } void CodeOperation::updateContent() { // Empty. Unlike codeaccessor methods for most (all?) languages // we don't auto-generate content for operations }
3,950
C++
.cpp
130
27.692308
131
0.74486
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,507
codeparameter.cpp
KDE_umbrello/umbrello/codegenerators/codeparameter.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codeparameter.h" // local includes #include "association.h" #include "attribute.h" #include "classifiercodedocument.h" #include "debug_utils.h" #include "umldoc.h" #include "umlobject.h" #include "umlrole.h" #include "uml.h" #include "codegenfactory.h" // qt/kde includes #include <QXmlStreamWriter> /** * Constructor. */ CodeParameter::CodeParameter(ClassifierCodeDocument * parentDoc, UMLObject * parentObject) : QObject(parentObject) { setObjectName(QStringLiteral("ACodeParam")); initFields(parentDoc, parentObject); } /** * Destructor. */ CodeParameter::~CodeParameter() { } /** * Utility method to get the value of parent object abstract value * @return the value of parent object abstrtact */ bool CodeParameter::getAbstract() { return m_parentObject->isAbstract(); } /** * Utility method to get the value of parent object static * Whether or not this is static. * @return the value of static */ bool CodeParameter::getStatic() { return m_parentObject->isStatic(); } /** * Utility method to get the value of parent object name * The name of this code parameter. * @return the value */ QString CodeParameter::getName() const { return m_parentObject->name(); } /** * Utility method to get the value of parent object type. * the typeName of this parameters (e.g. boolean, int, etc or perhaps Class name of * an object) * @return the value of type */ QString CodeParameter::getTypeName() { UMLAttribute * at = (UMLAttribute*) m_parentObject; return at->getTypeName(); } /** * Utility method to get the value of parent object scope. * The visibility of this code parameter. * @return the value of parent object scope */ Uml::Visibility::Enum CodeParameter::getVisibility() const { return m_parentObject->visibility(); } /** * Set the value of m_initialValue. * The initial value of this code parameter. * @param new_var the new value of m_initialValue */ void CodeParameter::setInitialValue(const QString &new_var) { m_initialValue = new_var; } /** * Get the value of m_initialValue * The initial value of this code parameter * @return the value of m_initialValue */ QString CodeParameter::getInitialValue() { return m_initialValue; } /** * Set a Comment object. */ void CodeParameter::setComment(CodeComment * object) { m_comment = object; } /** * Get the Comment on this object. */ CodeComment * CodeParameter::getComment() { return m_comment; } /** * Get the parent Code Document */ ClassifierCodeDocument * CodeParameter::getParentDocument() { return m_parentDocument; } /** * Get the ParentObject object. */ UMLObject * CodeParameter::getParentObject() { return m_parentObject; } // need to get the ID of the parent object // this is kind of broken for UMLRoles. QString CodeParameter::ID() const { const UMLRole * role = m_parentObject->asUMLRole(); if (role) { // cant use Role "ID" as that is used to distinquish if its // role "A" or "B" const UMLAssociation *assoc = role->parentAssociation(); return Uml::ID::toString(assoc->id()); } else return Uml::ID::toString(m_parentObject->id()); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeParameter::setAttributesOnNode(QXmlStreamWriter& writer) { // set local attributes writer.writeAttribute(QStringLiteral("parent_id"), ID()); // setting ID's takes special treatment // as UMLRoles arent properly stored in the XMI right now. // (change would break the XMI format..save for big version change) const UMLRole * role = m_parentObject->asUMLRole(); if (role) writer.writeAttribute(QStringLiteral("role_id"), QString::number(role->role())); else writer.writeAttribute(QStringLiteral("role_id"), QStringLiteral("-1")); writer.writeAttribute(QStringLiteral("initialValue"), getInitialValue()); // a comment which we will store in its own separate child node block writer.writeStartElement(QStringLiteral("header")); getComment()->saveToXMI(writer); // comment writer.writeEndElement(); } /** * Set the class attributes of this object from * the passed element node. */ void CodeParameter::setAttributesFromNode(QDomElement & root) { // set local attributes, parent object first QString idStr = root.attribute(QStringLiteral("parent_id"), QStringLiteral("-1")); Uml::ID::Type id = Uml::ID::fromString(idStr); // always disconnect m_parentObject->disconnect(this); // now, what is the new object we want to set? UMLObject * obj = UMLApp::app()->document()->findObjectById(id); if (obj) { // FIX..one day. // Ugh. This is UGLY, but we have to do it this way because UMLRoles // don't go into the document list of UMLobjects, and have the same // ID as their parent UMLAssociations. So..the drill is then special // for Associations..in that case we need to find out which role will // serve as the parameter here. The REAL fix, of course, would be to // treat UMLRoles on a more even footing, but im not sure how that change // might ripple throughout the code and cause problems. Thus, since the // change appears to be needed for only this part, I'll do this crappy // change instead. -b.t. UMLAssociation * assoc = obj->asUMLAssociation(); if (assoc) { // In this case we init with indicated role child obj. UMLRole *role = nullptr; int role_id = root.attribute(QStringLiteral("role_id"), QStringLiteral("-1")).toInt(); if (role_id == 1) role = assoc->getUMLRole(Uml::RoleType::A); else if (role_id == 0) role = assoc->getUMLRole(Uml::RoleType::B); else logError2("CodeParameter::setAttributesFromNode: corrupt save file? " "cant get proper UMLRole for codeparameter uml id: %1 w/role_id: %2", Uml::ID::toString(id), role_id); // init using UMLRole obj if (role) initFields (m_parentDocument, role); } else initFields (m_parentDocument, obj); // just the regular approach } else logError1("CodeParameter::setAttributesFromNode: Cant load CodeParam: parentUMLObject w/id: %1 not found", Uml::ID::toString(id)); // other attribs now setInitialValue(root.attribute(QStringLiteral("initialValue"))); // load comment now // by looking for our particular child element QDomNode node = root.firstChild(); QDomElement element = node.toElement(); bool gotComment = false; while (!element.isNull()) { QString tag = element.tagName(); if (tag == QStringLiteral("header")) { QDomNode cnode = element.firstChild(); QDomElement celem = cnode.toElement(); getComment()->loadFromXMI(celem); gotComment = true; break; } node = element.nextSibling(); element = node.toElement(); } if (!gotComment) logWarn0("CodeParameter::setAttributesFromNode: unable to initialize CodeComment in codeparam"); } /** * Create the string representation of this code parameter. * @return QString */ void CodeParameter::syncToParent() { getComment()->setText(getParentObject()->doc()); updateContent(); } void CodeParameter::initFields(ClassifierCodeDocument * doc, UMLObject * obj) { m_parentObject = obj; m_parentDocument = doc; m_initialValue.clear(); m_comment = CodeGenFactory::newCodeComment(m_parentDocument); m_comment->setText(getParentObject()->doc()); connect(m_parentObject, SIGNAL(modified()), this, SLOT(syncToParent())); }
8,108
C++
.cpp
248
28.217742
114
0.686869
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,508
codegenfactory.cpp
KDE_umbrello/umbrello/codegenerators/codegenfactory.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2002 Luis De la Parra Blum <luis@delaparra.org> Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codegenfactory.h" // app includes #include "attribute.h" #include "codegenerator.h" #include "debug_utils.h" #include "optionstate.h" #include "operation.h" #include "uml.h" #include "umldoc.h" #include "umlrole.h" #include "adawriter.h" #include "cppwriter.h" #include "csharpwriter.h" #include "dwriter.h" #include "idlwriter.h" #include "javawriter.h" #include "mysqlwriter.h" #include "pascalwriter.h" #include "perlwriter.h" #include "phpwriter.h" #include "php5writer.h" #include "postgresqlwriter.h" #include "pythonwriter.h" #include "rubywriter.h" #include "sqlwriter.h" #include "aswriter.h" #include "jswriter.h" #include "tclwriter.h" #include "valawriter.h" #include "xmlschemawriter.h" // the new #include "cppcodegenerator.h" #include "dcodegenerator.h" #include "javacodegenerator.h" #include "rubycodegenerator.h" #include "cppheadercodedocument.h" #include "cppsourcecodedocument.h" #include "dclassifiercodedocument.h" #include "javaclassifiercodedocument.h" #include "rubyclassifiercodedocument.h" #include "javaantcodedocument.h" #include "cppheadercodeoperation.h" #include "cppsourcecodeoperation.h" #include "dcodeoperation.h" #include "javacodeoperation.h" #include "rubycodeoperation.h" #include "cppcodeclassfield.h" #include "dcodeclassfield.h" #include "javacodeclassfield.h" #include "rubycodeclassfield.h" #include "cppheadercodeaccessormethod.h" #include "cppsourcecodeaccessormethod.h" #include "dcodeaccessormethod.h" #include "javacodeaccessormethod.h" #include "rubycodeaccessormethod.h" #include "cppheadercodeclassfielddeclarationblock.h" #include "cppsourcecodeclassfielddeclarationblock.h" #include "dcodeclassfielddeclarationblock.h" #include "javacodeclassfielddeclarationblock.h" #include "rubycodeclassfielddeclarationblock.h" #include "cppcodedocumentation.h" #include "dcodecomment.h" #include "javacodecomment.h" #include "rubycodecomment.h" #include "xmlcodecomment.h" #include "cppcodegenerationpolicy.h" #include "dcodegenerationpolicy.h" #include "javacodegenerationpolicy.h" #include "rubycodegenerationpolicy.h" namespace CodeGenFactory { CodeGenerator* createObject(Uml::ProgrammingLanguage::Enum pl) { if (pl == Uml::ProgrammingLanguage::Reserved) return nullptr; CodeGenerator *obj = nullptr; Settings::OptionState optionState = Settings::optionState(); switch (pl) { case Uml::ProgrammingLanguage::Ada: obj = new AdaWriter(); break; case Uml::ProgrammingLanguage::ActionScript: obj = new ASWriter(); break; case Uml::ProgrammingLanguage::Cpp: if (optionState.generalState.newcodegen) { obj = new CPPCodeGenerator(); } else { obj = new CppWriter(); } break; case Uml::ProgrammingLanguage::CSharp: obj = new CSharpWriter(); break; case Uml::ProgrammingLanguage::D: if (optionState.generalState.newcodegen) { obj = new DCodeGenerator(); } else { obj = new DWriter(); } break; case Uml::ProgrammingLanguage::IDL: obj = new IDLWriter(); break; case Uml::ProgrammingLanguage::Java: if (optionState.generalState.newcodegen) { obj = new JavaCodeGenerator(); } else { obj = new JavaWriter(); } break; case Uml::ProgrammingLanguage::JavaScript: obj = new JSWriter(); break; case Uml::ProgrammingLanguage::MySQL: obj = new MySQLWriter(); break; case Uml::ProgrammingLanguage::PHP: obj = new PhpWriter(); break; case Uml::ProgrammingLanguage::PHP5: obj = new Php5Writer(); break; case Uml::ProgrammingLanguage::Pascal: obj = new PascalWriter(); break; case Uml::ProgrammingLanguage::Perl: obj = new PerlWriter(); break; case Uml::ProgrammingLanguage::PostgreSQL: obj = new PostgreSQLWriter(); break; case Uml::ProgrammingLanguage::Python: obj = new PythonWriter(); break; case Uml::ProgrammingLanguage::Ruby: if (optionState.generalState.newcodegen) { obj = new RubyCodeGenerator(); } else { obj = new RubyWriter(); } break; case Uml::ProgrammingLanguage::SQL: obj = new SQLWriter(); break; case Uml::ProgrammingLanguage::Tcl: obj = new TclWriter(); break; case Uml::ProgrammingLanguage::Vala: obj = new ValaWriter(); break; case Uml::ProgrammingLanguage::XMLSchema: obj = new XMLSchemaWriter(); break; default: logWarn1("CodeGenFactory::createObject: cannot create object of type %1 (unknown)", Uml::ProgrammingLanguage::toString(pl)); break; } UMLApp::app()->setPolicyExt(CodeGenFactory::newCodeGenPolicyExt(pl)); if (obj) { obj->initFromParentDocument(); } return obj; } CodeDocument * newClassifierCodeDocument(UMLClassifier * c) { Settings::OptionState optionState = Settings::optionState(); if (!optionState.generalState.newcodegen) { return nullptr; } ClassifierCodeDocument *retval = nullptr; switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: retval = new CPPSourceCodeDocument(c); break; case Uml::ProgrammingLanguage::D: retval = new DClassifierCodeDocument(c); break; case Uml::ProgrammingLanguage::Java: retval = new JavaClassifierCodeDocument(c); break; case Uml::ProgrammingLanguage::Ruby: retval = new RubyClassifierCodeDocument(c); break; default: break; } if (retval) { retval->initCodeClassFields(); retval->synchronize(); } return retval; } CodeOperation *newCodeOperation(ClassifierCodeDocument *ccd, UMLOperation * op) { CodeOperation *retval = nullptr; switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: { CPPHeaderCodeDocument *hcd = dynamic_cast<CPPHeaderCodeDocument*>(ccd); if (hcd) { CPPHeaderCodeOperation *cpphcd = new CPPHeaderCodeOperation(hcd, op); cpphcd->updateMethodDeclaration(); cpphcd->updateContent(); return cpphcd; } CPPSourceCodeDocument *scd = dynamic_cast<CPPSourceCodeDocument*>(ccd); if (scd) { CPPSourceCodeOperation *cppscd = new CPPSourceCodeOperation(scd, op); cppscd->updateMethodDeclaration(); cppscd->updateContent(); return cppscd; } } break; case Uml::ProgrammingLanguage::D: retval = new DCodeOperation(dynamic_cast<DClassifierCodeDocument*>(ccd), op); retval->updateMethodDeclaration(); retval->updateContent(); break; case Uml::ProgrammingLanguage::Java: retval = new JavaCodeOperation(dynamic_cast<JavaClassifierCodeDocument*>(ccd), op); retval->updateMethodDeclaration(); retval->updateContent(); break; case Uml::ProgrammingLanguage::Ruby: retval = new RubyCodeOperation(dynamic_cast<RubyClassifierCodeDocument*>(ccd), op); retval->updateMethodDeclaration(); retval->updateContent(); break; default: break; } return retval; } CodeClassField * newCodeClassField(ClassifierCodeDocument *ccd, UMLAttribute *at) { CodeClassField *retval = nullptr; switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: retval = new CPPCodeClassField(ccd, at); break; case Uml::ProgrammingLanguage::D: retval = new DCodeClassField(ccd, at); break; case Uml::ProgrammingLanguage::Java: retval = new JavaCodeClassField(ccd, at); break; case Uml::ProgrammingLanguage::Ruby: retval = new RubyCodeClassField(ccd, at); break; default: break; } if (retval) retval->finishInitialization(); return retval; } CodeClassField * newCodeClassField(ClassifierCodeDocument *ccd, UMLRole *role) { CodeClassField *retval = nullptr; switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: retval = new CPPCodeClassField(ccd, role); break; case Uml::ProgrammingLanguage::D: retval = new DCodeClassField(ccd, role); break; case Uml::ProgrammingLanguage::Java: retval = new JavaCodeClassField(ccd, role); break; case Uml::ProgrammingLanguage::Ruby: retval = new RubyCodeClassField(ccd, role); break; default: break; } if (retval) retval->finishInitialization(); return retval; } CodeAccessorMethod * newCodeAccessorMethod(ClassifierCodeDocument *ccd, CodeClassField *cf, CodeAccessorMethod::AccessorType type) { CodeAccessorMethod *retval = nullptr; switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: { CPPHeaderCodeDocument *hcd = dynamic_cast<CPPHeaderCodeDocument*>(ccd); if (hcd) { CPPHeaderCodeAccessorMethod *chcam = new CPPHeaderCodeAccessorMethod(cf, type); chcam->update(); retval = chcam; } else { CPPSourceCodeAccessorMethod *cscam = new CPPSourceCodeAccessorMethod(cf, type); cscam->update(); retval = cscam; } } break; case Uml::ProgrammingLanguage::D: { DCodeAccessorMethod *jcam = new DCodeAccessorMethod(cf, type); jcam->update(); retval = jcam; retval->setOverallIndentationLevel(1); } break; case Uml::ProgrammingLanguage::Java: { JavaCodeAccessorMethod *jcam = new JavaCodeAccessorMethod(cf, type); jcam->update(); retval = jcam; retval->setOverallIndentationLevel(1); } break; case Uml::ProgrammingLanguage::Ruby: { RubyCodeAccessorMethod *rcam = new RubyCodeAccessorMethod(cf, type); rcam->update(); retval = rcam; retval->setOverallIndentationLevel(1); } break; default: break; } return retval; } CodeClassFieldDeclarationBlock * newDeclarationCodeBlock(ClassifierCodeDocument *cd, CodeClassField * cf) { CodeClassFieldDeclarationBlock *retval = nullptr; switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: { CPPHeaderCodeDocument *hcd = dynamic_cast<CPPHeaderCodeDocument*>(cd); if (hcd) { CPPHeaderCodeClassFieldDeclarationBlock * cpphcd = new CPPHeaderCodeClassFieldDeclarationBlock(cf); cpphcd->updateContent(); return cpphcd; } CPPSourceCodeDocument *scd = dynamic_cast<CPPSourceCodeDocument*>(cd); if (scd) { CPPSourceCodeClassFieldDeclarationBlock *cppscd = new CPPSourceCodeClassFieldDeclarationBlock(cf); cppscd->updateContent(); return cppscd; } } break; case Uml::ProgrammingLanguage::D: retval = new DCodeClassFieldDeclarationBlock(cf); retval->updateContent(); break; case Uml::ProgrammingLanguage::Java: retval = new JavaCodeClassFieldDeclarationBlock(cf); retval->updateContent(); break; case Uml::ProgrammingLanguage::Ruby: retval = new RubyCodeClassFieldDeclarationBlock(cf); retval->updateContent(); break; default: break; } return retval; } CodeComment * newCodeComment(CodeDocument *cd) { switch (UMLApp::app()->activeLanguage()) { case Uml::ProgrammingLanguage::Cpp: if (dynamic_cast<CPPHeaderCodeDocument*>(cd) || dynamic_cast<CPPSourceCodeDocument*>(cd)) { return new CPPCodeDocumentation(cd); } break; case Uml::ProgrammingLanguage::D: if (dynamic_cast<DClassifierCodeDocument*>(cd)) { return new DCodeComment(cd); } break; case Uml::ProgrammingLanguage::Java: if (dynamic_cast<JavaClassifierCodeDocument*>(cd)) { return new JavaCodeComment(cd); } break; case Uml::ProgrammingLanguage::Ruby: if (dynamic_cast<RubyClassifierCodeDocument*>(cd)) { return new RubyCodeComment(cd); } break; default: break; } if (dynamic_cast<JavaANTCodeDocument*>(cd)) { return new XMLCodeComment(cd); } return new CodeComment(cd); } CodeGenPolicyExt* newCodeGenPolicyExt(Uml::ProgrammingLanguage::Enum pl) { Settings::OptionState optionState = Settings::optionState(); if (pl == Uml::ProgrammingLanguage::Cpp) { return new CPPCodeGenerationPolicy(); } if (optionState.generalState.newcodegen) { switch(pl) { case Uml::ProgrammingLanguage::Java: return new JavaCodeGenerationPolicy(); break; case Uml::ProgrammingLanguage::D: return new DCodeGenerationPolicy(); break; case Uml::ProgrammingLanguage::Ruby: return new RubyCodeGenerationPolicy(); break; default: return nullptr; } } return nullptr; } } // end namespace CodeGenFactory
15,088
C++
.cpp
432
25.305556
119
0.605851
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,509
codegenerationpolicy.cpp
KDE_umbrello/umbrello/codegenerators/codegenerationpolicy.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codegenerationpolicy.h" // app includes #include "codegenerationpolicypage.h" #include "debug_utils.h" #include "uml.h" #include "umldoc.h" #include "umbrellosettings.h" // kde includes #include <kconfig.h> // qt includes #include <QDateTime> #include <QRegularExpression> #include <QStandardPaths> #include <QStringList> #include <QTextStream> using namespace std; #define MAXLINES 256 /** * Constructor. * @param clone generation policy to clone */ CodeGenerationPolicy::CodeGenerationPolicy(CodeGenerationPolicy * clone) { // first call the function which can give us values from disk, so that we have something to fall back on setDefaults(false); // then set the values from the object passed. setDefaults(clone, false); } /** * Constructor. */ CodeGenerationPolicy::CodeGenerationPolicy() { setDefaults(false); } /** * Destructor */ CodeGenerationPolicy::~CodeGenerationPolicy() { } /** * Set the value of m_overwritePolicy * Policy of how to deal with overwriting existing files. Allowed values are "ask", * "yes" and "no". * @param new_var the new value of m_overwritePolicy */ void CodeGenerationPolicy::setOverwritePolicy (OverwritePolicy new_var) { Settings::optionState().codeGenerationState.overwritePolicy = new_var; } /** * Get the value of m_overwritePolicy * Policy of how to deal with overwriting existing files. Allowed values are "ask", * "yes" and "no". * @return the overwrite policy */ CodeGenerationPolicy::OverwritePolicy CodeGenerationPolicy::getOverwritePolicy () const { return Settings::optionState().codeGenerationState.overwritePolicy; } /** * Set the value of m_commentStyle * @param new_var the new value of m_commentStyle */ void CodeGenerationPolicy::setCommentStyle (CommentStyle new_var) { Settings::optionState().codeGenerationState.commentStyle = new_var; Q_EMIT modifiedCodeContent(); } /** * Get the value of m_commentStyle * @return the comment style */ CodeGenerationPolicy::CommentStyle CodeGenerationPolicy::getCommentStyle() { return Settings::optionState().codeGenerationState.commentStyle; } /** * Set the value of Settings::optionState().codeGenerationState.writeSectionComments * Whether or not verbose code commenting for sections is desired. * If the value is Always, comments for sections will be written even if the section * is empty. * @param new_var the new WriteSectionCommentsPolicy to set */ void CodeGenerationPolicy::setSectionCommentsPolicy (WriteSectionCommentsPolicy new_var) { Settings::optionState().codeGenerationState.writeSectionComments = new_var; Q_EMIT modifiedCodeContent(); } /** * Get the value of Settings::optionState().codeGenerationState.writeSectionComments * Whether or not verbose code commenting for sections is desired. * If the value is Always, comments for sections will be written even if the section * is empty. * @return the flag whether verbose code commenting for sections is desired */ CodeGenerationPolicy::WriteSectionCommentsPolicy CodeGenerationPolicy::getSectionCommentsPolicy () const { return Settings::optionState().codeGenerationState.writeSectionComments; } /** * Set the value of m_codeVerboseDocumentComments * Whether or not verbose code commenting for documentation is desired. If true, * documentation for various code will be written even if no code would normally be * created at that point in the file. * @param new_var the new value to set verbose code commenting */ void CodeGenerationPolicy::setCodeVerboseDocumentComments (bool new_var) { Settings::optionState().codeGenerationState.forceDoc = new_var; Q_EMIT modifiedCodeContent(); } /** * Get the value of m_codeVerboseDocumentComments * Whether or not verbose code commenting for documentation is desired. If true, * documentation for various code will be written even if no code would normally be * created at that point in the file. * @return the value of m_codeVerboseDocumentComments */ bool CodeGenerationPolicy::getCodeVerboseDocumentComments () const { return Settings::optionState().codeGenerationState.forceDoc; } /** * Set the value of m_headingFileDir * location of the header file template. * @param path the new value of m_headingFileDir */ void CodeGenerationPolicy::setHeadingFileDir (const QString & path) { Settings::optionState().codeGenerationState.headingsDirectory.setPath(path); } /** * Get the value of m_headingFileDir * location of the header file template. * @return the value of m_headingFileDir */ QString CodeGenerationPolicy::getHeadingFileDir () const { return Settings::optionState().codeGenerationState.headingsDirectory.absolutePath(); } /** * Set the value of m_includeHeadings * @param new_var the new value of m_includeHeadings */ void CodeGenerationPolicy::setIncludeHeadings (bool new_var) { Settings::optionState().codeGenerationState.includeHeadings = new_var; Q_EMIT modifiedCodeContent(); } /** * Get the value of m_includeHeadings * @return the value of m_includeHeadings */ bool CodeGenerationPolicy::getIncludeHeadings () const { return Settings::optionState().codeGenerationState.includeHeadings; } /** * Set the value of m_outputDirectory * location of where output files will go. * @param new_var the new value of m_outputDirectory */ void CodeGenerationPolicy::setOutputDirectory (QDir new_var) { Settings::optionState().codeGenerationState.outputDirectory = new_var; } /** * Get the value of m_outputDirectory * location of where output files will go. * @return the value of m_outputDirectory */ QDir CodeGenerationPolicy::getOutputDirectory () { return Settings::optionState().codeGenerationState.outputDirectory; } /** * Set the value of m_lineEndingType * What line ending characters to use. * @param type the new value of m_lineEndingType */ void CodeGenerationPolicy::setLineEndingType (NewLineType type) { Settings::optionState().codeGenerationState.lineEndingType = type; switch (Settings::optionState().codeGenerationState.lineEndingType) { case DOS: m_lineEndingChars = QString(QStringLiteral("\r\n")); break; case MAC: m_lineEndingChars = QString(QStringLiteral("\r")); break; case UNIX: default: m_lineEndingChars = QString(QStringLiteral("\n")); break; } Q_EMIT modifiedCodeContent(); } /** * Get the value of m_lineEndingType * What line ending characters to use. * @return the value of m_lineEndingType */ CodeGenerationPolicy::NewLineType CodeGenerationPolicy::getLineEndingType () { return Settings::optionState().codeGenerationState.lineEndingType; } /** * Utility function to get the actual characters. * @return the line ending characters */ QString CodeGenerationPolicy::getNewLineEndingChars () const { return m_lineEndingChars; } /** * Set the value of m_indentationType * The amount and type of whitespace to indent with. * @param new_var the new value of m_indentationType */ void CodeGenerationPolicy::setIndentationType (IndentationType new_var) { Settings::optionState().codeGenerationState.indentationType = new_var; calculateIndentation(); Q_EMIT modifiedCodeContent(); } /** * Get the value of m_indentationType */ CodeGenerationPolicy::IndentationType CodeGenerationPolicy::getIndentationType () { return Settings::optionState().codeGenerationState.indentationType; } /** * Set how many units to indent for each indentation level. * @param amount the amount of indentation units */ void CodeGenerationPolicy::setIndentationAmount (int amount) { if (amount > -1) { Settings::optionState().codeGenerationState.indentationAmount = amount; calculateIndentation(); Q_EMIT modifiedCodeContent(); } } /** * Get indentation level units. */ int CodeGenerationPolicy::getIndentationAmount () { return Settings::optionState().codeGenerationState.indentationAmount; } /** * Utility method to get the amount (and type of whitespace) to indent with. * @return the value of the indentation */ QString CodeGenerationPolicy::getIndentation () const { return m_indentation; } /** * Calculate the indentation. */ void CodeGenerationPolicy::calculateIndentation () { QString indent; m_indentation.clear(); switch (Settings::optionState().codeGenerationState.indentationType) { case NONE: break; case TAB: indent = QString(QStringLiteral("\t")); break; default: case SPACE: indent = QString(QStringLiteral(" ")); break; } for (int i = 0; i < Settings::optionState().codeGenerationState.indentationAmount; ++i) { m_indentation += indent; } } /** * Set the value of m_modifyPolicy * @param new_var the new value of m_modifyPolicy */ void CodeGenerationPolicy::setModifyPolicy (ModifyNamePolicy new_var) { Settings::optionState().codeGenerationState.modnamePolicy = new_var; } /** * Get the value of m_modifyPolicy * @return the value of m_modifyPolicy */ CodeGenerationPolicy::ModifyNamePolicy CodeGenerationPolicy::getModifyPolicy () const { return Settings::optionState().codeGenerationState.modnamePolicy; } /** * Set the value of m_autoGenerateConstructors * @param var the new value */ void CodeGenerationPolicy::setAutoGenerateConstructors(bool var) { Settings::optionState().codeGenerationState.autoGenEmptyConstructors = var; Q_EMIT modifiedCodeContent(); } /** * Get the value of m_autoGenerateConstructors * @return the value of m_autoGenerateConstructors */ bool CodeGenerationPolicy::getAutoGenerateConstructors() { return Settings::optionState().codeGenerationState.autoGenEmptyConstructors; } /** * Set the value of m_attributeAccessorScope * @param var the new value */ void CodeGenerationPolicy::setAttributeAccessorScope(Uml::Visibility::Enum var) { Settings::optionState().codeGenerationState.defaultAttributeAccessorScope = var; Q_EMIT modifiedCodeContent(); } /** * Get the value of m_attributeAccessorScope * @return the Visibility value of m_attributeAccessorScope */ Uml::Visibility::Enum CodeGenerationPolicy::getAttributeAccessorScope() { return Settings::optionState().codeGenerationState.defaultAttributeAccessorScope; } /** * Set the value of m_associationFieldScope * @param var the new value */ void CodeGenerationPolicy::setAssociationFieldScope(Uml::Visibility::Enum var) { Settings::optionState().codeGenerationState.defaultAssocFieldScope = var; Q_EMIT modifiedCodeContent(); } /** * Get the value of m_associationFieldScope * @return the Visibility value of m_associationFieldScope */ Uml::Visibility::Enum CodeGenerationPolicy::getAssociationFieldScope() { return Settings::optionState().codeGenerationState.defaultAssocFieldScope; } /** * Create a new dialog interface for this object. * @return dialog object */ CodeGenerationPolicyPage * CodeGenerationPolicy::createPage (QWidget *pWidget, const char *name) { return new CodeGenerationPolicyPage (pWidget, name, nullptr); } /** * Emits the signal 'ModifiedCodeContent'. */ void CodeGenerationPolicy::emitModifiedCodeContentSig() { if (!UMLApp::app()->document()->loading()) Q_EMIT modifiedCodeContent(); } /** * set the defaults from a config file */ void CodeGenerationPolicy::setDefaults (CodeGenerationPolicy * clone, bool emitUpdateSignal) { if (!clone) return; blockSignals(true); // we need to do this because otherwise most of these // settors below will each send the modifiedCodeContent() signal // needlessly (we can just make one call at the end). setSectionCommentsPolicy (clone->getSectionCommentsPolicy()); setCodeVerboseDocumentComments (clone->getCodeVerboseDocumentComments()); setHeadingFileDir (clone->getHeadingFileDir()); setIncludeHeadings (clone->getIncludeHeadings()); setOutputDirectory (clone->getOutputDirectory()); setLineEndingType (clone->getLineEndingType()); setIndentationAmount (clone->getIndentationAmount()); setIndentationType (clone->getIndentationType()); setModifyPolicy (clone->getModifyPolicy()); setOverwritePolicy (clone->getOverwritePolicy()); calculateIndentation(); blockSignals(false); // "as you were citizen" if (emitUpdateSignal) Q_EMIT modifiedCodeContent(); } /** * set the defaults from a config file */ void CodeGenerationPolicy::setDefaults(bool emitUpdateSignal) { blockSignals(true); // we need to do this because otherwise most of these // settors below will each send the modifiedCodeContent() signal // needlessly (we can just make one call at the end). setSectionCommentsPolicy(UmbrelloSettings::writeSectionComments()); setCodeVerboseDocumentComments(UmbrelloSettings::forceDoc()); setLineEndingType(UmbrelloSettings::lineEndingType()); setIndentationType(UmbrelloSettings::indentationType()); setIndentationAmount(UmbrelloSettings::indentationAmount()); setAutoGenerateConstructors(UmbrelloSettings::autoGenEmptyConstructors()); setAttributeAccessorScope(UmbrelloSettings::defaultAttributeAccessorScope()); setAssociationFieldScope(UmbrelloSettings::defaultAssocFieldScope()); setCommentStyle(UmbrelloSettings::commentStyle()); calculateIndentation(); QString path = UmbrelloSettings::outputDirectory(); if (path.isEmpty()) path = QDir::homePath() + QStringLiteral("/uml-generated-code/"); setOutputDirectory (QDir (path)); path = UmbrelloSettings::headingsDirectory(); if (path.isEmpty()) { path = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("umbrello5/headings"), QStandardPaths::LocateDirectory).first(); } setHeadingFileDir (path); setIncludeHeadings(UmbrelloSettings::includeHeadings()); setOverwritePolicy(UmbrelloSettings::overwritePolicy()); setModifyPolicy(UmbrelloSettings::modnamePolicy()); blockSignals(false); // "as you were citizen" if (emitUpdateSignal) Q_EMIT modifiedCodeContent(); } /** * Write Default params. */ void CodeGenerationPolicy::writeConfig () { UmbrelloSettings::setDefaultAttributeAccessorScope(getAttributeAccessorScope()); UmbrelloSettings::setDefaultAssocFieldScope(getAssociationFieldScope()); UmbrelloSettings::setCommentStyle(getCommentStyle()); UmbrelloSettings::setAutoGenEmptyConstructors(getAutoGenerateConstructors()); //UmbrelloSettings::setNewcodegen(getNewCodegen()); UmbrelloSettings::setForceDoc(getCodeVerboseDocumentComments()); UmbrelloSettings::setWriteSectionComments(getSectionCommentsPolicy()); UmbrelloSettings::setLineEndingType(getLineEndingType()); UmbrelloSettings::setIndentationType(getIndentationType()); UmbrelloSettings::setIndentationAmount(getIndentationAmount()); UmbrelloSettings::setOutputDirectory(getOutputDirectory().absolutePath()); UmbrelloSettings::setHeadingsDirectory(getHeadingFileDir()); UmbrelloSettings::setIncludeHeadings(getIncludeHeadings()); UmbrelloSettings::setOverwritePolicy(getOverwritePolicy()); UmbrelloSettings::setModnamePolicy(getModifyPolicy()); // this will be written to the disk from the place it was called :) } /** * Gets the heading file (as a string) to be inserted at the * beginning of the generated file. you give the file type as * parameter and get the string. if fileName starts with a * period (.) then fileName is the extension (.cpp, .h, * .java) if fileName starts with another character you are * requesting a specific file (mylicensefile.txt). The files * can have parameters which are denoted by %parameter%. * * current parameters are * %author% * %date% * %time% * %filepath% */ QString CodeGenerationPolicy::getHeadingFile(const QString& str) { if (!getIncludeHeadings() || str.isEmpty()) return QString(); if (str.contains(QStringLiteral(" ")) || str.contains(QStringLiteral(";"))) { logWarn0("CodeGenerationPolicy::getHeadingFile: File folder must not have spaces or semicolons!"); return QString(); } //if we only get the extension, then we look for the default // heading.[extension]. If there is no such file, we try to // get any file with the same extension QString filename; QDir headingFiles = Settings::optionState().codeGenerationState.headingsDirectory; if (str.startsWith(QLatin1Char('.'))) { if (QFile::exists(headingFiles.absoluteFilePath(QStringLiteral("heading") + str))) filename = headingFiles.absoluteFilePath(QStringLiteral("heading") + str); else { QStringList filters; filters << QLatin1Char('*') + str; headingFiles.setNameFilters(filters); //if there is more than one match we just take the first one QStringList fileList = headingFiles.entryList(); if (!fileList.isEmpty()) filename = headingFiles.absoluteFilePath(fileList.first()); // uWarning() << "header file name set to " << filename << " because it was *"; } } else { //we got a file name (not only extension) filename = headingFiles.absoluteFilePath(str); } if (filename.isEmpty()) return QString(); QFile f(filename); if (!f.open(QIODevice::ReadOnly)) { // uWarning() << "Error opening heading file: " << f.name(); // uWarning() << "Headings directory was " << headingFiles.absolutePath(); return QString(); } QTextStream ts(&f); QString retstr; QString endLine = getNewLineEndingChars(); for (int l = 0; l < MAXLINES && !ts.atEnd(); ++l) { retstr += ts.readLine()+endLine; } //do variable substitution retstr.replace(QRegularExpression(QStringLiteral("%author%")), QString::fromLatin1(qgetenv("USER"))); //get the user name from some where else retstr.replace(QRegularExpression(QStringLiteral("%headingpath%")), filename); retstr.replace(QRegularExpression(QStringLiteral("%time%")), QTime::currentTime().toString()); retstr.replace(QRegularExpression(QStringLiteral("%date%")), QDate::currentDate().toString()); // the replace filepath, time parts are also in the code document updateHeader method // (which is not a virtual function)... return retstr; }
18,745
C++
.cpp
525
32.219048
108
0.752768
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,510
codemethodblock.cpp
KDE_umbrello/umbrello/codegenerators/codemethodblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ #include "codemethodblock.h" #include "codeclassfield.h" #include "classifiercodedocument.h" #include "codegenerationpolicy.h" #include "uml.h" #include <QXmlStreamWriter> CodeMethodBlock::CodeMethodBlock(ClassifierCodeDocument * doc, UMLObject * parentObj, const QString & body, const QString & comment) : OwnedCodeBlock (parentObj), CodeBlockWithComments ((CodeDocument*)doc, body, comment) { m_startMethod.clear(); m_endMethod.clear(); } CodeMethodBlock::~CodeMethodBlock() { } /** * Get the parent code document. */ CodeDocument * CodeMethodBlock::getParentDocument() { // we can just call the superclass return TextBlock::getParentDocument(); } /** * Get the starting text that begins this method before the body is printed. */ QString CodeMethodBlock::getStartMethodText() const { return m_startMethod; } /** * Get the ending text that finishes this method after the body is printed. */ QString CodeMethodBlock::getEndMethodText() const { return m_endMethod; } /** * Set the starting text that begins this method before the body is printed. */ void CodeMethodBlock::setStartMethodText (const QString &value) { m_startMethod = value; } /** * Set the ending text that finishes this method after the body is printed. */ void CodeMethodBlock::setEndMethodText(const QString &value) { m_endMethod = value; } /** * Causes the text block to release all of its connections * and any other text blocks that it 'owns'. * needed to be called prior to deletion of the textblock. */ void CodeMethodBlock::release () { // just call super-class versions OwnedCodeBlock::release(); TextBlock::release(); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeMethodBlock::setAttributesOnNode(QXmlStreamWriter& writer) { // set super-class attributes CodeBlockWithComments::setAttributesOnNode(writer); OwnedCodeBlock::setAttributesOnNode(writer); // set local class attributes if (contentType() != AutoGenerated) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); writer.writeAttribute(QStringLiteral("startMethodText"), encodeText(getStartMethodText(), endLine)); writer.writeAttribute(QStringLiteral("endMethodText"), encodeText(getEndMethodText(), endLine)); } } /** * Set the class attributes of this object from * the passed element node. */ void CodeMethodBlock::setAttributesFromNode(QDomElement & elem) { // set attributes from the XMI CodeBlockWithComments::setAttributesFromNode(elem); // superclass load OwnedCodeBlock::setAttributesFromNode(elem); // superclass load // now load local attributes if (contentType() != AutoGenerated) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); setStartMethodText(decodeText(elem.attribute(QStringLiteral("startMethodText")), endLine)); setEndMethodText(decodeText(elem.attribute(QStringLiteral("endMethodText")), endLine)); } } /** * Set the class attributes from a passed object */ void CodeMethodBlock::setAttributesFromObject(TextBlock * obj) { CodeBlockWithComments::setAttributesFromObject(obj); CodeMethodBlock * mb = dynamic_cast<CodeMethodBlock*>(obj); if (mb) { setStartMethodText(mb->getStartMethodText()); setEndMethodText(mb->getEndMethodText()); } } /** * @return QString */ QString CodeMethodBlock::toString() const { QString string; if (getWriteOutText()) { QString indent = getIndentationString(); QString bodyIndent = getIndentationString(getIndentationLevel()+1); QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); QString startMethod = formatMultiLineText (getStartMethodText(), indent, endLine); QString body = formatMultiLineText (getText(), bodyIndent, endLine); QString endMethod = formatMultiLineText(getEndMethodText(), indent, endLine); QString comment = getComment()->toString(); if (!comment.isEmpty() && getComment()->getWriteOutText()) string.append(comment); if (!startMethod.isEmpty()) string.append(startMethod); if (!body.isEmpty()) string.append(body); if (!endMethod.isEmpty()) string.append(endMethod); } return string; } void CodeMethodBlock::syncToParent() { getComment()->setText(getParentObject()->doc()); updateMethodDeclaration(); // only update IF we are NOT AutoGenerated if (contentType() != AutoGenerated) return; updateContent(); }
4,882
C++
.cpp
148
29.047297
132
0.729747
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,511
ownedcodeblock.cpp
KDE_umbrello/umbrello/codegenerators/ownedcodeblock.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "ownedcodeblock.h" // local includes #include "association.h" #include "classifier.h" #include "debug_utils.h" #include "umldoc.h" #include "umlobject.h" #include "umlrole.h" #include "uml.h" #include "textblock.h" // qt includes #include <QXmlStreamWriter> /** * Constructor */ OwnedCodeBlock::OwnedCodeBlock (UMLObject * parent) : QObject (parent) { setObjectName(QStringLiteral("anOwnedCodeBlock")); initFields(parent); } /** * Empty Destructor */ OwnedCodeBlock::~OwnedCodeBlock () { /* if (m_parentObject) { m_parentObject->disconnect(this); } */ } /** * Causes the text block to release all of its connections * and any other text blocks that it 'owns'. * Needed to be called prior to deletion of the textblock. */ void OwnedCodeBlock::release () { if (m_parentObject) { m_parentObject->disconnect(this); } m_parentObject = nullptr; } /** * Get the value of m_parentObject. * @return the value of m_parentObject */ UMLObject * OwnedCodeBlock::getParentObject () { return m_parentObject; } /** * Set the class attributes from a passed object. */ void OwnedCodeBlock::setAttributesFromObject (TextBlock * obj) { OwnedCodeBlock * oc = dynamic_cast<OwnedCodeBlock*>(obj); if (oc) { m_parentObject->disconnect(this); initFields(oc->getParentObject()); } } void OwnedCodeBlock::setAttributesOnNode(QXmlStreamWriter& writer) { // set local class attributes // setting ID's takes special treatment // as UMLRoles arent properly stored in the XMI right now. // (change would break the XMI format..save for big version change) const UMLRole * role = m_parentObject->asUMLRole(); if (role) { writer.writeAttribute(QStringLiteral("parent_id"), Uml::ID::toString(role->parentAssociation()->id())); // CAUTION: role_id here is numerically inverted wrt Uml::Role_Type, // i.e. role A is 1 and role B is 0. // I'll resist the temptation to change this - // in order to maintain backward compatibility. writer.writeAttribute(QStringLiteral("role_id"), QString::number((role->role() == Uml::RoleType::A))); } else { writer.writeAttribute(QStringLiteral("parent_id"), Uml::ID::toString(m_parentObject->id())); //elem.setAttribute(QStringLiteral("role_id"),QStringLiteral("-1")); } } /** * Set the class attributes of this object from * the passed element node. */ void OwnedCodeBlock::setAttributesFromNode (QDomElement & elem) { // set local attributes, parent object first QString idStr = elem.attribute(QStringLiteral("parent_id"), QStringLiteral("-1")); Uml::ID::Type id = Uml::ID::fromString(idStr); // always disconnect from current parent getParentObject()->disconnect(this); // now, what is the new object we want to set? UMLObject * obj = UMLApp::app()->document()->findObjectById(id); if (obj) { // FIX..one day. // Ugh. This is UGLY, but we have to do it this way because UMLRoles // don't go into the document list of UMLobjects, and have the same // ID as their parent UMLAssociations. So..the drill is then special // for Associations..in that case we need to find out which role will // serve as the parametger here. The REAL fix, of course, would be to // treat UMLRoles on a more even footing, but im not sure how that change // might ripple throughout the code and cause problems. Thus, since the // change appears to be needed for only this part, I'll do this crappy // change instead. -b.t. const UMLAssociation * assoc = obj->asUMLAssociation(); if (assoc) { // In this case we init with indicated role child obj. UMLRole *role = nullptr; int role_id = elem.attribute(QStringLiteral("role_id"), QStringLiteral("-1")).toInt(); // see comment on role_id at setAttributesOnNode() if (role_id == 1) role = assoc->getUMLRole(Uml::RoleType::A); else if (role_id == 0) role = assoc->getUMLRole(Uml::RoleType::B); else // this will cause a crash logError2("OwnedCodeBlock::setAttributesFromNode: cannot get proper UMLRole for " "ownedcodeblock uml id: %1 w/role_id: %2", Uml::ID::toString(id), role_id); // init using UMLRole obj initFields (role); } else initFields (obj); // just the regular approach } else logError1("OwnedCodeBlock::setAttributesFromNode: cannot load ownedcodeblock: parentUMLObject " "w/id: %1 not found", Uml::ID::toString(id)); } void OwnedCodeBlock::initFields(UMLObject * parent) { m_parentObject = parent; // one reason for being: set up the connection between // this code block and the parent UMLObject..when the parent // signals a change has been made, we automatically update // ourselves connect(m_parentObject, SIGNAL(modified()), this, SLOT(syncToParent())); } void OwnedCodeBlock::syncToParent() { updateContent(); }
5,465
C++
.cpp
149
31.308725
111
0.665534
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
749,512
codegen_utils.cpp
KDE_umbrello/umbrello/codegenerators/codegen_utils.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codegen_utils.h" // app includes #include "uml.h" #include "umldoc.h" namespace Codegen_Utils { /** * Return list of C++ datatypes. */ QStringList cppDatatypes() { QStringList l; l.append(QStringLiteral("char")); l.append(QStringLiteral("int")); l.append(QStringLiteral("float")); l.append(QStringLiteral("double")); l.append(QStringLiteral("bool")); l.append(QStringLiteral("string")); l.append(QStringLiteral("unsigned char")); l.append(QStringLiteral("signed char")); l.append(QStringLiteral("unsigned int")); l.append(QStringLiteral("signed int")); l.append(QStringLiteral("short int")); l.append(QStringLiteral("unsigned short int")); l.append(QStringLiteral("signed short int")); l.append(QStringLiteral("long int")); l.append(QStringLiteral("signed long int")); l.append(QStringLiteral("unsigned long int")); l.append(QStringLiteral("long double")); l.append(QStringLiteral("wchar_t")); return l; } /** * Get list of C++ reserved keywords. */ const QStringList reservedCppKeywords() { static QStringList keywords; if (keywords.isEmpty()) { keywords.append(QStringLiteral("and")); keywords.append(QStringLiteral("and_eq")); keywords.append(QStringLiteral("__asm__")); keywords.append(QStringLiteral("asm")); keywords.append(QStringLiteral("__attribute__")); keywords.append(QStringLiteral("auto")); keywords.append(QStringLiteral("bitand")); keywords.append(QStringLiteral("bitor")); keywords.append(QStringLiteral("bool")); keywords.append(QStringLiteral("break")); keywords.append(QStringLiteral("BUFSIZ")); keywords.append(QStringLiteral("case")); keywords.append(QStringLiteral("catch")); keywords.append(QStringLiteral("char")); keywords.append(QStringLiteral("CHAR_BIT")); keywords.append(QStringLiteral("CHAR_MAX")); keywords.append(QStringLiteral("CHAR_MIN")); keywords.append(QStringLiteral("class")); keywords.append(QStringLiteral("CLOCKS_PER_SEC")); keywords.append(QStringLiteral("clock_t")); keywords.append(QStringLiteral("compl")); keywords.append(QStringLiteral("__complex__")); keywords.append(QStringLiteral("complex")); keywords.append(QStringLiteral("const")); keywords.append(QStringLiteral("const_cast")); keywords.append(QStringLiteral("continue")); keywords.append(QStringLiteral("__DATE__")); keywords.append(QStringLiteral("DBL_DIG")); keywords.append(QStringLiteral("DBL_EPSILON")); keywords.append(QStringLiteral("DBL_MANT_DIG")); keywords.append(QStringLiteral("DBL_MAX")); keywords.append(QStringLiteral("DBL_MAX_10_EXP")); keywords.append(QStringLiteral("DBL_MAX_EXP")); keywords.append(QStringLiteral("DBL_MIN")); keywords.append(QStringLiteral("DBL_MIN_10_EXP")); keywords.append(QStringLiteral("DBL_MIN_EXP")); keywords.append(QStringLiteral("default")); keywords.append(QStringLiteral("delete")); keywords.append(QStringLiteral("DIR")); keywords.append(QStringLiteral("div_t")); keywords.append(QStringLiteral("do")); keywords.append(QStringLiteral("double")); keywords.append(QStringLiteral("dynamic_cast")); keywords.append(QStringLiteral("E2BIG")); keywords.append(QStringLiteral("EACCES")); keywords.append(QStringLiteral("EAGAIN")); keywords.append(QStringLiteral("EBADF")); keywords.append(QStringLiteral("EBADMSG")); keywords.append(QStringLiteral("EBUSY")); keywords.append(QStringLiteral("ECANCELED")); keywords.append(QStringLiteral("ECHILD")); keywords.append(QStringLiteral("EDEADLK")); keywords.append(QStringLiteral("EDOM")); keywords.append(QStringLiteral("EEXIST")); keywords.append(QStringLiteral("EFAULT")); keywords.append(QStringLiteral("EFBIG")); keywords.append(QStringLiteral("EILSEQ")); keywords.append(QStringLiteral("EINPROGRESS")); keywords.append(QStringLiteral("EINTR")); keywords.append(QStringLiteral("EINVAL")); keywords.append(QStringLiteral("EIO")); keywords.append(QStringLiteral("EISDIR")); keywords.append(QStringLiteral("else")); keywords.append(QStringLiteral("EMFILE")); keywords.append(QStringLiteral("EMLINK")); keywords.append(QStringLiteral("EMSGSIZE")); keywords.append(QStringLiteral("ENAMETOOLONG")); keywords.append(QStringLiteral("ENFILE")); keywords.append(QStringLiteral("ENODEV")); keywords.append(QStringLiteral("ENOENT")); keywords.append(QStringLiteral("ENOEXEC")); keywords.append(QStringLiteral("ENOLCK")); keywords.append(QStringLiteral("ENOMEM")); keywords.append(QStringLiteral("ENOSPC")); keywords.append(QStringLiteral("ENOSYS")); keywords.append(QStringLiteral("ENOTDIR")); keywords.append(QStringLiteral("ENOTEMPTY")); keywords.append(QStringLiteral("ENOTSUP")); keywords.append(QStringLiteral("ENOTTY")); keywords.append(QStringLiteral("enum")); keywords.append(QStringLiteral("ENXIO")); keywords.append(QStringLiteral("EOF")); keywords.append(QStringLiteral("EPERM")); keywords.append(QStringLiteral("EPIPE")); keywords.append(QStringLiteral("ERANGE")); keywords.append(QStringLiteral("EROFS")); keywords.append(QStringLiteral("ESPIPE")); keywords.append(QStringLiteral("ESRCH")); keywords.append(QStringLiteral("ETIMEDOUT")); keywords.append(QStringLiteral("EXDEV")); keywords.append(QStringLiteral("EXIT_FAILURE")); keywords.append(QStringLiteral("EXIT_SUCCESS")); keywords.append(QStringLiteral("explicit")); keywords.append(QStringLiteral("export")); keywords.append(QStringLiteral("extern")); keywords.append(QStringLiteral("false")); keywords.append(QStringLiteral("__FILE__")); keywords.append(QStringLiteral("FILE")); keywords.append(QStringLiteral("FILENAME_MAX")); keywords.append(QStringLiteral("float")); keywords.append(QStringLiteral("FLT_DIG")); keywords.append(QStringLiteral("FLT_EPSILON")); keywords.append(QStringLiteral("FLT_MANT_DIG")); keywords.append(QStringLiteral("FLT_MAX")); keywords.append(QStringLiteral("FLT_MAX_10_EXP")); keywords.append(QStringLiteral("FLT_MAX_EXP")); keywords.append(QStringLiteral("FLT_MIN")); keywords.append(QStringLiteral("FLT_MIN_10_EXP")); keywords.append(QStringLiteral("FLT_MIN_EXP")); keywords.append(QStringLiteral("FLT_RADIX")); keywords.append(QStringLiteral("FLT_ROUNDS")); keywords.append(QStringLiteral("FOPEN_MAX")); keywords.append(QStringLiteral("for")); keywords.append(QStringLiteral("fpos_t")); keywords.append(QStringLiteral("friend")); keywords.append(QStringLiteral("__FUNCTION__")); keywords.append(QStringLiteral("__GNUC__")); keywords.append(QStringLiteral("goto")); keywords.append(QStringLiteral("HUGE_VAL")); keywords.append(QStringLiteral("if")); keywords.append(QStringLiteral("__imag__")); keywords.append(QStringLiteral("inline")); keywords.append(QStringLiteral("int")); keywords.append(QStringLiteral("INT16_MAX")); keywords.append(QStringLiteral("INT16_MIN")); keywords.append(QStringLiteral("int16_t")); keywords.append(QStringLiteral("INT32_MAX")); keywords.append(QStringLiteral("INT32_MIN")); keywords.append(QStringLiteral("int32_t")); keywords.append(QStringLiteral("INT64_MAX")); keywords.append(QStringLiteral("INT64_MIN")); keywords.append(QStringLiteral("int64_t")); keywords.append(QStringLiteral("INT8_MAX")); keywords.append(QStringLiteral("INT8_MIN")); keywords.append(QStringLiteral("int8_t")); keywords.append(QStringLiteral("INT_FAST16_MAX")); keywords.append(QStringLiteral("INT_FAST16_MIN")); keywords.append(QStringLiteral("int_fast16_t")); keywords.append(QStringLiteral("INT_FAST32_MAX")); keywords.append(QStringLiteral("INT_FAST32_MIN")); keywords.append(QStringLiteral("int_fast32_t")); keywords.append(QStringLiteral("INT_FAST64_MAX")); keywords.append(QStringLiteral("INT_FAST64_MIN")); keywords.append(QStringLiteral("int_fast64_t")); keywords.append(QStringLiteral("INT_FAST8_MAX")); keywords.append(QStringLiteral("INT_FAST8_MIN")); keywords.append(QStringLiteral("int_fast8_t")); keywords.append(QStringLiteral("INT_LEAST16_MAX")); keywords.append(QStringLiteral("INT_LEAST16_MIN")); keywords.append(QStringLiteral("int_least16_t")); keywords.append(QStringLiteral("INT_LEAST32_MAX")); keywords.append(QStringLiteral("INT_LEAST32_MIN")); keywords.append(QStringLiteral("int_least32_t")); keywords.append(QStringLiteral("INT_LEAST64_MAX")); keywords.append(QStringLiteral("INT_LEAST64_MIN")); keywords.append(QStringLiteral("int_least64_t")); keywords.append(QStringLiteral("INT_LEAST8_MAX")); keywords.append(QStringLiteral("INT_LEAST8_MIN")); keywords.append(QStringLiteral("int_least8_t")); keywords.append(QStringLiteral("INT_MAX")); keywords.append(QStringLiteral("INTMAX_MAX")); keywords.append(QStringLiteral("INTMAX_MIN")); keywords.append(QStringLiteral("intmax_t")); keywords.append(QStringLiteral("INT_MIN")); keywords.append(QStringLiteral("INTPTR_MAX")); keywords.append(QStringLiteral("INTPTR_MIN")); keywords.append(QStringLiteral("intptr_t")); keywords.append(QStringLiteral("_IOFBF")); keywords.append(QStringLiteral("_IOLBF")); keywords.append(QStringLiteral("_IONBF")); keywords.append(QStringLiteral("jmp_buf")); keywords.append(QStringLiteral("__label__")); keywords.append(QStringLiteral("LC_ALL")); keywords.append(QStringLiteral("LC_COLLATE")); keywords.append(QStringLiteral("LC_CTYPE")); keywords.append(QStringLiteral("LC_MONETARY")); keywords.append(QStringLiteral("LC_NUMERIC")); keywords.append(QStringLiteral("LC_TIME")); keywords.append(QStringLiteral("LDBL_DIG")); keywords.append(QStringLiteral("LDBL_EPSILON")); keywords.append(QStringLiteral("LDBL_MANT_DIG")); keywords.append(QStringLiteral("LDBL_MAX")); keywords.append(QStringLiteral("LDBL_MAX_10_EXP")); keywords.append(QStringLiteral("LDBL_MAX_EXP")); keywords.append(QStringLiteral("LDBL_MIN")); keywords.append(QStringLiteral("LDBL_MIN_10_EXP")); keywords.append(QStringLiteral("LDBL_MIN_EXP")); keywords.append(QStringLiteral("ldiv_t")); keywords.append(QStringLiteral("__LINE__")); keywords.append(QStringLiteral("LLONG_MAX")); keywords.append(QStringLiteral("long")); keywords.append(QStringLiteral("LONG_MAX")); keywords.append(QStringLiteral("LONG_MIN")); keywords.append(QStringLiteral("L_tmpnam")); keywords.append(QStringLiteral("M_1_PI")); keywords.append(QStringLiteral("M_2_PI")); keywords.append(QStringLiteral("M_2_SQRTPI")); keywords.append(QStringLiteral("MB_CUR_MAX")); keywords.append(QStringLiteral("MB_LEN_MAX")); keywords.append(QStringLiteral("mbstate_t")); keywords.append(QStringLiteral("M_E")); keywords.append(QStringLiteral("M_LN10")); keywords.append(QStringLiteral("M_LN2")); keywords.append(QStringLiteral("M_LOG10E")); keywords.append(QStringLiteral("M_LOG2E")); keywords.append(QStringLiteral("M_PI")); keywords.append(QStringLiteral("M_PI_2")); keywords.append(QStringLiteral("M_PI_4")); keywords.append(QStringLiteral("M_SQRT1_2")); keywords.append(QStringLiteral("M_SQRT2")); keywords.append(QStringLiteral("mutable")); keywords.append(QStringLiteral("namespace")); keywords.append(QStringLiteral("new")); keywords.append(QStringLiteral("not")); keywords.append(QStringLiteral("not_eq")); keywords.append(QStringLiteral("NPOS")); keywords.append(QStringLiteral("NULL")); keywords.append(QStringLiteral("operator")); keywords.append(QStringLiteral("or")); keywords.append(QStringLiteral("or_eq")); keywords.append(QStringLiteral("__PRETTY_FUNCTION__")); keywords.append(QStringLiteral("private")); keywords.append(QStringLiteral("protected")); keywords.append(QStringLiteral("PTRDIFF_MAX")); keywords.append(QStringLiteral("PTRDIFF_MIN")); keywords.append(QStringLiteral("ptrdiff_t")); keywords.append(QStringLiteral("public")); keywords.append(QStringLiteral("RAND_MAX")); keywords.append(QStringLiteral("__real__")); keywords.append(QStringLiteral("register")); keywords.append(QStringLiteral("reinterpret_cast")); keywords.append(QStringLiteral("restrict")); keywords.append(QStringLiteral("return")); keywords.append(QStringLiteral("SCHAR_MAX")); keywords.append(QStringLiteral("SCHAR_MIN")); keywords.append(QStringLiteral("SEEK_CUR")); keywords.append(QStringLiteral("SEEK_END")); keywords.append(QStringLiteral("SEEK_SET")); keywords.append(QStringLiteral("short")); keywords.append(QStringLiteral("SHRT_MAX")); keywords.append(QStringLiteral("SHRT_MIN")); keywords.append(QStringLiteral("SIGABRT")); keywords.append(QStringLiteral("SIGALRM")); keywords.append(QStringLiteral("SIG_ATOMIC_MAX")); keywords.append(QStringLiteral("SIG_ATOMIC_MIN")); keywords.append(QStringLiteral("sig_atomic_t")); keywords.append(QStringLiteral("SIGCHLD")); keywords.append(QStringLiteral("SIGCONT")); keywords.append(QStringLiteral("SIG_DFL")); keywords.append(QStringLiteral("SIG_ERR")); keywords.append(QStringLiteral("SIGFPE")); keywords.append(QStringLiteral("SIGHUP")); keywords.append(QStringLiteral("SIG_IGN")); keywords.append(QStringLiteral("SIGILL")); keywords.append(QStringLiteral("SIGINT")); keywords.append(QStringLiteral("SIGKILL")); keywords.append(QStringLiteral("signed")); keywords.append(QStringLiteral("SIGPIPE")); keywords.append(QStringLiteral("SIGQUIT")); keywords.append(QStringLiteral("SIGSEGV")); keywords.append(QStringLiteral("SIGSTOP")); keywords.append(QStringLiteral("SIGTERM")); keywords.append(QStringLiteral("SIGTRAP")); keywords.append(QStringLiteral("SIGTSTP")); keywords.append(QStringLiteral("SIGTTIN")); keywords.append(QStringLiteral("SIGTTOU")); keywords.append(QStringLiteral("SIGUSR1")); keywords.append(QStringLiteral("SIGUSR2")); keywords.append(QStringLiteral("SINT_MAX")); keywords.append(QStringLiteral("SINT_MIN")); keywords.append(QStringLiteral("SIZE_MAX")); keywords.append(QStringLiteral("sizeof")); keywords.append(QStringLiteral("size_t")); keywords.append(QStringLiteral("SLONG_MAX")); keywords.append(QStringLiteral("SLONG_MIN")); keywords.append(QStringLiteral("SSHRT_MAX")); keywords.append(QStringLiteral("SSHRT_MIN")); keywords.append(QStringLiteral("ssize_t")); keywords.append(QStringLiteral("static")); keywords.append(QStringLiteral("constexpr")); keywords.append(QStringLiteral("static_cast")); keywords.append(QStringLiteral("__STDC__")); keywords.append(QStringLiteral("__STDC_VERSION__")); keywords.append(QStringLiteral("stderr")); keywords.append(QStringLiteral("stdin")); keywords.append(QStringLiteral("stdout")); keywords.append(QStringLiteral("struct")); keywords.append(QStringLiteral("switch")); keywords.append(QStringLiteral("template")); keywords.append(QStringLiteral("this")); keywords.append(QStringLiteral("throw")); keywords.append(QStringLiteral("__TIME__")); keywords.append(QStringLiteral("time_t")); keywords.append(QStringLiteral("TMP_MAX")); keywords.append(QStringLiteral("true")); keywords.append(QStringLiteral("try")); keywords.append(QStringLiteral("typedef")); keywords.append(QStringLiteral("typeid")); keywords.append(QStringLiteral("typename")); keywords.append(QStringLiteral("typeof")); keywords.append(QStringLiteral("UCHAR_MAX")); keywords.append(QStringLiteral("UINT16_MAX")); keywords.append(QStringLiteral("uint16_t")); keywords.append(QStringLiteral("UINT32_MAX")); keywords.append(QStringLiteral("uint32_t")); keywords.append(QStringLiteral("UINT64_MAX")); keywords.append(QStringLiteral("uint64_t")); keywords.append(QStringLiteral("UINT8_MAX")); keywords.append(QStringLiteral("uint8_t")); keywords.append(QStringLiteral("UINT_FAST16_MAX")); keywords.append(QStringLiteral("uint_fast16_t")); keywords.append(QStringLiteral("UINT_FAST32_MAX")); keywords.append(QStringLiteral("uint_fast32_t")); keywords.append(QStringLiteral("UINT_FAST64_MAX")); keywords.append(QStringLiteral("uint_fast64_t")); keywords.append(QStringLiteral("UINT_FAST8_MAX")); keywords.append(QStringLiteral("uint_fast8_t")); keywords.append(QStringLiteral("UINT_LEAST16_MAX")); keywords.append(QStringLiteral("uint_least16_t")); keywords.append(QStringLiteral("UINT_LEAST32_MAX")); keywords.append(QStringLiteral("uint_least32_t")); keywords.append(QStringLiteral("UINT_LEAST64_MAX")); keywords.append(QStringLiteral("uint_least64_t")); keywords.append(QStringLiteral("UINT_LEAST8_MAX")); keywords.append(QStringLiteral("uint_least8_t")); keywords.append(QStringLiteral("UINT_MAX")); keywords.append(QStringLiteral("UINTMAX_MAX")); keywords.append(QStringLiteral("uintmax_t")); keywords.append(QStringLiteral("UINTPTR_MAX")); keywords.append(QStringLiteral("uintptr_t")); keywords.append(QStringLiteral("ULLONG_MAX")); keywords.append(QStringLiteral("ULONG_MAX")); keywords.append(QStringLiteral("union")); keywords.append(QStringLiteral("unsigned")); keywords.append(QStringLiteral("USHRT_MAX")); keywords.append(QStringLiteral("using")); keywords.append(QStringLiteral("va_list")); keywords.append(QStringLiteral("virtual")); keywords.append(QStringLiteral("void")); keywords.append(QStringLiteral("__volatile__")); keywords.append(QStringLiteral("volatile")); keywords.append(QStringLiteral("WCHAR_MAX")); keywords.append(QStringLiteral("WCHAR_MIN")); keywords.append(QStringLiteral("wchar_t")); keywords.append(QStringLiteral("wctrans_t")); keywords.append(QStringLiteral("wctype_t")); keywords.append(QStringLiteral("WEOF")); keywords.append(QStringLiteral("while")); keywords.append(QStringLiteral("WINT_MAX")); keywords.append(QStringLiteral("WINT_MIN")); keywords.append(QStringLiteral("wint_t")); keywords.append(QStringLiteral("xor")); keywords.append(QStringLiteral("xor_eq")); } return keywords; } /** * Add C++ stereotypes. */ void createCppStereotypes() { UMLDoc *umldoc = UMLApp::app()->document(); umldoc->findOrCreateStereotype(QStringLiteral("constructor")); // declares an operation as friend umldoc->findOrCreateStereotype(QStringLiteral("friend")); // to use in methods that aren't abstract umldoc->findOrCreateStereotype(QStringLiteral("virtual")); } /** * Return the input string with the first letter capitalized. */ QString capitalizeFirstLetter(const QString &string) { if (string.isEmpty()) return QString(); QChar firstChar = string.at(0); return firstChar.toUpper() + string.mid(1); } } // end namespace Codegen_Utils
20,825
C++
.cpp
422
41.258294
92
0.678976
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
749,513
codedocument.cpp
KDE_umbrello/umbrello/codegenerators/codedocument.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org> */ // own header #include "codedocument.h" // local includes #include "codegenerator.h" #include "debug_utils.h" #include "package.h" #include "umldoc.h" #include "uml.h" // qt includes #include <QDateTime> #include <QRegularExpression> #include <QXmlStreamWriter> /** * Constructor. */ CodeDocument::CodeDocument () : CodeGenObjectWithTextBlocks(this), m_lastTagIndex(0), m_filename(QString()), m_fileExtension(QString()), m_ID(QString()), m_pathName(QString()), m_package(nullptr), m_writeOutCode(true) { setHeader(new CodeComment(this)); // m_dialog = new CodeDocumentDialog(); } /** * Destructor. */ CodeDocument::~CodeDocument () { // delete all the text blocks we have while (!m_textblockVector.isEmpty()) { delete m_textblockVector.takeFirst(); } delete m_header; } /** * Set the complete value (name plus any extension) of m_filename. * @param new_var the new value of m_filename */ void CodeDocument::setFileName (const QString &new_var) { m_filename = new_var; } /** * Get the value of m_filename. This name is the "complete" filename, * meaning that it contains both the file name plus any extension (e.g. "file.cpp"). * @return the value of m_filename */ QString CodeDocument::getFileName () const { return m_filename; } /** * Set the value of m_fileExtension. * @param new_var the new value of m_fileExtension */ void CodeDocument::setFileExtension (const QString &new_var) { m_fileExtension = new_var; updateHeader(); // because we are using new heading file } /** * Get the value of m_fileExtension. * @return the value of m_fileExtension */ QString CodeDocument::getFileExtension() const { return m_fileExtension; } /** * Set the value of m_package. * @param new_var the new value of m_package */ void CodeDocument::setPackage (UMLPackage *new_var) { m_package = new_var; } /** * Get the value of the path to this code document. * @return the value of m_pathName */ QString CodeDocument::getPath () const { QString path = getPackage(); // Replace all white spaces with blanks path = path.simplified(); // Replace all blanks with underscore path.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_")); // this allows multiple directory paths (ala Java, some other languages) // in from the package specification path.replace(QRegularExpression(QStringLiteral("\\.")), QStringLiteral("/")); // Simple hack!.. but this is more or less language // dependent and should probably be commented out. // Still, as a general default it may be useful -b.t. return path; } /** * Get the value of the package of this code document. * @return the value of m_pathName */ QString CodeDocument::getPackage () const { if (m_package) return m_package->name(); return QString(); } /** * Set the value of m_ID. * @param new_id the new value of m_ID */ void CodeDocument::setID (const QString &new_id) { m_ID = new_id; } /** * Get the value of m_ID. * @return the value of m_ID */ QString CodeDocument::ID () const { return m_ID; } /** * Set the value of m_writeOutCode. * Whether or not to write out this code document and any codeblocks, etc that it * owns. * @param new_var the new value of m_writeOutCode */ void CodeDocument::setWriteOutCode (bool new_var) { m_writeOutCode = new_var; } /** * Get the value of m_writeOutCode. * Whether or not to write out this code document and any codeblocks, etc that it * owns. * @return the value of m_writeOutCode */ bool CodeDocument::getWriteOutCode () const { return m_writeOutCode; } /** * Set a Header comment object. * @param comment the comment for the header */ void CodeDocument::setHeader (CodeComment * comment) { m_header = comment; } /** * Get the Header comment object. * @return the comment for the header */ CodeComment * CodeDocument::getHeader () const { return m_header; } /** * Return a unique and currently unallocated text block tag for this document. * @param prefix the prefix to add * @return the just created unique tag */ QString CodeDocument::getUniqueTag (const QString& prefix) { QString tag = prefix ; if(tag.isEmpty()) tag += QStringLiteral("tblock"); tag = tag + QStringLiteral("_0"); int number = m_lastTagIndex; for (; findTextBlockByTag(tag, true); ++number) { tag = prefix + QLatin1Char('_') + QString::number(number); } m_lastTagIndex = number; return tag; } /** * Insert a new text block after the existing text block. Returns * false if it cannot insert the textblock. * @param newBlock the text block to insert * @param existingBlock the place where to insert * @param after at the index of the existingBlock or after * @return the success status */ bool CodeDocument::insertTextBlock(TextBlock * newBlock, TextBlock * existingBlock, bool after) { if (!newBlock || !existingBlock) return false; QString tag = existingBlock->getTag(); if (!findTextBlockByTag(tag, true)) return false; int index = m_textblockVector.indexOf(existingBlock); if (index < 0) { // may be hiding in child hierarchical codeblock for(TextBlock* tb: m_textblockVector) { HierarchicalCodeBlock * hb = dynamic_cast<HierarchicalCodeBlock*>(tb); if (hb && hb->insertTextBlock(newBlock, existingBlock, after)) return true; // found, and inserted, otherwise keep going } // ugh. where is the child block? logWarn2("couldnt insert text block (tag %1). Reference text block (tag %2) not found.", newBlock->getTag(), existingBlock->getTag()); return false; } // if we get here.. it was in this object so insert // check for tag FIRST QString new_tag = newBlock->getTag(); // assign a tag if one doesn't already exist if (new_tag.isEmpty()) { new_tag = getUniqueTag(); newBlock->setTag(new_tag); } if (m_textBlockTagMap.contains(new_tag)) return false; // return false, we already have some object with this tag in the list else m_textBlockTagMap.insert(new_tag, newBlock); if (after) index++; m_textblockVector.insert(index, newBlock); return true; } /** * A little utility method which calls CodeGenerator::cleanName. * @param name the cleanable name * @return the cleaned name */ QString CodeDocument::cleanName (const QString &name) { return CodeGenerator::cleanName(name); } /** * Update the header text of this codedocument * (text and status of the head comment). */ void CodeDocument::updateHeader () { //try to find a heading file (license, comments, etc) then extract its text QString headingText = UMLApp::app()->commonPolicy()->getHeadingFile(getFileExtension()); headingText.replace(QRegularExpression(QStringLiteral("%filename%")), getFileName()+getFileExtension()); headingText.replace(QRegularExpression(QStringLiteral("%filepath%")), getPath()); headingText.replace(QRegularExpression(QStringLiteral("%time%")), QTime::currentTime().toString()); headingText.replace(QRegularExpression(QStringLiteral("%date%")), QDate::currentDate().toString()); getHeader()->setText(headingText); // update the write out status of the header if (UMLApp::app()->commonPolicy()->getIncludeHeadings()) getHeader()->setWriteOutText(true); else getHeader()->setWriteOutText(false); } /** * Create the string representation of this object. * @return the created string */ QString CodeDocument::toString () const { // IF the whole document is turned "Off" then don't bother // checking individual code blocks, just send back empty string if (!getWriteOutCode()) return QString(); QString content = getHeader()->toString(); // update the time/date // comments, import, package codeblocks go next TextBlockList * items = getTextBlockList(); for (TextBlock* c: *items) { if (c->getWriteOutText()) { QString str = c->toString(); if (!str.isEmpty()) content.append(str); } } return content; } /** * Cause this code document to synchronize to current generator policy. */ void CodeDocument::synchronize() { updateContent(); } /** * Reset/clear our inventory of textblocks in this document. * Need to overload method to be able to clear the childTextBlockMap. */ void CodeDocument::resetTextBlocks() { CodeGenObjectWithTextBlocks::resetTextBlocks(); m_childTextBlockTagMap.clear(); } /** * Load params from the appropriate XMI element node. * @param root the starting point for loading */ void CodeDocument::loadFromXMI (QDomElement & root) { setAttributesFromNode(root); } /** * Set attributes of the node that represents this class * in the XMI document. */ void CodeDocument::setAttributesOnNode (QXmlStreamWriter& writer) { // superclass call CodeGenObjectWithTextBlocks::setAttributesOnNode(writer); // now set local attributes/fields writer.writeAttribute(QStringLiteral("fileName"), getFileName()); writer.writeAttribute(QStringLiteral("fileExt"), getFileExtension()); Uml::ID::Type pkgId = Uml::ID::None; if (m_package) pkgId = m_package->id(); writer.writeAttribute(QStringLiteral("package"), Uml::ID::toString(pkgId)); writer.writeAttribute(QStringLiteral("writeOutCode"), getWriteOutCode() ? QStringLiteral("true") : QStringLiteral("false")); writer.writeAttribute(QStringLiteral("id"), ID()); // set the a header // which we will store in its own separate child node block writer.writeStartElement(QStringLiteral("header")); getHeader()->saveToXMI(writer); // comment writer.writeEndElement(); // doc codePolicy? // FIX: store ONLY if different from the parent generator // policy.. something which is not possible right now. -b.t. } /** * Set the class attributes of this object from * the passed element node. */ void CodeDocument::setAttributesFromNode (QDomElement & root) { // now set local attributes setFileName(root.attribute(QStringLiteral("fileName"))); setFileExtension(root.attribute(QStringLiteral("fileExt"))); QString pkgStr = root.attribute(QStringLiteral("package")); if (!pkgStr.isEmpty() && pkgStr != QStringLiteral("-1")) { UMLDoc *umldoc = UMLApp::app()->document(); if (pkgStr.contains(QRegularExpression(QStringLiteral("\\D")))) { // suspecting pre-1.5.3 file format where the package name was // saved instead of the package ID. UMLObject *o = umldoc->findUMLObject(pkgStr); m_package = o->asUMLPackage(); } if (m_package == nullptr) { UMLObject *o = umldoc->findObjectById(Uml::ID::fromString(pkgStr)); m_package = o->asUMLPackage(); } } const QString trueStr = QStringLiteral("true"); const QString wrOutCode = root.attribute(QStringLiteral("writeOutCode"), trueStr); setWriteOutCode(wrOutCode == trueStr); setID(root.attribute(QStringLiteral("id"))); // load comment now // by looking for our particular child element QDomNode node = root.firstChild(); QDomElement element = node.toElement(); while (!element.isNull()) { QString tag = element.tagName(); if (tag == QStringLiteral("header")) { QDomNode cnode = element.firstChild(); QDomElement celem = cnode.toElement(); getHeader()->loadFromXMI(celem); break; } node = element.nextSibling(); element = node.toElement(); } // a rare case where the super-class load is AFTER local attributes CodeGenObjectWithTextBlocks::setAttributesFromNode(root); } /** * Save the XMI representation of this object. * @param writer QXmlStreamWriter serialization target */ void CodeDocument::saveToXMI(QXmlStreamWriter& writer) { writer.writeStartElement(QStringLiteral("codedocument")); setAttributesOnNode(writer); writer.writeEndElement(); } /** * Update the content of this code document. * This is where you should lay out your code document structure of textblocks * in the inheriting class, should it have any text in it. * Vanilla code documents don't have much to do.. override this with a different * version for your own documents. */ void CodeDocument::updateContent() { updateHeader(); // doing this insures time/date stamp is at the time of this call } /** * Create a new CodeBlock object belonging to this CodeDocument. * @return the just created CodeBlock */ CodeBlock * CodeDocument::newCodeBlock () { return new CodeBlock(this); } /** * Create a new CodeBlockWithComments object belonging to this CodeDocument. * @return the just created CodeBlockWithComments */ CodeBlockWithComments * CodeDocument::newCodeBlockWithComments () { return new CodeBlockWithComments(this); } /** * Create a new HierarchicalCodeBlock object belonging to this CodeDocument. * @return the just created HierarchicalCodeBlock */ HierarchicalCodeBlock * CodeDocument::newHierarchicalCodeBlock () { HierarchicalCodeBlock *hb = new HierarchicalCodeBlock(this); //hb->update(); return hb; } void CodeDocument::removeChildTagFromMap (const QString &tag) { m_childTextBlockTagMap.remove(tag); } void CodeDocument::addChildTagToMap (const QString &tag, TextBlock * tb) { m_childTextBlockTagMap.insert(tag, tb); } /** * Lookup a certain textblock by its tag value, returns NULL if it cannot * find the TextBlock with such a tag. If descendIntoChildren is true, then * any child hierarchical textblocks will also be searched for a match. * @param tag the tag to look for * @param descendIntoChildren look down the hierarchy * @return the found text block */ TextBlock * CodeDocument::findTextBlockByTag(const QString &tag, bool descendIntoChildren) const { //if we already know to which file this class was written/should be written, just return it. if (m_textBlockTagMap.contains(tag)) return m_textBlockTagMap[tag]; if (descendIntoChildren) if (m_childTextBlockTagMap.contains(tag)) return m_childTextBlockTagMap[tag]; return nullptr; } /** * Have to implement this for CodeObjectWithTextBlocks. * Actually does not do anything for a vanilla code document. */ TextBlock * CodeDocument::findCodeClassFieldTextBlockByTag (const QString &tag) { logWarn1("Called findCodeClassFieldMethodByTag(%1) for a regular CodeDocument", tag); return nullptr; } QDebug operator<<(QDebug os, const CodeDocument& obj) { os.nospace() << "CodeDocument: id=" << obj.ID() << ", file=" << obj.getFileName(); //:TODO: add all attributes return os.space(); }
15,335
C++
.cpp
463
29.190065
108
0.698339
KDE/umbrello
114
36
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false