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,313
|
umlinstanceattributedialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlinstanceattributedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
//local includes
#include "umlinstanceattributedialog.h"
#include "ui_umlinstanceattributedialog.h"
#include "attribute.h"
#include "uml.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
UMLInstanceAttributeDialog::UMLInstanceAttributeDialog(QWidget *parent, UMLInstanceAttribute *pInstanceAttr)
: SinglePageDialogBase(parent),
ui(new Ui::UMLInstanceAttributeDialog),
m_pInstanceAttr(pInstanceAttr)
{
setCaption(i18n("Object Attribute Properties"));
ui->setupUi(mainWidget());
ui->nameLE->setReadOnly(true);
ui->nameLE->setText(pInstanceAttr->getAttribute()->name());
QString initValue = pInstanceAttr->getValue();
if (initValue.isEmpty())
initValue = pInstanceAttr->getAttribute()->getInitialValue();
ui->valueLE->setText(initValue);
}
UMLInstanceAttributeDialog::~UMLInstanceAttributeDialog()
{
delete ui;
}
bool UMLInstanceAttributeDialog::apply()
{
QString value = ui->valueLE->text();
if (value.isEmpty()) {
KMessageBox::error(this, i18n("You have entered an invalid attribute value."),
i18n("Value Invalid"));
return false;
}
m_pInstanceAttr->setValue(value);
m_pInstanceAttr->emitModified();
return true;
}
| 1,404
|
C++
|
.cpp
| 42
| 29.261905
| 108
| 0.732301
|
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,314
|
umlroledialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlroledialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlroledialog.h"
// kde includes
#include <KLocalizedString>
// app includes
#include "umlrole.h"
#include "umlroleproperties.h"
UMLRoleDialog::UMLRoleDialog(QWidget * parent, UMLRole * pRole)
: SinglePageDialogBase(parent)
{
setCaption(i18n("Role Properties"));
m_pRole = pRole;
setupDialog();
}
UMLRoleDialog::~UMLRoleDialog()
{
}
/**
* Sets up the dialog
*/
void UMLRoleDialog::setupDialog()
{
// UMLRoleDialogLayout = new QGridLayout(this, 1, 1, 11, 6, "UMLRoleLayout");
m_pRoleProps = new UMLRoleProperties(this, m_pRole);
setMainWidget(m_pRoleProps);
resize(QSize(425, 620).expandedTo(minimumSizeHint()));
// topLayout->addWidget(m_pParmsGB);
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false
*/
bool UMLRoleDialog::apply()
{
if (m_pRoleProps) {
m_pRoleProps->apply();
return true;
}
return false;
}
| 1,092
|
C++
|
.cpp
| 44
| 21.886364
| 92
| 0.713873
|
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,315
|
stereoattributedialog.cpp
|
KDE_umbrello/umbrello/dialogs/stereoattributedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "stereoattributedialog.h"
// app includes
#include "stereotype.h"
#include "umldoc.h"
#include "uml.h"
#include "dialog_utils.h"
#include "debug_utils.h"
// kde includes
#include <QLineEdit>
#include <kcombobox.h>
#include <kcompletion.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QGridLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLayout>
#include <QLabel>
#include <QGroupBox>
#include <QComboBox>
#include <QDialogButtonBox>
DEBUG_REGISTER(StereoAttributeDialog)
StereoAttributeDialog::StereoAttributeDialog(QWidget *parent, UMLStereotype *stereotype)
: SinglePageDialogBase(parent)
{
setCaption(i18n("Stereotype Properties"));
m_pStereotype = stereotype;
setupDialog();
}
StereoAttributeDialog::~StereoAttributeDialog()
{
}
/**
* Sets up the dialog
*/
void StereoAttributeDialog::setupDialog()
{
int margin = fontMetrics().height();
QFrame * frame = new QFrame(this);
setMainWidget(frame);
QVBoxLayout * mainLayout = new QVBoxLayout(frame);
m_pValuesGB = new QGroupBox(i18n("Stereotype Attributes for ") + m_pStereotype->name(true),
frame);
QGridLayout * valuesLayout = new QGridLayout(m_pValuesGB);
valuesLayout->setContentsMargins(margin, margin, margin, margin);
valuesLayout->setSpacing(10);
/*
QLabel *m_pNameLabel[N_STEREOATTRS];
QLineEdit *m_pNameEdit [N_STEREOATTRS];
QLabel *m_pTypeLabel[N_STEREOATTRS];
QComboBox *m_pTypeCombo[N_STEREOATTRS];
*/
const UMLStereotype::AttributeDefs& adefs = m_pStereotype->getAttributeDefs();
for (int row = 0; row < N_STEREOATTRS; row++) {
Dialog_Utils::makeLabeledEditField(valuesLayout, row,
m_pNameLabel[row], i18nc("attribute name", "&Name:"),
m_pNameEdit[row]); // columns 0, 1
m_pTypeLabel[row] = new QLabel(i18nc("attribute type", "&Type:"));
valuesLayout->addWidget(m_pTypeLabel[row], row, 2); // column 2
m_pTypeCombo[row] = new QComboBox(this);
for (int type = 0; type < Uml::PrimitiveTypes::n_types; type++) {
m_pTypeCombo[row]->addItem(Uml::PrimitiveTypes::toString(type));
}
valuesLayout->addWidget(m_pTypeCombo[row], row, 3); // column 3
m_pTypeLabel[row]->setBuddy(m_pTypeCombo[row]);
Dialog_Utils::makeLabeledEditField(valuesLayout, row,
m_pDefaultValueLabel[row], i18nc("default value", "&Default:"),
m_pDefaultValueEdit[row], QString(), 4); // columns 4, 5
if (adefs.count() > row) {
const UMLStereotype::AttributeDef& adef = adefs.at(row);
if (!adef.name.isEmpty()) {
m_pNameEdit[row]->setText(adef.name.trimmed());
int type = int(adef.type);
if (type >= 0 && type < m_pTypeCombo[row]->count())
m_pTypeCombo[row]->setCurrentIndex(type);
else
logDebug1("StereoAttributeDialog::setupDialog: Illegal type %1", type);
const QString& dfltVal = adef.defaultVal;
if (!dfltVal.isEmpty())
m_pDefaultValueEdit[row]->setText(dfltVal);
}
}
}
mainLayout->addWidget(m_pValuesGB);
}
/**
* Used when the OK button is clicked. Applies the stereotype attribute changes.
*/
bool StereoAttributeDialog::apply()
{
m_pStereotype->clearAttributeDefs();
UMLStereotype::AttributeDefs adefs;
for (int i = 0; i < N_STEREOATTRS; i++) {
QString name = m_pNameEdit[i]->text().trimmed();
if (!name.isEmpty()) {
int typeIndex = m_pTypeCombo[i]->currentIndex();
if (typeIndex < 0)
typeIndex = 0;
Uml::PrimitiveTypes::Enum type = Uml::PrimitiveTypes::Enum(typeIndex);
QString dfltVal = m_pDefaultValueEdit[i]->text().trimmed();
UMLStereotype::AttributeDef attrDef(name, type, dfltVal);
adefs.append(attrDef);
}
}
if (adefs.count())
m_pStereotype->setAttributeDefs(adefs);
return true;
}
| 4,375
|
C++
|
.cpp
| 114
| 30.991228
| 99
| 0.635014
|
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,316
|
umluniqueconstraintdialog.cpp
|
KDE_umbrello/umbrello/dialogs/umluniqueconstraintdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umluniqueconstraintdialog.h"
#include "attribute.h"
#include "classifierlistitem.h"
#include "classifier.h"
#include "debug_utils.h"
#include "entity.h"
#include "entityattribute.h"
#include "enumliteral.h"
#include "enum.h"
#include "object_factory.h"
#include "operation.h"
#include "template.h"
#include "uml.h"
#include "uniqueconstraint.h"
#include "umldoc.h"
#include <kcombobox.h>
#include <QLineEdit>
#include <KLocalizedString>
#include <KMessageBox>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
#include <QVBoxLayout>
DEBUG_REGISTER(UMLUniqueConstraintDialog)
/**
* Sets up the UMLUniqueConstraintDialog.
* @param parent The parent to the UMLUniqueConstraintDialog.
* @param pUniqueConstraint The Unique Constraint to show the properties of.
*/
UMLUniqueConstraintDialog::UMLUniqueConstraintDialog(QWidget* parent, UMLUniqueConstraint* pUniqueConstraint)
: SinglePageDialogBase(parent, true),
m_pUniqueConstraint(pUniqueConstraint)
{
setCaption(i18n("Unique Constraint Properties"));
setupDialog();
}
/**
* Standard destructor.
*/
UMLUniqueConstraintDialog::~UMLUniqueConstraintDialog()
{
}
/**
* Sets up the dialog.
*/
void UMLUniqueConstraintDialog::setupDialog()
{
QFrame *frame = new QFrame(this);
setMainWidget(frame);
int margin = fontMetrics().height();
// what do we need,
// we need one label, line edir
// a list item box
// a combo box, two push buttons, yeah that's it.
// start
//main layout contains the name fields, the column group box
QVBoxLayout* mainLayout = new QVBoxLayout(frame);
mainLayout->setSpacing(10);
// layout to hold the name label and line edit
QHBoxLayout* nameLayout = new QHBoxLayout();
mainLayout->addItem(nameLayout);
// name label
m_pNameL = new QLabel(i18nc("name label", "Name"), this);
nameLayout->addWidget(m_pNameL);
// name lineEdit
m_pNameLE = new QLineEdit(this);
nameLayout->addWidget(m_pNameLE);
// group box to hold the column details
// top group box, contains a vertical layout with list box above and buttons below
m_pAttributeListGB = new QGroupBox(i18n("Attribute Details"), frame);
mainLayout->addWidget(m_pAttributeListGB);
QVBoxLayout* listVBoxLayout = new QVBoxLayout(m_pAttributeListGB);
listVBoxLayout->setContentsMargins(margin, margin, margin, margin);
listVBoxLayout->setSpacing (10);
m_pAttributeListLW = new QListWidget(m_pAttributeListGB);
listVBoxLayout->addWidget(m_pAttributeListLW);
// Horizontal Layout to hold attributes CB, the add, and remove buttons
QHBoxLayout* comboButtonHBoxLayout = new QHBoxLayout();
listVBoxLayout->addItem(comboButtonHBoxLayout);
// the Combo Box containing the attributes
m_pAttributeCB = new KComboBox(true, m_pAttributeListGB);
m_pAttributeCB->setEditable(false);
comboButtonHBoxLayout->addWidget(m_pAttributeCB);
//the action buttons
QDialogButtonBox* buttonBox = new QDialogButtonBox(m_pAttributeListGB);
m_pAddPB = buttonBox->addButton(i18n("&Add"), QDialogButtonBox::ActionRole);
connect(m_pAddPB, SIGNAL(clicked()), this, SLOT(slotAddAttribute()));
m_pRemovePB = buttonBox->addButton(i18n("&Delete"), QDialogButtonBox::ActionRole);
connect(m_pRemovePB, SIGNAL(clicked()), this, SLOT(slotDeleteAttribute()));
comboButtonHBoxLayout->addWidget(buttonBox);
// We first insert all attributes to the combo box
const UMLEntity* ue = m_pUniqueConstraint->umlParent()->asUMLEntity();
logDebug1("UMLUniqueConstraintDialog::setupDialog: UniqueConstraint parent=%1", ue->name());
if (ue) {
UMLClassifierListItemList ual = ue->getFilteredList(UMLObject::ot_EntityAttribute);
for(UMLClassifierListItem* att : ual) {
m_pEntityAttributeList.append(att->asUMLEntityAttribute());
m_pAttributeCB->addItem(att->toString(Uml::SignatureType::SigNoVis));
}
}
// Then we add the attributes in the constraint to the list box
UMLEntityAttributeList eal = m_pUniqueConstraint->getEntityAttributeList();
for(UMLEntityAttribute* att : eal) {
// add to local cache
m_pConstraintAttributeList.append(att);
// add to list box
m_pAttributeListLW->addItem(att->toString(Uml::SignatureType::SigNoVis));
int index = m_pEntityAttributeList.indexOf(att);
m_pEntityAttributeList.removeAt(index);
m_pAttributeCB->removeItem(index);
}
// set text of label
m_pNameLE->setText(m_pUniqueConstraint->name());
// select firstItem
if (m_pAttributeListLW->count() != 0) {
m_pAttributeListLW->setCurrentRow(0);
}
slotResetWidgetState();
connect(m_pAttributeListLW, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotResetWidgetState()));
}
/**
* Adds attribute to the list.
*/
void UMLUniqueConstraintDialog::slotAddAttribute()
{
int index = m_pAttributeCB->currentIndex();
if (index == -1) {
return;
}
// get reference
UMLEntityAttribute* entAtt = m_pEntityAttributeList.at(index);
//find and remove from list
index = m_pEntityAttributeList.indexOf(entAtt);
m_pEntityAttributeList.removeAt(index);
// remove from combo box
m_pAttributeCB->removeItem(index);
// add to local cache
m_pConstraintAttributeList.append(entAtt);
// add to list box
int count = m_pAttributeListLW->count();
m_pAttributeListLW->insertItem(count, entAtt->toString(Uml::SignatureType::SigNoVis));
slotResetWidgetState();
}
/**
* Deletes an attribute from the list.
*/
void UMLUniqueConstraintDialog::slotDeleteAttribute()
{
int index = m_pAttributeListLW->currentRow();
if (index == -1) {
return;
}
// get reference
UMLEntityAttribute* entAtt = m_pConstraintAttributeList.at(index);
//remove from constraint
m_pConstraintAttributeList.removeAt(index);
// remove from list box
m_pAttributeListLW->takeItem(index);
// add to list
m_pEntityAttributeList.append(entAtt);
// add to combo box
int count = m_pAttributeCB->count();
m_pAttributeCB->insertItem(count, entAtt->toString(Uml::SignatureType::SigNoVis));
slotResetWidgetState();
}
/**
* Apply changes.
*/
bool UMLUniqueConstraintDialog::apply()
{
QString name = m_pNameLE->text();
if (name.length() == 0) {
KMessageBox::error(this, i18n("You have entered an invalid constraint name."),
i18n("Constraint Name Invalid"));
m_pNameLE->setText(m_pUniqueConstraint->name());
return false;
}
// clear the old list
m_pUniqueConstraint->clearAttributeList();
// fill it with contents of local cache
for(UMLEntityAttribute* att : m_pConstraintAttributeList) {
m_pUniqueConstraint->addEntityAttribute(att);
}
// set name
m_pUniqueConstraint->setName(name);
// propagate changes to tree view
m_pUniqueConstraint->emitModified();
return true;
}
/**
* Enable or Disable the widgets.
*/
void UMLUniqueConstraintDialog::slotResetWidgetState()
{
m_pAttributeCB->setEnabled(true);
m_pAddPB->setEnabled(true);
m_pRemovePB->setEnabled(true);
// get index of selected Attribute in List Box
int index = m_pAttributeListLW->currentRow();
// if index is not invalid (-1), then activate the Remove Button
if (index == -1) {
m_pRemovePB->setEnabled(false);
}
// check for number of items in ComboBox
int count = m_pAttributeCB->count();
// if count is 0 disable Combo Box and Add Button
if (count == 0) {
m_pAttributeCB->setEnabled(false);
m_pAddPB->setEnabled(false);
}
}
| 7,920
|
C++
|
.cpp
| 217
| 32.004608
| 109
| 0.719326
|
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,317
|
classpropertiesdialog.cpp
|
KDE_umbrello/umbrello/dialogs/classpropertiesdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "classpropertiesdialog.h"
// app includes
#include "classassociationspage.h"
#include "classgeneralpage.h"
#include "classifierlistpage.h"
#include "classifierwidget.h"
#include "classoptionspage.h"
#include "componentwidget.h"
#include "constraintlistpage.h"
#include "debug_utils.h"
#include "entity.h"
#include "objectwidget.h"
#include "packagecontentspage.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
#include "umlview.h"
#include "umlwidgetstylepage.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QFrame>
#include <QHBoxLayout>
/**
* Sets up a ClassPropDialog.
*
* @param parent The parent of the ClassPropDialog
* @param c The UMLObject to display properties of.
* @param assoc Determines whether to display associations
*/
ClassPropertiesDialog::ClassPropertiesDialog(QWidget *parent, UMLObject * c, bool assoc)
: MultiPageDialogBase(parent)
{
init();
m_pWidget = nullptr;
m_pObject = c;
setupPages(assoc);
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Sets up a ClassPropDialog.
*
* @param parent The parent of the ClassPropDialog
* @param o The ObjectWidget to display properties of.
*/
ClassPropertiesDialog::ClassPropertiesDialog(QWidget *parent, ObjectWidget *o)
: MultiPageDialogBase(parent)
{
init();
m_pWidget = o;
m_pObject = m_pWidget->umlObject();
m_doc = UMLApp::app()->document();
setupGeneralPage();
setupStylePage(m_pWidget);
setupFontPage(m_pWidget);
setMinimumSize(340, 420);
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Sets up a ClassPropDialog.
*
* @param parent The parent of the ClassPropDialog
* @param w The UMLWidget to display properties of.
*/
ClassPropertiesDialog::ClassPropertiesDialog(QWidget *parent, UMLWidget *w)
: MultiPageDialogBase(parent)
{
init();
m_pWidget = w;
m_pObject = w->umlObject();
if (w->isClassWidget()
|| w->isInterfaceWidget()
|| w->isEnumWidget()
|| w->isPackageWidget()) {
setupPages(true);
} else if (w->isComponentWidget()) {
if (w->isInstance()) {
setupInstancePages();
} else {
setupPages(true);
}
} else if (w->isNodeWidget()) {
setupInstancePages();
} else {
setupPages();
}
// now setup the options page for classes
if (w->isClassWidget() || w->isInterfaceWidget()) {
setupDisplayPage();
}
setupStylePage(m_pWidget);
setupFontPage(m_pWidget);
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
void ClassPropertiesDialog::init()
{
setCaption(i18n("Properties"));
m_pAssocPage = nullptr;
m_pGenPage = nullptr;
m_pAttPage = nullptr;
m_pOpsPage = nullptr;
m_pPkgContentsPage = nullptr;
m_pTemplatePage = nullptr;
m_pEnumLiteralPage = nullptr;
m_pEntityAttributePage = nullptr;
m_pEntityConstraintPage = nullptr;
m_pOptionsPage = nullptr;
m_doc = UMLApp::app()->document();
}
/**
* Standard destructor.
*/
ClassPropertiesDialog::~ClassPropertiesDialog()
{
}
/**
* Calls slotApply()
*/
void ClassPropertiesDialog::apply()
{
slotApply();
}
/**
* Calls slotApply() and accepts (closes) the dialog.
*/
void ClassPropertiesDialog::slotOk()
{
slotApply();
accept();
}
/**
* Applies the settings in the dialog to the widget and object.
*/
void ClassPropertiesDialog::slotApply()
{
if (m_pGenPage) {
m_pGenPage->apply();
}
if (m_pAttPage) {
m_pAttPage->apply();
}
if (m_pOpsPage) {
m_pOpsPage->apply();
}
if (m_pTemplatePage) {
m_pTemplatePage->apply();
}
if (m_pEnumLiteralPage) {
m_pEnumLiteralPage->apply();
}
if (m_pEntityAttributePage) {
m_pEntityAttributePage->apply();
}
if (m_pEntityConstraintPage) {
m_pEntityConstraintPage->apply();
}
if (m_pOptionsPage) {
m_pOptionsPage->apply();
}
if (m_pStylePage) {
m_pStylePage->apply();
}
if (m_pWidget) {
applyFontPage(m_pWidget);
}
}
/**
* Sets up the general, attribute, operations, template and association pages as appropriate.
*/
void ClassPropertiesDialog::setupPages(bool assoc)
{
setupGeneralPage();
UMLObject::ObjectType ot = UMLObject::ot_UMLObject;
if (m_pObject) {
ot = m_pObject->baseType();
}
// add extra pages for class
if (ot == UMLObject::ot_Class) {
setupAttributesPage();
}
if (ot == UMLObject::ot_Class || ot == UMLObject::ot_Interface) {
setupOperationsPage();
}
if (ot == UMLObject::ot_Class || ot == UMLObject::ot_Interface) {
setupTemplatesPage();
}
if (ot == UMLObject::ot_Enum) {
setupEnumLiteralsPage();
}
if (ot == UMLObject::ot_Entity) {
setupEntityAttributesPage();
setupEntityConstraintsPage();
if (m_pWidget && m_pWidget->isEntityWidget())
setupEntityDisplayPage(m_pWidget->asEntityWidget());
}
if (ot == UMLObject::ot_Package) {
setupContentsPage();
}
if (assoc) {
setupAssociationsPage();
} else {
m_pAssocPage = nullptr;
}
}
/**
* Sets up the page "General" for the component.
*/
void ClassPropertiesDialog::setupGeneralPage()
{
if (m_pWidget && m_pWidget->baseType() == UMLWidget::wt_Object)
m_pGenPage = new ClassGeneralPage(m_doc, nullptr, static_cast<ObjectWidget*>(m_pWidget));
else if (m_pWidget && !m_pObject)
m_pGenPage = new ClassGeneralPage(m_doc, nullptr, m_pWidget);
else
m_pGenPage = new ClassGeneralPage(m_doc, nullptr, m_pObject);
createPage(i18nc("general settings page name", "General"), i18n("General Settings"),
Icon_Utils::it_Properties_General, m_pGenPage)->widget()->setMinimumSize(310, 330);
m_pGenPage->setFocus();
}
/**
* Sets up the page "Display" for the component.
*/
void ClassPropertiesDialog::setupDisplayPage()
{
ClassifierWidget *cw = m_pWidget->asClassifierWidget();
m_pOptionsPage = new ClassOptionsPage(nullptr, cw);
createPage(i18nc("display option page name", "Display"), i18n("Display Options"),
Icon_Utils::it_Properties_Display, m_pOptionsPage);
}
/**
* Sets up the page "Display" for the component.
*/
void ClassPropertiesDialog::setupEntityDisplayPage(EntityWidget *widget)
{
m_pOptionsPage = new ClassOptionsPage(nullptr, widget);
createPage(i18nc("display option page name", "Display"), i18n("Display Options"),
Icon_Utils::it_Properties_Display, m_pOptionsPage);
}
/**
* Sets up the page "Attributes" for the component.
*/
void ClassPropertiesDialog::setupAttributesPage()
{
m_pAttPage = new ClassifierListPage(nullptr, (UMLClassifier *)m_pObject, m_doc, UMLObject::ot_Attribute);
createPage(i18n("Attributes"), i18n("Attribute Settings"),
Icon_Utils::it_Properties_Attributes, m_pAttPage);
}
/**
* Sets up the page "Operations" for the component.
*/
void ClassPropertiesDialog::setupOperationsPage()
{
m_pOpsPage = new ClassifierListPage(nullptr, (UMLClassifier*)m_pObject, m_doc, UMLObject::ot_Operation);
createPage(i18n("Operations"), i18n("Operation Settings"),
Icon_Utils::it_Properties_Operations, m_pOpsPage);
}
/**
* Sets up the page "Templates" for the component.
*/
void ClassPropertiesDialog::setupTemplatesPage()
{
m_pTemplatePage = new ClassifierListPage(nullptr, (UMLClassifier *)m_pObject, m_doc, UMLObject::ot_Template);
createPage(i18n("Templates"), i18n("Templates Settings"),
Icon_Utils::it_Properties_Templates, m_pTemplatePage);
}
/**
* Sets up the page "Enum Literals" for the component.
*/
void ClassPropertiesDialog::setupEnumLiteralsPage()
{
m_pEnumLiteralPage = new ClassifierListPage(nullptr, (UMLClassifier*)m_pObject, m_doc, UMLObject::ot_EnumLiteral);
createPage(i18n("Enum Literals"), i18n("Enum Literals Settings"),
Icon_Utils::it_Properties_EnumLiterals, m_pEnumLiteralPage);
}
/**
* Sets up the page "Entity Attributes" for the component.
*/
void ClassPropertiesDialog::setupEntityAttributesPage()
{
m_pEntityAttributePage = new ClassifierListPage(nullptr, (UMLEntity*)m_pObject, m_doc, UMLObject::ot_EntityAttribute);
createPage(i18n("Entity Attributes"), i18n("Entity Attributes Settings"),
Icon_Utils::it_Properties_EntityAttributes, m_pEntityAttributePage);
}
/**
* Sets up the page "Entity Constraints" for the component.
*/
void ClassPropertiesDialog::setupEntityConstraintsPage()
{
m_pEntityConstraintPage = new ConstraintListPage(nullptr, (UMLClassifier*)m_pObject, m_doc, UMLObject::ot_EntityConstraint);
createPage(i18n("Entity Constraints"), i18n("Entity Constraints Settings"),
Icon_Utils::it_Properties_EntityConstraints, m_pEntityConstraintPage);
}
/**
* Sets up the page "Contents" for the component.
*/
void ClassPropertiesDialog::setupContentsPage()
{
m_pPkgContentsPage = new PackageContentsPage(nullptr, (UMLPackage*)m_pObject);
createPage(i18nc("contents settings page name", "Contents"), i18n("Contents Settings"),
Icon_Utils::it_Properties_Contents, m_pPkgContentsPage);
}
/**
* Sets up the page "Associations" for the component.
*/
void ClassPropertiesDialog::setupAssociationsPage()
{
m_pAssocPage = new ClassAssociationsPage(nullptr, UMLApp::app()->currentView()->umlScene(), m_pObject);
createPage(i18n("Associations"), i18n("Class Associations"),
Icon_Utils::it_Properties_Associations, m_pAssocPage);
}
/**
* Sets up the general page for the component.
*/
void ClassPropertiesDialog::setupInstancePages()
{
m_pGenPage = new ClassGeneralPage(m_doc, nullptr, m_pWidget);
createPage(i18nc("instance general settings page name", "General"), i18n("General Settings"),
Icon_Utils::it_Properties_General, m_pGenPage)->widget()->setMinimumSize(310, 330);
m_pAssocPage = nullptr;
}
| 10,472
|
C++
|
.cpp
| 328
| 27.704268
| 128
| 0.690139
|
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,319
|
umltemplatedialog.cpp
|
KDE_umbrello/umbrello/dialogs/umltemplatedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umltemplatedialog.h"
// app includes
#include "template.h"
#include "classifier.h"
#include "documentationwidget.h"
#include "umldoc.h"
#include "uml.h"
#include "dialog_utils.h"
#include "umldatatypewidget.h"
#include "umlstereotypewidget.h"
// kde includes
#include <klineedit.h>
#include <kcombobox.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QComboBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QVBoxLayout>
UMLTemplateDialog::UMLTemplateDialog(QWidget* pParent, UMLTemplate* pTemplate)
: SinglePageDialogBase(pParent)
{
m_pTemplate = pTemplate;
setCaption(i18n("Template Properties"));
setupDialog();
}
UMLTemplateDialog::~UMLTemplateDialog()
{
}
/**
* Sets up the dialog
*/
void UMLTemplateDialog::setupDialog()
{
int margin = fontMetrics().height();
QFrame *frame = new QFrame(this);
setMainWidget(frame);
QVBoxLayout* mainLayout = new QVBoxLayout(frame);
m_pValuesGB = new QGroupBox(i18n("General Properties"), frame);
QGridLayout* valuesLayout = new QGridLayout(m_pValuesGB);
valuesLayout->setContentsMargins(margin, margin, margin, margin);;
valuesLayout->setSpacing(10);
m_datatypeWidget = new UMLDatatypeWidget(m_pTemplate);
m_datatypeWidget->addToLayout(valuesLayout, 0);
Dialog_Utils::makeLabeledEditField(valuesLayout, 1,
m_pNameL, i18nc("template name", "&Name:"),
m_pNameLE, m_pTemplate->name());
m_stereotypeWidget = new UMLStereotypeWidget(m_pTemplate);
m_stereotypeWidget->addToLayout(valuesLayout, 2);
mainLayout->addWidget(m_pValuesGB);
m_docWidget = new DocumentationWidget(m_pTemplate, this);
mainLayout->addWidget(m_docWidget);
m_pNameLE->setFocus();
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false
*/
bool UMLTemplateDialog::apply()
{
m_datatypeWidget->apply();
QString name = m_pNameLE->text();
if(name.length() == 0) {
KMessageBox::error(this, i18n("You have entered an invalid template name."),
i18n("Template Name Invalid"));
m_pNameLE->setText(m_pTemplate->name());
return false;
}
const UMLClassifier * pClass = m_pTemplate->umlParent()->asUMLClassifier();
if (pClass) {
UMLObject *o = pClass->findChildObject(name);
if (o && o != m_pTemplate) {
KMessageBox::error(this, i18n("The template parameter name you have chosen is already being used in this operation."),
i18n("Template Name Not Unique"));
m_pNameLE->setText(m_pTemplate->name());
return false;
}
}
m_pTemplate->setName(name);
m_stereotypeWidget->apply();
m_docWidget->apply();
return true;
}
| 3,043
|
C++
|
.cpp
| 91
| 28.351648
| 130
| 0.68701
|
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,320
|
statedialog.cpp
|
KDE_umbrello/umbrello/dialogs/statedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "statedialog.h"
// local includes
#include "activitypage.h"
#include "documentationwidget.h"
#include "umlview.h"
#include "umlscene.h"
#include "umlviewlist.h"
#include "umldoc.h"
#include "uml.h"
#include "selectdiagramwidget.h"
#include "statewidget.h"
#include "dialog_utils.h"
#include "icon_utils.h"
// kde includes
#include <KComboBox>
#include <klineedit.h>
#include <KLocalizedString>
// qt includes
#include <QFrame>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
/**
* Constructor.
*/
StateDialog::StateDialog(QWidget * parent, StateWidget * pWidget)
: MultiPageDialogBase(parent),
m_pActivityPage(nullptr),
m_pStateWidget(pWidget),
m_bChangesMade(false),
pageActivity(nullptr)
{
setCaption(i18n("Properties"));
setupPages();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Entered when OK button pressed.
*/
void StateDialog::slotOk()
{
applyPage(pageGeneral);
applyPage(pageFont);
applyPage(pageActivity);
applyPage(pageStyle);
accept();
}
/**
* Entered when Apply button pressed.
*/
void StateDialog::slotApply()
{
applyPage(currentPage());
}
/**
* Sets up the pages of the dialog.
*/
void StateDialog::setupPages()
{
setupGeneralPage();
if (m_pStateWidget->stateType() == StateWidget::Normal) {
setupActivityPage();
}
pageStyle = setupStylePage(m_pStateWidget);
pageFont = setupFontPage(m_pStateWidget);
}
/**
* Applies changes to the given page.
*/
void StateDialog::applyPage(KPageWidgetItem*item)
{
m_bChangesMade = true;
if (item == pageGeneral) {
if (m_pStateWidget->stateType() == StateWidget::Combined) {
m_pStateWidget->setDiagramLink(m_GenPageWidgets.diagramLinkWidget->currentID());
}
m_pStateWidget->setName(m_GenPageWidgets.nameLE->text());
m_GenPageWidgets.docWidget->apply();
}
else if (item == pageActivity) {
if (m_pActivityPage) {
m_pActivityPage->updateActivities();
}
}
else if (item == pageStyle) {
applyStylePage();
}
else if (item == pageFont) {
applyFontPage(m_pStateWidget);
}
}
/**
* Sets up the general page of the dialog.
*/
void StateDialog::setupGeneralPage()
{
StateWidget::StateType type = m_pStateWidget->stateType();
int margin = fontMetrics().height();
QWidget* page = new QWidget();
QVBoxLayout* topLayout = new QVBoxLayout();
page->setLayout(topLayout);
pageGeneral = createPage(i18nc("general page", "General"), i18n("General Properties"),
Icon_Utils::it_Properties_General, page);
m_GenPageWidgets.generalGB = new QGroupBox(i18n("Properties"));
topLayout->addWidget(m_GenPageWidgets.generalGB);
QGridLayout * generalLayout = new QGridLayout(m_GenPageWidgets.generalGB);
generalLayout->setSpacing(Dialog_Utils::spacingHint());
generalLayout->setContentsMargins(margin, margin, margin, margin);
QString typeStr;
switch (type) {
case StateWidget::Initial:
typeStr = i18nc("initial state in statechart", "Initial state");
break;
case StateWidget::Normal:
typeStr = i18nc("state in statechart", "State");
break;
case StateWidget::End:
typeStr = i18nc("end state in statechart", "End state");
break;
case StateWidget::Fork:
typeStr = i18nc("fork state in statechart", "Fork");
break;
case StateWidget::Join:
typeStr = i18nc("join state in statechart", "Join");
break;
case StateWidget::Junction:
typeStr = i18nc("junction state in statechart", "Junction");
break;
case StateWidget::DeepHistory:
typeStr = i18nc("deep history state in statechart", "DeepHistory");
break;
case StateWidget::ShallowHistory:
typeStr = i18nc("shallow history state in statechart", "ShallowHistory");
break;
case StateWidget::Choice:
typeStr = i18nc("choice state in statechart", "Choice");
break;
case StateWidget::Combined:
typeStr = i18nc("combined state in statechart", "Combined");
break;
default:
typeStr = QString::fromLatin1("???");
break;
}
int row = 0;
Dialog_Utils::makeLabeledEditField(generalLayout, row++,
m_GenPageWidgets.typeL, i18n("State type:"),
m_GenPageWidgets.typeLE, typeStr);
m_GenPageWidgets.typeLE->setEnabled(false);
Dialog_Utils::makeLabeledEditField(generalLayout, row++,
m_GenPageWidgets.nameL, i18n("State name:"),
m_GenPageWidgets.nameLE);
if (type != StateWidget::Normal && type != StateWidget::Combined) {
m_GenPageWidgets.nameLE->setEnabled(false);
m_GenPageWidgets.nameLE->setText(QString());
} else
m_GenPageWidgets.nameLE->setText(m_pStateWidget->name());
if (type == StateWidget::Combined) {
m_GenPageWidgets.diagramLinkWidget = new SelectDiagramWidget(i18n("Linked diagram:"), this);
m_GenPageWidgets.diagramLinkWidget->setupWidget(Uml::DiagramType::State,
m_pStateWidget->linkedDiagram() ? m_pStateWidget->linkedDiagram()->name() : QString(),
m_pStateWidget->umlScene()->name(), false);
m_GenPageWidgets.diagramLinkWidget->addToLayout(generalLayout, row++);
}
m_GenPageWidgets.docWidget = new DocumentationWidget(m_pStateWidget);
generalLayout->addWidget(m_GenPageWidgets.docWidget, row, 0, 1, 2);
m_GenPageWidgets.nameLE->setFocus();
}
/**
* Sets up the activity page.
*/
void StateDialog::setupActivityPage()
{
m_pActivityPage = new ActivityPage(nullptr, m_pStateWidget);
pageActivity = createPage(i18n("Activities"), i18n("Activities"),
Icon_Utils::it_Properties_Activities, m_pActivityPage);
}
| 6,210
|
C++
|
.cpp
| 184
| 28.038043
| 100
| 0.669664
|
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,321
|
codeeditor.cpp
|
KDE_umbrello/umbrello/dialogs/codeeditor.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <brian.thomas@gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codeeditor.h"
// local includes
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "umlrole.h"
#include "codeaccessormethod.h"
#include "codeclassfield.h"
#include "codeclassfielddeclarationblock.h"
#include "codedocument.h"
#include "codeoperation.h"
#include "codemethodblock.h"
#include "classifiercodedocument.h"
#include "ownedhierarchicalcodeblock.h"
#include "codegenfactory.h"
#include "codeviewerdialog.h"
#include "classpropertiesdialog.h"
#include "umlattributedialog.h"
#include "umlroledialog.h"
#include "umloperationdialog.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QBrush>
#include <QColor>
#include <QKeyEvent>
#include <QKeySequence>
#include <QLabel>
#include <QLayout>
#include <QMenu>
#include <QMouseEvent>
#include <QPointer>
#include <QRegularExpression>
#include <QTextBlock>
DEBUG_REGISTER(CodeEditor)
/**
* Constructor.
*/
CodeEditor::CodeEditor(const QString & text, CodeViewerDialog * parent, CodeDocument * doc)
: QTextEdit(text, parent)
{
init(parent, doc);
}
/**
* Constructor.
*/
CodeEditor::CodeEditor(CodeViewerDialog * parent, CodeDocument * doc)
: QTextEdit(parent)
{
init(parent, doc);
}
/**
* Destructor.
*/
CodeEditor::~CodeEditor()
{
}
/**
* Clear the display of all text.
*/
void CodeEditor::clearText()
{
m_selectedTextBlock = nullptr;
// now call super-class
clear();
// logDebug1("text block list size=%1", m_textBlockList.size());
while (!m_textBlockList.isEmpty()) {
/*;TODO:? delete */ m_textBlockList.takeFirst();
}
m_tbInfoMap.clear();
}
/**
* Return code viewer state.
* @return state of the code viewer
*/
Settings::CodeViewerState CodeEditor::state()
{
return m_parentDialog->state();
}
/**
* Return the label on the dialog window. Some info can be shown.
* @return label widget of dialog
*/
QLabel * CodeEditor::componentLabel()
{
return m_parentDialog->ui_componentLabel;
}
/**
* TODO: Used only for debugging right now.
* int para = tc.position(); --> is the character in the editor
* int pos = tc.blockNumber(); --> is the row in the editor
*/
void CodeEditor::clicked(int para, int pos)
{
QString txt = QString::fromLatin1("position:") + QString::number(para) +
QString::fromLatin1(" / row (block):") + QString::number(pos);
if (m_parentDialog->ui_highlightCheckBox->isChecked()) {
TextBlock* tb = findTextBlockAt(para);
if (tb) {
TextBlockInfo* info = m_tbInfoMap[tb];
if (info) {
txt += QString::fromLatin1(" / <b>") + info->displayName() + QString::fromLatin1("</b>");
}
}
}
componentLabel()->setText(txt);
}
/**
* Slot which closes this widget. Returns true if the widget was closed;
* otherwise returns false.
* Reimplemented from QWidget.
* @return state of close action
*/
bool CodeEditor::close()
{
// capture last code block, if it exists
if (m_lastTextBlockToBeEdited) {
updateTextBlockFromText (m_lastTextBlockToBeEdited);
m_lastTextBlockToBeEdited = nullptr;
}
return QTextEdit::close();
}
/**
* Allow us to edit, as appropriate, the parent UMLObject of the
* given text block.
*/
void CodeEditor::editTextBlock(TextBlock * tBlock, int para)
{
if (tBlock) {
TextBlockInfo *info = m_tbInfoMap[tBlock];
if (info) {
UMLObject *obj = info->parent();
if (obj) {
if (obj->showPropertiesDialog(this)) {
rebuildView(para);
}
} else {
logError0("UNKNOWN parent for textBlock");
}
}
}
else {
logDebug0("CodeEditor::editTextBlock: TextBlock is NULL!");
}
}
/**
* Return whether or not the passed string is empty or
* contains nothing but whitespace.
* Note: The logic is the other way round. In this way
* we do not need all the "!" in if statements.
*/
bool CodeEditor::isNonBlank(const QString &str)
{
if (str.isEmpty() || str.trimmed().isEmpty()) {
return false;
}
return true;
}
/**
* Implemented so we may capture certain key presses, namely backspace
* and 'return' events.
*/
void CodeEditor::keyPressEvent(QKeyEvent * e)
{
QString eText(e->text());
logDebug2("CodeEditor::keyPressEvent: [%1] ASCII code: %2", eText, e->key());
if (e->key() == 8) { // || (e->key() == 127)) // what about delete?
m_backspacePressed = true;
}
// Q: can the MAC or WIN/DOS sequences occur?
if ((e->key() == 10) || (e->key() == 13) || (e->text() == QString::fromLatin1("\r\n"))) {
m_newLinePressed = true;
}
QTextEdit::keyPressEvent(e);
}
/**
* (Re) Load the parent code document into the editor.
*/
void CodeEditor::loadFromDocument()
{
// clear the tool
clearText();
// set caption on tool
QString caption = m_parentDoc->getFileName() + m_parentDoc->getFileExtension();
setWindowTitle(i18n(caption.toUtf8().constData()));
logDebug1("CodeEditor::loadFromDocument: set window title to %1", caption);
// header for document
QString header = m_parentDoc->getHeader()->toString();
QString componentName = QString::fromLatin1("header for file ") + caption;
if (isNonBlank(header)) {
logDebug1("CodeEditor::loadFromDocument header for document: %1", header);
insertText(header, m_parentDoc->getHeader(), false, state().fontColor,
state().nonEditBlockColor, nullptr, componentName);
}
// now all the text blocks in the document
TextBlockList * items = m_parentDoc->getTextBlockList();
logDebug1("CodeEditor::loadFromDocument TextBlockList: %1", items->count());
appendText(items);
textCursor().setPosition(0);
}
/**
* Main insert routine. Will append if startLine is not supplied or -1.
* @param text the text which has to be inserted
* @param parent the parent @ref TextBlock
* @param editable flag if editable
* @param fgcolor foreground color
* @param bgcolor background color
* @param umlobj the UML object
* @param displayName the name which can be displayed
* @param startLine the starting line
*/
void CodeEditor::insertText(const QString & text, TextBlock * parent,
bool editable, const QColor & fgcolor, const QColor & bgcolor,
UMLObject * umlobj, const QString & displayName, int startLine)
{
// set some params
bool isInsert = false;
setTextColor(fgcolor);
// it is an append op if startLine is -1, otherwise it is
// an actual insert, which is more complicated
if (startLine == -1) {
startLine = 0;
if (!m_textBlockList.isEmpty()) {
TextBlock* lastTb = m_textBlockList.last();
if (m_tbInfoMap.contains(lastTb)) {
TextBlockInfo *tbi = m_tbInfoMap[lastTb];
if (tbi && !tbi->m_paraList.isEmpty()) {
ParaInfo* pi = tbi->m_paraList.last();
startLine = pi->end + 1;
}
}
}
QTextEdit::append(text); // put actual text in. Use insert instead of append so history is preserved?
}
else {
isInsert = true;
textCursor().setPosition(startLine);
textCursor().insertText(text);
}
int endLine = text.count(QChar::fromLatin1('\n')) + startLine;
// now do 'paragraph' background highlighting
if (m_isHighlighted) {
for (int ln = startLine; ln <= endLine; ++ln) {
setParagraphBackgroundColor(ln, bgcolor);
}
}
// record paragraph information
// Did we already start recording info for this parent object?
TextBlockInfo * tbinfo;
if (m_tbInfoMap.contains(parent)) {
tbinfo = m_tbInfoMap[parent];
}
else {
tbinfo = new TextBlockInfo();
tbinfo->setDisplayName(displayName);
tbinfo->isCodeAccessorMethod = dynamic_cast<CodeAccessorMethod*>(parent) ? true : false;
m_tbInfoMap.insert(parent, tbinfo);
}
// set a parent, if it is not already set
if (umlobj && !tbinfo->parent()) {
tbinfo->setDisplayName(displayName);
tbinfo->setParent(umlobj);
tbinfo->isClickable = textBlockIsClickable(umlobj);
}
// now mark all lines that we just inserted as belonging to the parent
for (int ln = startLine; ln <= endLine; ++ln) {
m_textBlockList.insert(ln, parent);
}
// create the object that records this particular "paragraph"
ParaInfo * item = new ParaInfo();
item->start = startLine;
item->size = text.size();
item->end = endLine;
item->fgcolor = fgcolor;
item->bgcolor = bgcolor;
item->isEditable = editable;
logDebug4("CodeEditor::insertText startLine: %1 / endLine: %2 / size: %3 / text: %4",
item->start, item->end, item->size, text);
if (isInsert) {
// now we have to fix the 'start' value for all the para
// info blocks that correspond to textblocks that we inserted
// inside of. This means parent tblock paragraph locations
// that are greater than zero in that type of textblock
int increase = item->size + 1;
QMap<TextBlock*, TextBlockInfo*>::Iterator it;
for (it = m_tbInfoMap.begin(); it != m_tbInfoMap.end(); ++it) {
TextBlock * tblock = it.key();
TextBlockInfo * thisTbInfo = it.value();
int firstLoc = m_textBlockList.indexOf(tblock);
for(ParaInfo * pi : thisTbInfo->m_paraList) {
int minPara = pi->start + firstLoc;
// only worth doing if in range of the whole representation
ParaInfo * lastPi = thisTbInfo->m_paraList.last();
if (!pi->start &&
(startLine > (lastPi->start + firstLoc + lastPi->size) || endLine < minPara)) {
break;
}
// now, only for those paraInfo blocks which
// have exceeded our last line, we increase them
if (pi->start && minPara >= endLine) {
pi->start += increase;
}
}
}
}
tbinfo->m_paraList.append(item);
}
/**
* Appends a @ref TextBlockList to the widget.
* @param items list of @ref TextBlock items
*/
void CodeEditor::appendText(TextBlockList * items)
{
logDebug0("CodeEditor::appendText text block list");
for(TextBlock* tb : *items) {
// types of things we may cast our text block into
// This isnt efficient, and is a vote for recording
// code block types in an enumerated list somewhere,
// as well as a generic attribute "blockType" we could
// quickly access, rather than casting. -b.t.
HierarchicalCodeBlock *hb = nullptr;
CodeMethodBlock *mb = nullptr;
CodeClassFieldDeclarationBlock *db = nullptr;
CodeBlockWithComments *cb = nullptr;
// CodeComment *cm = nullptr;
if ((hb = dynamic_cast<HierarchicalCodeBlock *>(tb)))
appendText(hb);
else if ((mb = dynamic_cast<CodeMethodBlock*>(tb)))
appendText(mb);
else if ((db = dynamic_cast<CodeClassFieldDeclarationBlock*>(tb)))
appendText(db);
else if ((cb = dynamic_cast<CodeBlockWithComments*>(tb)))
appendText(cb);
/*
// No! Shouldn't be any 'naked' comments floating about. Always
// are associated with a parent code block.
else if ((cm = dynamic_cast<CodeComment*>(tb)))
appendText(cm);
*/
else
appendText(tb); // No cast worked. Just do a text block
}
}
/**
* Appends a @ref CodeComment to the widget.
* @param comment the code comment to add
* @param parent the parent text block
* @param umlObj the UML object
* @param componentName the name of the component
*/
void CodeEditor::appendText(CodeComment * comment, TextBlock * parent, UMLObject * umlObj, const QString & componentName)
{
logDebug0("CodeEditor::appendText comment");
if (!comment->getWriteOutText() && !m_showHiddenBlocks)
return;
QColor bgcolor = state().nonEditBlockColor;
if (!comment->getWriteOutText() && m_showHiddenBlocks)
bgcolor = state().hiddenColor;
QString indent = comment->getIndentationString();
QString text = comment->toString(); // use comment formatting, NOT formatMultiLineText(comment->toString(), indent, "\n");
if (isNonBlank(text))
insertText(text, parent, true, state().fontColor, bgcolor, umlObj, componentName);
}
/**
* Appends a @ref CodeBlockWithComments to the widget.
* @param cb the code block to add
*/
void CodeEditor::appendText(CodeBlockWithComments * cb)
{
logDebug0("CodeEditor::appendText code block with comments");
if (!cb->getWriteOutText() && !m_showHiddenBlocks)
return;
QString indent = cb->getIndentationString();
QString body = cb->formatMultiLineText(cb->getText(), indent, QString::fromLatin1("\n"));
QColor bgcolor = state().editBlockColor;
QString componentName = QString::fromLatin1("CodeBlock");
appendText(cb->getComment(), cb, nullptr, componentName);
if (!cb->getWriteOutText() && m_showHiddenBlocks)
bgcolor = state().hiddenColor;
if (isNonBlank(body))
insertText(body, cb, true, state().fontColor, bgcolor, nullptr);
}
/**
* Appends a @ref CodeClassFieldDeclarationBlock to the widget.
* @param db the code class field declaration block to add
*/
void CodeEditor::appendText(CodeClassFieldDeclarationBlock * db)
{
logDebug0("CodeEditor::appendText code class field declaration block");
if (!db->getWriteOutText() && !m_showHiddenBlocks)
return;
QString indent = db->getIndentationString();
QString body = db->formatMultiLineText (db->getText(), indent, QString::fromLatin1("\n"));
UMLObject * parentObj = db->getParentClassField()->getParentObject();
QColor bgcolor = state().editBlockColor;
QString componentName;
if (parentObj)
{
if (db->getParentClassField()->parentIsAttribute()) {
componentName = m_parentDocName + QString::fromLatin1("::attribute_field(") + parentObj->name() + QChar::fromLatin1(')');
}
else {
const UMLRole * role = parentObj->asUMLRole();
componentName = m_parentDocName + QString::fromLatin1("::association_field(") + role->name() + QChar::fromLatin1(')');
}
bgcolor = state().umlObjectColor;
}
appendText(db->getComment(), db, parentObj, componentName);
if (!db->getWriteOutText() && m_showHiddenBlocks)
bgcolor = state().hiddenColor;
if (isNonBlank(body))
insertText(body, db, false, state().fontColor, bgcolor, parentObj);
}
/**
* Appends a @ref CodeMethodBlock to the widget.
* @param mb the code method block to add
*/
void CodeEditor::appendText(CodeMethodBlock * mb)
{
logDebug0("CodeEditor::appendText code method block");
// Note: IF CodeAccessors are hidden, we DON'T show
// it even when requested as the hiddeness of these methods
// should be controlled by the class fields, not the user in the editor.
if (!mb->getWriteOutText() && (!m_showHiddenBlocks || dynamic_cast<CodeAccessorMethod*>(mb)))
return;
QColor bgcolor = state().umlObjectColor;
QString indent = mb->getIndentationString();
QString bodyIndent = mb->getIndentationString(mb->getIndentationLevel()+1);
QString startText = mb->formatMultiLineText (mb->getStartMethodText(), indent, QString::fromLatin1("\n"));
QString body = mb->formatMultiLineText (mb->getText(), bodyIndent, QString::fromLatin1("\n"));
QString endText = mb->formatMultiLineText(mb->getEndMethodText(), indent, QString::fromLatin1("\n"));
if (body.isEmpty())
body = QString::fromLatin1(" \n");
if (!mb->getWriteOutText() && m_showHiddenBlocks) {
// it gets the 'hidden' color
bgcolor = state().hiddenColor;
}
QString componentName = QString::fromLatin1("<b>parentless method\?</b>");
// ugly, but we need to know if there is a parent object here.
CodeOperation * op = dynamic_cast<CodeOperation*>(mb);
CodeAccessorMethod * accessor = dynamic_cast<CodeAccessorMethod*>(mb);
UMLObject *parentObj = nullptr;
if (op) {
parentObj = op->getParentOperation();
if (((UMLOperation*)parentObj)->isConstructorOperation())
componentName = m_parentDocName + QString::fromLatin1("::operation(")+ parentObj->name()+QString::fromLatin1(") constructor method");
else
componentName = m_parentDocName + QString::fromLatin1("::operation(")+ parentObj->name()+QString::fromLatin1(") method");
}
if (accessor) {
parentObj = accessor->getParentObject();
if (accessor->getParentClassField()->parentIsAttribute()) {
componentName = m_parentDocName + QString::fromLatin1("::attribute_field(") + parentObj->name() + QString::fromLatin1(") accessor method");
}
else {
const UMLRole * role = parentObj->asUMLRole();
componentName = m_parentDocName + QString::fromLatin1("::association_field(") + role->name() + QString::fromLatin1(") accessor method");
}
}
//appendText(mb->getComment(), mb, parentObj, componentName);
appendText(mb->getComment(), mb->getComment(), parentObj, componentName);
if (isNonBlank(startText))
insertText(startText, mb, false, state().fontColor, bgcolor, parentObj);
// always insert body for methods. IF we don't, we create a
// situation where the user cannot edit the body (!)
insertText(body, mb, true, state().fontColor, bgcolor, parentObj);
if (isNonBlank(endText))
insertText(endText, mb, false, state().fontColor, bgcolor, parentObj);
}
/**
* Appends a @ref TextBlock to the widget.
* @param tb the text block to add
*/
void CodeEditor::appendText(TextBlock * tb)
{
logDebug0("CodeEditor::appendText text block");
if (!tb->getWriteOutText() && !m_showHiddenBlocks)
return;
QColor bgcolor = state().nonEditBlockColor;
if (!tb->getWriteOutText() && m_showHiddenBlocks)
bgcolor = state().hiddenColor;
QString str = tb->toString();
insertText(str, tb, false, state().fontColor, bgcolor);
}
/**
* Appends a @ref HierarchicalCodeBlock to the widget.
* @param hblock the hierarchical code block to add
*/
void CodeEditor::appendText(HierarchicalCodeBlock * hblock)
{
logDebug0("CodeEditor::appendText hierarchical code block");
if (!hblock->getWriteOutText() && !m_showHiddenBlocks)
return;
OwnedHierarchicalCodeBlock * test = dynamic_cast<OwnedHierarchicalCodeBlock *>(hblock);
UMLObject *parentObj = nullptr;
QString componentName;
QColor paperColor = state().nonEditBlockColor;
if (test) {
parentObj = test->getParentObject();
const UMLClassifier *c = parentObj->asUMLClassifier();
if (c) {
QString typeStr;
if (c->isInterface())
typeStr = QString::fromLatin1("Interface");
else
typeStr = QString::fromLatin1("Class");
componentName = m_parentDocName + QString::fromLatin1("::") + typeStr + QChar::fromLatin1('(') + parentObj->name() + QChar::fromLatin1(')');
}
else {
componentName = m_parentDocName + QString::fromLatin1("::UNKNOWN(") + parentObj->name() + QChar::fromLatin1(')');
}
paperColor = state().umlObjectColor;
}
if (!hblock->getWriteOutText() && m_showHiddenBlocks)
paperColor = state().hiddenColor;
TextBlockList * items = hblock->getTextBlockList();
QString indent = hblock->getIndentationString();
QString startText = hblock->formatMultiLineText (hblock->getStartText(), indent, QString::fromLatin1("\n"));
QString endText = hblock->formatMultiLineText(hblock->getEndText(), indent, QString::fromLatin1("\n"));
appendText(hblock->getComment(), hblock, parentObj, componentName);
if (isNonBlank(startText))
insertText(startText, hblock, false, state().fontColor, paperColor, parentObj);
appendText(items);
if (isNonBlank(endText))
insertText(endText, hblock, false, state().fontColor, paperColor);
}
/**
* Insert a paragraph at a given position.
* @param text the paragraph text
* @param para the position where to add the text
*/
void CodeEditor::insertParagraph(const QString & text, int para)
{
textCursor().setPosition(para);
textCursor().insertText(text);
}
/**
* Remove a paragraph from a given position.
* @param para the position from where to remove the text
*/
void CodeEditor::removeParagraph(int para)
{
textCursor().setPosition(para);
textCursor().select(QTextCursor::BlockUnderCursor);
textCursor().removeSelectedText();
}
/**
* All umlobjects which may have pop-up boxes should return true here.
* Yes, a CRAPPY way of doing this. Im not proud. =b.t.
*/
bool CodeEditor::textBlockIsClickable(UMLObject * obj)
{
if (obj->asUMLAttribute())
return true;
else if (obj->asUMLClassifier())
return true;
else if (obj->asUMLRole())
return true;
else if (obj->asUMLOperation())
return true;
return false;
}
/**
* Slot to change the view of the selected block.
* This is called from a popup menu item.
*/
void CodeEditor::slotChangeSelectedBlockView()
{
TextBlock * tb = m_selectedTextBlock;
if (tb) {
tb->setWriteOutText(tb->getWriteOutText() ? false : true);
rebuildView(m_lastPara);
}
}
/**
* Change the status of the comment writeOutText value to
* opposite of current value.
*/
void CodeEditor::slotChangeSelectedBlockCommentView()
{
TextBlock * tb = m_selectedTextBlock;
CodeBlockWithComments *cb = nullptr;
if (tb && (cb = dynamic_cast<CodeBlockWithComments*>(tb))) {
CodeComment* codcom = cb->getComment();
if (codcom) {
codcom->setWriteOutText(codcom->getWriteOutText() ? false : true);
rebuildView(m_lastPara);
}
}
}
/**
* Slot to insert a code block before the selection.
*/
void CodeEditor::slotInsertCodeBlockBeforeSelected()
{
TextBlock * tb = m_selectedTextBlock;
CodeBlockWithComments * newBlock = m_parentDoc->newCodeBlockWithComments();
newBlock->setText(QString::fromLatin1("<<INSERT>>"));
newBlock->getComment()->setWriteOutText(false);
m_parentDoc->insertTextBlock(newBlock, tb, false);
int location = m_textBlockList.indexOf(m_selectedTextBlock); // find first para of selected block
QString body = newBlock->formatMultiLineText(newBlock->getText(), newBlock->getIndentationString(), QString::fromLatin1("\n"));
insertText(body, newBlock, true, state().fontColor,
state().editBlockColor, nullptr, QString::fromLatin1("CodeBlock"), location);
}
/**
* Slot to insert a code block after the selection.
*/
void CodeEditor::slotInsertCodeBlockAfterSelected()
{
TextBlock * tb = m_selectedTextBlock;
CodeBlockWithComments * newBlock = m_parentDoc->newCodeBlockWithComments();
newBlock->setText(QString::fromLatin1("<<INSERT>>"));
newBlock->getComment()->setWriteOutText(false);
m_parentDoc->insertTextBlock(newBlock, tb, true);
// find last para of selected block
TextBlockInfo *tbinfo = m_tbInfoMap[m_selectedTextBlock];
ParaInfo * lastpi = tbinfo->m_paraList.last();
int location = m_textBlockList.indexOf(m_selectedTextBlock) + lastpi->start + lastpi->size + 1;
QString body = newBlock->formatMultiLineText(newBlock->getText(), newBlock->getIndentationString(), QString::fromLatin1("\n"));
insertText(body, newBlock, true, state().fontColor,
state().editBlockColor, nullptr, QString::fromLatin1("CodeBlock"), location);
}
/**
* Shows the context menu.
* Reimplemented from QWidget::contextMenuEvent().
*/
void CodeEditor::contextMenuEvent(QContextMenuEvent * event)
{
QMenu* menu = createPopup();
menu->exec(event->globalPos());
delete menu;
}
/**
* Create the popup menu.
* @return the popup menu
*/
QMenu * CodeEditor::createPopup()
{
logDebug0("CodeEditor::createPopup is called");
QMenu * menu = new QMenu(this);
TextBlock * tb = m_selectedTextBlock;
if (tb) {
if (tb->getWriteOutText()) {
QAction* hideAct = new QAction(i18n("Hide"), this);
hideAct->setShortcut(Qt::Key_H);
connect(hideAct, SIGNAL(triggered()), this, SLOT(slotChangeSelectedBlockView()));
menu->addAction(hideAct);
}
else {
QAction* showAct = new QAction(i18n("Show"), this);
showAct->setShortcut(Qt::Key_S);
connect(showAct, SIGNAL(triggered()), this, SLOT(slotChangeSelectedBlockView()));
menu->addAction(showAct);
}
CodeBlockWithComments * cb = dynamic_cast<CodeBlockWithComments*>(tb);
if (cb) {
if (cb->getComment()->getWriteOutText()) {
QAction* hideCommAct = new QAction(i18n("Hide Comment"), this);
hideCommAct->setShortcut(Qt::CTRL + Qt::Key_H);
connect(hideCommAct, SIGNAL(triggered()), this, SLOT(slotChangeSelectedBlockCommentView()));
menu->addAction(hideCommAct);
}
else {
QAction* showCommAct = new QAction(i18n("Show Comment"), this);
showCommAct->setShortcut(Qt::CTRL + Qt::Key_S);
connect(showCommAct, SIGNAL(triggered()), this, SLOT(slotChangeSelectedBlockCommentView()));
menu->addAction(showCommAct);
}
}
menu->addSeparator();
QAction* insCodeBeforeAct = new QAction(i18n("Insert Code Block Before"), this);
insCodeBeforeAct->setShortcut(Qt::CTRL + Qt::Key_B);
connect(insCodeBeforeAct, SIGNAL(triggered()), this, SLOT(slotInsertCodeBlockBeforeSelected()));
menu->addAction(insCodeBeforeAct);
QAction* insCodeAfterAct = new QAction(i18n("Insert Code Block After"), this);
insCodeAfterAct->setShortcut(Qt::CTRL + Qt::Key_A);
connect(insCodeAfterAct, SIGNAL(triggered()), this, SLOT(slotInsertCodeBlockAfterSelected()));
menu->addAction(insCodeAfterAct);
menu->addSeparator();
QAction* copyAct = new QAction(i18n("Copy"), this);
copyAct->setShortcut(Qt::CTRL + Qt::Key_C);
connect(copyAct, SIGNAL(triggered()), this, SLOT(slotCopyTextBlock()));
menu->addAction(copyAct);
QAction* pasteAct = new QAction(i18n("Paste"), this);
pasteAct->setShortcut(Qt::CTRL + Qt::Key_V);
connect(pasteAct, SIGNAL(triggered()), this, SLOT(slotPasteTextBlock()));
menu->addAction(pasteAct);
QAction* cutAct = new QAction(i18n("Cut"), this);
cutAct->setShortcut(Qt::CTRL + Qt::Key_X);
connect(cutAct, SIGNAL(triggered()), this, SLOT(slotCutTextBlock()));
menu->addAction(cutAct);
// enable/disable based on conditions
if (m_selectedTextBlock == m_parentDoc->getHeader())
insCodeBeforeAct->setEnabled(false);
if (!m_textBlockToPaste)
pasteAct->setEnabled(false);
if (!tb->canDelete())
cutAct->setEnabled(false);
// manythings cant be copied. Right now, lets just limit ourselves to
// owned things and hierarchicalcodeblocks
if (dynamic_cast<OwnedCodeBlock*>(m_selectedTextBlock) ||
dynamic_cast<HierarchicalCodeBlock*>(m_selectedTextBlock))
copyAct->setEnabled(false);
// TBD
// m_selectedTextBlock->insertCodeEditMenuItems(menu, this);
}
return menu;
}
/**
* Slot to copy a text block.
*/
void CodeEditor::slotCopyTextBlock()
{
// make a copy
if (dynamic_cast<HierarchicalCodeBlock*>(m_selectedTextBlock))
m_textBlockToPaste = m_parentDoc->newHierarchicalCodeBlock();
else if (dynamic_cast<CodeBlockWithComments*>(m_selectedTextBlock))
m_textBlockToPaste = m_parentDoc->newCodeBlockWithComments();
else if (dynamic_cast<CodeBlock*>(m_selectedTextBlock))
m_textBlockToPaste = m_parentDoc->newCodeBlock();
else if (dynamic_cast<CodeComment*>(m_selectedTextBlock))
m_textBlockToPaste = CodeGenFactory::newCodeComment(m_parentDoc);
else {
logError0("CodeEditor cannot copy selected block of unknown type");
m_textBlockToPaste = nullptr;
return; // error!
}
m_textBlockToPaste->setAttributesFromObject(m_selectedTextBlock);
}
/**
* Slot to cut a text block.
*/
void CodeEditor::slotCutTextBlock()
{
// make a copy first
slotCopyTextBlock();
// This could cause problems, but we are OK as
// long as we only try to delete 'canDelete' textblocks
if (m_selectedTextBlock->canDelete()) {
// just in case there are pending edits
// we don't want to lose them
if (m_lastTextBlockToBeEdited && m_lastTextBlockToBeEdited == (CodeBlock*) m_selectedTextBlock) {
updateTextBlockFromText (m_lastTextBlockToBeEdited);
m_lastTextBlockToBeEdited = nullptr;
}
m_parentDoc->removeTextBlock(m_selectedTextBlock);
rebuildView(m_lastPara);
// removeTextBlock(m_selectedTextBlock);
m_selectedTextBlock = nullptr;
}
}
/**
* Slot to paste a text block.
*/
void CodeEditor::slotPasteTextBlock()
{
if (m_textBlockToPaste) {
m_parentDoc->insertTextBlock(m_textBlockToPaste, m_selectedTextBlock);
m_textBlockToPaste = nullptr;
rebuildView(m_lastPara);
}
}
/**
* Slot to redraw the text.
*/
void CodeEditor::slotRedrawText()
{
rebuildView(m_lastPara);
}
/**
* Initialization routine which is used in the constructors.
* @param parentDialog the parent @ref CodeViewerDialog
* @param parentDoc the parent @ref CodeDocument
*/
void CodeEditor::init(CodeViewerDialog * parentDialog, CodeDocument * parentDoc)
{
// safety to insure that we are up to date
parentDoc->synchronize();
setObjectName(QString::fromLatin1("CodeEditor"));
m_parentDialog = parentDialog;
m_parentDoc = parentDoc;
setUndoRedoEnabled(false);
// setCursor(QCursor(0)); // this line crashes the whole application
setMouseTracking(true);
setReadOnly (true);
m_isHighlighted = state().blocksAreHighlighted;
m_showHiddenBlocks = state().showHiddenBlocks;
m_newLinePressed = false;
m_backspacePressed = false;
m_textBlockToPaste = nullptr;
m_selectedTextBlock = nullptr;
m_lastTextBlockToBeEdited = nullptr;
setFont(state().font);
// set name of parent doc
ClassifierCodeDocument * cdoc = dynamic_cast<ClassifierCodeDocument*>(m_parentDoc);
if (cdoc)
m_parentDocName = cdoc->getParentClassifier()->name();
else
m_parentDocName = QString();
// set some viewability parameters
//int margin = fontMetrics().height();
setTextBackgroundColor(state().paperColor);
// setMargin(margin);
// connect(this, SIGNAL(newLinePressed()), this, SLOT(newLinePressed()));
// connect(this, SIGNAL(backspacePressed()), this, SLOT(backspacePressed()));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged()));
// do this last
loadFromDocument();
}
/**
* Read the text under the cursor and add it to the text block.
* @param block the text block to which the text is added
*/
void CodeEditor::updateTextBlockFromText(TextBlock * block)
{
if (block) {
CodeMethodBlock * cmb = dynamic_cast<CodeMethodBlock*>(block);
//QString baseIndent = block->getNewEditorLine(block->getIndentationLevel() + (cmb ? 1 : 0));
QString baseIndent = block->getIndentationString(block->getIndentationLevel() + (cmb ? 1 : 0));
TextBlockInfo *info = m_tbInfoMap[block];
int pstart = m_textBlockList.indexOf(block);
QString content;
// Assemble content from editiable paras
if (info) {
QList<ParaInfo*> list = info->m_paraList;
for(ParaInfo * item : list) {
if (item->isEditable) {
int lastpara = item->start+pstart+item->size;
int endEdit = block->lastEditableLine();
int lastLineToAddNewLine = lastpara + endEdit;
for (int para=(item->start+pstart); para<=lastpara; ++para) {
textCursor().setPosition(para);
QString paraTxt = textCursor().block().text();
QString line = block->unformatText(paraTxt, baseIndent);
content += line;
// \n are implicit in the editor (!) so we should put them
// back in, if there is any content from the line
if (!line.isEmpty() && para != lastLineToAddNewLine)
content += QChar::fromLatin1('\n');
}
}
}
}
if (content.isEmpty()) {
logDebug0("CodeEditor::updateTextBlockFromText: nothing to add!");
}
else {
logDebug1("CodeEditor::updateTextBlockFromText content [%1]", content);
block->setText(content);
// if a parent for the block, try to set its documentation
// as long as it is NOT an accessor codeblock.
if (info) {
UMLObject * parentObj = info->parent();
if (parentObj && !info->isCodeAccessorMethod) {
parentObj->setDoc(content);
}
}
// make note that it is now user generated
if (cmb) {
cmb->setContentType(CodeBlock::UserGenerated);
}
}
}
}
/**
* Slot for cursor position changed signal.
*/
void CodeEditor::slotCursorPositionChanged()
{
QTextCursor tc = textCursor();
int para = tc.position();
int pos = tc.blockNumber();
clicked(para, pos);
// safety.. this is endemic of a 'bad' pointer event and can crash us otherwise
if (pos < 0)
return;
// bool lastParaIsEditable = isReadOnly() ? false : true;
bool lastParaIsEditable = isParaEditable(m_lastPara);
// IF last para where cursor is coming from was editable
// we have a variety of things to look out for.
if (lastParaIsEditable) {
// If we got here as the result of a newline, then expansion
// of a para editablity occurs.
if ((para-1) == m_lastPara && m_newLinePressed)
expandSelectedParagraph (m_lastPara);
// conversely, we contract the zone of editablity IF we
// got to current position as result of backspace
if ((para+1) == m_lastPara && m_backspacePressed)
contractSelectedParagraph(para);
}
// now check if the current paragraph is really editiable, and if so,
// do some things
bool editPara = isParaEditable(para);
if (editPara) {
TextBlock * tBlock = m_textBlockList.at(para);
if (!tBlock) {
logWarn1("no text block found in list at position %1", para);
return;
}
//DEBUG() << tBlock;
CodeMethodBlock * cmb = dynamic_cast<CodeMethodBlock*>(tBlock);
if (!cmb) {
logWarn0("cast to CodeMethodBlock failed");
return;
}
// auto-indent new lines
textCursor().setPosition(para);
QString currentParaText = textCursor().block().text();
QString baseIndent = tBlock->getNewEditorLine(tBlock->getIndentationLevel() + 1);
// cerr<<"AUTO INDENT:["<<baseIndent.latin1()<<"] isMethod?"<<(cmb?"true":"false")<<endl;
int minPos = baseIndent.length();
// add indent chars to the current line, if missing
if (!m_backspacePressed && !currentParaText.contains(QRegularExpression(QChar::fromLatin1('^')+baseIndent))) {
textCursor().setPosition(para);
textCursor().insertText(baseIndent);
//:TODO: setCursorPosition(para, pos+minPos); // crashes the application !?
return;
}
if (pos < minPos) {
bool priorParaIsEditable = isParaEditable(para-1);
if (m_backspacePressed && para && priorParaIsEditable) {
textCursor().setPosition(para-1);
//:TODO:unused int endOfPriorLine = textCursor().block().length();
// In this case, we remove old (para) line, and tack its
// contents on the line we are going to.
QString contents = textCursor().block().text();
contents = contents.right(contents.length()-m_lastPos+1);
// this next thing happens when we arent deleting last line
// of editable text, so we want to append whats left of this line
// onto the one we are backspacing into
if (paraIsNotSingleLine(para)) {
removeParagraph(para);
//:TODO: insertAt(contents, (para-1), endOfPriorLine);
textCursor().setPosition(para-1);
textCursor().insertText(contents);
//:TODO: setCursorPosition((para-1), endOfPriorLine); // crashes the application !?
}
}
else {
// well, if the following is true, then they
// are trying to hack away at the last line, which
// we cant allow to entirely disappear. Lets preserve
// the indentation
if (m_backspacePressed && !priorParaIsEditable) {
textCursor().setPosition(para);
QString contents = textCursor().block().text();
contents = contents.right(contents.length()-m_lastPos+1);
contents = baseIndent + contents.left(contents.length()-1); // left is to remove trailing space
insertParagraph(contents, para+1);
removeParagraph(para);
// furthermore, If it is nothing but indentation + whitespace
// we switch this back to Auto-Generated.
if (cmb && contents.contains(QRegularExpression(QChar::fromLatin1('^')+baseIndent+QString::fromLatin1("\\s$")))) {
cmb->setContentType(CodeBlock::AutoGenerated);
cmb->syncToParent();
}
}
// send them to the first spot in the line which is editable
//:TODO: setCursorPosition(para, minPos); // crashes the application !?
}
return;
}
}
// look for changes in editability, if they occur, we need to record
// the edits which have been made
if ((editPara && !m_lastTextBlockToBeEdited) || (!editPara && m_lastTextBlockToBeEdited))
{
setReadOnly(editPara ? false : true);
// IF this is a different text block, update the body of the method
// it belongs to
if (m_lastTextBlockToBeEdited && (m_lastTextBlockToBeEdited != m_textBlockList.at(para) || !editPara))
{
updateTextBlockFromText (m_lastTextBlockToBeEdited);
m_lastTextBlockToBeEdited = nullptr;
}
if (editPara)
m_lastTextBlockToBeEdited = m_textBlockList.at(para);
else
m_lastTextBlockToBeEdited = nullptr;
}
m_lastPara = para;
m_lastPos = pos;
m_newLinePressed = false;
m_backspacePressed = false;
}
/**
* Check whether a block at a given position is on a single line.
* @param para the index of the block in the list
* @return flag whether block is on a single line
*/
bool CodeEditor::paraIsNotSingleLine(int para)
{
TextBlock * tBlock = m_textBlockList.at(para);
if (tBlock) {
int pstart = m_textBlockList.indexOf(tBlock);
TextBlockInfo *info = m_tbInfoMap[tBlock];
QList<ParaInfo*> list = info->m_paraList;
for(ParaInfo *item : list) {
if ((pstart+item->start) <= para && (item->start+pstart+item->size) >= para)
if (item->size > 0)
return true;
}
}
return false;
}
/**
* Find the text block in which the character position is located.
* @param characterPos the given character position
* @return the text block in which the character position is found
*/
TextBlock* CodeEditor::findTextBlockAt(int characterPos)
{
int charCount = 0;
for (int tbIdx = 0; tbIdx < m_textBlockList.count(); ++tbIdx) {
TextBlock* tb = m_textBlockList.at(tbIdx);
if (m_tbInfoMap.contains(tb)) {
TextBlockInfo *tbi = m_tbInfoMap[tb];
if (tbi && !tbi->m_paraList.isEmpty()) {
for (int idx = 0; idx < tbi->m_paraList.count(); ++idx) {
ParaInfo* pi = tbi->m_paraList.at(idx);
charCount += pi->size;
if (characterPos < charCount) {
return tb;
}
}
}
}
}
return nullptr;
}
/**
* Checks if paragraph is editable or not.
* Method is used only in @ref slotCursorPositionChanged.
* @param para the desired paragraph (character number)
* @return flag if paragraph is editable or not
*/
bool CodeEditor::isParaEditable(int para)
{
//:unused: int endLine = 0;
if (!m_textBlockList.isEmpty()) {
TextBlock* lastTb = m_textBlockList.last();
if (m_tbInfoMap.contains(lastTb)) {
// TextBlockInfo *tbi = m_tbInfoMap[lastTb];
// if (tbi && !tbi->m_paraList.isEmpty()) {
// ParaInfo* pi = tbi->m_paraList.last();
// endLine = pi->end + 1;
// }
}
}
if ((para < 0) || (para >= document()->characterCount())) {
logDebug2("CodeEditor::isParaEditable para: %1 not in range 0..%2", para, document()->characterCount());
return false;
}
TextBlock * tBlock = findTextBlockAt(para);
if (tBlock) {
int editStart = tBlock->firstEditableLine();
int editEnd = tBlock->lastEditableLine();
bool hasEditableRange = (editStart > 0 || editEnd < 0) ? true : false;
TextBlockInfo *info = m_tbInfoMap[tBlock];
if (info) {
int pstart = m_textBlockList.indexOf(tBlock);
int relativeLine = para - pstart;
QList<ParaInfo*> list = info->m_paraList;
for(ParaInfo *item : list) {
if (item->start+pstart <= para && item->start+pstart+item->size >= para) {
if (item->isEditable && hasEditableRange) {
if (relativeLine >= editStart && relativeLine <= (item->size + editEnd))
return true;
else
return false;
}
else
return item->isEditable;
}
}
}
else {
logDebug0("CodeEditor::isParaEditable: TextBlockInfo not found in info map!");
}
}
else {
logDebug1("CodeEditor::isParaEditable: TextBlock not found at position %1", para);
}
return false;
}
/**
* :TODO:
*/
void CodeEditor::changeTextBlockHighlighting(TextBlock * tBlock, bool selected)
{
if (tBlock) {
TextBlockInfo *info = m_tbInfoMap[tBlock];
if (!info) {
logWarn0("zero TextBlockInfo instance");
return;
}
QList<ParaInfo*> list = info->m_paraList;
int pstart = m_textBlockList.indexOf(tBlock);
for(ParaInfo *item : list) {
for (int p=(item->start+pstart); p<=(item->start+pstart+item->size); ++p) {
if (selected) {
if (info->isClickable) {
setParagraphBackgroundColor(p, state().selectedColor);
}
else {
setParagraphBackgroundColor(p, state().nonEditBlockColor);
}
}
else if (m_isHighlighted) {
setParagraphBackgroundColor(p, item->bgcolor);
}
else {
setParagraphBackgroundColor(p, state().paperColor);
}
}
}
}
}
/**
* Set the background color at the cursor position.
* @param position the character position
* @param color the desired color
*/
void CodeEditor::setParagraphBackgroundColor(int position, const QColor& color)
{
textCursor().setPosition(position);
QTextCharFormat format;
format.setBackground(color);
textCursor().setCharFormat(format);
}
/**
* :TODO:
*/
void CodeEditor::changeShowHidden(int signal)
{
if (signal)
m_showHiddenBlocks = true;
else
m_showHiddenBlocks = false;
rebuildView(m_lastPara);
}
/**
* Colorizes/uncolorizes type for ALL paragraphs.
*/
void CodeEditor::changeHighlighting(int signal)
{
int total_para = textCursor().blockNumber()-1;
if (signal) {
// we want to highlight
m_isHighlighted = true;
for (int para = 0; para < total_para; ++para) {
TextBlock * tblock = m_textBlockList.at(para);
changeTextBlockHighlighting(tblock, false);
}
}
else {
// we DON'T want to highlight
m_isHighlighted = false;
for (int para = 0; para < total_para; ++para) {
setParagraphBackgroundColor(para, state().paperColor);
}
}
// now redo the "selected" para, should it exist
if (m_selectedTextBlock) {
changeTextBlockHighlighting(m_selectedTextBlock, true);
}
}
/**
* :TODO:
*/
void CodeEditor::contractSelectedParagraph(int paraToRemove)
{
if ((paraToRemove >= 0) && (paraToRemove < m_textBlockList.size())) {
TextBlock * tBlock = m_textBlockList.at(paraToRemove);
if (tBlock) {
int pstart = m_textBlockList.indexOf(tBlock);
TextBlockInfo *info = m_tbInfoMap[tBlock];
QList<ParaInfo*> list = info->m_paraList;
bool lowerStartPosition = false;
for(ParaInfo *item : list) {
if (lowerStartPosition) {
item->start -= 1;
}
if ((pstart+item->start) <= paraToRemove && (item->start+pstart+item->size) >= paraToRemove) {
item->size -= 1;
// a little cheat.. we don't want to remove last line as we need
// to leave a place that can be 'edited' by the tool IF the user
// changes their mind about method body content
if (item->size < 0) {
item->size = 0;
}
lowerStartPosition = true;
}
}
m_textBlockList.removeAt(paraToRemove);
}
}
}
/**
* :TODO:
*/
void CodeEditor::expandSelectedParagraph(int priorPara)
{
TextBlock * tBlock = m_textBlockList.at(priorPara);
if (tBlock) {
// add this tBlock in
m_textBlockList.insert(priorPara, tBlock);
TextBlockInfo *info = m_tbInfoMap[tBlock];
QList<ParaInfo*> list = info->m_paraList;
int pstart = m_textBlockList.indexOf(tBlock);
// now update the paragraph information
bool upStartPosition = false;
for(ParaInfo *item : list) {
// AFTER we get a match, then following para's need to have start position upped too
if (upStartPosition)
item->start += 1;
if ((pstart+item->start) <= priorPara && (item->start+pstart+item->size) >= priorPara) {
item->size += 1;
slotCursorPositionChanged(); //:TODO: m_lastPara, m_lastPos);
upStartPosition = true;
}
}
}
}
/**
* Override the QT event so we can do appropriate things.
*/
void CodeEditor::mouseDoubleClickEvent(QMouseEvent * e)
{
QTextCursor tc = cursorForPosition(e->pos());
int para = tc.position();
int pos = tc.blockNumber();
clicked(para, pos);
m_lastPara = para;
m_lastPos = pos;
// ugh. more ugliness. We want to be able to call up the
// correct editing dialog for the given attribute.
if ((para >= 0) && (para < document()->characterCount())) {
TextBlock * tBlock = findTextBlockAt(para);
editTextBlock(tBlock, para);
}
else {
logDebug2("CodeEditor::mouseDoubleClickEvent para: %1 not in range 0..%2",
para, document()->characterCount());
}
}
/**
* Override the QT event so we can do appropriate things.
*/
void CodeEditor::contentsMouseMoveEvent(QMouseEvent * e)
{
QTextCursor tc = cursorForPosition(e->pos());
int para = tc.position();
int pos = tc.blockNumber();
clicked(para, pos);
if (para < 0)
return; // shouldn't happen..
TextBlock * tblock = m_textBlockList.at(para);
if (tblock && m_selectedTextBlock != tblock) {
TextBlockInfo * info = m_tbInfoMap[tblock];
// unhighlight old selected textblock regardless of whether
// it was selected or not.
changeTextBlockHighlighting(m_selectedTextBlock, false);
// highlight new block
changeTextBlockHighlighting(tblock, true);
// FIX: update the label that shows what type of component this is
componentLabel()->setText(QString::fromLatin1("<b>")+info->displayName()+QString::fromLatin1("</b>"));
m_selectedTextBlock = tblock;
if (m_lastTextBlockToBeEdited) {
updateTextBlockFromText (m_lastTextBlockToBeEdited);
m_lastTextBlockToBeEdited = nullptr;
}
}
// record this as the last paragraph
}
/**
* Rebuild our view of the document. Happens whenever we change
* some field/aspect of an underlying UML object used to create
* the view.
* If connections are right, then the UMLObject will send out the modified()
* signal which will trigger a call to re-generate the appropriate code within
* the code document. Our burden is to appropriately prepare the tool: we clear
* out ALL the textblocks in the KTextEdit widget and then re-show them
* after the dialog disappears.
*/
void CodeEditor::rebuildView(int startCursorPos)
{
Q_UNUSED(startCursorPos); //:TODO:
loadFromDocument();
// make a minimal attempt to leave the cursor (view of the code) where
// we started
//:TODO: int new_nrof_para = paragraphs() -1;
//:TODO: setCursorPosition((startCursorPos < new_nrof_para ? startCursorPos : 0), 0); //:TODO: crashes the application
}
| 51,329
|
C++
|
.cpp
| 1,303
| 32.185725
| 152
| 0.633925
|
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,322
|
objectnodedialog.cpp
|
KDE_umbrello/umbrello/dialogs/objectnodedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "objectnodedialog.h"
// local includes
#include "debug_utils.h"
#include "documentationwidget.h"
#include "dialog_utils.h"
#include "icon_utils.h"
#include "objectnodewidget.h"
#include "umlview.h"
#include "uml.h" // only needed for log{Warn,Error}
// kde includes
#include <klineedit.h>
#include <KLocalizedString>
// qt includes
#include <QCheckBox>
#include <QFrame>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QRadioButton>
/**
* Constructor.
*/
ObjectNodeDialog::ObjectNodeDialog(QWidget *parent, ObjectNodeWidget * pWidget)
: MultiPageDialogBase(parent),
m_pObjectNodeWidget(pWidget),
m_bChangesMade(false)
{
setCaption(i18n("Properties"));
setupPages();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Entered when OK button pressed.
*/
void ObjectNodeDialog::slotOk()
{
applyPage(pageItemStyle);
applyPage(pageItemFont);
applyPage(pageItemGeneral);
accept();
}
/**
* Entered when Apply button pressed.
*/
void ObjectNodeDialog::slotApply()
{
applyPage(currentPage());
}
void ObjectNodeDialog::slotShowState()
{
m_GenPageWidgets.stateL->show();
m_GenPageWidgets.stateLE->show();
m_GenPageWidgets.stateLE->setText(m_pObjectNodeWidget->state());
}
void ObjectNodeDialog::slotHideState()
{
m_GenPageWidgets.stateL->hide();
m_GenPageWidgets.stateLE->hide();
}
/**
* Sets up the pages of the dialog.
*/
void ObjectNodeDialog::setupPages()
{
setupGeneralPage();
pageItemStyle = setupStylePage(m_pObjectNodeWidget) ;
pageItemFont = setupFontPage(m_pObjectNodeWidget);
}
/**
* Applies changes to the given page.
*/
void ObjectNodeDialog::applyPage(KPageWidgetItem *item)
{
m_bChangesMade = true;
if (item == pageItemGeneral)
{
m_pObjectNodeWidget->setName(m_GenPageWidgets.nameLE->text());
m_GenPageWidgets.docWidget->apply();
m_pObjectNodeWidget->setState(m_GenPageWidgets.stateLE->text());
ObjectNodeWidget::ObjectNodeType newType = ObjectNodeWidget::Normal;
if (m_GenPageWidgets.bufferRB->isChecked())
newType = ObjectNodeWidget::Buffer;
else if (m_GenPageWidgets.dataRB->isChecked())
newType = ObjectNodeWidget::Data;
else if (m_GenPageWidgets.flowRB->isChecked())
newType = ObjectNodeWidget::Flow;
m_pObjectNodeWidget->setObjectNodeType (newType);
}
else if (item == pageItemFont)
{
applyFontPage(m_pObjectNodeWidget);
}
else if (item == pageItemStyle)
{
applyStylePage();
}
}
/**
* Sets up the general page of the dialog.
*/
void ObjectNodeDialog::setupGeneralPage()
{
QStringList types;
types << i18n("Central Buffer") << i18n("Data Store") << i18n("ObjectFlow");
ObjectNodeWidget::ObjectNodeType type = m_pObjectNodeWidget->objectNodeType();
int margin = fontMetrics().height();
QWidget *page = new QWidget();
QVBoxLayout *topLayout = new QVBoxLayout(page);
pageItemGeneral = createPage(i18n("General"), i18n("General Properties"),
Icon_Utils::it_Properties_General, page);
m_GenPageWidgets.generalGB = new QGroupBox(i18nc("properties group title", "Properties"));
topLayout->addWidget(m_GenPageWidgets.generalGB);
QGridLayout * generalLayout = new QGridLayout(m_GenPageWidgets.generalGB);
generalLayout->setSpacing(Dialog_Utils::spacingHint());
generalLayout->setContentsMargins(margin, margin, margin, margin);
QString objType;
if (type < types.count()) {
objType = types.at((int)type);
} else {
logWarn1("ObjectNodeDialog::setupGeneralPage: type of ObjectNodeWidget is out of range! "
"Value=%1", type);
}
Dialog_Utils::makeLabeledEditField(generalLayout, 0,
m_GenPageWidgets.typeL, i18n("Object Node type:"),
m_GenPageWidgets.typeLE, objType);
m_GenPageWidgets.typeLE->setEnabled(false);
Dialog_Utils::makeLabeledEditField(generalLayout, 1,
m_GenPageWidgets.nameL, i18n("Object Node name:"),
m_GenPageWidgets.nameLE);
Dialog_Utils::makeLabeledEditField(generalLayout, 2,
m_GenPageWidgets.stateL, i18nc("enter state label", "State :"),
m_GenPageWidgets.stateLE);
m_GenPageWidgets.stateL->hide();
m_GenPageWidgets.stateLE->hide();
m_GenPageWidgets.bufferRB = new QRadioButton(i18n("&Central Buffer"));
generalLayout->addWidget(m_GenPageWidgets.bufferRB, 3, 0);
m_GenPageWidgets.dataRB = new QRadioButton(i18n("&Data Store "));
generalLayout->addWidget(m_GenPageWidgets.dataRB, 3, 1);
m_GenPageWidgets.flowRB = new QRadioButton(i18n("&Object Flow"));
generalLayout->addWidget(m_GenPageWidgets.flowRB, 4, 1);
if (type == ObjectNodeWidget::Flow)
{
showState();
}
connect(m_GenPageWidgets.bufferRB, SIGNAL(clicked()), this, SLOT(slotHideState()));
connect(m_GenPageWidgets.dataRB, SIGNAL(clicked()), this, SLOT(slotHideState()));
connect(m_GenPageWidgets.flowRB, SIGNAL(clicked()), this, SLOT(slotShowState()));
ObjectNodeWidget::ObjectNodeType newType = m_pObjectNodeWidget->objectNodeType() ;
m_GenPageWidgets.bufferRB->setChecked(newType == ObjectNodeWidget::Buffer);
m_GenPageWidgets.dataRB->setChecked (newType == ObjectNodeWidget::Data);
m_GenPageWidgets.flowRB->setChecked (newType == ObjectNodeWidget::Flow);
m_GenPageWidgets.docWidget = new DocumentationWidget(m_pObjectNodeWidget);
generalLayout->addWidget(m_GenPageWidgets.docWidget, 5, 0, 1, 2);
if (type != ObjectNodeWidget::Buffer && type != ObjectNodeWidget::Data && type != ObjectNodeWidget::Flow) {
m_GenPageWidgets.nameLE->setEnabled(false);
m_GenPageWidgets.nameLE->setText(QString());
} else
m_GenPageWidgets.nameLE->setText(m_pObjectNodeWidget->name());
}
/**
* Show the State entry text.
*/
void ObjectNodeDialog::showState()
{
m_GenPageWidgets.stateL->show();
m_GenPageWidgets.stateLE->show();
m_GenPageWidgets.stateLE->setText(m_pObjectNodeWidget->state());
}
| 6,518
|
C++
|
.cpp
| 175
| 31.765714
| 111
| 0.695246
|
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,323
|
dontaskagain.cpp
|
KDE_umbrello/umbrello/dialogs/dontaskagain.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "dontaskagain.h"
// Qt includes
#include <QCheckBox>
#include <QGroupBox>
#include <QMetaType>
#include <QVariant>
#include <QVBoxLayout>
// KDE includes
#include <KLocalizedString>
#include <KMessageBox>
Q_DECLARE_METATYPE(DontAskAgainItem*)
DontAskAgainItem::DontAskAgainItem(const QString &name)
: m_name(name)
{
DontAskAgainHandler::instance().addItem(this);
}
DontAskAgainItem::~DontAskAgainItem()
{
}
QString &DontAskAgainItem::name()
{
return m_name;
}
bool DontAskAgainItem::isAll()
{
return m_name == QStringLiteral("all");
}
bool DontAskAgainItem::isEnabled()
{
return isAll() ? false : KMessageBox::shouldBeShownContinue(m_name);
}
void DontAskAgainItem::setEnabled(bool state)
{
if (isAll())
KMessageBox::enableAllMessages();
else if(state)
KMessageBox::enableMessage(m_name);
else
KMessageBox::saveDontShowAgainContinue(m_name);
}
DontAskAgainWidget::DontAskAgainWidget(QList<DontAskAgainItem *> &items, QWidget *parent)
: QWidget(parent),
m_items(items)
{
setLayout(new QVBoxLayout(this));
QGroupBox *box = new QGroupBox(i18n("Notifications"));
layout()->addWidget(box);
m_layout = new QVBoxLayout(box);
for(DontAskAgainItem *item : m_items) {
addItem(item);
}
}
bool DontAskAgainWidget::apply()
{
// handle 'all messages' case
for(QCheckBox *c : this->findChildren<QCheckBox *>()) {
DontAskAgainItem *item = c->property("data").value<DontAskAgainItem*>();
if (item->isAll() && c->isChecked()) {
item->setEnabled();
return true;
}
}
// handle 'single message' case
for(QCheckBox *c : this->findChildren<QCheckBox *>()) {
DontAskAgainItem *item = c->property("data").value<DontAskAgainItem*>();
if (!item->isAll() && c->isChecked() ^ item->isEnabled())
item->setEnabled(c->isChecked());
}
return true;
}
void DontAskAgainWidget::setDefaults()
{
for(QCheckBox *c : this->findChildren<QCheckBox *>()) {
DontAskAgainItem *item = c->property("data").value<DontAskAgainItem*>();
if (item->isAll())
c->setChecked(true);
else
c->setChecked(false);
}
}
void DontAskAgainWidget::addItem(DontAskAgainItem *item)
{
QCheckBox *c = new QCheckBox(item->text());
c->setChecked(item->isEnabled());
c->setProperty("data", QVariant::fromValue(item));
connect(c, SIGNAL(toggled(bool)), this, SLOT(slotToggled(bool)));
m_layout->addWidget(c);
}
void DontAskAgainWidget::slotToggled(bool state)
{
QCheckBox *c = dynamic_cast<QCheckBox*>(sender());
if (!c)
return;
DontAskAgainItem *item = c->property("data").value<DontAskAgainItem*>();
if (item->isAll()) {
for(QCheckBox *cb : this->findChildren<QCheckBox *>()) {
if (cb != c)
cb->setEnabled(!state);
}
}
}
void DontAskAgainHandler::addItem(DontAskAgainItem *item)
{
m_items.append(item);
}
DontAskAgainWidget *DontAskAgainHandler::createWidget()
{
return new DontAskAgainWidget(m_items);
}
DontAskAgainHandler &DontAskAgainHandler::instance()
{
static DontAskAgainHandler handler;
return handler;
}
| 3,376
|
C++
|
.cpp
| 118
| 24.330508
| 92
| 0.681074
|
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,324
|
diagramselectiondialog.cpp
|
KDE_umbrello/umbrello/dialogs/diagramselectiondialog.cpp
|
/*
SPDX-FileCopyrightText: 2015 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "diagramselectiondialog.h"
#include "diagramprintpage.h"
DiagramSelectionDialog::DiagramSelectionDialog(DiagramPrintPage *page, QWidget *parent) :
SinglePageDialogBase(parent)
{
setMainWidget(page);
}
DiagramSelectionDialog::~DiagramSelectionDialog()
{
// keep settings
setMainWidget(nullptr);
}
| 495
|
C++
|
.cpp
| 16
| 28.125
| 89
| 0.791139
|
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,325
|
codegenerationpolicypage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/codegenerationpolicypage.cpp
|
/*
SPDX-FileCopyrightText: 2003 Brian Thomas <brian.thomas@gsfc.nasa.gov>
SPDX-License-Identifier: GPL-2.0-or-later
*/
// own header
#include "codegenerationpolicypage.h"
// qt/kde includes
#include <qlabel.h>
#include <KLocalizedString>
// local includes
#include "../codegenerationpolicy.h"
/** This is the page which comes up IF there is no special options for the
* code generator.
*/
CodeGenerationPolicyPage::CodeGenerationPolicyPage(QWidget *parent, const char *name, CodeGenPolicyExt * policy)
: DialogPageBase(parent)
{
setObjectName(QLatin1String(name));
m_parentPolicy = policy;
}
CodeGenerationPolicyPage::~CodeGenerationPolicyPage()
{
this->disconnect();
}
void CodeGenerationPolicyPage::apply()
{
// do nothing in vanilla version
}
void CodeGenerationPolicyPage::setDefaults()
{
}
| 832
|
C++
|
.cpp
| 31
| 24.645161
| 112
| 0.777778
|
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,326
|
diagrampropertiespage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/diagrampropertiespage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "diagrampropertiespage.h"
// local includes
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
// kde includes
#include <KMessageBox>
// qt includes
/**
* Constructor
* @param parent the parent (wizard) of this wizard page
* @param scene the UMLScene to which the properties apply
*/
DiagramPropertiesPage::DiagramPropertiesPage(QWidget *parent, UMLScene *scene)
: DialogPageBase(parent), m_scene(scene)
{
setupUi(this);
ui_diagramName->setText(scene->name());
ui_zoom->setValue(scene->activeView()->zoom());
ui_width->setValue(scene->width());
ui_height->setValue(scene->height());
ui_checkBoxShowGrid->setChecked(scene->isSnapGridVisible());
ui_snapToGrid->setChecked(scene->snapToGrid());
ui_snapComponentSizeToGrid->setChecked(scene->snapComponentSizeToGrid());
ui_gridSpaceX->setValue(scene->snapX());
ui_gridSpaceY->setValue(scene->snapY());
ui_documentation->setText(scene->documentation());
if (scene->isSequenceDiagram() || scene->isCollaborationDiagram()) {
ui_autoIncrementSequence->setVisible(true);
ui_autoIncrementSequence->setChecked(scene->autoIncrementSequence());
} else {
ui_autoIncrementSequence->setVisible(false);
}
}
/**
* destructor
*/
DiagramPropertiesPage::~DiagramPropertiesPage()
{
}
/**
* sets default values
*/
void DiagramPropertiesPage::setDefaults()
{
}
/**
Checks whether the diagram name is unique and sets it if it is.
*/
bool DiagramPropertiesPage::checkUniqueDiagramName()
{
// check name
QString newName = ui_diagramName->text();
if (newName.length() == 0) {
KMessageBox::information(this, i18n("The name you have entered is invalid."),
i18n("Invalid Name"), QString(), KMessageBox::Options(0));
ui_diagramName->setText(m_scene->name());
return false;
}
if (newName != m_scene->name()) {
UMLDoc* doc = UMLApp::app()->document();
UMLView* view = doc->findView(m_scene->type(), newName);
if (view) {
KMessageBox::information(this, i18n("The name you have entered is not unique."),
i18n("Name Not Unique"), QString(), KMessageBox::Options(0));
ui_diagramName->setText(m_scene->name());
}
else {
// logDebug1("Cannot find view with name %1", newName);
m_scene->setName(newName);
doc->signalDiagramRenamed(m_scene->activeView());
return true;
}
}
return false;
}
/**
* Reads the set values from their corresponding widgets, writes them back to
* the data structure, and notifies clients.
*/
void DiagramPropertiesPage::apply()
{
checkUniqueDiagramName();
m_scene->activeView()->setZoom(ui_zoom->value());
m_scene->setSceneRect(0.0, 0.0, ui_width->value(), ui_height->value());
m_scene->setDocumentation(ui_documentation->toPlainText());
m_scene->setSnapSpacing(ui_gridSpaceX->value(), ui_gridSpaceY->value());
m_scene->setSnapToGrid(ui_snapToGrid->isChecked());
m_scene->setSnapComponentSizeToGrid(ui_snapComponentSizeToGrid->isChecked());
m_scene->setSnapGridVisible(ui_checkBoxShowGrid->isChecked());
if (m_scene->isSequenceDiagram() || m_scene->isCollaborationDiagram()) {
m_scene->setAutoIncrementSequence(ui_autoIncrementSequence->isChecked());
}
Q_EMIT applyClicked();
}
| 3,602
|
C++
|
.cpp
| 101
| 30.732673
| 92
| 0.6832
|
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,327
|
classgeneralpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/classgeneralpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// my own header
#include "classgeneralpage.h"
// app includes
#include "debug_utils.h"
#include "documentationwidget.h"
#include "dialog_utils.h"
#include "classifier.h"
#include "datatype.h"
#include "instance.h"
#include "umlobject.h"
#include "objectwidget.h"
#include "uml.h"
#include "umldoc.h"
#include "artifact.h"
#include "component.h"
#include "umlview.h"
#include "stereotype.h"
#include "umlpackagelist.h"
#include "model_utils.h"
#include "package.h"
#include "folder.h"
#include "import_utils.h"
#include "umlscene.h"
#include "umlobjectnamewidget.h"
#include "umlpackagewidget.h"
#include "umlstereotypewidget.h"
#include "umlartifacttypewidget.h"
#include "visibilityenumwidget.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
#include <kcombobox.h>
#include <klineedit.h>
// qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QRadioButton>
#include <QVBoxLayout>
#include <QLineEdit>
ClassGeneralPage::ClassGeneralPage(UMLDoc* d, QWidget* parent, UMLObject* o)
: DialogPageBase(parent),
m_pObject(o),
m_pWidget(nullptr),
m_pInstanceWidget(nullptr),
m_pUmldoc(d),
m_pMultiCB(nullptr),
m_pDrawActorCB(nullptr),
m_pAbstractCB(nullptr),
m_pDeconCB(nullptr),
m_pExecutableCB(nullptr),
m_docWidget(nullptr),
m_nameWidget(nullptr),
m_instanceNameWidget(nullptr),
m_stereotypeWidget(nullptr),
m_packageWidget(nullptr),
m_artifactTypeWidget(nullptr),
m_visibilityEnumWidget(nullptr)
{
if (!m_pObject) {
logWarn0("ClassGeneralPage: Given UMLObject is NULL.");
return;
}
for (int i = 0; i < N_STEREOATTRS; i++) {
m_pTagL [i] = nullptr;
m_pTagLE[i] = nullptr;
}
setMinimumSize(310, 330);
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
// setup name
UMLObject::ObjectType t = m_pObject->baseType();
m_pNameLayout = new QGridLayout();
m_pNameLayout->setSpacing(6);
topLayout->addLayout(m_pNameLayout, 4);
if (t == UMLObject::ot_Instance) {
const UMLInstance *inst = m_pObject->asUMLInstance();
Q_ASSERT(inst);
QString name = UMLObject::toI18nString(t);
m_instanceNameWidget = new UMLObjectNameWidget(name, m_pObject->name());
m_instanceNameWidget->addToLayout(m_pNameLayout, 0);
setFocusProxy(m_instanceNameWidget);
QString classNameLabel = UMLObject::toI18nString(UMLObject::ot_Class);
QString className;
if (inst->classifier())
className = inst->classifier()->name();
m_nameWidget = new UMLObjectNameWidget(classNameLabel, className);
m_nameWidget->addToLayout(m_pNameLayout, 1);
}
else {
QString name = UMLObject::toI18nString(t);
m_nameWidget = new UMLObjectNameWidget(name, m_pObject->name());
m_nameWidget->addToLayout(m_pNameLayout, 0);
setFocusProxy(m_nameWidget);
}
if (t != UMLObject::ot_Stereotype && t != UMLObject::ot_Instance) {
m_stereotypeWidget = new UMLStereotypeWidget(m_pObject);
if (t == UMLObject::ot_Interface || t == UMLObject::ot_Datatype || t == UMLObject::ot_Enum) {
m_stereotypeWidget->setEditable(false);
}
m_stereotypeWidget->addToLayout(m_pNameLayout, 1);
connect(m_stereotypeWidget->editField(), SIGNAL(currentTextChanged(const QString&)),
this, SLOT(slotStereoTextChanged(const QString&)));
Dialog_Utils::makeTagEditFields(m_pObject, m_pNameLayout, m_pTagL, m_pTagLE);
}
int row = 2;
if (m_pObject->isUMLDatatype()) {
const UMLDatatype *d = m_pObject->asUMLDatatype();
if (d && d->isReference() && d->originType()) {
QLabel *label = new QLabel(i18n("Reference:"), this);
m_pNameLayout->addWidget(label, row, 0);
QLabel *reference = new QLabel(d->originType()->name(), this);
m_pNameLayout->addWidget(reference, row, 1);
++row;
}
}
if (t == UMLObject::ot_Class || t == UMLObject::ot_Interface || t == UMLObject::ot_Enum || t == UMLObject::ot_Entity) {
m_packageWidget = new UMLPackageWidget(m_pObject);
m_packageWidget->addToLayout(m_pNameLayout, row);
++row;
}
if (t == UMLObject::ot_Class || t == UMLObject::ot_UseCase) {
QString abstractCaption;
if (t == UMLObject::ot_Class) {
abstractCaption = i18n("A&bstract class");
} else {
abstractCaption = i18n("A&bstract use case");
}
m_pAbstractCB = new QCheckBox(abstractCaption, this);
m_pAbstractCB->setChecked(m_pObject->isAbstract());
m_pNameLayout->addWidget(m_pAbstractCB, row, 0);
++row;
}
if (t == UMLObject::ot_Component) {
m_pExecutableCB = new QCheckBox(i18nc("component is executable", "&Executable"), this);
m_pExecutableCB->setChecked((o->asUMLComponent())->getExecutable());
m_pNameLayout->addWidget(m_pExecutableCB, row, 0);
++row;
}
if (t == UMLObject::ot_Artifact) {
m_artifactTypeWidget = new UMLArtifactTypeWidget(o->asUMLArtifact());
m_artifactTypeWidget->addToLayout(topLayout);
}
// setup scope
if (t != UMLObject::ot_Stereotype && t!= UMLObject::ot_Instance) {
m_visibilityEnumWidget = new VisibilityEnumWidget(m_pObject, this);
m_visibilityEnumWidget->addToLayout(topLayout);
}
m_docWidget = new DocumentationWidget(m_pObject, this);
topLayout->addWidget(m_docWidget);
}
ClassGeneralPage::ClassGeneralPage(UMLDoc* d, QWidget* parent, ObjectWidget* o)
: DialogPageBase(parent),
m_pObject(nullptr),
m_pWidget(o),
m_pInstanceWidget(nullptr),
m_pUmldoc(d),
m_pMultiCB(nullptr),
m_pDrawActorCB(nullptr),
m_pAbstractCB(nullptr),
m_pDeconCB(nullptr),
m_pExecutableCB(nullptr),
m_docWidget(nullptr),
m_nameWidget(nullptr),
m_instanceNameWidget(nullptr),
m_stereotypeWidget(nullptr),
m_packageWidget(nullptr),
m_artifactTypeWidget(nullptr),
m_visibilityEnumWidget(nullptr)
{
if (!m_pWidget) {
logWarn0("ClassGeneralPage: Given ObjectWidget is NULL.");
return;
}
for (int i = 0; i < N_STEREOATTRS; i++) {
m_pTagL [i] = nullptr;
m_pTagLE[i] = nullptr;
}
setMinimumSize(310, 330);
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
// setup name
m_pNameLayout = new QGridLayout();
m_pNameLayout->setSpacing(6);
topLayout->addLayout(m_pNameLayout, 4);
QString name = UMLObject::toI18nString(UMLObject::ot_Instance);
m_instanceNameWidget = new UMLObjectNameWidget(name , m_pWidget->instanceName());
m_instanceNameWidget->addToLayout(m_pNameLayout, 0);
setFocusProxy(m_instanceNameWidget);
QString className = UMLObject::toI18nString(UMLObject::ot_Class);
m_nameWidget = new UMLObjectNameWidget(className, m_pWidget->name());
m_nameWidget->addToLayout(m_pNameLayout, 1);
UMLView *view = UMLApp::app()->currentView();
m_pDrawActorCB = new QCheckBox(i18n("Draw as actor"), this);
m_pDrawActorCB->setChecked(m_pWidget->drawAsActor());
m_pNameLayout->addWidget(m_pDrawActorCB, 2, 0);
if (view->umlScene()->isCollaborationDiagram()) {
m_pMultiCB = new QCheckBox(i18n("Multiple instance"), this);
m_pMultiCB->setChecked(m_pWidget->multipleInstance());
m_pNameLayout->addWidget(m_pMultiCB, 2, 1);
if (m_pDrawActorCB->isChecked())
m_pMultiCB->setEnabled(false);
} else { // sequence diagram
m_pDeconCB = new QCheckBox(i18n("Show destruction"), this);
m_pDeconCB->setChecked(m_pWidget->showDestruction());
m_pNameLayout->addWidget(m_pDeconCB, 2, 1);
}
m_docWidget = new DocumentationWidget(m_pWidget, this);
topLayout->addWidget(m_docWidget);
if (m_pMultiCB) {
connect(m_pDrawActorCB, SIGNAL(toggled(bool)), this, SLOT(slotActorToggled(bool)));
}
}
ClassGeneralPage::ClassGeneralPage(UMLDoc* d, QWidget* parent, UMLWidget* widget)
: DialogPageBase(parent),
m_pObject(nullptr),
m_pWidget(nullptr),
m_pInstanceWidget(widget),
m_pUmldoc(d),
m_pMultiCB(nullptr),
m_pDrawActorCB(nullptr),
m_pAbstractCB(nullptr),
m_pDeconCB(nullptr),
m_pExecutableCB(nullptr),
m_docWidget(nullptr),
m_nameWidget(nullptr),
m_instanceNameWidget(nullptr),
m_stereotypeWidget(nullptr),
m_packageWidget(nullptr),
m_artifactTypeWidget(nullptr),
m_visibilityEnumWidget(nullptr)
{
for (int i = 0; i < N_STEREOATTRS; i++) {
m_pTagL [i] = nullptr;
m_pTagLE[i] = nullptr;
}
setMinimumSize(310, 330);
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
// setup name
m_pNameLayout = new QGridLayout();
m_pNameLayout->setSpacing(6);
topLayout->addLayout(m_pNameLayout, 4);
QString typeName = UMLWidget::toI18nString(widget->baseType());
m_nameWidget = new UMLObjectNameWidget(typeName, widget->name());
m_nameWidget->addToLayout(m_pNameLayout, 0);
setFocusProxy(m_nameWidget);
if (widget->umlObject()) {
m_stereotypeWidget = new UMLStereotypeWidget(widget->umlObject());
m_stereotypeWidget->addToLayout(m_pNameLayout, 1);
}
m_instanceNameWidget = new UMLObjectNameWidget(
UMLObject::toI18nString(UMLObject::ot_Instance), widget->instanceName());
m_instanceNameWidget->addToLayout(m_pNameLayout, 2);
m_docWidget = new DocumentationWidget(widget, this);
topLayout->addWidget(m_docWidget);
}
ClassGeneralPage::~ClassGeneralPage()
{
}
void ClassGeneralPage::slotStereoTextChanged(const QString &stereoText)
{
Dialog_Utils::remakeTagEditFields(stereoText, m_pObject, m_pNameLayout, m_pTagL, m_pTagLE);
}
/**
* Will move information from the dialog into the object.
* Call when the ok or apply button is pressed.
*/
void ClassGeneralPage::apply()
{
QString name = m_nameWidget->text();
m_docWidget->apply();
if (m_stereotypeWidget) {
m_stereotypeWidget->apply();
if (m_pObject) {
Dialog_Utils::updateTagsFromEditFields(m_pObject, m_pTagLE);
}
}
if (m_pObject) {
UMLObject::ObjectType t = m_pObject->baseType();
if (t == UMLObject::ot_Class || t == UMLObject::ot_Interface || t == UMLObject::ot_Enum || t == UMLObject::ot_Entity) {
m_packageWidget->apply();
}
if (m_pAbstractCB) {
m_pObject->setAbstract(m_pAbstractCB->isChecked());
}
if(m_instanceNameWidget && m_pObject->isUMLInstance()) {
m_pObject->asUMLInstance()->setName(m_instanceNameWidget->text());
}
//make sure unique name
if(m_pObject->baseType() != UMLObject::ot_Instance) {
UMLObject *o = m_pUmldoc->findUMLObject(name);
if (o && m_pObject != o) {
KMessageBox::information(this, i18n("The name you have chosen\nis already being used.\nThe name has been reset."),
i18n("Name is Not Unique"), QString(), KMessageBox::Options(0));
m_nameWidget->reset();
} else {
m_pObject->setName(name);
}
}
if (t != UMLObject::ot_Stereotype) {
if (m_visibilityEnumWidget)
m_visibilityEnumWidget->apply();
}
if (m_pObject->baseType() == UMLObject::ot_Component) {
(m_pObject->asUMLComponent())->setExecutable(m_pExecutableCB->isChecked());
}
if (m_pObject->baseType() == UMLObject::ot_Artifact) {
m_artifactTypeWidget->apply();
m_pObject->emitModified();
}
} // end if m_pObject
else if (m_pWidget) {
m_pWidget->setInstanceName(m_instanceNameWidget->text());
if (m_pMultiCB) {
m_pWidget->setMultipleInstance(m_pMultiCB->isChecked());
}
m_pWidget->setDrawAsActor(m_pDrawActorCB->isChecked());
if (m_pDeconCB) {
m_pWidget->setShowDestruction(m_pDeconCB->isChecked());
}
UMLObject * o = m_pWidget->umlObject();
if (!o) {
logError0("ClassGeneralPage::apply: UML object of widget is null");
return;
}
UMLObject * old = m_pUmldoc->findUMLObject(name);
if (old && o != old) {
KMessageBox::information(this, i18n("The name you have chosen\nis already being used.\nThe name has been reset."),
i18n("Name is Not Unique"), QString(), KMessageBox::Options(0));
m_nameWidget->reset();
} else {
o->setName(name);
}
} // end if m_pWidget
else if (m_pInstanceWidget) {
m_pInstanceWidget->setInstanceName(m_instanceNameWidget->text());
UMLObject* o = m_pInstanceWidget->umlObject();
if (!o) {
logError0("ClassGeneralPage::apply: UML object of instance widget is null");
setInstanceWidgetNameIfApplicable(name);
return;
}
UMLObject* old = m_pUmldoc->findUMLObject(name);
if (old && o != old) {
KMessageBox::information(this, i18n("The name you have chosen\nis already being used.\nThe name has been reset."),
i18n("Name is Not Unique"), QString(), KMessageBox::Options(0));
m_nameWidget->reset();
} else {
o->setName(name);
}
} // end if m_pInstanceWidget
}
/**
* When the draw as actor check box is toggled, the draw
* as multi instance need to be enabled/disabled. They
* both can't be available at the same time.
*/
void ClassGeneralPage::slotActorToggled(bool state)
{
if (m_pMultiCB) {
m_pMultiCB->setEnabled(!state);
}
}
/**
* Sets the input name to the instance widget if the change is applicable.
* @param name The name of the widget
*/
void ClassGeneralPage::setInstanceWidgetNameIfApplicable(const QString& name) const
{
if(!m_pInstanceWidget)
return;
if(m_pInstanceWidget->isCombinedFragmentWidget() || m_pInstanceWidget->isFloatingDashLineWidget())
{
m_pInstanceWidget->setName(name);
}
}
| 14,534
|
C++
|
.cpp
| 383
| 31.334204
| 131
| 0.652864
|
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,328
|
defaultcodegenpolicypage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/defaultcodegenpolicypage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <brian.thomas@gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "defaultcodegenpolicypage.h"
// qt/kde includes
#include <QLabel>
#include <KLocalizedString>
/**
* This is the page which comes up IF there is no special options for the
* code generator.
*/
DefaultCodeGenPolicyPage::DefaultCodeGenPolicyPage(QWidget *parent, const char *name, CodeGenPolicyExt * policy)
:CodeGenerationPolicyPage(parent, name, policy)
{
m_textLabel = new QLabel(this);
m_textLabel->setObjectName(QStringLiteral("textLabel"));
m_textLabel->setText(i18n("<p align=\"center\">No Options Available.</p>"));
}
DefaultCodeGenPolicyPage::~DefaultCodeGenPolicyPage()
{
}
| 853
|
C++
|
.cpp
| 24
| 32.833333
| 112
| 0.764277
|
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,329
|
umlwidgetstylepage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/umlwidgetstylepage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlwidgetstylepage.h"
#include "associationline.h"
#include "associationwidget.h"
#include "selectlayouttypewidget.h"
#include "debug_utils.h"
#include "optionstate.h"
#include "uml.h"
#include "umlscene.h"
#include "umlview.h"
#include "widgetbase.h"
#include <KLocalizedString>
#include <kcolorbutton.h>
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QPushButton>
#include <QSpinBox>
#include <QVBoxLayout>
/**
* Constructor - Observe a UMLWidget.
*/
UMLWidgetStylePage::UMLWidgetStylePage(QWidget *pParent, WidgetBase *pWidget)
: QWidget(pParent)
, m_pUMLWidget(pWidget)
, m_options(nullptr)
, m_layoutTypeW(nullptr)
{
init();
if (m_pUMLWidget->isAssociationWidget()) {
m_pFillColorB->setEnabled(false);
m_pFillColorL->setEnabled(false);
m_pFillDefaultB->setEnabled(false);
m_pUseFillColorCB->setEnabled(false);
}
m_pTextColorB->setColor(pWidget->textColor());
m_pLineColorB->setColor(pWidget->lineColor());
if (m_pFillColorB->isEnabled())
m_pFillColorB->setColor(pWidget->fillColor());
if (m_pUseFillColorCB->isEnabled())
m_pUseFillColorCB->setChecked(pWidget->useFillColor());
m_lineWidthB->setValue(pWidget->lineWidth());
}
/**
* Constructor - Observe an OptionState structure.
*/
UMLWidgetStylePage::UMLWidgetStylePage(QWidget * pParent, Settings::OptionState *options)
: QWidget(pParent)
, m_pUMLWidget(nullptr)
, m_options(options)
, m_layoutTypeW(nullptr)
{
init();
m_pTextColorB->setColor(m_options->uiState.textColor);
m_pLineColorB->setColor(m_options->uiState.lineColor);
m_pFillColorB->setColor(m_options->uiState.fillColor);
m_pUseFillColorCB->setChecked(m_options->uiState.useFillColor);
m_GridDotColorB->setColor(m_options->uiState.gridDotColor);
m_BackgroundColorB->setColor(m_options->uiState.backgroundColor);
m_lineWidthB->setValue(m_options->uiState.lineWidth);
}
/**
* Constructor - Observe a UMLScene.
*/
UMLWidgetStylePage::UMLWidgetStylePage(QWidget *pParent, UMLScene *scene)
: QWidget(pParent)
, m_pUMLWidget(nullptr)
, m_scene(scene)
, m_options(nullptr)
, m_layoutTypeW(nullptr)
{
init();
const Settings::OptionState state = m_scene->optionState();
m_pTextColorB->setColor(state.uiState.textColor);
m_pLineColorB->setColor(state.uiState.lineColor);
m_pFillColorB->setColor(state.uiState.fillColor);
m_pUseFillColorCB->setChecked(state.uiState.useFillColor);
m_lineWidthB->setValue(state.uiState.lineWidth);
m_GridDotColorB->setColor(state.uiState.gridDotColor);
m_BackgroundColorB->setColor(state.uiState.backgroundColor);
}
void UMLWidgetStylePage::init()
{
int margin = fontMetrics().height();
//setup GUI
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
int row = 0;
m_pColorGB = new QGroupBox(i18nc("title of color group", "Color"), this);
topLayout->addWidget(m_pColorGB);
QGridLayout * colorLayout = new QGridLayout(m_pColorGB);
colorLayout->setContentsMargins(margin, margin, margin, margin);
m_pTextColorL = new QLabel(i18nc("text color", "&Text:"), m_pColorGB);
colorLayout->addWidget(m_pTextColorL, row, 0);
m_pTextColorB = new KColorButton(m_pColorGB);
colorLayout->addWidget(m_pTextColorB, row, 1);
m_pTextColorL->setBuddy(m_pTextColorB);
m_pTextDefaultB = new QPushButton(i18nc("default text color button", "Defaul&t"), m_pColorGB) ;
colorLayout->addWidget(m_pTextDefaultB, row, 2);
m_pLineColorL = new QLabel(i18nc("line color", "&Line:"), m_pColorGB);
colorLayout->addWidget(m_pLineColorL, ++row, 0);
m_pLineColorB = new KColorButton(m_pColorGB);
colorLayout->addWidget(m_pLineColorB, row, 1);
m_pLineColorL->setBuddy(m_pLineColorB);
m_pLineDefaultB = new QPushButton(i18nc("default line color button", "&Default"), m_pColorGB) ;
colorLayout->addWidget(m_pLineDefaultB, row, 2);
m_pFillColorL = new QLabel(i18n("&Fill:"), m_pColorGB);
colorLayout->addWidget(m_pFillColorL, ++row, 0);
m_pFillColorB = new KColorButton(m_pColorGB);
colorLayout->addWidget(m_pFillColorB, row, 1);
m_pFillColorL->setBuddy(m_pFillColorB);
m_pFillDefaultB = new QPushButton(i18nc("default fill color button", "D&efault"), m_pColorGB);
colorLayout->addWidget(m_pFillDefaultB, row, 2);
m_pUseFillColorCB = new QCheckBox(i18n("&Use fill"), m_pColorGB);
colorLayout->setRowStretch(3, 2);
colorLayout->addWidget(m_pUseFillColorCB, ++row, 0);
//connect button signals up
connect(m_pTextDefaultB, SIGNAL(clicked()), this, SLOT(slotTextButtonClicked())) ;
connect(m_pLineDefaultB, SIGNAL(clicked()), this, SLOT(slotLineButtonClicked())) ;
connect(m_pFillDefaultB, SIGNAL(clicked()), this, SLOT(slotFillButtonClicked()));
if (!m_pUMLWidget) { // when we are on the diagram
m_BackgroundColorL = new QLabel(i18nc("background color", "&Background:"), m_pColorGB);
colorLayout->addWidget(m_BackgroundColorL, ++row, 0);
m_BackgroundColorB = new KColorButton(m_pColorGB);
colorLayout->addWidget(m_BackgroundColorB, row, 1);
m_BackgroundColorL->setBuddy(m_BackgroundColorB);
m_BackgroundDefaultB = new QPushButton(i18nc("default background color button", "De&fault"), m_pColorGB) ;
colorLayout->addWidget(m_BackgroundDefaultB, row, 2);
m_GridDotColorL = new QLabel(i18nc("grid dot color", "&Grid dot:"), m_pColorGB);
colorLayout->addWidget(m_GridDotColorL, ++row, 0);
m_GridDotColorB = new KColorButton(m_pColorGB);
colorLayout->addWidget(m_GridDotColorB, row, 1);
m_GridDotColorL->setBuddy(m_GridDotColorB);
m_GridDotDefaultB = new QPushButton(i18nc("default grid dot color button", "Def&ault"), m_pColorGB) ;
colorLayout->addWidget(m_GridDotDefaultB, row, 2);
//connect button signals up
connect(m_BackgroundDefaultB, SIGNAL(clicked()), this, SLOT(slotBackgroundButtonClicked()));
connect(m_GridDotDefaultB, SIGNAL(clicked()), this, SLOT(slotGridDotButtonClicked()));
}
m_pStyleGB = new QGroupBox(i18nc("title of width group", "Width"), this);
topLayout->addWidget(m_pStyleGB);
QGridLayout *styleLayout = new QGridLayout(m_pStyleGB);
styleLayout->setContentsMargins(margin, margin, margin, margin);
m_lineWidthL = new QLabel(i18nc("line width", "Line &width:"), m_pStyleGB);
styleLayout->addWidget(m_lineWidthL, ++row, 0);
m_lineWidthB = new QSpinBox(m_pStyleGB);
m_lineWidthB->setRange(0, 10);
m_lineWidthB->setSingleStep(1);
m_lineWidthB->setValue(0);
m_lineWidthL->setBuddy(m_lineWidthB);
styleLayout->addWidget(m_lineWidthB, row, 1);
m_lineWidthDefaultB = new QPushButton(i18nc("default line width button", "Defa&ult"), m_pStyleGB) ;
styleLayout->addWidget(m_lineWidthDefaultB, row, 2);
//connect button signals up
connect(m_lineWidthDefaultB, SIGNAL(clicked()), this, SLOT(slotLineWidthButtonClicked()));
if (m_pUMLWidget && m_pUMLWidget->isAssociationWidget()) {
AssociationWidget *aw = m_pUMLWidget->asAssociationWidget();
QGroupBox *boxMisc = new QGroupBox(i18nc("miscellaneous group box", "Miscellaneous"), this);
QGridLayout *layoutAssocs = new QGridLayout(boxMisc);
layoutAssocs->setContentsMargins(margin, margin, margin, margin);
topLayout->addWidget(boxMisc);
m_layoutTypeW = new SelectLayoutTypeWidget(i18n("Layout of the line:"), aw->associationLine().layout(), boxMisc);
m_layoutTypeW->addToLayout(layoutAssocs, 1);
}
topLayout->addStretch(1);
}
/**
* Destructor.
*/
UMLWidgetStylePage::~UMLWidgetStylePage()
{
}
/**
* Sets the default text color when default text button
* clicked.
*/
void UMLWidgetStylePage::slotTextButtonClicked()
{
m_pTextColorB->setColor(Settings::optionState().uiState.textColor);
}
/**
* Sets the default line color when default line button
* clicked.
*/
void UMLWidgetStylePage::slotLineButtonClicked()
{
m_pLineColorB->setColor(Settings::optionState().uiState.lineColor);
}
/**
* Sets the default fill color when default fill button
* clicked.
*/
void UMLWidgetStylePage::slotFillButtonClicked()
{
m_pFillColorB->setColor(Settings::optionState().uiState.fillColor);
}
/**
* Sets the default fill color when default fill button
* clicked.
*/
void UMLWidgetStylePage::slotBackgroundButtonClicked()
{
m_BackgroundColorB->setColor(Settings::optionState().uiState.backgroundColor);
}
/**
* Sets the default fill color when default fill button
* clicked.
*/
void UMLWidgetStylePage::slotGridDotButtonClicked()
{
m_GridDotColorB->setColor(Settings::optionState().uiState.gridDotColor);
}
/**
* Sets the default line color when default line button
* clicked.
*/
void UMLWidgetStylePage::slotLineWidthButtonClicked()
{
m_lineWidthB->setValue(Settings::optionState().uiState.lineWidth);
}
/**
* Updates the @ref UMLWidget with the dialog properties.
*/
void UMLWidgetStylePage::apply()
{
if (m_pUMLWidget) {
if (m_pUseFillColorCB->isEnabled())
m_pUMLWidget->setUseFillColor(m_pUseFillColorCB->isChecked());
m_pUMLWidget->setTextColor(m_pTextColorB->color());
m_pUMLWidget->setLineColor(m_pLineColorB->color());
if (m_pFillColorB->isEnabled())
m_pUMLWidget->setFillColor(m_pFillColorB->color());
m_pUMLWidget->setLineWidth(m_lineWidthB->value());
if (m_layoutTypeW) {
m_pUMLWidget->asAssociationWidget()->associationLine().setLayout(m_layoutTypeW->currentLayout());
}
}
else if (m_options) {
m_options->uiState.useFillColor = m_pUseFillColorCB->isChecked();
m_options->uiState.textColor = m_pTextColorB->color();
m_options->uiState.lineColor = m_pLineColorB->color();
m_options->uiState.fillColor = m_pFillColorB->color();
m_options->uiState.backgroundColor = m_BackgroundColorB->color();
m_options->uiState.gridDotColor = m_GridDotColorB->color();
m_options->uiState.lineWidth = m_lineWidthB->value();
}
else if (m_scene) {
Settings::OptionState state = m_scene->optionState();
state.uiState.useFillColor = m_pUseFillColorCB->isChecked();
state.uiState.textColor = m_pTextColorB->color();
state.uiState.lineColor = m_pLineColorB->color();
state.uiState.fillColor = m_pFillColorB->color();
state.uiState.backgroundColor = m_BackgroundColorB->color();
state.uiState.gridDotColor = m_GridDotColorB->color();
state.uiState.lineWidth = m_lineWidthB->value();
m_scene->setOptionState(state);
//:TODO: gridCrossColor, gridTextColor, gridTextFont, gridTextIsVisible
}
}
| 11,036
|
C++
|
.cpp
| 264
| 37.189394
| 121
| 0.716536
|
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,330
|
classoptionspage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/classoptionspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "classoptionspage.h"
// local includes
#include "umlscene.h"
#include "umlview.h"
#include "classifierwidget.h"
#include "entitywidget.h"
#include "widgetbase.h"
// kde includes
#include <KLocalizedString>
#include <KComboBox>
// qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QVBoxLayout>
/**
* Constructor - observe and modify a Widget
*/
ClassOptionsPage::ClassOptionsPage(QWidget* pParent, ClassifierWidget* pWidget)
: QWidget(pParent),
m_isDiagram(false)
{
init();
//WidgetType type = pWidget->baseType();
m_pWidget = pWidget;
setupPage();
}
ClassOptionsPage::ClassOptionsPage(QWidget *pParent, UMLScene *scene)
: QWidget(pParent),
m_isDiagram(true)
{
init();
m_scene = scene;
// class diagram uses full UIState
if (scene->isClassDiagram()) {
m_options = &scene->optionState();
setupClassPageOption();
}
else {
setupPageFromScene();
}
}
/**
* Constructor - observe and modify an OptionState structure
*
* @param pParent Parent widget
* @param options Settings to read from/save into
* @param isDiagram Flag if object is for display diagram class options
*/
ClassOptionsPage::ClassOptionsPage(QWidget* pParent, Settings::OptionState *options, bool isDiagram)
: QWidget(pParent),
m_isDiagram(isDiagram)
{
init();
m_options = options;
setupClassPageOption();
}
ClassOptionsPage::ClassOptionsPage(QWidget *pParent, EntityWidget *widget)
: QWidget(pParent),
m_isDiagram(false)
{
init();
m_entityWidget = widget;
setupPageFromEntityWidget();
}
/**
* Destructor
*/
ClassOptionsPage::~ClassOptionsPage()
{
}
void ClassOptionsPage::setDefaults()
{
m_showVisibilityCB->setChecked(false);
m_showAttsCB->setChecked(true);
#ifdef ENABLE_WIDGET_SHOW_DOC
m_showDocumentationCB->setChecked(false);
#endif
m_showOpsCB->setChecked(true);
m_showStereotypeCB->setCurrentIndex(2); // Tags
m_showAttSigCB->setChecked(false);
m_showOpSigCB->setChecked(false);
m_showPackageCB->setChecked(false);
m_showPublicOnlyCB->setChecked(true);
m_attribScopeCB->setCurrentIndex(1); // Private
m_operationScopeCB->setCurrentIndex(0); // Public
}
/**
* apply changes
*/
void ClassOptionsPage::apply()
{
if (m_pWidget) {
applyWidget();
} else if (m_scene) {
applyScene();
} else if (m_options) {
applyOptionState();
} else if (m_entityWidget) {
applyEntityWidget();
}
}
/**
* Set related uml widget
*/
void ClassOptionsPage::setWidget(ClassifierWidget * pWidget)
{
m_pWidget = pWidget;
}
/**
* Creates the page with the correct options for the class/interface
*/
void ClassOptionsPage::setupPage()
{
int margin = fontMetrics().height();
bool sig = false;
Uml::SignatureType::Enum sigtype;
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
m_visibilityGB = new QGroupBox(i18n("Show"), this);
topLayout->addWidget(m_visibilityGB);
QGridLayout * visibilityLayout = new QGridLayout(m_visibilityGB);
visibilityLayout->setSpacing(10);
visibilityLayout->setContentsMargins(margin, margin, margin, margin);
visibilityLayout->setRowStretch(3, 1);
#ifdef ENABLE_WIDGET_SHOW_DOC
m_showDocumentationCB = new QCheckBox(i18n("&Documentation"), m_visibilityGB);
m_showDocumentationCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::ShowDocumentation));
visibilityLayout->addWidget(m_showDocumentationCB, 0, 0);
#endif
m_showOpsCB = new QCheckBox(i18n("Operatio&ns"), m_visibilityGB);
m_showOpsCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::ShowOperations));
visibilityLayout->addWidget(m_showOpsCB, 1, 0);
m_showVisibilityCB = new QCheckBox(i18n("&Visibility"), m_visibilityGB);
m_showVisibilityCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::ShowVisibility));
visibilityLayout->addWidget(m_showVisibilityCB, 1, 1);
sigtype = m_pWidget->operationSignature();
if (sigtype == Uml::SignatureType::NoSig || sigtype == Uml::SignatureType::NoSigNoVis)
sig = false;
else
sig = true;
m_showOpSigCB = new QCheckBox(i18n("O&peration signature"), m_visibilityGB);
m_showOpSigCB->setChecked(sig);
visibilityLayout->addWidget(m_showOpSigCB, 2, 0);
m_showPackageCB = new QCheckBox(i18n("Pac&kage"), m_visibilityGB);
m_showPackageCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::ShowPackage));
visibilityLayout->addWidget(m_showPackageCB, 2, 1);
WidgetBase::WidgetType type = m_pWidget->baseType();
if (type == WidgetBase::wt_Class) {
m_showAttsCB = new QCheckBox(i18n("Att&ributes"), m_visibilityGB);
m_showAttsCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::ShowAttributes));
visibilityLayout->addWidget(m_showAttsCB, 3, 0);
m_showStereotypeCB = createShowStereotypeCB(m_visibilityGB);
m_showStereotypeCB->setCurrentIndex(m_pWidget->showStereotype());
visibilityLayout->addWidget(m_showStereotypeCB, 3, 1);
m_showAttSigCB = new QCheckBox(i18n("Attr&ibute signature"), m_visibilityGB);
sigtype = m_pWidget->attributeSignature();
if (sigtype == Uml::SignatureType::NoSig || sigtype == Uml::SignatureType::NoSigNoVis)
sig = false;
else
sig = true;
m_showAttSigCB->setChecked(sig);
visibilityLayout->addWidget(m_showAttSigCB, 4, 0);
m_showPublicOnlyCB = new QCheckBox(i18n("&Public Only"), m_visibilityGB);
m_showPublicOnlyCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::ShowPublicOnly));
visibilityLayout->addWidget(m_showPublicOnlyCB, 4, 1);
} else if (type == WidgetBase::wt_Interface) {
m_drawAsCircleCB = new QCheckBox(i18n("Draw as circle"), m_visibilityGB);
m_drawAsCircleCB->setChecked(m_pWidget->visualProperty(ClassifierWidget::DrawAsCircle));
visibilityLayout->addWidget(m_drawAsCircleCB, 3, 0);
}
}
void ClassOptionsPage::setupPageFromScene()
{
int margin = fontMetrics().height();
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
m_visibilityGB = new QGroupBox(i18n("Show"), this);
topLayout->addWidget(m_visibilityGB);
QGridLayout * visibilityLayout = new QGridLayout(m_visibilityGB);
visibilityLayout->setSpacing(10);
visibilityLayout->setContentsMargins(margin, margin, margin, margin);
visibilityLayout->setRowStretch(3, 1);
m_showOpSigCB = new QCheckBox(i18n("O&peration signature"), m_visibilityGB);
m_showOpSigCB->setChecked(m_scene->showOpSig());
visibilityLayout->addWidget(m_showOpSigCB, 1, 0);
}
/**
* Creates the page based on the OptionState
*/
void ClassOptionsPage::setupClassPageOption()
{
int margin = fontMetrics().height();
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
m_visibilityGB = new QGroupBox(i18n("Show"), this);
topLayout->addWidget(m_visibilityGB);
QGridLayout * visibilityLayout = new QGridLayout(m_visibilityGB);
visibilityLayout->setSpacing(10);
visibilityLayout->setContentsMargins(margin, margin, margin, margin);
#ifdef ENABLE_WIDGET_SHOW_DOC
m_showDocumentationCB = new QCheckBox(i18n("&Documentation"), m_visibilityGB);
m_showDocumentationCB->setChecked(m_options->classState.showDocumentation);
visibilityLayout->addWidget(m_showDocumentationCB, 0, 0);
#endif
m_showOpsCB = new QCheckBox(i18n("Operatio&ns"), m_visibilityGB);
m_showOpsCB->setChecked(m_options->classState.showOps);
visibilityLayout->addWidget(m_showOpsCB, 1, 0);
m_showOpSigCB = new QCheckBox(i18n("O&peration signature"), m_visibilityGB);
m_showOpSigCB->setChecked(m_options->classState.showOpSig);
visibilityLayout->addWidget(m_showOpSigCB, 2, 0);
visibilityLayout->setRowStretch(3, 1);
m_showAttsCB = new QCheckBox(i18n("Att&ributes"), m_visibilityGB);
m_showAttsCB->setChecked(m_options->classState.showAtts);
visibilityLayout->addWidget(m_showAttsCB, 3, 0);
m_showAttSigCB = new QCheckBox(i18n("Attr&ibute signature"), m_visibilityGB);
m_showAttSigCB->setChecked(m_options->classState.showAttSig);
visibilityLayout->addWidget(m_showAttSigCB, 4, 0);
m_showVisibilityCB = new QCheckBox(i18n("&Visibility"), m_visibilityGB);
m_showVisibilityCB->setChecked(m_options->classState.showVisibility);
visibilityLayout->addWidget(m_showVisibilityCB, 1, 1);
m_showPackageCB = new QCheckBox(i18n("Pac&kage"), m_visibilityGB);
m_showPackageCB->setChecked(m_options->classState.showPackage);
visibilityLayout->addWidget(m_showPackageCB, 2, 1);
m_showStereotypeCB = createShowStereotypeCB(m_visibilityGB);
m_showStereotypeCB->setCurrentIndex(m_options->classState.showStereoType);
visibilityLayout->addWidget(m_showStereotypeCB, 3, 1);
m_showAttribAssocsCB = new QCheckBox(i18n("&Attribute associations"), m_visibilityGB);
m_showAttribAssocsCB->setChecked(m_options->classState.showAttribAssocs);
visibilityLayout->addWidget(m_showAttribAssocsCB, 4, 1);
m_showPublicOnlyCB = new QCheckBox(i18n("&Public Only"), m_visibilityGB);
m_showPublicOnlyCB->setChecked(m_options->classState.showPublicOnly);
visibilityLayout->addWidget(m_showPublicOnlyCB, 5, 1);
if (!m_isDiagram) {
m_scopeGB = new QGroupBox(i18n("Starting Scope"));
topLayout->addWidget(m_scopeGB);
QGridLayout * scopeLayout = new QGridLayout(m_scopeGB);
scopeLayout->setSpacing(10);
scopeLayout->setContentsMargins(margin, margin, margin, margin);
m_attributeLabel = new QLabel(i18n("Default attribute scope:"), m_scopeGB);
scopeLayout->addWidget(m_attributeLabel, 0, 0);
m_operationLabel = new QLabel(i18n("Default operation scope:"), m_scopeGB);
scopeLayout->addWidget(m_operationLabel, 1, 0);
m_attribScopeCB = new KComboBox(m_scopeGB);
insertAttribScope(i18n("Public"));
insertAttribScope(i18n("Private"));
insertAttribScope(i18n("Protected"));
m_attribScopeCB->setCurrentIndex(m_options->classState.defaultAttributeScope);
scopeLayout->addWidget(m_attribScopeCB, 0, 1);
m_operationScopeCB = new KComboBox(m_scopeGB);
insertOperationScope(i18n("Public"));
insertOperationScope(i18n("Private"));
insertOperationScope(i18n("Protected"));
m_operationScopeCB->setCurrentIndex(m_options->classState.defaultOperationScope);
scopeLayout->addWidget(m_operationScopeCB, 1, 1);
topLayout->addWidget(m_scopeGB);
}
}
void ClassOptionsPage::setupPageFromEntityWidget()
{
int margin = fontMetrics().height();
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
m_visibilityGB = new QGroupBox(i18n("Show"), this);
topLayout->addWidget(m_visibilityGB);
QGridLayout * visibilityLayout = new QGridLayout(m_visibilityGB);
visibilityLayout->setSpacing(10);
visibilityLayout->setContentsMargins(margin, margin, margin, margin);
visibilityLayout->setRowStretch(3, 1);
m_showAttSigCB = new QCheckBox(i18n("Attribute Signatures"), m_visibilityGB);
m_showAttSigCB->setChecked(m_entityWidget->showAttributeSignature());
visibilityLayout->addWidget(m_showAttSigCB, 1, 0);
m_showStereotypeCB = createShowStereotypeCB(m_visibilityGB);
m_showStereotypeCB->setCurrentIndex(m_entityWidget->showStereotype());
visibilityLayout->addWidget(m_showStereotypeCB, 2, 0);
}
/**
* Sets the ClassifierWidget's properties to those selected in this dialog page.
*/
void ClassOptionsPage::applyWidget()
{
#ifdef ENABLE_WIDGET_SHOW_DOC
m_pWidget->setVisualProperty(ClassifierWidget::ShowDocumentation, m_showDocumentationCB->isChecked());
#endif
m_pWidget->setVisualProperty(ClassifierWidget::ShowPackage, m_showPackageCB->isChecked());
m_pWidget->setVisualProperty(ClassifierWidget::ShowVisibility, m_showVisibilityCB->isChecked());
m_pWidget->setVisualProperty(ClassifierWidget::ShowOperations, m_showOpsCB->isChecked());
m_pWidget->setVisualProperty(ClassifierWidget::ShowOperationSignature, m_showOpSigCB->isChecked());
WidgetBase::WidgetType type = m_pWidget->baseType();
if (type == WidgetBase::wt_Class) {
m_pWidget->setShowStereotype(Uml::ShowStereoType::Enum(m_showStereotypeCB->currentIndex()));
m_pWidget->setVisualProperty(ClassifierWidget::ShowAttributes, m_showAttsCB->isChecked());
m_pWidget->setVisualProperty(ClassifierWidget::ShowAttributeSignature, m_showAttSigCB->isChecked());
m_pWidget->setVisualProperty(ClassifierWidget::ShowPublicOnly, m_showPublicOnlyCB->isChecked());
} else if (type == WidgetBase::wt_Interface) {
if (m_drawAsCircleCB)
m_pWidget->setVisualProperty(ClassifierWidget::DrawAsCircle, m_drawAsCircleCB->isChecked());
}
}
/**
* Sets the OptionState to the values selected in this dialog page.
*/
void ClassOptionsPage::applyOptionState()
{
#ifdef ENABLE_WIDGET_SHOW_DOC
m_options->classState.showDocumentation = m_showDocumentationCB->isChecked();
#endif
m_options->classState.showVisibility = m_showVisibilityCB->isChecked();
if (m_showAttsCB)
m_options->classState.showAtts = m_showAttsCB->isChecked();
m_options->classState.showOps = m_showOpsCB->isChecked();
if (m_showStereotypeCB)
m_options->classState.showStereoType = Uml::ShowStereoType::Enum(m_showStereotypeCB->currentIndex());
m_options->classState.showPackage = m_showPackageCB->isChecked();
if (m_showAttribAssocsCB)
m_options->classState.showAttribAssocs = m_showAttribAssocsCB->isChecked();
if (m_showAttSigCB)
m_options->classState.showAttSig = m_showAttSigCB->isChecked();
m_options->classState.showOpSig = m_showOpSigCB->isChecked();
m_options->classState.showPublicOnly = m_showPublicOnlyCB->isChecked();
if (!m_isDiagram) {
m_options->classState.defaultAttributeScope = Uml::Visibility::fromInt(m_attribScopeCB->currentIndex());
m_options->classState.defaultOperationScope = Uml::Visibility::fromInt(m_operationScopeCB->currentIndex());
}
}
/**
* Sets the UMLScene's properties to those selected in this dialog page.
*/
void ClassOptionsPage::applyScene()
{
if (m_scene->isClassDiagram()) {
applyOptionState();
m_scene->setClassWidgetOptions(this);
}
else
m_scene->setShowOpSig(m_showOpSigCB->isChecked());
}
void ClassOptionsPage::applyEntityWidget()
{
Q_ASSERT(m_entityWidget);
m_entityWidget->setShowStereotype(Uml::ShowStereoType::Enum(m_showStereotypeCB->currentIndex()));
m_entityWidget->setShowAttributeSignature(m_showAttSigCB->isChecked());
}
/**
* Initialize optional items
*/
void ClassOptionsPage::init()
{
m_scene = nullptr;
m_options = nullptr;
m_pWidget = nullptr;
m_entityWidget = nullptr;
m_showStereotypeCB = nullptr;
m_showAttsCB = nullptr;
m_showAttSigCB = nullptr;
m_showAttribAssocsCB = nullptr;
m_showDocumentationCB = nullptr;
m_showPublicOnlyCB = nullptr;
m_drawAsCircleCB = nullptr;
}
/**
* This need not be a member method, it can be made "static" or be moved to Dialog_Utils
*/
KComboBox * ClassOptionsPage::createShowStereotypeCB(QGroupBox * grpBox)
{
KComboBox * cobox = new KComboBox(grpBox);
cobox->setEditable(false);
cobox->addItem(i18n("No Stereotype"));
cobox->addItem(i18n("Stereotype Name"));
cobox->addItem(i18n("Stereotype with Tags"));
return cobox;
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
*/
void ClassOptionsPage::insertAttribScope(const QString& type, int index)
{
m_attribScopeCB->insertItem(index, type);
m_attribScopeCB->completionObject()->addItem(type);
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
*/
void ClassOptionsPage::insertOperationScope(const QString& type, int index)
{
m_operationScopeCB->insertItem(index, type);
m_operationScopeCB->completionObject()->addItem(type);
}
| 16,366
|
C++
|
.cpp
| 394
| 36.979695
| 115
| 0.73356
|
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,331
|
associationgeneralpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/associationgeneralpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "associationgeneralpage.h"
// local includes
#include "associationwidget.h"
#include "association.h"
#include "assocrules.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "documentationwidget.h"
#include "objectwidget.h"
#include "umldoc.h"
#include "umlobject.h"
#include "uml.h"
// kde includes
#include <kcombobox.h>
#include <QLineEdit>
#include <KLocalizedString>
#include <KMessageBox>
#include <QTextEdit>
// qt includes
#include <QHBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QCheckBox>
#include <QLabel>
#include <QLayout>
#include <QVBoxLayout>
DEBUG_REGISTER(AssociationGeneralPage)
/**
* Sets up the AssociationGeneralPage.
*
* @param parent The parent to the AssociationGeneralPage.
* @param assoc The AssociationWidget to display the properties of.
*/
AssociationGeneralPage::AssociationGeneralPage (QWidget *parent, AssociationWidget *assoc)
: DialogPageBase(parent),
m_pAssocNameL(nullptr),
m_pAssocNameLE(nullptr),
m_pAssocNameComB(nullptr),
m_pStereoChkB(nullptr),
m_pTypeCB(nullptr),
m_pAssociationWidget(assoc),
m_pWidget(nullptr)
{
constructWidget();
}
/**
* Standard destructor.
*/
AssociationGeneralPage::~AssociationGeneralPage()
{
}
/**
* Construct all the widgets for this dialog.
*/
void AssociationGeneralPage::constructWidget()
{
// general configuration of the GUI
int margin = fontMetrics().height();
setMinimumSize(310, 330);
QVBoxLayout * topLayout = new QVBoxLayout(this);
topLayout->setSpacing(6);
// group boxes for name+type, documentation properties
QGroupBox *nameAndTypeGB = new QGroupBox(this);
nameAndTypeGB->setTitle(i18n("Properties"));
topLayout->addWidget(nameAndTypeGB);
m_pNameAndTypeLayout = new QGridLayout(nameAndTypeGB);
m_pNameAndTypeLayout->setSpacing(6);
m_pNameAndTypeLayout->setContentsMargins(margin, margin, margin, margin);;
// Association name
m_pAssocNameL = new QLabel(i18nc("name of association widget", "Name:"));
m_pNameAndTypeLayout->addWidget(m_pAssocNameL, 0, 0);
m_pAssocNameLE = new QLineEdit(m_pAssociationWidget->name());
m_pAssocNameComB = new KComboBox(true, nameAndTypeGB);
m_pAssocNameComB->setDuplicatesEnabled(false); // only allow one of each type in box
QWidget *nameInputWidget = m_pAssocNameLE;
UMLAssociation *umlAssoc = m_pAssociationWidget->association();
if (umlAssoc && umlAssoc->umlStereotype()) {
m_pAssocNameLE->hide();
Dialog_Utils::insertStereotypesSorted(m_pAssocNameComB, umlAssoc->stereotype());
nameInputWidget = m_pAssocNameComB;
} else {
m_pAssocNameComB->hide();
}
m_pNameAndTypeLayout->addWidget(nameInputWidget, 0, 1);
nameInputWidget->setFocus();
m_pAssocNameL->setBuddy(nameInputWidget);
if (umlAssoc) {
// stereotype checkbox
m_pStereoChkB = new QCheckBox(i18n("Stereotype"), nameAndTypeGB);
m_pStereoChkB->setChecked(umlAssoc->umlStereotype() != nullptr);
connect(m_pStereoChkB, SIGNAL(stateChanged(int)), this, SLOT(slotStereoCheckboxChanged(int)));
m_pNameAndTypeLayout->addWidget(m_pStereoChkB, 0, 2);
}
// type
Uml::AssociationType::Enum currentType = m_pAssociationWidget->associationType();
QString currentTypeAsString = Uml::AssociationType::toStringI18n(currentType);
QLabel *pTypeL = new QLabel(i18n("Type:"), nameAndTypeGB);
m_pNameAndTypeLayout->addWidget(pTypeL, 1, 0);
// Here is a list of all the supported choices for changing
// association types.
m_AssocTypes.clear();
m_AssocTypes << currentType;
logDebug1("AssociationGeneralPage::constructWidget: current type = %1",
Uml::AssociationType::toString(currentType));
// dynamically load all allowed associations
for (int i = Uml::AssociationType::Generalization; i < Uml::AssociationType::Reserved; ++i) {
// we don't need to check for current type
Uml::AssociationType::Enum assocType = Uml::AssociationType::fromInt(i);
if (assocType == currentType)
continue;
// UMLScene based checks
if (m_pAssociationWidget->umlScene()->type() == Uml::DiagramType::Collaboration
&& !(assocType == Uml::AssociationType::Coll_Mesg_Async
|| assocType == Uml::AssociationType::Coll_Mesg_Sync
|| assocType == Uml::AssociationType::Anchor))
continue;
if (AssocRules::allowAssociation(assocType,
m_pAssociationWidget->widgetForRole(Uml::RoleType::A),
m_pAssociationWidget->widgetForRole(Uml::RoleType::B))) {
m_AssocTypes << assocType;
logDebug1("AssociationGeneralPage::constructWidget: adding %1 to assoctype list",
Uml::AssociationType::toString(assocType));
}
}
bool found = false;
m_AssocTypeStrings.clear();
for (int i = 0; i < m_AssocTypes.size(); ++i) {
if (m_AssocTypes[i] == currentType) {
found = true;
}
m_AssocTypeStrings << Uml::AssociationType::toStringI18n(m_AssocTypes[i]);
}
if (!found) {
m_AssocTypes.clear();
m_AssocTypes << currentType;
m_AssocTypeStrings.clear();
m_AssocTypeStrings << currentTypeAsString;
}
m_pTypeCB = new KComboBox(nameAndTypeGB);
pTypeL->setBuddy(m_pTypeCB);
m_pTypeCB->addItems(m_AssocTypeStrings);
m_pTypeCB->setCompletedItems(m_AssocTypeStrings);
m_pTypeCB->setDuplicatesEnabled(false); // only allow one of each type in box
m_pNameAndTypeLayout->addWidget(m_pTypeCB, 1, 1);
// documentation
m_docWidget = new DocumentationWidget(m_pAssociationWidget, this);
topLayout->addWidget(m_docWidget);
}
void AssociationGeneralPage::slotStereoCheckboxChanged(int state)
{
QWidget *nameInputWidget = nullptr;
if (state) {
m_pAssocNameLE->hide();
m_pNameAndTypeLayout->removeWidget(m_pAssocNameLE);
UMLAssociation *umlAssoc = m_pAssociationWidget->association();
Dialog_Utils::insertStereotypesSorted(m_pAssocNameComB, umlAssoc->stereotype());
nameInputWidget = m_pAssocNameComB;
} else {
m_pAssocNameComB->hide();
m_pNameAndTypeLayout->removeWidget(m_pAssocNameComB);
nameInputWidget = m_pAssocNameLE;
}
m_pNameAndTypeLayout->addWidget(nameInputWidget, 0, 1);
nameInputWidget->show();
nameInputWidget->setFocus();
m_pAssocNameL->setBuddy(nameInputWidget);
}
/**
* Will move information from the dialog into the object.
* Call when the ok or apply button is pressed.
*/
void AssociationGeneralPage::apply()
{
if (m_pAssociationWidget) {
int comboBoxItem = m_pTypeCB->currentIndex();
Uml::AssociationType::Enum newType = m_AssocTypes[comboBoxItem];
m_pAssociationWidget->setAssociationType(newType);
m_docWidget->apply();
if (m_pStereoChkB && m_pStereoChkB->isChecked()) {
QString stereo = m_pAssocNameComB->currentText();
// keep the order
m_pAssociationWidget->setName(QStringLiteral(""));
m_pAssociationWidget->setStereotype(stereo);
} else {
// keep the order
m_pAssociationWidget->setStereotype(QStringLiteral(""));
m_pAssociationWidget->setName(m_pAssocNameLE->text());
}
}
}
| 7,649
|
C++
|
.cpp
| 195
| 33.25641
| 102
| 0.693199
|
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,332
|
constraintlistpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/constraintlistpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "constraintlistpage.h"
#include "attribute.h"
#include "debug_utils.h"
#include "classifierlistitem.h"
#include "classifier.h"
#include "enum.h"
#include "entity.h"
#include "entityattribute.h"
#include "enumliteral.h"
#include "object_factory.h"
#include "operation.h"
#include "template.h"
#include "umldoc.h"
#include "uml.h" // only needed for log{Warn,Error}
#include "uniqueconstraint.h"
#include <KLocalizedString>
#include <QMenu>
#include <QApplication>
#include <QHBoxLayout>
#include <QPushButton>
#include <QVBoxLayout>
/**
* Sets up the ConstraintListPage
*
* @param parent The parent to the ConstraintListPage.
* @param classifier The Concept to display the properties of.
* @param doc The UMLDoc document
* @param type The object type
*/
ConstraintListPage::ConstraintListPage(QWidget* parent, UMLClassifier* classifier,
UMLDoc* doc, UMLObject::ObjectType type)
: ClassifierListPage(parent, classifier, doc, type)
{
setupActions();
buttonMenu = new QMenu(this);
// add a button menu
m_pNewClassifierListItemButton->setMenu(buttonMenu);
buttonMenu->addAction(newPrimaryKeyConstraintAction);
buttonMenu->addAction(newUniqueConstraintAction);
buttonMenu->addAction(newForeignKeyConstraintAction);
buttonMenu->addAction(newCheckConstraintAction);
// because we order the list items. first the Unique Constraints and then the ForeignKey Constraints
hideArrowButtons(true);
}
/**
* Standard destructor.
*/
ConstraintListPage::~ConstraintListPage()
{
}
void ConstraintListPage::setupActions()
{
newUniqueConstraintAction = new QAction(i18n("Unique Constraint..."), this);
connect(newUniqueConstraintAction, SIGNAL(triggered(bool)),
this, SLOT(slotNewUniqueConstraint()));
newPrimaryKeyConstraintAction = new QAction(i18n("Primary Key Constraint..."), this);
connect(newPrimaryKeyConstraintAction, SIGNAL(triggered(bool)),
this, SLOT(slotNewPrimaryKeyConstraint()));
newForeignKeyConstraintAction = new QAction(i18n("Foreign Key Constraint..."), this);
connect(newForeignKeyConstraintAction, SIGNAL(triggered(bool)),
this, SLOT(slotNewForeignKeyConstraint()));
newCheckConstraintAction = new QAction(i18n("Check Constraint..."), this);
connect(newCheckConstraintAction, SIGNAL(triggered(bool)),
this, SLOT(slotNewCheckConstraint()));
}
void ConstraintListPage::slotNewUniqueConstraint()
{
m_itemType = UMLObject::ot_UniqueConstraint;
ClassifierListPage::slotNewListItem();
// shift back
m_itemType = UMLObject::ot_EntityConstraint;
}
void ConstraintListPage::slotNewPrimaryKeyConstraint()
{
m_itemType = UMLObject::ot_UniqueConstraint;
ClassifierListPage::slotNewListItem();
// set the last object created as Primary Key
UMLEntity* ent = m_pClassifier->asUMLEntity();
if (ent == nullptr) {
logError0("ConstraintListPage::slotNewPrimaryKeyConstraint: Could not set Primary Key. "
"Entity Value is Null");
return;
}
if (m_pLastObjectCreated != nullptr) {
m_bSigWaiting = true;
ent->setAsPrimaryKey(m_pLastObjectCreated->asUMLUniqueConstraint());
m_itemType = UMLObject::ot_EntityConstraint;
reloadItemListBox();
}
// shift back
m_itemType = UMLObject::ot_EntityConstraint;
}
void ConstraintListPage::slotNewForeignKeyConstraint()
{
m_itemType = UMLObject::ot_ForeignKeyConstraint;
ClassifierListPage::slotNewListItem();
// shift back
m_itemType = UMLObject::ot_EntityConstraint;
}
void ConstraintListPage::slotNewCheckConstraint()
{
m_itemType = UMLObject::ot_CheckConstraint;
ClassifierListPage::slotNewListItem();
// shift back
m_itemType = UMLObject::ot_EntityConstraint;
}
// /**
// * Calculates the new index to be assigned when an object of type ot is to
// * be added to the list box. The default Implementation is to add it to the end of the list
// * param ot The Object Type to be added
// * return The index
// */
// int ConstraintListPage::calculateNewIndex(Uml::ObjectType ot)
// {
// // we want to show all Unique Constraints first, followed by ForeignKey Constraints
// UMLClassifierListItemList ucList, fkcList, ccList;
// ucList = m_pClassifier->getFilteredList(UMLObject::ot_UniqueConstraint);
// fkcList = m_pClassifier->getFilteredList(UMLObject::ot_ForeignKeyConstraint);
// ccList = m_pClassifier->getFilteredList(UMLObject::ot_CheckConstraint);
//
// int ucCount, fkcCount, ccCount;
// ucCount = ucList.count();
// fkcCount = fkcList.count();
// ccCount = ccList.count();
//
// int index = 0;
//
// if (greaterThan(UMLObject::ot_UniqueConstraint, ot)) {
// index += ucCount;
// }
//
// if (greaterThan(UMLObject::ot_ForeignKeyConstraint, ot)) {
// index += fkcCount;
// }
//
// if (greaterThan(UMLObject::ot_CheckConstraint, ot)) {
// index += ccCount;
// }
//
// // we subtract 1 from the count as the new item is already in the list (m_List) and
// // hence contributes to the count we obtained
// index = index - 1;
//
// return index;
// }
// /**
// * Returns the index of the Item in the List Box
// */
// int ConstraintListPage::relativeIndexOf(QListWidgetItem* item)
// {
// int actualIndex = ClassifierListPage::relativeIndexOf(item);
//
// int ucCount = m_pClassifier->getFilteredList(UMLObject::ot_UniqueConstraint).count();
// int fkcCount = m_pClassifier->getFilteredList(UMLObject::ot_ForeignKeyConstraint).count();
// //int ccCount = m_pClassifier->getFilteredList(UMLObject::ot_CheckConstraint).count();
//
// //if (m_itemType == UMLObject::ot_EntityConstraint)
// // return actualIndex;
//
// int newIndex = actualIndex;
//
// if (!greaterThan(m_itemType, UMLObject::ot_UniqueConstraint)) {
// newIndex -= ucCount;
// }
//
// if (!greaterThan(m_itemType, UMLObject::ot_ForeignKeyConstraint)) {
// newIndex -= fkcCount;
// }
//
// return newIndex;
// }
/**
* Will return true if ct1 has a higher (top) place in the list than ct2
*
* @param ct1 Constraint Type 1
* @param ct2 Constraint Type 2
* @return true if ct1 is to be shown above ct2 else false
*/
bool ConstraintListPage::greaterThan(UMLObject::ObjectType ct1, UMLObject::ObjectType ct2)
{
// define ordering
switch(ct1) {
case UMLObject::ot_EntityConstraint:
case UMLObject::ot_UniqueConstraint:
// Unique Constraint greater than all others
return true;
break;
case UMLObject::ot_ForeignKeyConstraint:
if (ct2 != UMLObject::ot_UniqueConstraint)
return true;
else
return false;
break;
case UMLObject::ot_CheckConstraint:
if (ct2 != UMLObject::ot_CheckConstraint)
return false;
else
return true;
break;
default:
return false;
}
}
/**
* Get constraint list items for all types (unique, foreign-key
* and check-constraints)
*/
UMLClassifierListItemList ConstraintListPage::getItemList()
{
return m_pClassifier->getFilteredList(UMLObject::ot_EntityConstraint);
}
| 7,513
|
C++
|
.cpp
| 215
| 31.116279
| 104
| 0.698666
|
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,333
|
dialogpagebase.cpp
|
KDE_umbrello/umbrello/dialogs/pages/dialogpagebase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dialogpagebase.h"
// qt includes
#include <QKeyEvent>
/**
* Constructor
*/
DialogPageBase::DialogPageBase(QWidget *parent)
: QWidget(parent),
m_isModified(false)
{
}
DialogPageBase::~DialogPageBase()
{
}
/**
* Return state if page has been modified by user.
*
* The state will be used to determine changed pages.
*
* @return true page has been modified
*/
bool DialogPageBase::isModified()
{
return m_isModified;
}
/**
* Handle key press event.
* @param event key press event
*/
void DialogPageBase::keyPressEvent(QKeyEvent *event)
{
// Set modified state if any text has been typed in
if (event->key() >= Qt::Key_Space
&& event->key() < Qt::Key_Multi_key)
m_isModified = true;
QWidget::keyPressEvent(event);
}
| 936
|
C++
|
.cpp
| 42
| 19.642857
| 87
| 0.709932
|
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,334
|
classassociationspage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/classassociationspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "classassociationspage.h"
#include "associationwidget.h"
#include "associationpropertiesdialog.h"
#include "debug_utils.h"
#include "dialogpagebase.h"
#include "dialogspopupmenu.h"
#include "umlobject.h"
#include "umlscene.h"
#include "uml.h"
#include <KLocalizedString>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QListWidgetItem>
DEBUG_REGISTER(ClassAssociationsPage)
/**
* Constructs an instance of AssocPage.
*
* @param parent The parent of the page
* @param s The scene on which the UMLObject is being represented
* @param o The UMLObject being represented
*/
ClassAssociationsPage::ClassAssociationsPage(QWidget *parent, UMLScene *s, UMLObject *o)
: DialogPageBase(parent),
m_pObject(o),
m_pScene(s)
{
int margin = fontMetrics().height();
QHBoxLayout * mainLayout = new QHBoxLayout(this);
mainLayout->setSpacing(10);
m_pAssocGB = new QGroupBox(i18n("Associations"), this);
mainLayout->addWidget(m_pAssocGB);
QHBoxLayout * layout = new QHBoxLayout(m_pAssocGB);
layout->setSpacing(10);
layout->setContentsMargins(margin, margin, margin, margin);
m_pAssocLW = new QListWidget(m_pAssocGB);
m_pAssocLW->setContextMenuPolicy(Qt::CustomContextMenu);
layout->addWidget(m_pAssocLW);
setMinimumSize(310, 330);
fillListBox();
connect(m_pAssocLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(slotDoubleClick(QListWidgetItem*)));
connect(m_pAssocLW, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(slotRightButtonPressed(QPoint)));
}
/**
* Standard destructor.
*/
ClassAssociationsPage::~ClassAssociationsPage()
{
disconnect(m_pAssocLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(slotDoubleClick(QListWidgetItem*)));
disconnect(m_pAssocLW, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(slotRightButtonPressed(QPoint)));
}
void ClassAssociationsPage::slotDoubleClick(QListWidgetItem * item)
{
if (!item) {
return;
}
int row = m_pAssocLW->currentRow();
if (row == -1) {
return;
}
AssociationWidget * a = m_List.at(row);
a->showPropertiesDialog();
fillListBox();
}
/**
* Fills the list box with the objects associations.
*/
void ClassAssociationsPage::fillListBox()
{
m_List.clear();
m_pAssocLW->clear();
m_pScene->getWidgetAssocs(m_pObject, m_List);
int i = 0;
for(AssociationWidget *assocwidget : m_List) {
if(assocwidget->associationType() != Uml::AssociationType::Anchor) {
m_pAssocLW->insertItem(i, assocwidget->toString());
i++;
}
}
}
void ClassAssociationsPage::slotRightButtonPressed(const QPoint &p)
{
DialogsPopupMenu popup(this, DialogsPopupMenu::tt_Association_Selected);
QAction *triggered = popup.exec(m_pAssocLW->mapToGlobal(p));
slotMenuSelection(triggered);
}
void ClassAssociationsPage::slotMenuSelection(QAction* action)
{
int currentItemIndex = m_pAssocLW->currentRow();
if (currentItemIndex == -1) {
return;
}
AssociationWidget * a = m_List.at(currentItemIndex);
ListPopupMenu::MenuType id = ListPopupMenu::typeFromAction(action);
switch (id) {
case ListPopupMenu::mt_Delete:
m_pScene->removeAssocInViewAndDoc(a);
fillListBox();
break;
case ListPopupMenu::mt_Line_Color:
//:TODO:
logDebug0("ClassAssociationsPage::slotMenuSelection: MenuType mt_Line_Color not yet implemented!");
break;
case ListPopupMenu::mt_Properties:
slotDoubleClick(m_pAssocLW->currentItem());
break;
default:
logDebug1("ClassAssociationsPage::slotMenuSelection: MenuType %1 not implemented",
ListPopupMenu::toString(id));
}
}
| 3,966
|
C++
|
.cpp
| 118
| 28.898305
| 107
| 0.709357
|
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,335
|
codeimportoptionspage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/codeimportoptionspage.cpp
|
/*
SPDX-FileCopyrightText: 2011-2014 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-or-later
*/
// own header
#include "codeimportoptionspage.h"
// app includes
#include "optionstate.h"
// qt includes
/**
* Constructor.
* @param parent the parent (wizard) of this wizard page
*/
CodeImportOptionsPage::CodeImportOptionsPage(QWidget *parent)
: DialogPageBase(parent)
{
setupUi(this);
createArtifactCheckBox->setChecked(Settings::optionState().codeImportState.createArtifacts);
resolveDependenciesCheckBox->setChecked(Settings::optionState().codeImportState.resolveDependencies);
supportCPP11CheckBox->setChecked(Settings::optionState().codeImportState.supportCPP11);
}
/**
* destructor
*/
CodeImportOptionsPage::~CodeImportOptionsPage()
{
}
/**
* sets default values
*/
void CodeImportOptionsPage::setDefaults()
{
Settings::CodeImportState dummy;
createArtifactCheckBox->setChecked(dummy.createArtifacts);
resolveDependenciesCheckBox->setChecked(dummy.resolveDependencies);
supportCPP11CheckBox->setChecked(dummy.supportCPP11);
}
/**
* Reads the set values from their corresponding widgets, writes them back to
* the data structure, and notifies clients.
*/
void CodeImportOptionsPage::apply()
{
Settings::optionState().codeImportState.createArtifacts = createArtifactCheckBox->isChecked();
Settings::optionState().codeImportState.resolveDependencies = resolveDependenciesCheckBox->isChecked();
Settings::optionState().codeImportState.supportCPP11 = supportCPP11CheckBox->isChecked();
Q_EMIT applyClicked();
}
| 1,615
|
C++
|
.cpp
| 48
| 31.041667
| 107
| 0.79525
|
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,336
|
notepage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/notepage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "notepage.h"
#include "notewidget.h"
#include "documentationwidget.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QVBoxLayout>
/**
* Constructs an note page.
*/
NotePage::NotePage(QWidget *parent, NoteWidget *note)
: DialogPageBase(parent),
m_noteWidget(note)
{
QVBoxLayout *layout = new QVBoxLayout(this);
m_docWidget = new DocumentationWidget(m_noteWidget);
layout->addWidget(m_docWidget, 10);
setMinimumSize(600, 250);
m_docWidget->setFocus();
}
/**
* Standard destructor.
*/
NotePage::~NotePage()
{
}
bool NotePage::apply()
{
m_docWidget->apply();
return true;
}
| 807
|
C++
|
.cpp
| 36
| 19.916667
| 92
| 0.728702
|
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,337
|
codevieweroptionspage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/codevieweroptionspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Luis De la Parra <luis@delaparra.org>
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codevieweroptionspage.h"
// qt/kde includes
#include <kcolorbutton.h>
CodeViewerOptionsPage::CodeViewerOptionsPage(Settings::CodeViewerState options, QWidget *parent, const char *name)
: DialogPageBase(parent),
m_options(options)
{
setObjectName(QLatin1String(name));
setupUi(this);
// set widget stuff
/*
fontChooser->setFont(options.font);
selectColorButton->setColor (options.selectedColor);
fontColorButton->setColor (options.fontColor);
paperColorButton->setColor (options.paperColor);
editBlockColorButton->setColor (options.editBlockColor);
nonEditBlockColorButton->setColor (options.nonEditBlockColor);
umlObjectColorButton->setColor (options.umlObjectColor);
*/
}
CodeViewerOptionsPage::~CodeViewerOptionsPage()
{
}
void CodeViewerOptionsPage::apply()
{
/*
m_options.umlObjectColor = umlObjectColorButton->color();
m_options.editBlockColor = editBlockColorButton->color();
m_options.nonEditBlockColor = nonEditBlockColorButton->color();
m_options.selectedColor = selectColorButton->color();
m_options.paperColor = paperColorButton->color();
m_options.fontColor = fontColorButton->color();
m_options.font = fontChooser->font();
*/
Q_EMIT applyClicked();
}
Settings::CodeViewerState CodeViewerOptionsPage::getOptions()
{
return m_options;
}
| 1,659
|
C++
|
.cpp
| 46
| 31.195652
| 114
| 0.736744
|
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,338
|
uioptionspage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/uioptionspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "uioptionspage.h"
//// local includes
#include "optionstate.h"
#include "dialog_utils.h"
#include "umbrellosettings.h"
// #include "dialog_utils.h"
#include "selectlayouttypewidget.h"
//// kde includes
#include <KLocalizedString>
#include <KColorButton>
//// qt includes
#include <QCheckBox>
#include <QApplication>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QSpinBox>
/**
* Constructor - observe and modify an OptionState structure
*
* @param pParent Parent widget
* @param options Settings to read from/save into
*/
UIOptionsPage::UIOptionsPage(QWidget* pParent, Settings::OptionState *options)
: DialogPageBase(pParent),
m_options(options)
{
setupPage();
}
/**
* Destructor
*/
UIOptionsPage::~UIOptionsPage()
{
}
/**
* Creates the page with the correct options for the class/interface
*/
void UIOptionsPage::setupPage()
{
int margin = fontMetrics().height();
QVBoxLayout* uiPageLayout = new QVBoxLayout(this);
QGroupBox *box = new QGroupBox(i18nc("General options", "General"), this);
QGridLayout * otherLayout = new QGridLayout(box);
otherLayout->setSpacing(Dialog_Utils::spacingHint());
otherLayout->setContentsMargins(margin, margin, margin, margin);
uiPageLayout->addWidget(box);
m_rightToLeftUI = new QCheckBox(i18n("Right to left user interface"), box);
m_rightToLeftUI->setChecked(UmbrelloSettings::rightToLeftUI());
otherLayout->addWidget(m_rightToLeftUI, 0, 0);
QGroupBox *boxAssocs = new QGroupBox(i18nc("Association options", "Associations"), this);
QGridLayout *layoutAssocs = new QGridLayout(boxAssocs);
layoutAssocs->setContentsMargins(margin, margin, margin, margin);
uiPageLayout->addWidget(boxAssocs);
m_layoutTypeW = new SelectLayoutTypeWidget(i18n("Create new association lines as:"), Settings::optionState().generalState.layoutType, boxAssocs);
m_layoutTypeW->addToLayout(layoutAssocs, 1);
m_colorGB = new QGroupBox(i18nc("color group box", "Color"), this);
QGridLayout * colorLayout = new QGridLayout(m_colorGB);
colorLayout->setSpacing(Dialog_Utils::spacingHint());
colorLayout->setContentsMargins(margin, margin, margin, margin);
uiPageLayout->addWidget(m_colorGB);
uiPageLayout->addItem(new QSpacerItem(0, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));
m_textColorCB = new QCheckBox(i18n("Custom text color"), m_colorGB);
colorLayout->addWidget(m_textColorCB, 0, 0);
m_textColorB = new KColorButton(m_options->uiState.textColor, m_colorGB);
//m_lineColorB->setObjectName(m_colorGB);
colorLayout->addWidget(m_textColorB, 0, 1);
m_lineColorCB = new QCheckBox(i18n("Custom line color"), m_colorGB);
colorLayout->addWidget(m_lineColorCB, 1, 0);
m_lineColorB = new KColorButton(m_options->uiState.lineColor, m_colorGB);
//m_lineColorB->setObjectName(m_colorGB);
colorLayout->addWidget(m_lineColorB, 1, 1);
// m_lineDefaultB = new QPushButton(i18n("D&efault Color"), m_colorGB);
// colorLayout->addWidget(m_lineDefaultB, 0, 2);
m_fillColorCB = new QCheckBox(i18n("Custom fill color"), m_colorGB);
colorLayout->addWidget(m_fillColorCB, 2, 0);
m_fillColorB = new KColorButton(m_options->uiState.fillColor, m_colorGB);
colorLayout->addWidget(m_fillColorB, 2, 1);
m_gridColorCB = new QCheckBox(i18n("Custom grid color"), m_colorGB);
colorLayout->addWidget(m_gridColorCB, 3, 0);
m_gridColorB = new KColorButton(m_options->uiState.gridDotColor, m_colorGB);
colorLayout->addWidget(m_gridColorB, 3, 1);
m_bgColorCB = new QCheckBox(i18n("Custom background color"), m_colorGB);
colorLayout->addWidget(m_bgColorCB, 4, 0);
m_bgColorB = new KColorButton(m_options->uiState.backgroundColor, m_colorGB);
colorLayout->addWidget(m_bgColorB, 4, 1);
m_lineWidthCB = new QCheckBox(i18n("Custom line width"), m_colorGB);
colorLayout->addWidget(m_lineWidthCB, 5, 0);
m_lineWidthB = new QSpinBox(m_colorGB);
m_lineWidthB->setMinimum(0);
m_lineWidthB->setMaximum(10);
m_lineWidthB->setSingleStep(1);
m_lineWidthB->setValue(m_options->uiState.lineWidth);
colorLayout->addWidget(m_lineWidthB, 5, 1);
m_useFillColorCB = new QCheckBox(i18n("&Use fill color"), m_colorGB);
//colorLayout->setRowStretch(3, 2);
colorLayout->addWidget(m_useFillColorCB, 6, 0);
m_useFillColorCB->setChecked(m_options->uiState.useFillColor);
//connect button signals up
connect(m_textColorCB, SIGNAL(toggled(bool)), this, SLOT(slotTextCBChecked(bool)));
connect(m_lineColorCB, SIGNAL(toggled(bool)), this, SLOT(slotLineCBChecked(bool)));
connect(m_fillColorCB, SIGNAL(toggled(bool)), this, SLOT(slotFillCBChecked(bool)));
connect(m_gridColorCB, SIGNAL(toggled(bool)), this, SLOT(slotGridCBChecked(bool)));
connect(m_bgColorCB, SIGNAL(toggled(bool)), this, SLOT(slotBgCBChecked(bool)));
connect(m_lineWidthCB, SIGNAL(toggled(bool)), this, SLOT(slotLineWidthCBChecked(bool)));
// initial setup
slotTextCBChecked(false);
slotLineCBChecked(false);
slotFillCBChecked(false);
slotGridCBChecked(false);
slotBgCBChecked(false);
slotLineWidthCBChecked(false);
}
void UIOptionsPage::setDefaults()
{
m_useFillColorCB->setChecked(true);
m_textColorCB->setChecked(false);
m_lineColorCB->setChecked(false);
m_fillColorCB->setChecked(false);
m_gridColorCB->setChecked(false);
m_bgColorCB->setChecked(false);
m_lineWidthCB->setChecked(false);
slotTextCBChecked(false);
slotLineCBChecked(false);
slotFillCBChecked(false);
slotGridCBChecked(false);
slotBgCBChecked(false);
slotLineWidthCBChecked(false);
m_rightToLeftUI->setChecked(false);
m_layoutTypeW->setCurrentLayout(Uml::LayoutType::Direct);
}
/**
* apply changes
*/
void UIOptionsPage::apply()
{
m_options->uiState.useFillColor = m_useFillColorCB->isChecked();
m_options->uiState.fillColor = m_fillColorB->color();
m_options->uiState.textColor = m_textColorB->color();
m_options->uiState.lineColor = m_lineColorB->color();
m_options->uiState.lineWidth = m_lineWidthB->value();
m_options->uiState.backgroundColor = m_bgColorB->color();
m_options->uiState.gridDotColor = m_gridColorB->color();
m_options->generalState.layoutType = m_layoutTypeW->currentLayout();
UmbrelloSettings::setRightToLeftUI(m_rightToLeftUI->isChecked());
qApp->setLayoutDirection(UmbrelloSettings::rightToLeftUI() ? Qt::RightToLeft : Qt::LeftToRight);
}
void UIOptionsPage::slotTextCBChecked(bool value)
{
if (value == false) {
m_textColorB->setColor(m_options->uiState.textColor);
m_textColorB->setDisabled(true);
}
else {
m_textColorB->setDisabled(false);
}
}
void UIOptionsPage::slotLineCBChecked(bool value)
{
if (value == false) {
m_lineColorB->setColor(m_options->uiState.lineColor);
m_lineColorB->setDisabled(true);
}
else {
m_lineColorB->setDisabled(false);
}
}
void UIOptionsPage::slotFillCBChecked(bool value)
{
if (value == false) {
m_fillColorB->setColor(m_options->uiState.fillColor);
m_fillColorB->setDisabled(true);
}
else {
m_fillColorB->setDisabled(false);
}
}
void UIOptionsPage::slotGridCBChecked(bool value)
{
if (value == false) {
QPalette palette;
m_gridColorB->setColor(palette.alternateBase().color());
m_gridColorB->setDisabled(true);
}
else {
m_gridColorB->setDisabled(false);
}
}
void UIOptionsPage::slotBgCBChecked(bool value)
{
if (value == false) {
QPalette palette;
m_bgColorB->setColor(palette.base().color());
m_bgColorB->setDisabled(true);
}
else {
m_bgColorB->setDisabled(false);
}
}
void UIOptionsPage::slotLineWidthCBChecked(bool value)
{
if (value == false) {
m_lineWidthB->setValue(0);
m_lineWidthB->setDisabled(true);
}
else {
m_lineWidthB->setDisabled(false);
}
}
| 8,212
|
C++
|
.cpp
| 215
| 33.934884
| 149
| 0.721643
|
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,339
|
packagecontentspage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/packagecontentspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "packagecontentspage.h"
#include "classpropertiesdialog.h"
#include "debug_utils.h"
#include "dialogspopupmenu.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobjectlist.h"
#include <KLocalizedString>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QLayout>
#include <QListWidget>
#include <QPointer>
DEBUG_REGISTER(PackageContentsPage)
/**
* Constructs an instance of PackageContentsPage.
* @param parent The parent of the page.
* @param pkg The UMLPackage being represented.
*/
PackageContentsPage::PackageContentsPage(QWidget *parent, UMLPackage *pkg)
: DialogPageBase(parent)
{
m_package = pkg;
int margin = fontMetrics().height();
QHBoxLayout * mainLayout = new QHBoxLayout(this);
mainLayout->setSpacing(10);
m_contentGB = new QGroupBox(i18n("Contained Items"), this);
mainLayout->addWidget(m_contentGB);
QHBoxLayout * layout = new QHBoxLayout(m_contentGB);
layout->setSpacing(10);
layout->setContentsMargins(margin, margin, margin, margin);
m_contentLW = new QListWidget(m_contentGB);
m_contentLW->setContextMenuPolicy(Qt::CustomContextMenu);
layout->addWidget(m_contentLW);
setMinimumSize(310, 330);
fillListBox();
connect(m_contentLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(slotDoubleClick(QListWidgetItem*)));
connect(m_contentLW, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(slotShowContextMenu(QPoint)));
}
/**
* Standard destructor.
*/
PackageContentsPage::~PackageContentsPage()
{
disconnect(m_contentLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(slotDoubleClick(QListWidgetItem*)));
disconnect(m_contentLW, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(slotShowContextMenu(QPoint)));
}
void PackageContentsPage::slotDoubleClick(QListWidgetItem *item)
{
if (!item) {
return;
}
int index = m_contentLW->currentRow();
if (index == -1) {
return;
}
UMLObjectList contents = m_package->containedObjects();
UMLObject *o = contents.at(index);
QPointer<ClassPropertiesDialog> dlg = new ClassPropertiesDialog(this, o, true);
dlg->exec();
delete dlg;
}
/**
* Fills the list box with the package's contents.
*/
void PackageContentsPage::fillListBox()
{
m_contentLW->clear();
UMLObjectList contents = m_package->containedObjects();
UMLObjectListIt objList_it(contents);
UMLObject *umlo = nullptr;
while (objList_it.hasNext()) {
umlo = objList_it.next();
uIgnoreZeroPointer(umlo);
m_contentLW->addItem(umlo->name());
}
}
/**
* Slot for the context menu by right clicking in the list widget.
* @param p point of the right click inside the list widget
*/
void PackageContentsPage::slotShowContextMenu(const QPoint &p)
{
DialogsPopupMenu popup(this, DialogsPopupMenu::tt_Association_Selected);
QAction *triggered = popup.exec(mapToGlobal(p) + QPoint(0, 20));
slotMenuSelection(triggered);
}
void PackageContentsPage::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType id = ListPopupMenu::typeFromAction(action);
switch(id) {
case ListPopupMenu::mt_Delete:
{
UMLObjectList contents = m_package->containedObjects();
if (m_contentLW->currentRow() == -1)
break;
UMLObject *o = contents.at(m_contentLW->currentRow());
UMLApp::app()->document()->removeUMLObject(o);
fillListBox();
}
break;
case ListPopupMenu::mt_Properties:
slotDoubleClick(m_contentLW->item(m_contentLW->currentRow()));
break;
default:
logDebug1("PackageContentsPage::slotMenuSelection: MenuType %1 not implemented",
ListPopupMenu::toString(id));
}
}
| 4,007
|
C++
|
.cpp
| 118
| 29.161017
| 92
| 0.70646
|
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,340
|
activitypage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/activitypage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "activitypage.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "dialogspopupmenu.h"
#include "statewidget.h"
#include "uml.h"
#include <KLocalizedString>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QDialogButtonBox>
#include <QLayout>
#include <QPushButton>
#include <QStringList>
#include <QToolButton>
#include <QVBoxLayout>
DEBUG_REGISTER(ActivityPage)
/**
* Constructor.
*/
ActivityPage::ActivityPage(QWidget * pParent, StateWidget * pWidget)
: DialogPageBase(pParent)
{
m_pStateWidget = pWidget;
setupPage();
}
/**
* Destructor.
*/
ActivityPage::~ActivityPage()
{
}
/**
* Sets up the page.
*/
void ActivityPage::setupPage()
{
int margin = fontMetrics().height();
QVBoxLayout * mainLayout = new QVBoxLayout(this);
mainLayout->setSpacing(10);
m_pActivityGB = new QGroupBox(i18n("Activities"), this);
// vertical box layout for the activity lists, arrow buttons and the button box
QVBoxLayout* listVBoxLayout = new QVBoxLayout(m_pActivityGB);
listVBoxLayout->setContentsMargins(margin, margin, margin, margin);
listVBoxLayout->setSpacing(10);
//horizontal box contains the list box and the move up/down buttons
QHBoxLayout* listHBoxLayout = new QHBoxLayout();
listHBoxLayout->setSpacing(10);
listVBoxLayout->addItem(listHBoxLayout);
m_pActivityLW = new QListWidget(m_pActivityGB);
m_pActivityLW->setContextMenuPolicy(Qt::CustomContextMenu);
listHBoxLayout->addWidget(m_pActivityLW);
QVBoxLayout * buttonLayout = new QVBoxLayout();
listHBoxLayout->addItem(buttonLayout);
m_pTopArrowB = new QToolButton(m_pActivityGB);
m_pTopArrowB->setArrowType(Qt::UpArrow);
m_pTopArrowB->setEnabled(false);
m_pTopArrowB->setToolTip(i18n("Move selected item to the top"));
buttonLayout->addWidget(m_pTopArrowB);
m_pUpArrowB = new QToolButton(m_pActivityGB);
m_pUpArrowB->setArrowType(Qt::UpArrow);
m_pUpArrowB->setEnabled(false);
m_pUpArrowB->setToolTip(i18n("Move selected item up"));
buttonLayout->addWidget(m_pUpArrowB);
m_pDownArrowB = new QToolButton(m_pActivityGB);
m_pDownArrowB->setArrowType(Qt::DownArrow);
m_pDownArrowB->setEnabled(false);
m_pDownArrowB->setToolTip(i18n("Move selected item down"));
buttonLayout->addWidget(m_pDownArrowB);
m_pBottomArrowB = new QToolButton(m_pActivityGB);
m_pBottomArrowB->setArrowType(Qt::DownArrow);
m_pBottomArrowB->setEnabled(false);
m_pBottomArrowB->setToolTip(i18n("Move selected item to the bottom"));
buttonLayout->addWidget(m_pBottomArrowB);
QDialogButtonBox* buttonBox = new QDialogButtonBox(m_pActivityGB);
QPushButton* newActivity = buttonBox->addButton(i18n("New Activity..."), QDialogButtonBox::ActionRole);
connect(newActivity, SIGNAL(clicked()), this, SLOT(slotNewActivity()));
m_pDeleteActivityButton = buttonBox->addButton(i18n("Delete"), QDialogButtonBox::ActionRole);
connect(m_pDeleteActivityButton, SIGNAL(clicked()), this, SLOT(slotDelete()));
m_pRenameButton = buttonBox->addButton(i18n("Rename"), QDialogButtonBox::ActionRole);
connect(m_pRenameButton, SIGNAL(clicked()), this, SLOT(slotRename()));
listVBoxLayout->addWidget(buttonBox);
mainLayout->addWidget(m_pActivityGB);
//now fill activity list box
QStringList list = m_pStateWidget->activities();
QStringList::ConstIterator end(list.end());
for(QStringList::ConstIterator it(list.begin()); it != end; ++it) {
m_pActivityLW->addItem(*it);
}
//now setup the signals
connect(m_pActivityLW, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotClicked(QListWidgetItem*)));
connect(m_pActivityLW, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(slotRightButtonPressed(QPoint)));
connect(m_pTopArrowB, SIGNAL(clicked()), this, SLOT(slotTopClicked()));
connect(m_pUpArrowB, SIGNAL(clicked()), this, SLOT(slotUpClicked()));
connect(m_pDownArrowB, SIGNAL(clicked()), this, SLOT(slotDownClicked()));
connect(m_pBottomArrowB, SIGNAL(clicked()), this, SLOT(slotBottomClicked()));
connect(m_pActivityLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(slotDoubleClicked(QListWidgetItem*)));
enableWidgets(false);
}
/**
* Sets the activities of the widget.
*/
void ActivityPage::updateActivities()
{
QStringList list;
int count = m_pActivityLW->count();
for (int i = 0; i < count; ++i) {
list.append(m_pActivityLW->item(i)->text());
}
m_pStateWidget->setActivities(list);
}
/**
* Popup menu item selected.
*/
void ActivityPage::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_New_Activity:
slotNewActivity();
break;
case ListPopupMenu::mt_Delete:
slotDelete();
break;
case ListPopupMenu::mt_Rename:
slotRename();
break;
default:
logDebug1("ActivityPage::slotMenuSelection: MenuType %1 not implemented",
ListPopupMenu::toString(sel));
}
}
void ActivityPage::slotNewActivity()
{
QString name;
if (Dialog_Utils::askDefaultNewName(WidgetBase::wt_Activity, name) && name.length() > 0) {
m_pActivityLW->addItem(name);
m_pActivityLW->setCurrentRow(m_pActivityLW->count() - 1);
m_pStateWidget->addActivity(name);
slotClicked(m_pActivityLW->item(m_pActivityLW->count() - 1));
}
}
void ActivityPage::slotDelete()
{
QString name = m_pActivityLW->currentItem()->text();
m_pStateWidget->removeActivity(name);
m_pActivityLW->takeItem(m_pActivityLW->currentRow());
slotClicked(nullptr);
}
void ActivityPage::slotRename()
{
QString name = m_pActivityLW->currentItem()->text();
QString oldName = name;
bool ok = Dialog_Utils::askRenameName(WidgetBase::wt_Activity, name);
if (ok && name.length() > 0) {
QListWidgetItem* item = m_pActivityLW->currentItem();
item->setText(name);
m_pStateWidget->renameActivity(oldName, name);
slotClicked(item);
}
}
void ActivityPage::slotRightButtonPressed(const QPoint & p)
{
DialogsPopupMenu::TriggerType type = DialogsPopupMenu::tt_Undefined;
QListWidgetItem* item = m_pActivityLW->itemAt(p);
if (item) { //pressed on an item
type = DialogsPopupMenu::tt_Activity_Selected;
} else { //pressed into fresh air
type = DialogsPopupMenu::tt_New_Activity;
}
DialogsPopupMenu popup(this, type);
QAction *triggered = popup.exec(m_pActivityLW->mapToGlobal(p));
slotMenuSelection(triggered);
}
void ActivityPage::slotTopClicked()
{
int count = m_pActivityLW->count();
int index = m_pActivityLW->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index <= 0)
return;
//swap the text around in the ListBox
QListWidgetItem* item = m_pActivityLW->takeItem(index);
m_pActivityLW->insertItem(0, item);
//set the moved item selected
m_pActivityLW->setCurrentRow(0);
slotClicked(m_pActivityLW->currentItem());
}
void ActivityPage::slotUpClicked()
{
int count = m_pActivityLW->count();
int index = m_pActivityLW->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index <= 0) {
return;
}
QListWidgetItem* item = m_pActivityLW->takeItem(index);
m_pActivityLW->insertItem(index - 1, item);
//set the moved attribute selected
m_pActivityLW->setCurrentRow(index - 1);
slotClicked(m_pActivityLW->currentItem());
}
void ActivityPage::slotDownClicked()
{
int count = m_pActivityLW->count();
int index = m_pActivityLW->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index >= count - 1) {
return;
}
QListWidgetItem* item = m_pActivityLW->takeItem(index);
m_pActivityLW->insertItem(index + 1, item);
//set the moved attribute selected
m_pActivityLW->setCurrentRow(index + 1);
slotClicked(m_pActivityLW->currentItem());
}
void ActivityPage::slotBottomClicked()
{
int count = m_pActivityLW->count();
int index = m_pActivityLW->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index >= count - 1)
return;
QListWidgetItem* item = m_pActivityLW->takeItem(index);
m_pActivityLW->insertItem(m_pActivityLW->count(), item);
//set the moved item selected
m_pActivityLW->setCurrentRow(m_pActivityLW->count() - 1);
slotClicked(m_pActivityLW->currentItem());
}
void ActivityPage::slotClicked(QListWidgetItem *item)
{
//make sure clicked on an item
if (!item) {
enableWidgets(false);
m_pActivityLW->clearSelection();
} else {
enableWidgets(true);
}
}
void ActivityPage::slotDoubleClicked(QListWidgetItem* item)
{
if (item) {
slotRename();
}
}
/**
* Set the state of the widgets on the page with the given value.
* @param state The state to set the widgets as.
*/
void ActivityPage::enableWidgets(bool state)
{
if (!state) {
m_pTopArrowB->setEnabled(false);
m_pUpArrowB->setEnabled(false);
m_pDownArrowB->setEnabled(false);
m_pBottomArrowB->setEnabled(false);
m_pDeleteActivityButton->setEnabled(false);
m_pRenameButton->setEnabled(false);
return;
}
/*now check the order buttons.
Double check an item is selected
If only one att. in list make sure there disabled.
If at top item, only allow down arrow to be enabled.
If at bottom item. only allow up arrow to be enabled.
*/
int index = m_pActivityLW->currentRow();
if (m_pActivityLW->count() == 1 || index == -1) {
m_pTopArrowB->setEnabled(false);
m_pUpArrowB->setEnabled(false);
m_pDownArrowB->setEnabled(false);
m_pBottomArrowB->setEnabled(false);
} else if (index == 0) {
m_pTopArrowB->setEnabled(false);
m_pUpArrowB->setEnabled(false);
m_pDownArrowB->setEnabled(true);
m_pBottomArrowB->setEnabled(true);
} else if(index == (int)m_pActivityLW->count() - 1) {
m_pTopArrowB->setEnabled(true);
m_pUpArrowB->setEnabled(true);
m_pDownArrowB->setEnabled(false);
m_pBottomArrowB->setEnabled(false);
} else {
m_pTopArrowB->setEnabled(true);
m_pUpArrowB->setEnabled(true);
m_pDownArrowB->setEnabled(true);
m_pBottomArrowB->setEnabled(true);
}
m_pDeleteActivityButton->setEnabled(true);
m_pRenameButton->setEnabled(true);
}
| 10,754
|
C++
|
.cpp
| 296
| 31.486486
| 121
| 0.699692
|
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,341
|
associationrolepage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/associationrolepage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "associationrolepage.h"
// local includes
#include "associationwidget.h"
#include "dialog_utils.h"
#include "objectwidget.h"
#include "umldoc.h"
#include "umlobject.h"
#include "visibilityenumwidget.h"
// kde includes
#include <kcombobox.h>
#include <klineedit.h>
#include <KLocalizedString>
#include <KMessageBox>
#include <QTextEdit>
// qt includes
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayout>
#include <QRadioButton>
/**
* Sets up the AssociationRolePage.
* @param parent The parent to the AssociationRolePage.
* @param assoc The AssociationWidget to display the properties of.
*/
AssociationRolePage::AssociationRolePage (QWidget *parent, AssociationWidget *assoc)
: DialogPageBase(parent),
m_pRoleALE(nullptr),
m_pRoleBLE(nullptr),
m_pMultiACB(nullptr),
m_pMultiBCB(nullptr),
m_pAssociationWidget(assoc),
m_pWidget(nullptr)
{
constructWidget();
}
/**
* Standard destructor.
*/
AssociationRolePage::~AssociationRolePage()
{
}
void AssociationRolePage::constructWidget()
{
// underlying roles and objects
QString nameA = m_pAssociationWidget->roleName(Uml::RoleType::A);
QString nameB = m_pAssociationWidget->roleName(Uml::RoleType::B);
QString titleA = i18n("Role A Properties");
QString titleB = i18n("Role B Properties");
QString widgetNameA = m_pAssociationWidget->widgetForRole(Uml::RoleType::A)->name();
QString widgetNameB = m_pAssociationWidget->widgetForRole(Uml::RoleType::B)->name();
if(!widgetNameA.isEmpty())
titleA.append(QStringLiteral(" (") + widgetNameA + QLatin1Char(')'));
if(!widgetNameB.isEmpty())
titleB.append(QStringLiteral(" (") + widgetNameB + QLatin1Char(')'));
// general configuration of the GUI
int margin = fontMetrics().height();
QGridLayout * mainLayout = new QGridLayout(this);
mainLayout->setSpacing(6);
// group boxes for role, documentation properties
QGroupBox *propsAGB = new QGroupBox(this);
QGroupBox *propsBGB = new QGroupBox(this);
QGroupBox *changeABG = new QGroupBox(i18n("Role A Changeability"), this);
QGroupBox *changeBBG = new QGroupBox(i18n("Role B Changeability"), this);
QGroupBox *docAGB = new QGroupBox(this);
QGroupBox *docBGB = new QGroupBox(this);
propsAGB->setTitle(titleA);
propsBGB->setTitle(titleB);
docAGB->setTitle(i18n("Documentation"));
docBGB->setTitle(i18n("Documentation"));
QGridLayout * propsALayout = new QGridLayout(propsAGB);
propsALayout->setSpacing(6);
QGridLayout * propsBLayout = new QGridLayout(propsBGB);
propsBLayout->setSpacing(6);
propsBLayout->setContentsMargins(margin, margin, margin, margin);;
QStringList multiplicities;
multiplicities << QString()
<< QStringLiteral("1")
<< QStringLiteral("*")
<< QStringLiteral("1..*")
<< QStringLiteral("0..1");
// Properties
//
// Rolename A
QLabel *pRoleAL = nullptr;
Dialog_Utils::makeLabeledEditField(propsALayout, 0,
pRoleAL, i18n("Rolename:"),
m_pRoleALE, nameA);
// Multi A
QLabel *pMultiAL = nullptr;
pMultiAL = new QLabel(i18n("Multiplicity:"), propsAGB);
m_pMultiACB = new KComboBox(propsAGB);
m_pMultiACB->addItems(multiplicities);
m_pMultiACB->setDuplicatesEnabled(false);
m_pMultiACB->setEditable(true);
QString multiA = m_pAssociationWidget->multiplicity(Uml::RoleType::A);
if (!multiA.isEmpty())
m_pMultiACB->setEditText(multiA);
propsALayout->addWidget(pMultiAL, 1, 0);
propsALayout->addWidget(m_pMultiACB, 1, 1);
m_visibilityWidgetA = new VisibilityEnumWidget(m_pAssociationWidget, Uml::RoleType::A, this);
mainLayout->addWidget(m_visibilityWidgetA, 1, 0);
// Changeability A
QHBoxLayout * changeALayout = new QHBoxLayout(changeABG);
changeALayout->setContentsMargins(margin, margin, margin, margin);;
m_ChangeableARB = new QRadioButton(i18nc("changeability for A is changeable", "Changeable"), changeABG);
changeALayout->addWidget(m_ChangeableARB);
m_FrozenARB = new QRadioButton(i18nc("changeability for A is frozen", "Frozen"), changeABG);
changeALayout->addWidget(m_FrozenARB);
m_AddOnlyARB = new QRadioButton(i18nc("changeability for A is add only", "Add only"), changeABG);
changeALayout->addWidget(m_AddOnlyARB);
switch (m_pAssociationWidget->changeability(Uml::RoleType::A)) {
case Uml::Changeability::Changeable:
m_ChangeableARB->setChecked(true);
break;
case Uml::Changeability::Frozen:
m_FrozenARB->setChecked(true);
break;
default:
m_AddOnlyARB->setChecked(true);
break;
}
// Rolename B
QLabel *pRoleBL = nullptr;
Dialog_Utils::makeLabeledEditField(propsBLayout, 0,
pRoleBL, i18n("Rolename:"),
m_pRoleBLE, nameB);
// Multi B
QLabel *pMultiBL = nullptr;
pMultiBL = new QLabel(i18n("Multiplicity:"), propsBGB);
m_pMultiBCB = new KComboBox(propsBGB);
m_pMultiBCB->addItems(multiplicities);
m_pMultiBCB->setDuplicatesEnabled(false);
m_pMultiBCB->setEditable(true);
QString multiB = m_pAssociationWidget->multiplicity(Uml::RoleType::B);
if (!multiB.isEmpty())
m_pMultiBCB->setEditText(multiB);
propsBLayout->addWidget(pMultiBL, 1, 0);
propsBLayout->addWidget(m_pMultiBCB, 1, 1);
m_visibilityWidgetB = new VisibilityEnumWidget(m_pAssociationWidget, Uml::RoleType::B, this);
mainLayout->addWidget(m_visibilityWidgetB, 1, 1);
// Changeability B
QHBoxLayout * changeBLayout = new QHBoxLayout(changeBBG);
changeBLayout->setContentsMargins(margin, margin, margin, margin);;
m_ChangeableBRB = new QRadioButton(i18nc("changeability for B is changeable", "Changeable"), changeBBG);
changeBLayout->addWidget(m_ChangeableBRB);
m_FrozenBRB = new QRadioButton(i18nc("changeability for B is frozen", "Frozen"), changeBBG);
changeBLayout->addWidget(m_FrozenBRB);
m_AddOnlyBRB = new QRadioButton(i18nc("changeability for B is add only", "Add only"), changeBBG);
changeBLayout->addWidget(m_AddOnlyBRB);
switch (m_pAssociationWidget->changeability(Uml::RoleType::B)) {
case Uml::Changeability::Changeable:
m_ChangeableBRB->setChecked(true);
break;
case Uml::Changeability::Frozen:
m_FrozenBRB->setChecked(true);
break;
default:
m_AddOnlyBRB->setChecked(true);
break;
}
// Documentation
//
// Document A
QHBoxLayout * docALayout = new QHBoxLayout(docAGB);
docALayout->setContentsMargins(margin, margin, margin, margin);;
m_docA = new QTextEdit(docAGB);
docALayout->addWidget(m_docA);
m_docA-> setText(m_pAssociationWidget->roleDocumentation(Uml::RoleType::A));
// m_docA->setText("<<not implemented yet>>");
// m_docA->setEnabled(false);
m_docA->setLineWrapMode(QTextEdit::WidgetWidth);
// Document B
QHBoxLayout * docBLayout = new QHBoxLayout(docBGB);
docBLayout->setContentsMargins(margin, margin, margin, margin);;
m_docB = new QTextEdit(docBGB);
docBLayout->addWidget(m_docB);
m_docB->setText(m_pAssociationWidget->roleDocumentation(Uml::RoleType::B));
// m_docB->setEnabled(false);
m_docB->setLineWrapMode(QTextEdit::WidgetWidth);
// add group boxes to main layout
mainLayout->addWidget(propsAGB, 0, 0);
mainLayout->addWidget(changeABG, 2, 0);
mainLayout->addWidget(docAGB, 3, 0);
mainLayout->addWidget(propsBGB, 0, 1);
mainLayout->addWidget(changeBBG, 2, 1);
mainLayout->addWidget(docBGB, 3, 1);
}
/**
* Will move information from the dialog into the object.
* Call when the ok or apply button is pressed.
*/
void AssociationRolePage::apply()
{
if (m_pAssociationWidget) {
// set props
m_pAssociationWidget->setRoleName(m_pRoleALE->text(), Uml::RoleType::A);
m_pAssociationWidget->setRoleName(m_pRoleBLE->text(), Uml::RoleType::B);
m_pAssociationWidget->setMultiplicity(m_pMultiACB->currentText(), Uml::RoleType::A);
m_pAssociationWidget->setMultiplicity(m_pMultiBCB->currentText(), Uml::RoleType::B);
m_visibilityWidgetA->apply();
m_visibilityWidgetB->apply();
if (m_FrozenARB->isChecked())
m_pAssociationWidget->setChangeability(Uml::Changeability::Frozen, Uml::RoleType::A);
else if (m_AddOnlyARB->isChecked())
m_pAssociationWidget->setChangeability(Uml::Changeability::AddOnly, Uml::RoleType::A);
else
m_pAssociationWidget->setChangeability(Uml::Changeability::Changeable, Uml::RoleType::A);
if (m_FrozenBRB->isChecked())
m_pAssociationWidget->setChangeability(Uml::Changeability::Frozen, Uml::RoleType::B);
else if (m_AddOnlyBRB->isChecked())
m_pAssociationWidget->setChangeability(Uml::Changeability::AddOnly, Uml::RoleType::B);
else
m_pAssociationWidget->setChangeability(Uml::Changeability::Changeable, Uml::RoleType::B);
m_pAssociationWidget->setRoleDocumentation(m_docA->toPlainText(), Uml::RoleType::A);
m_pAssociationWidget->setRoleDocumentation(m_docB->toPlainText(), Uml::RoleType::B);
} //end if m_pAssociationWidget
}
| 9,624
|
C++
|
.cpp
| 224
| 36.977679
| 108
| 0.696493
|
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,342
|
autolayoutoptionpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/autolayoutoptionpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "autolayoutoptionpage.h"
// local includes
#include "layoutgenerator.h"
// kde includes
#include <QLineEdit>
#include <KLocalizedString>
// qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
/**
* Constructor.general
* @param parent the parent (wizard) of this wizard page
*/
AutoLayoutOptionPage::AutoLayoutOptionPage(QWidget* parent)
: DialogPageBase(parent)
{
setupUi(this);
m_autoDotPath->setChecked(Settings::optionState().autoLayoutState.autoDotPath);
m_dotPath->setText(Settings::optionState().autoLayoutState.dotPath);
m_showExportLayout->setChecked(Settings::optionState().autoLayoutState.showExportLayout);
connect(m_autoDotPath, SIGNAL(toggled(bool)), this, SLOT(slotAutoDotPathCBClicked(bool)));
if (Settings::optionState().autoLayoutState.autoDotPath) {
m_dotPath->setEnabled (false);
m_dotPath->setText(LayoutGenerator::currentDotPath());
}
}
/**
* destructor
*/
AutoLayoutOptionPage::~AutoLayoutOptionPage()
{
}
/**
* sets default values
*/
void AutoLayoutOptionPage::setDefaults()
{
m_autoDotPath->setChecked(true);
m_showExportLayout->setChecked(false);
}
/**
* Reads the set values from their corresponding widgets, writes them back to
* the data structure, and notifies clients.
*/
void AutoLayoutOptionPage::apply()
{
Settings::optionState().autoLayoutState.autoDotPath = m_autoDotPath->isChecked();
Settings::optionState().autoLayoutState.dotPath = m_autoDotPath->isChecked() ? QString()
: m_dotPath->text();
Settings::optionState().autoLayoutState.showExportLayout = m_showExportLayout->isChecked();
Q_EMIT applyClicked();
}
void AutoLayoutOptionPage::slotAutoDotPathCBClicked(bool value)
{
if (value)
m_dotPath->setText(LayoutGenerator::currentDotPath());
}
| 2,124
|
C++
|
.cpp
| 66
| 28.287879
| 101
| 0.733398
|
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,343
|
generaloptionpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/generaloptionpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "generaloptionpage.h"
// local includes
#include "dialog_utils.h"
#include "selectlayouttypewidget.h"
#include "optionstate.h"
// kde includes
#include <KComboBox>
#include <KLocalizedString>
// qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QRadioButton>
#include <QSpinBox>
/**
* Constructor.
* @param parent the parent (wizard) of this wizard page
*/
GeneralOptionPage::GeneralOptionPage(QWidget* parent)
: DialogPageBase(parent)
{
Settings::OptionState &optionState = Settings::optionState();
int spacingHint = Dialog_Utils::spacingHint();
int margin = fontMetrics().height();
QVBoxLayout *topLayout = new QVBoxLayout(this);
// Set up undo setting
m_GeneralWidgets.miscGB = new QGroupBox(i18nc("miscellaneous group box", "Miscellaneous"));
topLayout->addWidget(m_GeneralWidgets.miscGB);
QGridLayout * miscLayout = new QGridLayout(m_GeneralWidgets.miscGB);
miscLayout->setSpacing(spacingHint);
miscLayout->setContentsMargins(margin, margin, margin, margin);
m_GeneralWidgets.undoCB = new QCheckBox(i18n("Enable undo"), m_GeneralWidgets.miscGB);
m_GeneralWidgets.undoCB->setChecked(optionState.generalState.undo);
miscLayout->addWidget(m_GeneralWidgets.undoCB, 0, 0);
m_GeneralWidgets.tabdiagramsCB = new QCheckBox(i18n("Use tabbed diagrams"), m_GeneralWidgets.miscGB);
m_GeneralWidgets.tabdiagramsCB->setChecked(optionState.generalState.tabdiagrams);
miscLayout->addWidget(m_GeneralWidgets.tabdiagramsCB, 0, 1);
#ifdef ENABLE_NEW_CODE_GENERATORS
m_GeneralWidgets.newcodegenCB = new QCheckBox(i18n("Use new C++/Java/Ruby generators"), m_GeneralWidgets.miscGB);
m_GeneralWidgets.newcodegenCB->setChecked(optionState.generalState.newcodegen);
miscLayout->addWidget(m_GeneralWidgets.newcodegenCB, 1, 0);
#endif
m_GeneralWidgets.footerPrintingCB = new QCheckBox(i18n("Turn on footer and page numbers when printing"), m_GeneralWidgets.miscGB);
m_GeneralWidgets.footerPrintingCB->setChecked(optionState.generalState.footerPrinting);
miscLayout->addWidget(m_GeneralWidgets.footerPrintingCB, 2, 0);
m_GeneralWidgets.uml2CB = new QCheckBox(i18n("Enable UML2 support"), m_GeneralWidgets.miscGB);
m_GeneralWidgets.uml2CB->setChecked(optionState.generalState.uml2);
miscLayout->addWidget(m_GeneralWidgets.uml2CB, 2, 1);
//setup autosave settings
m_GeneralWidgets.autosaveGB = new QGroupBox(i18n("Autosave"));
topLayout->addWidget(m_GeneralWidgets.autosaveGB);
QGridLayout * autosaveLayout = new QGridLayout(m_GeneralWidgets.autosaveGB);
autosaveLayout->setSpacing(spacingHint);
autosaveLayout->setContentsMargins(margin, margin, margin, margin);
m_GeneralWidgets.autosaveCB = new QCheckBox(i18n("E&nable autosave"), m_GeneralWidgets.autosaveGB);
m_GeneralWidgets.autosaveCB->setChecked(optionState.generalState.autosave);
autosaveLayout->addWidget(m_GeneralWidgets.autosaveCB, 0, 0);
m_GeneralWidgets.autosaveL = new QLabel(i18n("Select auto-save time interval (mins):"), m_GeneralWidgets.autosaveGB);
autosaveLayout->addWidget(m_GeneralWidgets.autosaveL, 1, 0);
m_GeneralWidgets.timeISB = new QSpinBox(m_GeneralWidgets.autosaveGB);
m_GeneralWidgets.timeISB->setRange(1, 600);
m_GeneralWidgets.timeISB->setSingleStep(1);
m_GeneralWidgets.timeISB->setValue(optionState.generalState.autosavetime);
m_GeneralWidgets.timeISB->setEnabled(optionState.generalState.autosave);
autosaveLayout->addWidget(m_GeneralWidgets.timeISB, 1, 1);
// Allow definition of Suffix for autosave (default: ".xmi")generator
Dialog_Utils::makeLabeledEditField(autosaveLayout, 2,
m_GeneralWidgets.autosaveSuffixL, i18n("Set autosave suffix:"),
m_GeneralWidgets.autosaveSuffixT, optionState.generalState.autosavesuffix);
QString autoSaveSuffixToolTip = i18n("<qt><p>The autosave file will be saved to ~/autosave.xmi if the autosaving occurs "
"before you have manually saved the file.</p>"
"<p>If you have already saved it, the autosave file will be saved in the same folder as the file "
"and will be named like the file's name, followed by the suffix specified.</p>"
"<p>If the suffix is equal to the suffix of the file you have saved, "
"the autosave will overwrite your file automatically.</p></qt>");
m_GeneralWidgets.autosaveSuffixL->setToolTip(autoSaveSuffixToolTip);
m_GeneralWidgets.autosaveSuffixT->setToolTip(autoSaveSuffixToolTip);
topLayout->addWidget(m_GeneralWidgets.autosaveGB);
//setup startup settings
m_GeneralWidgets.startupGB = new QGroupBox(i18n("Startup"));
topLayout->addWidget(m_GeneralWidgets.startupGB);
QGridLayout * startupLayout = new QGridLayout(m_GeneralWidgets.startupGB);
startupLayout->setSpacing(Dialog_Utils::spacingHint());
m_GeneralWidgets.loadlastCB = new QCheckBox(i18n("&Load last project"), m_GeneralWidgets.startupGB);
m_GeneralWidgets.loadlastCB->setChecked(optionState.generalState.loadlast);
startupLayout->addWidget(m_GeneralWidgets.loadlastCB, 0, 0);
m_GeneralWidgets.startL = new QLabel(i18n("Start new project with:"), m_GeneralWidgets.startupGB);
startupLayout->addWidget(m_GeneralWidgets.startL, 1, 0);
m_GeneralWidgets.diagramKB = new KComboBox(m_GeneralWidgets.startupGB);
startupLayout->addWidget(m_GeneralWidgets.diagramKB, 1, 1);
// start at 1 because we don't allow No Diagram any more
// diagramNo 1 is Uml::DiagramType::Class
// digaramNo 9 is Uml::DiagramType::EntityRelationship
for (int diagramNo = 1; diagramNo < 10; ++diagramNo) {
Uml::DiagramType::Enum dt = Uml::DiagramType::fromInt(diagramNo);
insertDiagram(Uml::DiagramType::toString(dt), diagramNo - 1);
}
m_GeneralWidgets.diagramKB->setCurrentIndex((int)optionState.generalState.diagram-1);
connect(m_GeneralWidgets.autosaveCB, SIGNAL(clicked()), this, SLOT(slotAutosaveCBClicked()));
m_GeneralWidgets.defaultLanguageL = new QLabel(i18n("Default Language :"), m_GeneralWidgets.startupGB);
startupLayout->addWidget(m_GeneralWidgets.defaultLanguageL, 2, 0);
m_GeneralWidgets.languageKB = new KComboBox(m_GeneralWidgets.startupGB);
startupLayout->addWidget(m_GeneralWidgets.languageKB, 2, 1);
int indexCounter = 0;
while (indexCounter < Uml::ProgrammingLanguage::Reserved) {
QString language = Uml::ProgrammingLanguage::toString(Uml::ProgrammingLanguage::fromInt(indexCounter));
m_GeneralWidgets.languageKB->insertItem(indexCounter, language);
indexCounter++;
}
m_GeneralWidgets.languageKB->setCurrentIndex(optionState.generalState.defaultLanguage);
topLayout->addWidget(m_GeneralWidgets.startupGB);
}
/**
* Destructor.
*/
GeneralOptionPage::~GeneralOptionPage()
{
}
/**
* Sets default values.
*/
void GeneralOptionPage::setDefaults()
{
m_GeneralWidgets.autosaveCB->setChecked(false);
m_GeneralWidgets.timeISB->setValue(5);
m_GeneralWidgets.timeISB->setEnabled(true);
m_GeneralWidgets.loadlastCB->setChecked(true);
m_GeneralWidgets.diagramKB->setCurrentIndex(0);
m_GeneralWidgets.languageKB->setCurrentIndex(Uml::ProgrammingLanguage::Cpp);
}
/**
* Reads the set values from their corresponding widgets, writes them back to
* the data structure, and notifies clients.
*/
void GeneralOptionPage::apply()
{
Settings::OptionState &optionState = Settings::optionState();
optionState.generalState.undo = m_GeneralWidgets.undoCB->isChecked();
optionState.generalState.tabdiagrams = m_GeneralWidgets.tabdiagramsCB->isChecked();
#ifdef ENABLE_NEW_CODE_GENERATORS
optionState.generalState.newcodegen = m_GeneralWidgets.newcodegenCB->isChecked();
#endif
optionState.generalState.footerPrinting = m_GeneralWidgets.footerPrintingCB->isChecked();
optionState.generalState.uml2 = m_GeneralWidgets.uml2CB->isChecked();
optionState.generalState.autosave = m_GeneralWidgets.autosaveCB->isChecked();
optionState.generalState.autosavetime = m_GeneralWidgets.timeISB->value();
// retrieve Suffix setting from dialog entry
optionState.generalState.autosavesuffix = m_GeneralWidgets.autosaveSuffixT->text();
optionState.generalState.loadlast = m_GeneralWidgets.loadlastCB->isChecked();
optionState.generalState.diagram = Uml::DiagramType::fromInt(m_GeneralWidgets.diagramKB->currentIndex() + 1);
optionState.generalState.defaultLanguage = Uml::ProgrammingLanguage::fromInt(m_GeneralWidgets.languageKB->currentIndex());
Q_EMIT applyClicked();
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
*/
void GeneralOptionPage::insertDiagram(const QString& type, int index)
{
m_GeneralWidgets.diagramKB->insertItem(index, type);
m_GeneralWidgets.diagramKB->completionObject()->addItem(type);
}
/**
* Slot for clicked event.
*/
void GeneralOptionPage::slotAutosaveCBClicked()
{
m_GeneralWidgets.timeISB->setEnabled(m_GeneralWidgets.autosaveCB->isChecked());
}
| 9,514
|
C++
|
.cpp
| 176
| 48.448864
| 161
| 0.748898
|
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,344
|
umlroleproperties.cpp
|
KDE_umbrello/umbrello/dialogs/pages/umlroleproperties.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlroleproperties.h"
// kde includes
#include <KLocalizedString>
UMLRoleProperties::UMLRoleProperties (QWidget *parent, UMLRole *role)
: UMLRolePropertiesBase (parent)
{
m_pRole = role;
constructWidget();
}
UMLRoleProperties::~UMLRoleProperties()
{
}
void UMLRoleProperties::constructWidget()
{
// Use Parent Role to set starting Properties
// Rolename
ui_pRoleLE->setText(m_pRole->name());
// Multiplicity
ui_pMultiLE->setText(m_pRole->multiplicity());
// Visibility
switch (m_pRole->visibility()) {
case Uml::Visibility::Public:
ui_pPublicRB->setChecked(true);
break;
case Uml::Visibility::Private:
ui_pPrivateRB->setChecked(true);
break;
case Uml::Visibility::Protected:
ui_pProtectedRB->setChecked(true);
break;
case Uml::Visibility::Implementation:
ui_pImplementationRB->setChecked(true);
break;
default:
break;
}
// Changeability
switch (m_pRole->changeability()) {
case Uml::Changeability::Changeable:
ui_pChangeableRB->setChecked(true);
break;
case Uml::Changeability::Frozen:
ui_pFrozenRB->setChecked(true);
break;
default:
ui_pAddOnlyRB->setChecked(true);
break;
}
// Documentation
ui_pDocTE->setText(m_pRole->doc());
//ui_pDocTE->setWordWrap(QMultiLineEdit::WidgetWidth);
}
/**
* Will move information from the dialog into the object.
* Call when the ok or apply button is pressed.
*/
void UMLRoleProperties::apply()
{
if (m_pRole) {
// block signals to save work load. we only need to emit modified once,
// not each time we update an attribute of the association. I suppose
// we could check to see IF anything changed, but thats a lot more code,
// and not much gained. This way is easier, if less 'beautiful'. -b.t.
m_pRole->blockSignals(true);
// set props
m_pRole->setName(ui_pRoleLE->text());
m_pRole->setMultiplicity(ui_pMultiLE->text());
if (ui_pPrivateRB->isChecked())
m_pRole->setVisibility(Uml::Visibility::Private);
else if (ui_pProtectedRB->isChecked())
m_pRole->setVisibility(Uml::Visibility::Protected);
else if (ui_pPublicRB->isChecked())
m_pRole->setVisibility(Uml::Visibility::Public);
else if (ui_pImplementationRB->isChecked())
m_pRole->setVisibility(Uml::Visibility::Implementation);
if (ui_pFrozenRB->isChecked())
m_pRole->setChangeability(Uml::Changeability::Frozen);
else if (ui_pAddOnlyRB->isChecked())
m_pRole->setChangeability(Uml::Changeability::AddOnly);
else
m_pRole->setChangeability(Uml::Changeability::Changeable);
m_pRole->setDoc(ui_pDocTE->toPlainText());
m_pRole->blockSignals(false);
m_pRole->emitModified();
} //end if m_pRole
}
| 3,131
|
C++
|
.cpp
| 91
| 28.032967
| 92
| 0.659497
|
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,345
|
selectoperationpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/selectoperationpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "selectoperationpage.h"
// local includes
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "documentationwidget.h"
#include "messagewidget.h"
#include "operation.h"
#include "umlclassifierlistitemlist.h"
#include "umlscene.h"
#include "umlview.h"
#include "dialog_utils.h"
// kde includes
#include <QLineEdit>
#include <kcombobox.h>
#include <KLocalizedString>
// qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QPushButton>
#include <QRadioButton>
#include <QVBoxLayout>
static bool caseInsensitiveLessThan(const UMLOperation *s1, const UMLOperation *s2)
{
return s1->name().toLower() < s2->name().toLower();
}
/**
* Constructs a SelectOperationPage instance.
*
* @param parent The parent to this instance.
* @param c The classifier to get the operations from.
* @param widget The @ref LinkWidget with which the operation is associated on diagram
* @param enableAutoIncrement Flag to enable auto increment checkbox
*/
SelectOperationPage::SelectOperationPage(UMLView *parent, UMLClassifier *c, LinkWidget *widget, bool enableAutoIncrement)
: DialogPageBase(parent),
m_id(CUSTOM),
m_pView(parent),
m_classifier(c),
m_widget(widget),
m_enableAutoIncrement(false)
{
QVBoxLayout * topLayout = new QVBoxLayout(this);
m_pOpGB = new QGroupBox(i18n("Select Operation"));
topLayout->addWidget(m_pOpGB);
QGridLayout * mainLayout = new QGridLayout(m_pOpGB);
Dialog_Utils::makeLabeledEditField(mainLayout, 0,
m_pSeqL, i18n("Sequence number:"),
m_pSeqLE);
m_pOpAS = new QCheckBox(i18n("Auto increment:"), m_pOpGB);
mainLayout->addWidget(m_pOpAS, 0, 2);
connect(m_pOpAS, SIGNAL(toggled(bool)), this, SLOT(slotAutoIncrementChecked(bool)));
m_pOpAS->setEnabled(enableAutoIncrement);
m_pOpRB = new QLabel(i18n("Class operation:"), m_pOpGB);
mainLayout->addWidget(m_pOpRB, 1, 0);
m_pOpCB = new KComboBox(m_pOpGB);
m_pOpCB->setDuplicatesEnabled(false); // only allow one of each type in box
connect(m_pOpCB, SIGNAL(currentIndexChanged(int)), this, SLOT(slotIndexChanged(int)));
mainLayout->addWidget(m_pOpCB, 1, 1, 1, 2);
m_newOperationButton = new QPushButton(i18n("New Operation..."), m_pOpGB);
connect(m_newOperationButton, SIGNAL(clicked()), this, SLOT(slotNewOperation()));
mainLayout->addWidget(m_newOperationButton, 1, 3);
m_pCustomRB = new QLabel(i18n("Custom operation:"), m_pOpGB);
mainLayout->addWidget(m_pCustomRB, 2, 0);
m_pOpLE = new QLineEdit(m_pOpGB);
connect(m_pOpLE, SIGNAL(textChanged(QString)), this, SLOT(slotTextChanged(QString)));
mainLayout->addWidget(m_pOpLE, 2, 1, 1, 2);
if (m_widget->operation())
m_docWidget = new DocumentationWidget(m_widget->operation(), this);
else {
MessageWidget *w = dynamic_cast<MessageWidget*>(m_widget);
if (w)
m_docWidget = new DocumentationWidget(w, this);
}
topLayout->addWidget(m_docWidget);
setupOperationsList();
setupDialog();
}
/**
* Standard destructor.
*/
SelectOperationPage::~SelectOperationPage()
{
}
/**
* Returns the operation to display.
*
* @return The operation to display.
*/
QString SelectOperationPage::getOpText()
{
if (m_pOpLE->text().isEmpty())
return m_pOpCB->currentText();
else
return m_pOpLE->text();
}
/**
* Return whether the user selected a class operation
* or a custom operation.
*
* @return True if user selected a class operation,
* false if user selected a custom operation
*/
bool SelectOperationPage::isClassOp() const
{
return (m_id == OP);
}
/**
* Set the custom operation text.
*
* @param op The operation to set as the custom operation.
*/
void SelectOperationPage::setCustomOp(const QString &op)
{
m_pOpLE->setText(op);
slotTextChanged(op);
}
/**
* Handle auto increment checkbox click.
*/
void SelectOperationPage::slotAutoIncrementChecked(bool state)
{
m_enableAutoIncrement = state;
if (state && m_pSeqLE->text().isEmpty())
m_pSeqLE->setText(m_pView->umlScene()->autoIncrementSequenceValue());
}
/**
* Handle new operation button click.
*/
void SelectOperationPage::slotNewOperation()
{
UMLOperation *op = m_classifier->createOperation();
if (!op)
return;
setupOperationsList();
setClassOp(op->toString(Uml::SignatureType::SigNoVis));
Q_EMIT enableButtonOk(true);
}
/**
* Handle combox box changes.
*/
void SelectOperationPage::slotIndexChanged(int index)
{
if (index != -1) {
m_pOpLE->setText(QString());
m_id = OP;
Q_EMIT enableButtonOk(true);
}
if (m_pOpCB->currentText().isEmpty()) {
Q_EMIT enableButtonOk(false);
}
}
/**
* Handle custom line edit changes.
*/
void SelectOperationPage::slotTextChanged(const QString &text)
{
if (text.isEmpty()) {
Q_EMIT enableButtonOk(false);
}
else {
m_pOpCB->setCurrentIndex(-1);
m_id = CUSTOM;
Q_EMIT enableButtonOk(true);
}
}
/**
* Set the class operation text.
*
* @param op The operation to set as the class operation.
* @return false if no such operation exists.
*/
bool SelectOperationPage::setClassOp(const QString &op)
{
for (int i = 1; i != m_pOpCB->count(); ++i) {
if (m_pOpCB->itemText(i) == op) {
m_pOpCB->setCurrentIndex(i);
slotIndexChanged(i);
return true;
}
}
return false;
}
/**
* Setup dialog operations list.
*/
void SelectOperationPage::setupOperationsList()
{
m_pOpCB->clear();
UMLOperationList list = m_classifier->getOpList(true);
if (list.count() > 0)
m_pOpCB->insertItem(0, QString());
std::sort(list.begin(), list.end(), caseInsensitiveLessThan);
for(UMLOperation * obj : list) {
QString s = obj->toString(Uml::SignatureType::SigNoVis);
m_pOpCB->insertItem(list.count(), s);
m_pOpCB->completionObject()->addItem(s);
}
m_nOpCount = m_classifier->operations();
}
/**
* Returns the sequence number for the operation.
*
* @return Returns the sequence number for the operation.
*/
QString SelectOperationPage::getSeqNumber()
{
return m_pSeqLE->text();
}
/**
* Set the sequence number text.
*
* @param num The number to set the sequence to.
*/
void SelectOperationPage::setSeqNumber(const QString &num)
{
m_pSeqLE->setText(num);
}
/**
* Set the flag for auto increment sequence numbering.
* @param state the state of the flag
*/
void SelectOperationPage::setAutoIncrementSequence(bool state)
{
m_pOpAS->setChecked(state);
}
/**
* Return the flag for auto increment sequence numbering.
*/
bool SelectOperationPage::autoIncrementSequence()
{
return m_pOpAS->isChecked();
}
/**
* internal setup function
*/
void SelectOperationPage::setupDialog()
{
if (m_enableAutoIncrement && m_pView->umlScene()->autoIncrementSequence()) {
setAutoIncrementSequence(true);
setSeqNumber(m_pView->umlScene()->autoIncrementSequenceValue());
} else
setSeqNumber(m_widget->sequenceNumber());
if (m_widget->operation() == nullptr) {
setCustomOp(m_widget->lwOperationText());
} else {
setClassOp(m_widget->lwOperationText());
}
Q_EMIT enableButtonOk(false);
}
/**
* apply changes to the related instamces
* @return true - success
* @return false - failure
*/
bool SelectOperationPage::apply()
{
m_docWidget->apply();
QString opText = getOpText();
if (isClassOp()) {
Model_Utils::OpDescriptor od;
Model_Utils::Parse_Status st = Model_Utils::parseOperation(opText, od, m_classifier);
if (st == Model_Utils::PS_OK) {
UMLClassifierList selfAndAncestors = m_classifier->findSuperClassConcepts();
selfAndAncestors.prepend(m_classifier);
UMLOperation *op = nullptr;
for(UMLClassifier *cl : selfAndAncestors) {
op = cl->findOperation(od.m_name, od.m_args);
if (op) {
break;
}
}
if (!op) {
// The op does not yet exist. Create a new one.
UMLObject *o = m_classifier->createOperation(od.m_name, nullptr, &od.m_args);
op = o->asUMLOperation();
}
if (od.m_pReturnType) {
op->setType(od.m_pReturnType);
}
m_widget->setOperation(op);
opText.clear();
} else {
m_widget->setOperation(nullptr);
}
} else {
m_widget->setOperation(nullptr);
}
m_widget->setSequenceNumber(getSeqNumber());
m_widget->setOperationText(opText);
if (m_enableAutoIncrement) {
m_pView->umlScene()->setAutoIncrementSequence(autoIncrementSequence());
}
return true;
}
| 9,131
|
C++
|
.cpp
| 302
| 25.596026
| 121
| 0.669889
|
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,346
|
diagramprintpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/diagramprintpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "diagramprintpage.h"
// local includes
#include "basictypes.h"
#include "debug_utils.h"
#include "model_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlviewlist.h"
// kde includes
#include <kcombobox.h>
#include <KLocalizedString>
// qt includes
#include <QGroupBox>
#include <QHBoxLayout>
#include <QListWidget>
#include <QRadioButton>
#include <QVBoxLayout>
/**
* Constructs the diagram print page.
* @param parent The parent to the page.
* @param doc The @ref UMLDoc class instance being used.
*/
DiagramPrintPage::DiagramPrintPage(QWidget * parent, UMLDoc * doc)
: DialogPageBase(parent),
m_doc(doc)
{
int margin = fontMetrics().height();
setWindowTitle(i18n("&Diagrams"));
QHBoxLayout * mainLayout = new QHBoxLayout(this);
mainLayout->setSpacing(10);
mainLayout->setContentsMargins(margin, margin, margin, margin);
m_pFilterGB = new QGroupBox(i18n("Filter"), this);
mainLayout->addWidget(m_pFilterGB);
QVBoxLayout * filter = new QVBoxLayout(m_pFilterGB);
filter->setSpacing(10);
filter->setContentsMargins(margin, margin, margin, margin);
m_pCurrentRB = new QRadioButton(i18n("&Current diagram"), m_pFilterGB);
filter->addWidget(m_pCurrentRB);
m_pCurrentRB->setChecked(true);
m_pAllRB = new QRadioButton(i18n("&All diagrams"), m_pFilterGB);
filter->addWidget(m_pAllRB);
m_pSelectRB = new QRadioButton(i18n("&Select diagrams"), m_pFilterGB);
filter->addWidget(m_pSelectRB);
m_pTypeRB = new QRadioButton(i18n("&Type of diagram"), m_pFilterGB);
filter->addWidget(m_pTypeRB);
m_pSelectGB = new QGroupBox(i18nc("diagram selection for printing", "Selection"), this);
mainLayout->addWidget(m_pSelectGB);
QVBoxLayout * select = new QVBoxLayout(m_pSelectGB);
select->setSpacing(10);
select->setContentsMargins(margin, margin, margin, margin);
m_pTypeCB = new KComboBox(m_pSelectGB);
select->addWidget(m_pTypeCB);
m_pTypeCB->setEnabled(false);
m_pSelectLW = new QListWidget(m_pSelectGB);
select->addWidget(m_pSelectLW);
m_pSelectLW->setEnabled(false);
m_pSelectLW->setSelectionMode(QAbstractItemView::MultiSelection);
m_pSelectLW->addItem(UMLApp::app()->currentView()->umlScene()->name());
m_pSelectLW->setCurrentRow(0);
m_nIdList.clear();
m_nIdList.append(UMLApp::app()->currentView()->umlScene()->ID());
m_ViewType = Uml::DiagramType::Class;
connect(m_pAllRB, SIGNAL(clicked()), this, SLOT(slotClicked()));
connect(m_pCurrentRB, SIGNAL(clicked()), this, SLOT(slotClicked()));
connect(m_pSelectRB, SIGNAL(clicked()), this, SLOT(slotClicked()));
connect(m_pTypeRB, SIGNAL(clicked()), this, SLOT(slotClicked()));
connect(m_pTypeCB, SIGNAL(activated(int)), this, SLOT(slotActivated(int)));
QStringList types;
// diagramNo 1 is Uml::DiagramType::Class
// digaramNo 9 is Uml::DiagramType::EntityRelationship
for (int diagramNo = 1; diagramNo < Uml::DiagramType::N_DIAGRAMTYPES; ++diagramNo) {
Uml::DiagramType::Enum dt = Uml::DiagramType::fromInt(diagramNo);
types << Uml::DiagramType::toString(dt);
}
m_pTypeCB->insertItems(0, types);
}
/**
* Standard destructor.
*/
DiagramPrintPage::~DiagramPrintPage()
{
}
/**
* Get selected print options.
* @return number of selected items
*/
int DiagramPrintPage::printUmlCount()
{
QList<QListWidgetItem *> selectedItems = m_pSelectLW->selectedItems();
return selectedItems.count();
}
/**
* Return ID string of UML diagram.
* @param sel index of selected item
* @return ID as string or empty string
*/
QString DiagramPrintPage::printUmlDiagram(int sel)
{
int count = 0;
for (int i = 0; i < m_pSelectLW->count(); ++i) {
if (isSelected(i)) {
if (count == sel) {
UMLView *view = (UMLView *)m_doc->findView(m_nIdList[i]);
QString sID = QString::fromLatin1("%1").arg(Uml::ID::toString(view->umlScene()->ID()));
return sID;
}
count++;
}
}
return QString();
}
/**
* Overridden method.
*/
bool DiagramPrintPage::isValid(QString& msg)
{
int listCount = m_pSelectLW->count();
bool sel = false;
for (int i = 0; i < listCount; ++i) {
if (isSelected(i)) {
sel = true;
i = listCount;
}
}
msg = i18n("No diagrams selected.");
return sel;
}
/**
* Check if item with given index is selected.
* @param index index of selected item
* @return flag whether item is selected
*/
bool DiagramPrintPage::isSelected(int index)
{
QList<QListWidgetItem *> selectedItems = m_pSelectLW->selectedItems();
QListWidgetItem* itemAtIndex = m_pSelectLW->item(index);
if (selectedItems.contains(itemAtIndex)) {
return true;
}
else {
return false;
}
}
/**
* Gets called when the users chooses to print all diagrams, the current
* diagram, a selection of diagrams or diagrams by type. It will change the
* listed diagrams in the diagram box.
*/
void DiagramPrintPage::slotClicked()
{
UMLViewList list = m_doc->viewIterator();
QString type;
// clear list with diagrams to print
m_nIdList.clear();
UMLScene *currentScene = UMLApp::app()->currentView()->umlScene();
if (m_pCurrentRB->isChecked()) {
m_pTypeCB->setEnabled(false);
m_pSelectLW->setEnabled(false);
m_pSelectLW->clear();
m_pSelectLW->addItem(currentScene->name());
m_pSelectLW->setCurrentRow(0);
m_nIdList.append(currentScene->ID());
}
if (m_pAllRB->isChecked()) {
m_pTypeCB->setEnabled(false);
m_pSelectLW->setEnabled(false);
m_pSelectLW->clear();
for(UMLView * view : list) {
m_pSelectLW->addItem(view->umlScene()->name());
m_nIdList.append(view->umlScene()->ID());
}
m_pSelectLW->selectAll();
}
if (m_pSelectRB->isChecked()) {
m_pTypeCB->setEnabled(false);
m_pSelectLW->setEnabled(true);
m_pSelectLW->clear();
for(UMLView * view : list) {
m_pSelectLW->addItem(view->umlScene()->name());
m_nIdList.append(view->umlScene()->ID());
}
}
if (m_pTypeRB->isChecked()) {
m_pTypeCB->setEnabled(true);
m_pSelectLW->setEnabled(true);
m_pSelectLW->clear();
for(UMLView * view : list) {
if(view->umlScene()->type() == m_ViewType) {
m_pSelectLW->addItem(view->umlScene()->name());
m_nIdList.append(view->umlScene()->ID());
}
}
m_pSelectLW->selectAll();
}
}
/**
* Gets called when the user chooses another diagram type. Only diagrams of
* this type will be shown in the diagram box.
* @param index diagram type (combo box index)
*/
void DiagramPrintPage::slotActivated(int index)
{
UMLViewList list = m_doc->viewIterator();
// combo box entries start from 0 index
// valid diagram_type enum values start from 1
m_ViewType = Uml::DiagramType::fromInt(index + 1);
m_pSelectLW->clear();
m_nIdList.clear();
for(UMLView * view : list) {
if (view->umlScene()->type() == m_ViewType) {
m_pSelectLW->addItem(view->umlScene()->name());
m_nIdList.append(view->umlScene()->ID());
}
}
m_pSelectLW->selectAll();
}
| 7,574
|
C++
|
.cpp
| 222
| 28.95045
| 103
| 0.657053
|
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,347
|
classifierlistpage.cpp
|
KDE_umbrello/umbrello/dialogs/pages/classifierlistpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "classifierlistpage.h"
#include "basictypes.h"
#include "classifierlistitem.h"
#include "codetextedit.h"
#define DBG_SRC QStringLiteral("ClassifierListPage")
#include "debug_utils.h"
#include "umldoc.h"
#include "uml.h" // only needed for log{Warn,Error}
#include "classifier.h"
#include "enum.h"
#include "entity.h"
#include "attribute.h"
#include "dialogspopupmenu.h"
#include "operation.h"
#include "template.h"
#include "enumliteral.h"
#include "entityattribute.h"
#include "object_factory.h"
#include <KLocalizedString>
#include <QTextEdit>
#include <QApplication>
#include <QDialogButtonBox>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QListWidget>
#include <QPushButton>
#include <QToolButton>
#include <QVBoxLayout>
DEBUG_REGISTER(ClassifierListPage)
/**
* Sets up the ClassifierListPage.
* @param parent The parent to the ClassAttPage.
* @param classifier The Concept to display the properties of.
* @param doc The UMLDoc document
* @param type The type of listItem this handles
*/
ClassifierListPage::ClassifierListPage(QWidget* parent, UMLClassifier* classifier,
UMLDoc* doc, UMLObject::ObjectType type)
: DialogPageBase(parent)
{
m_itemType = type;
m_bSigWaiting = false;
m_doc = doc;
m_pClassifier = classifier;
setupPage();
}
/**
* Standard destructor.
*/
ClassifierListPage::~ClassifierListPage()
{
}
/**
* Sets up the page.
*/
void ClassifierListPage::setupPage()
{
int margin = fontMetrics().height();
setMinimumSize(310, 330);
//main layout contains our two group boxes, the list and the documentation
QVBoxLayout* mainLayout = new QVBoxLayout(this);
mainLayout->setSpacing(10);
setupListGroup(margin);
mainLayout->addWidget(m_pItemListGB);
setupDocumentationGroup(margin);
mainLayout->addWidget(m_docGB);
reloadItemListBox();
enableWidgets(false);//disable widgets until an att is chosen
m_pOldListItem = nullptr;
connect(m_pItemListLB, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(slotActivateItem(QListWidgetItem*)));
connect(m_pItemListLB, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(slotDoubleClick(QListWidgetItem*)));
connect(m_pItemListLB, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotRightButtonPressed(QPoint)));
connect(m_doc, SIGNAL(sigObjectCreated(UMLObject*)), this, SLOT(slotListItemCreated(UMLObject*)));
connect(m_pTopArrowB, SIGNAL(clicked()), this, SLOT(slotTopClicked()));
connect(m_pUpArrowB, SIGNAL(clicked()), this, SLOT(slotUpClicked()));
connect(m_pDownArrowB, SIGNAL(clicked()), this, SLOT(slotDownClicked()));
connect(m_pBottomArrowB, SIGNAL(clicked()), this, SLOT(slotBottomClicked()));
}
/**
* Sets up the list group.
* @param margin The margin of the group.
*/
void ClassifierListPage::setupListGroup(int margin)
{
QString typeName;
QString newItemType;
switch (m_itemType) {
case UMLObject::ot_Attribute:
typeName = i18n("Attributes");
newItemType = i18n("N&ew Attribute...");
break;
case UMLObject::ot_Operation:
typeName = i18n("Operations");
newItemType = i18n("N&ew Operation...");
break;
case UMLObject::ot_Template:
typeName = i18n("Templates");
newItemType = i18n("N&ew Template...");
break;
case UMLObject::ot_EnumLiteral:
typeName = i18n("Enum Literals");
newItemType = i18n("N&ew Enum Literal...");
break;
case UMLObject::ot_EntityAttribute:
typeName = i18n("Entity Attributes");
newItemType = i18n("N&ew Entity Attribute...");
break;
case UMLObject::ot_EntityConstraint:
typeName = i18n("Constraints");
newItemType = i18n("N&ew Constraint...");
break;
case UMLObject::ot_InstanceAttribute:
typeName = i18n("Instance Attribute");
newItemType = i18n("N&ew Instance Attribute...");
break;
default:
logWarn1("ClassifierListPage::setupListGroup: unknown listItem type %1",
UMLObject::toString(m_itemType));
break;
}
//top group box, contains a vertical layout with list box above and buttons below
m_pItemListGB = new QGroupBox(typeName, this);
QVBoxLayout* listVBoxLayout = new QVBoxLayout(m_pItemListGB);
listVBoxLayout->setContentsMargins(margin, margin, margin, margin);
listVBoxLayout->setSpacing(10);
//horizontal box contains the list box and the move up/down buttons
QHBoxLayout* listHBoxLayout = new QHBoxLayout();
listHBoxLayout->setSpacing(10);
listVBoxLayout->addItem(listHBoxLayout);
m_pItemListLB = new QListWidget(m_pItemListGB);
m_pItemListLB->setSelectionMode(QAbstractItemView::SingleSelection);
m_pItemListLB->setContextMenuPolicy(Qt::CustomContextMenu);
listHBoxLayout->addWidget(m_pItemListLB);
setupMoveButtons(listHBoxLayout);
setupActionButtons(newItemType, listVBoxLayout);
}
/**
* Sets up the move up/down buttons.
* @param parentLayout The parent layout to which this group belongs.
*/
void ClassifierListPage::setupMoveButtons(QHBoxLayout* parentLayout)
{
QVBoxLayout* buttonLayout = new QVBoxLayout();
parentLayout->addItem(buttonLayout);
m_pTopArrowB = new QToolButton(m_pItemListGB);
m_pTopArrowB->setArrowType(Qt::UpArrow);
m_pTopArrowB->setEnabled(false);
m_pTopArrowB->setToolTip(i18n("Move selected item to the top"));
buttonLayout->addWidget(m_pTopArrowB);
m_pUpArrowB = new QToolButton(m_pItemListGB);
m_pUpArrowB->setArrowType(Qt::UpArrow);
m_pUpArrowB->setEnabled(false);
m_pUpArrowB->setToolTip(i18n("Move selected item up"));
buttonLayout->addWidget(m_pUpArrowB);
m_pDownArrowB = new QToolButton(m_pItemListGB);
m_pDownArrowB->setArrowType(Qt::DownArrow);
m_pDownArrowB->setEnabled(false);
m_pDownArrowB->setToolTip(i18n("Move selected item down"));
buttonLayout->addWidget(m_pDownArrowB);
m_pBottomArrowB = new QToolButton(m_pItemListGB);
m_pBottomArrowB->setArrowType(Qt::DownArrow);
m_pBottomArrowB->setEnabled(false);
m_pBottomArrowB->setToolTip(i18n("Move selected item to the bottom"));
buttonLayout->addWidget(m_pBottomArrowB);
}
/**
* Sets up the action buttons.
* @param itemType The item type.
* @param parentLayout The parent layout to which this group belongs.
*/
void ClassifierListPage::setupActionButtons(const QString& itemType, QVBoxLayout* parentLayout)
{
QDialogButtonBox* buttonBox = new QDialogButtonBox(m_pItemListGB);
m_pNewClassifierListItemButton = buttonBox->addButton(itemType, QDialogButtonBox::ActionRole);
connect(m_pNewClassifierListItemButton, SIGNAL(clicked()), this, SLOT(slotNewListItem()));
m_pDeleteListItemButton = buttonBox->addButton(i18n("&Delete"), QDialogButtonBox::ActionRole);
connect(m_pDeleteListItemButton, SIGNAL(clicked()), this, SLOT(slotDelete()));
m_pPropertiesButton = buttonBox->addButton(i18n("&Properties"), QDialogButtonBox::ActionRole);
connect(m_pPropertiesButton, SIGNAL(clicked()), this, SLOT(slotProperties()));
parentLayout->addWidget(buttonBox);
}
/**
* Sets up the documentation group.
* @param margin The margin of the group.
*/
void ClassifierListPage::setupDocumentationGroup(int margin)
{
m_docGB = new QGroupBox(i18n("Documentation"), this);
QVBoxLayout* docLayout = new QVBoxLayout(m_docGB);
docLayout->setSpacing(10);
docLayout->setContentsMargins(margin, margin, margin, margin);
if (m_itemType == UMLObject::ot_Operation) {
m_docTE = new QTextEdit();
m_pCodeTE = new CodeTextEdit();
QTabWidget* tabWidget = new QTabWidget();
tabWidget->addTab(m_docTE, i18n("Comment"));
tabWidget->addTab(m_pCodeTE, i18n("Source Code"));
docLayout->addWidget(tabWidget);
}
else {
m_docTE = new QTextEdit();
docLayout->addWidget(m_docTE);
}
}
/**
* Loads the Item List Box.
*/
void ClassifierListPage::reloadItemListBox()
{
UMLClassifierListItemList itemList(getItemList());
// remove any items if present
m_pItemListLB->clear();
// add each item in the list to the ListBox and connect each item modified signal
// to the ListItemModified slot in this class
for(UMLClassifierListItem *listItem : itemList) {
m_pItemListLB->addItem(listItem->toString(Uml::SignatureType::SigNoVis));
connect(listItem, SIGNAL(modified()), this, SLOT(slotListItemModified()));
}
}
/**
* Set the state of the widgets on the page with the given value.
* @param state The state to set the widgets as.
*/
void ClassifierListPage::enableWidgets(bool state)
{
m_docTE->setEnabled(state);
if (m_itemType == UMLObject::ot_Operation) {
m_pCodeTE->setEnabled(state);
}
//if disabled clear contents
if (!state) {
m_docTE->setText(QString());
if (m_itemType == UMLObject::ot_Operation) {
m_pCodeTE->setPlainText(QString());
}
m_pTopArrowB->setEnabled(false);
m_pUpArrowB->setEnabled(false);
m_pDownArrowB->setEnabled(false);
m_pBottomArrowB->setEnabled(false);
m_pDeleteListItemButton->setEnabled(false);
m_pPropertiesButton->setEnabled(false);
return;
}
/*now check the order buttons.
Double check an item is selected
If only one item in list make sure they are disabled.
If at top item, only allow down arrow to be enabled.
If at bottom item, only allow up arrow to be enabled.
*/
int index = m_pItemListLB->currentRow();
if (m_pItemListLB->count() == 1 || index == -1) {
m_pTopArrowB->setEnabled(false);
m_pUpArrowB->setEnabled(false);
m_pDownArrowB->setEnabled(false);
m_pBottomArrowB->setEnabled(false);
} else if(index == 0) {
m_pTopArrowB->setEnabled(false);
m_pUpArrowB->setEnabled(false);
m_pDownArrowB->setEnabled(true);
m_pBottomArrowB->setEnabled(true);
} else if(index == m_pItemListLB->count() - 1) {
m_pTopArrowB->setEnabled(true);
m_pUpArrowB->setEnabled(true);
m_pDownArrowB->setEnabled(false);
m_pBottomArrowB->setEnabled(false);
} else {
m_pTopArrowB->setEnabled(true);
m_pUpArrowB->setEnabled(true);
m_pDownArrowB->setEnabled(true);
m_pBottomArrowB->setEnabled(true);
}
m_pDeleteListItemButton->setEnabled(true);
m_pPropertiesButton->setEnabled(true);
}
/**
* Called whenever the list item needs to be activated
* calls enableWidgets().
*/
void ClassifierListPage::slotActivateItem(QListWidgetItem* item)
{
//if not first time an item is highlighted
//save old highlighted item first
if (m_pOldListItem) {
m_pOldListItem->setDoc(m_docTE->toPlainText());
if (m_itemType == UMLObject::ot_Operation) {
UMLOperation* op = m_pOldListItem->asUMLOperation();
op->setSourceCode(m_pCodeTE->toPlainText());
}
}
// make sure clicked on an item
// it is impossible to deselect all items, because our list box has keyboard
// focus and so at least one item is always selected; this doesn't happen, if
// there are no items of course;
//
// for more information see Qt doc for void QListBox::clearSelection()
UMLClassifierListItemList itemList = getItemList();
int itemIndex;
if (item == nullptr) {
if (m_pItemListLB->count() == 0) {
enableWidgets(false);
m_pOldListItem = nullptr;
m_pItemListLB->clearSelection();
return;
}
m_pItemListLB->setCurrentRow(0);
itemIndex = 0;
} else {
itemIndex = m_pItemListLB->row(item);
}
// make sure the determined itemIndex is a valid position in the list
if (itemIndex >= 0 && itemIndex < itemList.size()) {
UMLClassifierListItem* listItem = itemList.at(itemIndex);
// now update screen
m_docTE->setText(listItem->doc());
if (m_itemType == UMLObject::ot_Operation) {
const UMLOperation* o = listItem->asUMLOperation();
if (!o) {
logError1("ClassifierListPage::slotActivateItem Dynamic cast to UMLOperation failed for %1",
listItem->name());
return;
}
m_pCodeTE->setPlainText(o->getSourceCode());
}
enableWidgets(true);
m_pOldListItem = listItem;
} else {
logDebug0("ClassifierListPage::slotActivateItem: Cannot find item in list.");
}
}
/**
* Will move information from the dialog into the object.
* Call when the ok or apply button is pressed.
*/
void ClassifierListPage::apply()
{
saveCurrentItemDocumentation();
QListWidgetItem* i = m_pItemListLB->currentItem();
slotActivateItem(i);
}
void ClassifierListPage::slotListItemCreated(UMLObject* object)
{
if (!m_bSigWaiting) {
return;
}
const UMLClassifierListItem *listItem = object->asUMLClassifierListItem();
if (listItem == nullptr) {
return;
}
QString itemStr = listItem->toString(Uml::SignatureType::SigNoVis);
// already in list?
QList<QListWidgetItem*> foundItems = m_pItemListLB->findItems(itemStr, Qt::MatchExactly);
int index = -1;
if (foundItems.empty()) {
index = m_pItemListLB->count();
m_pItemListLB->insertItem(index, itemStr);
}
else {
index = m_pItemListLB->row(foundItems[0]);
}
m_bSigWaiting = false;
// now select the new item, so that the user can go on adding doc or calling
// the property dialog
if (index > -1) {
m_pItemListLB->setCurrentItem(m_pItemListLB->item(index));
slotActivateItem(m_pItemListLB->item(index));
connect(object, SIGNAL(modified()), this, SLOT(slotListItemModified()));
}
}
void ClassifierListPage::slotListItemModified()
{
if (!m_bSigWaiting) {
return;
}
UMLClassifierListItem* object = dynamic_cast<UMLClassifierListItem*>(sender());
if (object) {
QListWidgetItem* item = m_pItemListLB->currentItem();
item->setText(object->toString(Uml::SignatureType::SigNoVis));
m_pItemListLB->setCurrentItem(item);
m_bSigWaiting = false;
}
}
void ClassifierListPage::slotRightButtonPressed(const QPoint& pos)
{
DialogsPopupMenu::TriggerType type = DialogsPopupMenu::tt_Undefined;
if (m_pItemListLB->itemAt(pos)) { //pressed on a list item
if (m_itemType == UMLObject::ot_Attribute) {
type = DialogsPopupMenu::tt_Attribute_Selected;
} else if (m_itemType == UMLObject::ot_Operation) {
type = DialogsPopupMenu::tt_Operation_Selected;
} else if (m_itemType == UMLObject::ot_Template) {
type = DialogsPopupMenu::tt_Template_Selected;
} else if (m_itemType == UMLObject::ot_EnumLiteral) {
type = DialogsPopupMenu::tt_EnumLiteral_Selected;
} else if (m_itemType == UMLObject::ot_EntityAttribute) {
type = DialogsPopupMenu::tt_EntityAttribute_Selected;
} else if(m_itemType == UMLObject::ot_InstanceAttribute){
type = DialogsPopupMenu::tt_InstanceAttribute_Selected;
} else {
logWarn1("ClassifierListPage::slotRightButtonPressed(selected): unknown type %1", m_itemType);
}
} else { //pressed into fresh air
if (m_itemType == UMLObject::ot_Attribute) {
type = DialogsPopupMenu::tt_New_Attribute;
} else if (m_itemType == UMLObject::ot_Operation) {
type = DialogsPopupMenu::tt_New_Operation;
} else if (m_itemType == UMLObject::ot_Template) {
type = DialogsPopupMenu::tt_New_Template;
} else if (m_itemType == UMLObject::ot_EnumLiteral) {
type = DialogsPopupMenu::tt_New_EnumLiteral;
} else if (m_itemType == UMLObject::ot_EntityAttribute) {
type = DialogsPopupMenu::tt_New_EntityAttribute;
} else if( m_itemType == UMLObject::ot_InstanceAttribute) {
type = DialogsPopupMenu::tt_New_InstanceAttribute;
} else {
logWarn1("ClassifierListPage::slotRightButtonPressed: unknown type %1", m_itemType);
}
}
DialogsPopupMenu popup(this, type);
QAction *triggered = popup.exec(mapToGlobal(pos) + QPoint(0, 40));
slotMenuSelection(triggered);
}
/**
* Called when an item is selected in a right click menu.
*/
void ClassifierListPage::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType id = ListPopupMenu::typeFromAction(action);
switch (id) {
case ListPopupMenu::mt_New_Attribute:
case ListPopupMenu::mt_New_Operation:
case ListPopupMenu::mt_New_Template:
case ListPopupMenu::mt_New_EnumLiteral:
case ListPopupMenu::mt_New_EntityAttribute:
case ListPopupMenu::mt_New_InstanceAttribute:
slotNewListItem();
break;
case ListPopupMenu::mt_Delete:
slotDelete();
break;
case ListPopupMenu::mt_Rename:
{
int currentItemIndex = m_pItemListLB->currentRow();
if (currentItemIndex == -1)
return;
UMLClassifierListItem* listItem = getItemList().at(currentItemIndex);
if (!listItem && id != ListPopupMenu::mt_New_Attribute) {
logDebug0("ClassifierListPage::slotMenuSelection: cannot find att from selection");
return;
}
m_bSigWaiting = true;
m_doc->renameChildUMLObject(listItem);
}
break;
case ListPopupMenu::mt_Properties:
slotProperties();
break;
default:
logDebug1("ClassifierListPage::slotMenuSelection: MenuType %1 not implemented",
ListPopupMenu::toString(id));
}
}
/**
* Utility for debugging, prints the current item list.
* Only effective if VERBOSE_DEBUGGING is defined.
*/
void ClassifierListPage::printItemList(const QString &prologue)
{
#ifdef VERBOSE_DEBUGGING
UMLClassifierListItem* item;
QString buf;
UMLClassifierListItemList itemList = getItemList();
for (UMLClassifierListItemListIt it(itemList); it.hasNext();) {
item = it.next();
buf.append(' ' + item->getName());
}
logDebug1("%1 %2", prologue, buf);
#else
Q_UNUSED(prologue);
#endif
}
/**
* Moves selected attribute to the top of the list.
*/
void ClassifierListPage::slotTopClicked()
{
int count = m_pItemListLB->count();
int index = m_pItemListLB->currentRow();
//shouldn't occur, but just in case
if(count <= 1 || index <= 0)
return;
m_pOldListItem = nullptr;
//swap the text around in the ListBox
QString currentString = m_pItemListLB->item(index)->text();
m_pItemListLB->takeItem(index);
m_pItemListLB->insertItem(0, currentString);
//set the moved item selected
QListWidgetItem* item = m_pItemListLB->item(0);
m_pItemListLB->setCurrentItem(item);
//now change around in the list
printItemList(QStringLiteral("itemList before change: "));
UMLClassifierListItem* currentAtt = getItemList().at(index);
// NB: The index in the m_pItemListLB is not necessarily the same
// as the index in the UMLClassifier::m_List.
// Reason: getItemList() returns only a subset of all entries
// in UMLClassifier::m_List.
takeItem(currentAtt, true, index); // now we index the UMLClassifier::m_List
logDebug2("ClassifierListPage::slotTopClicked %1: peer index in UMLCanvasItem::m_List is %2",
currentAtt->name(), index);
addToClassifier(currentAtt, 0);
printItemList(QStringLiteral("itemList after change: "));
slotActivateItem(item);
}
/**
* Moves selected attribute up in list.
*/
void ClassifierListPage::slotUpClicked()
{
int count = m_pItemListLB->count();
int index = m_pItemListLB->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index <= 0)
return;
m_pOldListItem = nullptr;
//swap the text around in the ListBox
QString aboveString = m_pItemListLB->item(index - 1)->text();
QString currentString = m_pItemListLB->item(index)->text();
m_pItemListLB->item(index - 1)->setText(currentString);
m_pItemListLB->item(index)->setText(aboveString);
//set the moved item selected
QListWidgetItem* item = m_pItemListLB->item(index - 1);
m_pItemListLB->setCurrentItem(item);
//now change around in the list
printItemList(QStringLiteral("itemList before change: "));
UMLClassifierListItem* currentAtt = getItemList().at(index);
// NB: The index in the m_pItemListLB is not necessarily the same
// as the index in the UMLClassifier::m_List.
// Reason: getItemList() returns only a subset of all entries
// in UMLClassifier::m_List.
takeItem(currentAtt, true, index); // now we index the UMLClassifier::m_List
logDebug2("ClassifierListPage::slotUpClicked %1: peer index in UMLCanvasItem::m_List is %2",
currentAtt->name(), index);
if (index == -1)
index = 0;
addToClassifier(currentAtt, index);
printItemList(QStringLiteral("itemList after change: "));
slotActivateItem(item);
}
/**
* Moved selected attribute down in list.
*/
void ClassifierListPage::slotDownClicked()
{
int count = m_pItemListLB->count();
int index = m_pItemListLB->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index >= count - 1 || index == -1)
return;
m_pOldListItem = nullptr;
//swap the text around in the ListBox
QString belowString = m_pItemListLB->item(index + 1)->text();
QString currentString = m_pItemListLB->item(index)->text();
m_pItemListLB->item(index + 1)->setText(currentString);
m_pItemListLB->item(index)->setText(belowString);
//set the moved item selected
QListWidgetItem* item = m_pItemListLB->item(index + 1);
m_pItemListLB->setCurrentItem(item);
//now change around in the list
printItemList(QStringLiteral("itemList before change: "));
UMLClassifierListItem* currentAtt = getItemList().at(index);
// NB: The index in the m_pItemListLB is not necessarily the same
// as the index in the UMLClassifier::m_List.
// Reason: getItemList() returns only a subset of all entries
// in UMLClassifier::m_List.
takeItem(currentAtt, false, index); // now we index the UMLClassifier::m_List
logDebug2("ClassifierListPage::slotDownClicked %1: peer index in UMLCanvasItem::m_List is %2",
currentAtt->name(), index);
if (index != -1)
index++; // because we want to go _after_ the following peer item
addToClassifier(currentAtt, index);
printItemList(QStringLiteral("itemList after change: "));
slotActivateItem(item);
}
/**
* Moved selected attribute to the bottom of the list.
*/
void ClassifierListPage::slotBottomClicked()
{
int count = m_pItemListLB->count();
int index = m_pItemListLB->currentRow();
//shouldn't occur, but just in case
if (count <= 1 || index >= count - 1 || index == -1)
return;
m_pOldListItem = nullptr;
//swap the text around in the ListBox
QString currentString = m_pItemListLB->item(index)->text();
m_pItemListLB->takeItem(index);
m_pItemListLB->insertItem(m_pItemListLB->count(), currentString);
//set the moved item selected
QListWidgetItem* item = m_pItemListLB->item(m_pItemListLB->count() - 1);
m_pItemListLB->setCurrentItem(item);
//now change around in the list
printItemList(QStringLiteral("itemList before change: "));
UMLClassifierListItem* currentAtt = getItemList().at(index);
// NB: The index in the m_pItemListLB is not necessarily the same
// as the index in the UMLClassifier::m_List.
// Reason: getItemList() returns only a subset of all entries
// in UMLClassifier::m_List.
takeItem(currentAtt, false, index); // now we index the UMLClassifier::m_List
logDebug2("ClassifierListPage::slotBottomClicked %1: peer index in UMLCanvasItem::m_List is %2",
currentAtt->name(), index);
addToClassifier(currentAtt, getItemList().count());
printItemList(QStringLiteral("itemList after change: "));
slotActivateItem(item);
}
/**
* Shows properties dialog for the attribute clicked on.
*/
void ClassifierListPage::slotDoubleClick(QListWidgetItem* item)
{
if (!item) {
return;
}
int row = m_pItemListLB->row(item);
UMLClassifierListItem* listItem = getItemList().at(row);
if (!listItem) {
logDebug1("ClassifierListPage::slotDoubleClick: cannot find att from selection (row %1)", row);
return;
}
m_bSigWaiting = true;
if (listItem->showPropertiesDialog(this)) {
m_pItemListLB->item(m_pItemListLB->row(item))->setText(listItem->toString(Uml::SignatureType::SigNoVis));
m_docTE->setText(listItem->doc());
if (m_itemType == UMLObject::ot_Operation) {
const UMLOperation* o = listItem->asUMLOperation();
if (!o) {
logError1("ClassifierListPage::slotDoubleClick: Dynamic cast to UMLOperation failed for %1",
listItem->name());
return;
}
m_pCodeTE->setPlainText(o->getSourceCode());
}
}
}
/**
* Removes currently selected attribute.
*/
void ClassifierListPage::slotDelete()
{
int currentItemIndex = m_pItemListLB->currentRow();
if (currentItemIndex > -1) {
// do this first
delete m_pItemListLB->takeItem(currentItemIndex);
UMLClassifierListItem* selectedItem = getItemList().at(currentItemIndex);
//should really wait for signal back
//but really shouldn't matter
m_doc->removeUMLObject(selectedItem);
m_pOldListItem = nullptr;
slotActivateItem(nullptr);
}
}
/**
* Shows properties dialog for currently selected attribute.
*/
void ClassifierListPage::slotProperties()
{
saveCurrentItemDocumentation();
slotDoubleClick(m_pItemListLB->currentItem());
}
/**
* Shows dialog for new attribute.
*/
void ClassifierListPage::slotNewListItem()
{
saveCurrentItemDocumentation();
m_bSigWaiting = true;
m_pLastObjectCreated = Object_Factory::createChildObject(m_pClassifier, m_itemType);
if (m_pLastObjectCreated)
m_docTE->setText(m_pLastObjectCreated->doc());
else
m_bSigWaiting = false;
}
/**
* Saves the documentation for the currently selected item.
*/
void ClassifierListPage::saveCurrentItemDocumentation()
{
int currentItemIndex = m_pItemListLB->currentRow();
// index is not in range, quit
if (currentItemIndex < 0 || currentItemIndex >= getItemList().count()) {
return;
}
UMLClassifierListItem* selectedItem = getItemList().at(currentItemIndex);
if (selectedItem) {
selectedItem->setDoc(m_docTE->toPlainText());
if (m_itemType == UMLObject::ot_Operation) {
selectedItem->asUMLOperation()->setSourceCode(m_pCodeTE->toPlainText());
}
}
}
/**
* Get classifier list items.
*/
UMLClassifierListItemList ClassifierListPage::getItemList()
{
return m_pClassifier->getFilteredList(m_itemType);
}
/**
* Attempts to add a @ref UMLClassifierListItem to @ref m_pClassifier.
* @param listitem Pointer to the classifier list item to add.
* @param position Index at which to insert into the list.
* @return true if the classifier could be added
*
*/
bool ClassifierListPage::addToClassifier(UMLClassifierListItem* listitem, int position)
{
switch (m_itemType) {
case UMLObject::ot_Attribute: {
UMLAttribute *att = listitem->asUMLAttribute();
if (!att) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLAttribute failed for %1",
listitem->name());
return false;
}
return m_pClassifier->addAttribute(att, nullptr, position);
}
case UMLObject::ot_Operation: {
UMLOperation *op = listitem->asUMLOperation();
if (!op) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLOperation failed for %1",
listitem->name());
return false;
}
return m_pClassifier->addOperation(op, position);
}
case UMLObject::ot_Template: {
UMLTemplate* t = listitem->asUMLTemplate();
if (!t) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLTemplate failed for %1",
listitem->name());
return false;
}
return m_pClassifier->addTemplate(t, position);
}
case UMLObject::ot_EnumLiteral: {
UMLEnum* c = m_pClassifier->asUMLEnum();
if (!c) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLEnum failed for %1",
m_pClassifier->name());
return false;
}
UMLEnumLiteral *l = listitem->asUMLEnumLiteral();
if (!l) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLEnumLiteral failed for %1",
listitem->name());
return false;
}
return c->addEnumLiteral(l, position);
break;
}
case UMLObject::ot_EntityAttribute: {
UMLEntity* c = m_pClassifier->asUMLEntity();
if (!c) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLEntity failed for %1",
m_pClassifier->name());
return false;
}
UMLEntityAttribute *a = listitem->asUMLEntityAttribute();
if (!a) {
logError1("ClassifierListPage::addClassifier: Dynamic cast to UMLEntityAttribute failed for %1",
listitem->name());
return false;
}
return c->addEntityAttribute(a, position);
break;
}
default: {
logWarn1("ClassifierListPage::addClassifier: unknown type %1", UMLObject::toString(m_itemType));
return false;
}
}
logError0("ClassifierListPage::addClassifier: unable to handle listitem type in current state");
return false;
}
/**
* Take a classifier's subordinate item.
* Ownership of the classifier list item is transferred to the caller.
* @param listItem UMLClassifierListItem to take.
* @param seekPeerBefore True if a peer index should be sought which
* is smaller than the current listitem's index.
* @param peerIndex Return value: Index in the UMLClassifier's
* item list at which a peer item, i.e. another
* UMLClassifierListItem of the same type as
* listItem, is found. If no such item exists
* then return -1.
* @return True for success.
*/
bool ClassifierListPage::takeItem(UMLClassifierListItem* listItem,
bool seekPeerBefore, int &peerIndex)
{
int wasAtIndex = m_pClassifier->takeItem(listItem);
if (wasAtIndex == -1)
return false;
qApp->processEvents();
peerIndex = -1;
const UMLObject::ObjectType seekType = listItem->baseType();
UMLObjectList listItems = m_pClassifier->subordinates();
for (int i = 0; i < listItems.count(); ++i) {
UMLObject *o = listItems.at(i);
if (seekPeerBefore) {
if (i >= wasAtIndex)
break;
if (o->baseType() == seekType)
peerIndex = i;
} else { // seekPeerAfter
if (i < wasAtIndex)
continue;
if (o->baseType() == seekType) {
peerIndex = i;
break;
}
}
}
return true;
}
/**
* Sets the visibility of the arrow buttons.
* @param hide true hides the arrow buttons
*/
void ClassifierListPage::hideArrowButtons(bool hide)
{
// if hide is true, we have to make state = false
bool state = !hide;
m_pTopArrowB->setVisible(state);
m_pUpArrowB->setVisible(state);
m_pDownArrowB->setVisible(state);
m_pBottomArrowB->setVisible(state) ;
}
| 32,727
|
C++
|
.cpp
| 841
| 32.596908
| 138
| 0.667086
|
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,348
|
resolutionwidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/resolutionwidget.cpp
|
/*
SPDX-FileCopyrightText: 2015-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 "resolutionwidget.h"
// kde includes
#include <KComboBox>
#include <KLocalizedString>
// qt includes
#include <QApplication>
#include <QDesktopWidget>
#include <QHBoxLayout>
#include <QLabel>
/**
* Constructor
* @param parent QWidget parent
*/
ResolutionWidget::ResolutionWidget(QWidget *parent) :
ComboBoxWidgetBase(i18n("&Resolution:"), i18n("DPI"), parent)
{
m_editField->clear();
m_editField->addItem(QStringLiteral("default"), QVariant(0.0));
for(const QString &key : resolutions()) {
m_editField->addItem(key, QVariant(key.toFloat()));
}
connect(m_editField, SIGNAL(editTextChanged(QString)), this, SLOT(slotTextChanged(QString)));
}
/**
* Return current selected resolution.
* @return resolutions as QString
*/
float ResolutionWidget::currentResolution()
{
QVariant v = m_editField->itemData(m_editField->currentIndex());
if (v.canConvert<float>()) {
return v.value<float>();
} else {
bool ok;
float value = m_editField->currentText().toFloat(&ok);
return ok ? value : 0.0;
}
}
bool numberLessThan(const QString &s1, const QString &s2)
{
return s1.toFloat() < s2.toFloat();
}
/**
* Returns a QStringList containing all supported resolutions
* @return QStringList with resolutions
*/
QStringList ResolutionWidget::resolutions()
{
QStringList result;
result << QStringLiteral("72");
result << QStringLiteral("96");
result << QStringLiteral("150");
result << QStringLiteral("300");
result << QStringLiteral("600");
result << QStringLiteral("1200");
QString currentResolution = QString::number(qApp->desktop()->logicalDpiX());
if (!result.contains(currentResolution))
result << currentResolution;
qSort(result.begin(), result.end(), numberLessThan);
return result;
}
/**
* Limit user to only be able to enter numbers.
* @param text Currently edited text
*/
void ResolutionWidget::slotTextChanged(const QString &text)
{
if (m_editField->currentText() == QStringLiteral("default"))
return;
bool ok;
text.toFloat(&ok);
if (!ok)
m_editField->setEditText(QStringLiteral(""));
}
| 2,363
|
C++
|
.cpp
| 78
| 26.75641
| 97
| 0.705055
|
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,349
|
comboboxwidgetbase.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/comboboxwidgetbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2019-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "comboboxwidgetbase.h"
#include <KComboBox>
#include <QHBoxLayout>
#include <QLabel>
ComboBoxWidgetBase::ComboBoxWidgetBase(const QString &title, const QString &postLabel, QWidget *parent)
: QWidget(parent)
, m_postLabel(nullptr)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
m_label = new QLabel(title, this);
layout->addWidget(m_label);
m_editField = new KComboBox(this);
m_editField->setEditable(true);
m_editField->setDuplicatesEnabled(false); // only allow one of each type in box
layout->addWidget(m_editField, 2);
m_label->setBuddy(m_editField);
if (!postLabel.isEmpty()) {
m_postLabel = new QLabel(postLabel, this);
layout->addWidget(m_postLabel);
}
setLayout(layout);
setFocusProxy(m_editField);
}
/**
* Return pointer to the KComboBox edit field.
*/
KComboBox * ComboBoxWidgetBase::editField()
{
return m_editField;
}
/**
* Add this widget to a given grid layout. Umbrello dialogs place labels in column 0
* and the editable field in column 1.
* @param layout The layout to which the widget should be added
* @param row The row in the grid layout where the widget should be placed
* @param startColumn The first column in the grid layout where the widget should be placed
*/
void ComboBoxWidgetBase::addToLayout(QGridLayout *layout, int row, int startColumn)
{
layout->addWidget(m_label, row, startColumn);
layout->addWidget(m_editField, row, startColumn + 1);
if (m_postLabel)
layout->addWidget(m_postLabel, row, startColumn + 2);
}
| 1,743
|
C++
|
.cpp
| 49
| 32.122449
| 103
| 0.732503
|
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,350
|
umldatatypewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/umldatatypewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umldatatypewidget.h"
#include "classifierlistitem.h"
#include "classifier.h"
#include "debug_utils.h"
#include "entityattribute.h"
#include "import_utils.h"
#include "model_utils.h"
#include "object_factory.h"
#include "operation.h"
#include "template.h"
#include "uml.h"
#include "umldoc.h"
#include <KComboBox>
#include <KLocalizedString>
#include <QApplication>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QWidget>
DEBUG_REGISTER(UMLDatatypeWidget)
UMLDatatypeWidget::UMLDatatypeWidget(UMLAttribute *attribute, QWidget *parent)
: ComboBoxWidgetBase(i18n("&Type:"), QString(), parent),
m_attribute(attribute),
m_datatype(nullptr),
m_entityAttribute(nullptr),
m_operation(nullptr),
m_template(nullptr)
{
init();
m_parent = m_attribute->umlParent()->umlParent()->asUMLClassifier();
insertTypesSortedParameter(m_attribute->getTypeName());
}
UMLDatatypeWidget::UMLDatatypeWidget(UMLClassifierListItem *datatype, QWidget *parent)
: ComboBoxWidgetBase(i18n("&Type:"), QString(), parent),
m_attribute(nullptr),
m_datatype(datatype),
m_entityAttribute(nullptr),
m_operation(nullptr),
m_template(nullptr)
{
init();
m_parent = m_datatype->umlParent()->asUMLClassifier();
insertTypesSortedAttribute(m_datatype->getTypeName());
}
UMLDatatypeWidget::UMLDatatypeWidget(UMLEntityAttribute *entityAttribute, QWidget *parent)
: ComboBoxWidgetBase(i18n("&Type:"), QString(), parent),
m_attribute(nullptr),
m_datatype(nullptr),
m_entityAttribute(entityAttribute),
m_operation(nullptr),
m_template(nullptr)
{
init();
m_parent = nullptr;
insertTypesSortedEntityAttribute(m_entityAttribute->getTypeName());
}
UMLDatatypeWidget::UMLDatatypeWidget(UMLOperation *operation, QWidget *parent)
: ComboBoxWidgetBase(i18n("&Type:"), QString(), parent),
m_attribute(nullptr),
m_datatype(nullptr),
m_entityAttribute(nullptr),
m_operation(operation),
m_template(nullptr)
{
init();
m_parent = m_operation->umlParent()->asUMLClassifier();
insertTypesSortedOperation(m_operation->getTypeName());
}
UMLDatatypeWidget::UMLDatatypeWidget(UMLTemplate *_template, QWidget *parent)
: ComboBoxWidgetBase(i18n("&Type:"), QString(), parent),
m_attribute(nullptr),
m_datatype(nullptr),
m_entityAttribute(nullptr),
m_operation(nullptr),
m_template(_template)
{
init();
m_parent = nullptr;
insertTypesSortedTemplate(m_template->getTypeName());
}
void UMLDatatypeWidget::init()
{
connect(m_editField, SIGNAL(editTextChanged(QString)), this, SIGNAL(editTextChanged(QString)));
}
bool UMLDatatypeWidget::apply()
{
if (m_datatype)
return applyAttribute();
else if (m_entityAttribute)
return applyEntityAttribute();
else if (m_operation)
return applyOperation();
else if (m_attribute)
return applyParameter();
else if (m_template)
return applyTemplate();
return false;
}
bool UMLDatatypeWidget::applyAttribute()
{
QString typeName = Model_Utils::normalize(m_editField->currentText());
UMLTemplate *tmplParam = m_parent->findTemplate(typeName);
if (tmplParam) {
m_datatype->setType(tmplParam);
return true;
}
UMLDoc * pDoc = UMLApp::app()->document();
UMLObject *obj = nullptr;
if (!typeName.isEmpty()) {
obj = pDoc->findUMLObject(typeName);
}
UMLClassifier *classifier = obj ? obj->asUMLClassifier() : nullptr;
if (classifier == nullptr) {
Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage();
// Import_Utils does not handle creating a new object with empty name
// string well. Use Object_Factory in those cases.
if (
(!typeName.isEmpty()) &&
((pl == Uml::ProgrammingLanguage::Cpp) ||
(pl == Uml::ProgrammingLanguage::Java))
) {
// Import_Utils::createUMLObject works better for C++ namespace
// and java package than Object_Factory::createUMLObject
Import_Utils::setRelatedClassifier(m_parent);
obj = Import_Utils::createUMLObject(UMLObject::ot_UMLObject, typeName);
Import_Utils::setRelatedClassifier(nullptr);
} else {
// If it's obviously a pointer type (C++) then create a datatype.
// Else we don't know what it is so as a compromise create a class.
UMLObject::ObjectType ot =
(typeName.contains(QChar::fromLatin1('*')) ? UMLObject::ot_Datatype
: UMLObject::ot_Class);
obj = Object_Factory::createUMLObject(ot, typeName);
}
if (obj == nullptr)
return false;
classifier = obj->asUMLClassifier();
}
m_datatype->setType(classifier);
return true;
}
bool UMLDatatypeWidget::applyEntityAttribute()
{
QString typeName = Model_Utils::normalize(m_editField->currentText());
UMLDoc *pDoc = UMLApp::app()->document();
UMLClassifierList dataTypes = pDoc->datatypes();
for(UMLClassifier* dat : dataTypes) {
if (typeName == dat->name()) {
m_entityAttribute->setType(dat);
return true;
}
}
UMLObject *obj = pDoc->findUMLObject(typeName);
UMLClassifier *classifier = obj->asUMLClassifier();
if (classifier == nullptr) {
// If it's obviously a pointer type (C++) then create a datatype.
// Else we don't know what it is so as a compromise create a class.
UMLObject::ObjectType ot =
(typeName.contains(QChar::fromLatin1('*')) ? UMLObject::ot_Datatype
: UMLObject::ot_Class);
obj = Object_Factory::createUMLObject(ot, typeName);
if (obj == nullptr)
return false;
classifier = obj->asUMLClassifier();
}
m_entityAttribute->setType(classifier);
return true;
}
bool UMLDatatypeWidget::applyOperation()
{
QString typeName = Model_Utils::normalize(m_editField->currentText());
UMLTemplate *tmplParam = nullptr;
if (m_parent) {
tmplParam = m_parent->findTemplate(typeName);
}
if (tmplParam)
m_operation->setType(tmplParam);
else
m_operation->setTypeName(typeName);
return true;
}
bool UMLDatatypeWidget::applyParameter()
{
// set the type name
QString typeName = Model_Utils::normalize(m_editField->currentText());
if (m_parent == nullptr) {
logError1("UMLDatatypeWidget::applyParameter: grandparent of %1 is not a UMLClassifier",
m_attribute->name());
} else {
UMLTemplate *tmplParam = m_parent->findTemplate(typeName);
if (tmplParam) {
m_attribute->setType(tmplParam);
return true;
}
}
UMLDoc * uDoc = UMLApp::app()->document();
UMLClassifierList namesList(uDoc->concepts());
bool matchFound = false;
for(UMLClassifier *obj : namesList) {
if (obj->fullyQualifiedName() == typeName) {
m_attribute->setType(obj);
matchFound = true;
break;
}
}
if (!matchFound) {
// Nothing found: Create a new type on the fly.
// @todo There should be an extra dialog to decide whether to
// create a datatype or a class. For now, we create a class.
logDebug1("UMLDatatypeWidget::applyParameter: %1 not found. Creating a new class for the type.",
typeName);
UMLObject *newObj = Object_Factory::createUMLObject(UMLObject::ot_Class, typeName);
m_attribute->setType(newObj);
}
return true;
}
bool UMLDatatypeWidget::applyTemplate()
{
QString typeName = Model_Utils::normalize(m_editField->currentText());
UMLDoc *pDoc = UMLApp::app()->document();
UMLClassifierList namesList(pDoc->concepts());
for(UMLClassifier *obj : namesList) {
if (typeName == obj->name()) {
m_template->setType(obj);
}
}
if (namesList.isEmpty()) { // not found.
// FIXME: This implementation is not good yet.
m_template->setTypeName(typeName);
}
return true;
}
/**
* Initialize types combo box from a list of types and a selected type.
* @param types list of types to add to combo box
* @param type selected type
*/
void UMLDatatypeWidget::initTypesBox(QStringList &types, const QString& type)
{
if (!types.contains(type)) {
types << type;
}
types.sort();
m_editField->clear();
m_editField->insertItems(-1, types);
int currentIndex = m_editField->findText(type);
if (currentIndex > -1) {
m_editField->setCurrentIndex(currentIndex);
}
m_editField->completionObject()->addItem(type);
}
/**
* Add classes and interfaces from document instance to the given string list.
* @param types list to store the classes and interfaces
* @param fullName if true then insert names including their package path
*/
void UMLDatatypeWidget::insertTypesFromConcepts(QStringList& types, bool fullName)
{
UMLDoc * uDoc = UMLApp::app()->document();
UMLClassifierList namesList(uDoc->concepts());
for(UMLClassifier *obj : namesList) {
types << (fullName ? obj->fullyQualifiedName() : obj->name());
}
}
/**
* Add datatypes from document instance to the given string list.
* @param types list to store the datatypes
*/
void UMLDatatypeWidget::insertTypesFromDatatypes(QStringList& types)
{
// add the data types
UMLDoc * pDoc = UMLApp::app()->document();
UMLClassifierList dataTypes = pDoc->datatypes();
if (dataTypes.count() == 0) {
// Switch to SQL as the active language if no datatypes are set.
UMLApp::app()->setActiveLanguage(Uml::ProgrammingLanguage::SQL);
pDoc->addDefaultDatatypes();
qApp->processEvents();
dataTypes = pDoc->datatypes();
}
for(UMLClassifier *dat : dataTypes) {
types << dat->name();
}
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
* The combobox is cleared and all types together with the optional new one
* sorted and then added again.
* @param type a new type to add
*/
void UMLDatatypeWidget::insertTypesSortedAttribute(const QString& type)
{
QStringList types;
insertTypesFromConcepts(types);
initTypesBox(types, type);
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
*/
void UMLDatatypeWidget::insertTypesSortedEntityAttribute(const QString& type)
{
QStringList types;
insertTypesFromDatatypes(types);
initTypesBox(types, type);
}
/**
* Inserts @p type into the type-combobox.
* The combobox is cleared and all types together with the optional new one
* sorted and then added again.
* @param type a new type to add and selected
*/
void UMLDatatypeWidget::insertTypesSortedOperation(const QString& type)
{
QStringList types;
// Add "void". We use this for denoting "no return type" independent
// of the programming language.
// For example, the Ada generator would interpret the return type
// "void" as an instruction to generate a procedure instead of a
// function.
types << QStringLiteral("void");
// add template parameters
const UMLClassifier *classifier = m_parent->asUMLClassifier();
if (classifier) {
UMLClassifierListItemList tmplParams(classifier->getFilteredList(UMLOperation::ot_Template));
for(UMLClassifierListItem *li : tmplParams) {
types << li->name();
}
}
insertTypesFromConcepts(types);
initTypesBox(types, type);
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
* The combobox is cleared and all types together with the optional new one
* sorted and then added again.
* @param type a new type to add and selected
*/
void UMLDatatypeWidget::insertTypesSortedParameter(const QString& type)
{
QStringList types;
// add template parameters
const UMLClassifier *pConcept = m_parent->asUMLClassifier();
if (pConcept == nullptr) {
logError1("UMLDatatypeWidget::insertTypesSortedParameter: grandparent of %1 "
" is not a UMLClassifier", m_attribute->name());
} else {
UMLTemplateList tmplParams(pConcept->getTemplateList());
for(UMLTemplate *t : tmplParams) {
types << t->name();
}
}
insertTypesFromConcepts(types);
initTypesBox(types, type);
}
/**
* Inserts @p type into the type-combobox.
* The combobox is cleared and all types together with the optional new one
* sorted and then added again.
* @param type a new type to add and selected
*/
void UMLDatatypeWidget::insertTypesSortedTemplate(const QString& type)
{
QStringList types;
// "class" is the nominal type of template parameter
types << QStringLiteral("class");
insertTypesFromConcepts(types, false);
initTypesBox(types, type);
}
| 13,153
|
C++
|
.cpp
| 372
| 29.913978
| 104
| 0.679398
|
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,351
|
imagetypewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/imagetypewidget.cpp
|
/*
SPDX-FileCopyrightText: 2015-2020 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 "imagetypewidget.h"
// kde includes
#include <KComboBox>
#include <KLocalizedString>
// qt includes
#include <QHBoxLayout>
#include <QLabel>
/**
* Constructor
* @param imageTypes A list of image types the user should be able to select from.
* @param _default String which is selected by default.
* @param parent Parent widget
*/
ImageTypeWidget::ImageTypeWidget(const QStringList &imageTypes, const QString &_default, QWidget *parent) :
QWidget(parent)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
m_label = new QLabel(i18n("&Image type:"), this);
m_label->setToolTip(i18n("The format that the images will be exported to"));
layout->addWidget(m_label);
m_comboBox = new KComboBox(this);
m_comboBox->addItems(imageTypes);
m_comboBox->setCurrentText(_default);
layout->addWidget(m_comboBox, 2);
m_comboBox->setEditable(false);
m_label->setBuddy(m_comboBox);
connect(m_comboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(slotCurrentIndexChanged(QString)));
setLayout(layout);
}
/**
* Return current type as string.
* @return String with currently selected type.
*/
QString ImageTypeWidget::currentType()
{
return m_comboBox->currentText();
}
/**
* Slot to export index changed signal from the combo box.
* @param index
*/
void ImageTypeWidget::slotCurrentIndexChanged(const QString &index)
{
Q_EMIT currentIndexChanged(index);
}
| 1,644
|
C++
|
.cpp
| 50
| 30.08
| 107
| 0.746062
|
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,352
|
documentationwidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/documentationwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "documentationwidget.h"
#include "associationwidget.h"
#include "codetextedit.h"
#include "operation.h"
#include "umlobject.h"
#include "umlwidget.h"
#include <QTextEdit>
#include <KLocalizedString>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QTabWidget>
DocumentationWidget::DocumentationWidget(UMLObject *o, QWidget *parent) :
QWidget(parent),
m_object(o),
m_widget(nullptr),
m_assocWidget(nullptr)
{
Q_ASSERT(o);
init(o->doc());
}
DocumentationWidget::DocumentationWidget(UMLWidget *w, QWidget *parent) :
QWidget(parent),
m_object(nullptr),
m_widget(w),
m_assocWidget(nullptr)
{
Q_ASSERT(w);
init(w->documentation());
}
DocumentationWidget::DocumentationWidget(AssociationWidget *w, QWidget *parent) :
QWidget(parent),
m_object(nullptr),
m_widget(nullptr),
m_assocWidget(w)
{
Q_ASSERT(w);
init(w->documentation());
}
DocumentationWidget::~DocumentationWidget()
{
delete m_editField;
delete m_box;
}
/**
* Apply changes to the related UMLObject.
*/
void DocumentationWidget::apply()
{
if (m_object) {
m_object->setDoc(m_editField->toPlainText());
if (m_object->isUMLOperation()) {
UMLOperation *o = m_object->asUMLOperation();
o->setSourceCode(m_codeEditField->toPlainText());
}
}
else if (m_widget) {
m_widget->setDocumentation(m_editField->toPlainText());
m_widget->updateGeometry();
}
else if (m_assocWidget) {
m_assocWidget->setDocumentation(m_editField->toPlainText());
}
}
/**
* initialize widget
* @param text text to display
*/
void DocumentationWidget::init(const QString &text)
{
QHBoxLayout *l = new QHBoxLayout;
l->setContentsMargins({});
m_box = new QGroupBox;
m_box->setTitle(i18n("Documentation"));
m_editField = new QTextEdit(m_box);
m_editField->setLineWrapMode(QTextEdit::WidgetWidth);
m_editField->setWordWrapMode(QTextOption::WordWrap);
m_editField->setText(text);
setFocusProxy(m_editField);
QHBoxLayout *layout = new QHBoxLayout(m_box);
if (m_object && m_object->isUMLOperation()) {
const UMLOperation *o = m_object->asUMLOperation();
m_codeEditField = new CodeTextEdit();
m_codeEditField->setPlainText(o->getSourceCode());
QTabWidget* tabWidget = new QTabWidget();
tabWidget->addTab(m_editField, i18n("Comment"));
tabWidget->addTab(m_codeEditField, i18n("Source Code"));
layout->addWidget(tabWidget);
} else {
layout->addWidget(m_editField);
}
int margin = fontMetrics().height();
layout->setContentsMargins(margin, margin, margin, margin);
l->addWidget(m_box);
setLayout(l);
}
| 2,890
|
C++
|
.cpp
| 99
| 24.848485
| 92
| 0.688601
|
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,353
|
defaultvaluewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/defaultvaluewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2018-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "defaultvaluewidget.h"
#include "enum.h"
#include "datatype.h"
#include "uml.h"
#include "umldoc.h"
#include <QLineEdit>
#include <KLocalizedString>
#include <QLabel>
#include <QHBoxLayout>
#include <QListWidget>
class DefaultValueWidget::Private {
public:
DefaultValueWidget *p;
QPointer<UMLObject>type;
QPointer<QLabel> label;
QPointer<QListWidget> listWidget;
QPointer<QLineEdit> lineWidget;
QString initialValue;
Private(DefaultValueWidget *parent, UMLObject *_type, const QString &_value)
: p(parent),
type(_type),
initialValue(_value)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
label = new QLabel(i18n("&Default value:"), p);
layout->addWidget(label);
listWidget = new QListWidget(p);
layout->addWidget(listWidget, 2);
lineWidget = new QLineEdit(p);
layout->addWidget(lineWidget, 2);
label->setBuddy(listWidget);
p->setLayout(layout);
p->setFocusProxy(listWidget);
setupWidget();
}
/**
* fill list widget with items
*/
void setupWidget()
{
if (type && type->isUMLEnum()) {
listWidget->clear();
listWidget->addItem(new QListWidgetItem);
const UMLEnum *e = type->asUMLEnum();
UMLClassifierListItemList enumLiterals = e->getFilteredList(UMLObject::ot_EnumLiteral);
for(UMLClassifierListItem* enumLiteral : enumLiterals) {
QListWidgetItem *item = new QListWidgetItem(enumLiteral->name());
listWidget->addItem(item);
}
QList<QListWidgetItem*> currentItem = listWidget->findItems(initialValue, Qt::MatchExactly);
if (currentItem.size() > 0)
listWidget->setCurrentItem(currentItem.at(0));
} else {
lineWidget->setText(initialValue);
}
setVisible(true);
}
void setVisible(bool state)
{
label->setVisible(state);
if (type && type->isUMLEnum()) {
listWidget->setVisible(state);
lineWidget->setVisible(false);
} else {
listWidget->setVisible(false);
lineWidget->setVisible(state);
}
}
void setValue(const QString &value)
{
initialValue = value;
}
QString value() const
{
if (type && type->isUMLEnum()) {
return listWidget && listWidget->currentItem() ? listWidget->currentItem()->text() : QString();
} else {
return lineWidget->text();
}
}
};
DefaultValueWidget::DefaultValueWidget(UMLObject *type, const QString &value, QWidget *parent)
: QWidget(parent),
m_d(new Private(this, type, value))
{
}
DefaultValueWidget::~DefaultValueWidget()
{
delete m_d;
}
/**
* Update widget with new data type
*
* @param type type to set widget from
*/
void DefaultValueWidget::setType(UMLObject *type)
{
if (m_d->type == type)
return;
m_d->type = type;
m_d->setupWidget();
}
/**
* Update widget with data type from a text string
*
* The method searches for a uml object with the specified
* name. If an object was found, the display of the selectable
* options depends on the type.
*
* @param _type type as text to set the widget from
*/
void DefaultValueWidget::setType(const QString &_type)
{
UMLObject *type = UMLApp::app()->document()->findUMLObject(_type, UMLObject::ot_UMLObject);
m_d->type = type;
m_d->setupWidget();
}
/**
* Add this widget to a given grid layout. Umbrello dialogs places labels in column 0
* and the editable field in column 1.
* @param layout The layout to which the widget should be added
* @param row The row in the grid layout where the widget should be placed
*/
void DefaultValueWidget::addToLayout(QGridLayout *layout, int row)
{
layout->addWidget(m_d->label, row, 0);
layout->addWidget(m_d->listWidget, row, 1);
layout->addWidget(m_d->lineWidget, row, 1);
}
/**
* return current text either from list box or from edit field
* @return current text
*/
QString DefaultValueWidget::value() const
{
return m_d->value();
}
/**
* Reimplemented from QWidget to control widgets visible state
* in case @ref addToLayout() has been called
*
* @param event show event
*/
void DefaultValueWidget::showEvent(QShowEvent *event)
{
m_d->setVisible(true);
QWidget::showEvent(event);
}
/**
* Reimplemented from QWidget to control widgets visible state
* in case @ref addToLayout() has been called
*
* @param event hide event
*/
void DefaultValueWidget::hideEvent(QHideEvent *event)
{
m_d->setVisible(false);
QWidget::hideEvent(event);
}
| 4,887
|
C++
|
.cpp
| 164
| 24.689024
| 107
| 0.665603
|
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,354
|
umlobjectnamewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/umlobjectnamewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlobjectnamewidget.h"
#include <QLineEdit>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QWidget>
UMLObjectNameWidget::UMLObjectNameWidget(const QString &label, const QString &text, QWidget *parent)
: QWidget(parent),
m_text(text)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
m_label = new QLabel(label, this);
layout->addWidget(m_label);
m_editField = new QLineEdit(this);
layout->addWidget(m_editField, 2);
m_editField->setText(text);
m_label->setBuddy(m_editField);
setLayout(layout);
setFocusProxy(m_editField);
}
UMLObjectNameWidget::~UMLObjectNameWidget()
{
delete m_editField;
delete m_label;
}
/**
* Add this widget to a given grid layout. Umbrello dialogs places labels in column 0
* and the editable field in column 1.
* @param layout The layout to which the widget should be added
* @param row The row in the grid layout where the widget should be placed
*/
void UMLObjectNameWidget::addToLayout(QGridLayout *layout, int row)
{
layout->addWidget(m_label, row, 0);
layout->addWidget(m_editField, row, 1);
}
QString UMLObjectNameWidget::text()
{
return m_editField->text();
}
void UMLObjectNameWidget::reset()
{
m_editField->setText(m_text);
}
| 1,459
|
C++
|
.cpp
| 49
| 26.795918
| 100
| 0.74
|
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,355
|
umlartifacttypewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/umlartifacttypewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlartifacttypewidget.h"
#include "uml.h"
#include <KLocalizedString>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QRadioButton>
typedef QMap<UMLArtifact::Draw_Type,QString> Map;
UMLArtifactTypeWidget::UMLArtifactTypeWidget(UMLArtifact *a, QWidget *parent) :
QWidget(parent),
m_object(a)
{
Map texts;
texts[UMLArtifact::file] = i18n("&File");
texts[UMLArtifact::library] = i18n("&Library");
texts[UMLArtifact::table] = i18n("&Table");
texts[UMLArtifact::defaultDraw] = i18nc("draw as default", "&Default");
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
m_box = new QGroupBox(i18n("Draw As"), this);
QHBoxLayout* drawAsLayout = new QHBoxLayout(m_box );
int margin = fontMetrics().height();
drawAsLayout->setContentsMargins(margin, margin, margin, margin);
for(Map::const_iterator i = texts.constBegin(); i != texts.constEnd(); ++i) {
QRadioButton *button = new QRadioButton(i.value(), m_box );
m_buttons[i.key()] = button;
drawAsLayout->addWidget(button);
}
m_buttons[a->getDrawAsType()]->setChecked(true);
layout->addWidget(m_box);
setLayout(layout);
}
UMLArtifactTypeWidget::~UMLArtifactTypeWidget()
{
delete m_box;
}
/**
* Add this widget to a given layout.
* @param layout The layout to which the widget should be added
*/
void UMLArtifactTypeWidget::addToLayout(QVBoxLayout *layout)
{
layout->addWidget(m_box);
}
/**
* Apply changes to the related UMLObject.
*/
void UMLArtifactTypeWidget::apply()
{
for(ButtonMap::const_iterator i = m_buttons.constBegin(); i != m_buttons.constEnd(); ++i) {
if (i.value()->isChecked())
m_object->setDrawAsType(i.key());
}
}
| 1,906
|
C++
|
.cpp
| 57
| 29.666667
| 95
| 0.70098
|
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,356
|
visibilityenumwidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/visibilityenumwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "visibilityenumwidget.h"
#include "associationwidget.h"
#include "uml.h"
#include "umlobject.h"
#include <KLocalizedString>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QRadioButton>
VisibilityEnumWidget::VisibilityEnumWidget(UMLObject *o, QWidget *parent)
: QWidget(parent),
m_object(o),
m_widget(nullptr),
m_role(Uml::RoleType::A)
{
Q_ASSERT(o);
m_texts[Uml::Visibility::Public] = i18nc("public visibility", "P&ublic");
m_texts[Uml::Visibility::Protected] = i18nc("protected visibility", "Pro&tected");
m_texts[Uml::Visibility::Private] = i18nc("private visibility", "P&rivate");
m_texts[Uml::Visibility::Implementation] = i18n("Imple&mentation");
init(i18n("Visibility"));
m_buttons[m_object->visibility()]->setChecked(true);
}
VisibilityEnumWidget::VisibilityEnumWidget(AssociationWidget *a, Uml::RoleType::Enum role, QWidget *parent)
: QWidget(parent),
m_object(nullptr),
m_widget(a),
m_role(role)
{
if (role == Uml::RoleType::A) {
m_texts[Uml::Visibility::Public] = i18nc("scope for A is public", "Public");
m_texts[Uml::Visibility::Protected] = i18nc("scope for A is protected", "Protected");
m_texts[Uml::Visibility::Private] = i18nc("scope for A is private", "Private");
m_texts[Uml::Visibility::Implementation] = i18nc("scope for A is implementation", "Implementation");
init(i18n("Role A Visibility"));
} else {
m_texts[Uml::Visibility::Public] = i18nc("scope for B is public", "Public");
m_texts[Uml::Visibility::Protected] = i18nc("scope for B is protected", "Protected");
m_texts[Uml::Visibility::Private] = i18nc("scope for B is private", "Private");
m_texts[Uml::Visibility::Implementation] = i18nc("scope for B is implementation", "Implementation");
init(i18n("Role B Visibility"));
}
m_buttons[a->visibility(role)]->setChecked(true);
}
VisibilityEnumWidget::~VisibilityEnumWidget()
{
// nothing here, parenting makes sure that all objects are destroyed
}
/**
* Add this widget to a given layout.
* @param layout The layout to which the widget should be added
*/
void VisibilityEnumWidget::addToLayout(QVBoxLayout *layout)
{
layout->addWidget(m_box);
}
/**
* Apply changes to the related UMLObject.
*/
void VisibilityEnumWidget::apply()
{
for(ButtonMap::const_iterator i = m_buttons.constBegin(); i != m_buttons.constEnd(); ++i) {
if (i.value()->isChecked()) {
if (m_object)
m_object->setVisibility(i.key());
else
m_widget->setVisibility(i.key(), m_role);
}
}
}
void VisibilityEnumWidget::init(const QString &title)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
m_box = new QGroupBox(title, this);
QHBoxLayout* boxlayout = new QHBoxLayout(m_box);
int margin = fontMetrics().height();
boxlayout->setContentsMargins(margin, margin, margin, margin);
QList<Uml::Visibility::Enum> orders;
orders << Uml::Visibility::Public << Uml::Visibility::Protected << Uml::Visibility::Private << Uml::Visibility::Implementation;
for(QList<Uml::Visibility::Enum>::const_iterator i = orders.constBegin(); i != orders.constEnd(); ++i) {
Uml::Visibility::Enum key = *i;
QRadioButton *button = new QRadioButton(m_texts[key], m_box);
m_buttons[key] = button;
boxlayout->addWidget(button);
}
layout->addWidget(m_box);
setLayout(layout);
}
| 3,681
|
C++
|
.cpp
| 92
| 35.076087
| 131
| 0.678412
|
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,357
|
umlpackagewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/umlpackagewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlpackagewidget.h"
#include "import_utils.h"
#include "model_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "folder.h"
#include "package.h"
#include <KComboBox>
#include <KLocalizedString>
#include <QHBoxLayout>
#include <QLabel>
UMLPackageWidget::UMLPackageWidget(UMLObject *o, QWidget *parent) :
QWidget(parent),
m_object(o)
{
Q_ASSERT(o);
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0,0,0,0);
m_label = new QLabel(i18n("Package path:"), this);
layout->addWidget(m_label);
m_editField = new KComboBox(this);
m_editField->setEditable(true);
layout->addWidget(m_editField, 2);
setLayout(layout);
m_label->setBuddy(m_editField);
Uml::ModelType::Enum guess = Model_Utils::guessContainer(o);
UMLPackageList packageList = UMLApp::app()->document()->packages(true, guess);
QStringList packages;
for(UMLPackage* package : packageList) {
packages << package->name();
}
packages.sort();
m_editField->insertItems(-1, packages);
QString packagePath = o->package();
UMLPackage* parentPackage = o->umlPackage();
UMLPackage* folderLogicalView =
UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical)->asUMLPackage();
if (parentPackage == nullptr ||
parentPackage == folderLogicalView) {
m_editField->setEditText(QString());
}
else {
m_editField->setEditText(packagePath);
}
}
UMLPackageWidget::~UMLPackageWidget()
{
delete m_editField;
delete m_label;
}
/**
* Add this widget to a given grid layout. Umbrello dialogs places labels in column 0
* and the editable field in column 1.
* @param layout The layout to which the widget should be added
* @param row The row in the grid layout where the widget should be placed
*/
void UMLPackageWidget::addToLayout(QGridLayout *layout, int row)
{
layout->addWidget(m_label, row, 0);
layout->addWidget(m_editField, row, 1);
}
/**
* Apply changes to the related UMLObject.
*/
void UMLPackageWidget::apply()
{
QString packageName = m_editField->currentText().trimmed();
UMLObject *newPackage = nullptr;
if (!packageName.isEmpty()) {
if ((newPackage = UMLApp::app()->document()->findUMLObject(packageName, UMLObject::ot_Package)) == nullptr) {
newPackage = Import_Utils::createUMLObject(UMLObject::ot_Package, packageName);
}
} else {
Uml::ModelType::Enum guess = Model_Utils::guessContainer(m_object);
newPackage = UMLApp::app()->document()->rootFolder(guess);
}
// adjust list view items
Model_Utils::treeViewMoveObjectTo(newPackage, m_object);
}
| 2,826
|
C++
|
.cpp
| 83
| 29.831325
| 117
| 0.69978
|
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,358
|
selectlayouttypewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/selectlayouttypewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2019-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "selectlayouttypewidget.h"
#include <KComboBox>
SelectLayoutTypeWidget::SelectLayoutTypeWidget(const QString &title, Uml::LayoutType::Enum selected, QWidget *parent)
: ComboBoxWidgetBase(title, QString(), parent)
{
for (int layoutTypeNo = Uml::LayoutType::Undefined + 1; layoutTypeNo < Uml::LayoutType::N_LAYOUTTYPES; ++layoutTypeNo) {
Uml::LayoutType::Enum lt = Uml::LayoutType::fromInt(layoutTypeNo);
const QString type = Uml::LayoutType::toString(lt);
m_editField->insertItem(layoutTypeNo-1, type);
m_editField->completionObject()->addItem(type);
}
m_editField->setCurrentIndex(selected - 1);
}
void SelectLayoutTypeWidget::setCurrentLayout(Uml::LayoutType::Enum layout)
{
m_editField->setCurrentIndex(layout - 1);
}
Uml::LayoutType::Enum SelectLayoutTypeWidget::currentLayout()
{
return Uml::LayoutType::fromInt(m_editField->currentIndex()+1);
}
| 1,063
|
C++
|
.cpp
| 25
| 38.84
| 124
| 0.749274
|
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,359
|
selectdiagramwidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/selectdiagramwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2019-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "selectdiagramwidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include <KComboBox>
#include <KLocalizedString>
#include <QLabel>
#include <QHBoxLayout>
/**
* constructor
* @param title title shown as label
* @param parent parent widget
*/
SelectDiagramWidget::SelectDiagramWidget(const QString &title, QWidget *parent)
: ComboBoxWidgetBase(title, QString(), parent)
{
}
/**
* setup widget woth diagram type, currently used diagram, diagram name to exclude and an option to choose a new diagram
* @param type
* @param currentName
* @param excludeName
* @param withNewEntry
*/
void SelectDiagramWidget::setupWidget(Uml::DiagramType::Enum type, const QString ¤tName, const QString &excludeName, bool withNewEntry)
{
QStringList diagrams;
for(UMLView *view : UMLApp::app()->document()->viewIterator()) {
QString name = view->umlScene()->name();
if (name == excludeName)
continue;
if (type == Uml::DiagramType::Undefined || type == view->umlScene()->type()) {
diagrams << name;
m_editField->completionObject()->addItem(name);
}
}
diagrams.sort();
if (withNewEntry)
diagrams.push_front(i18n("New"));
m_editField->clear();
m_editField->insertItems(-1, diagrams);
int currentIndex = m_editField->findText(currentName);
if (currentIndex > -1) {
m_editField->setCurrentIndex(currentIndex);
}
}
/**
* Return current text
* @return The text entered by the user
*/
QString SelectDiagramWidget::currentText()
{
return m_editField->currentText();
}
/**
* Return the id of the currently selected diagram
* @return id of diagram
* @return Uml::ID::None in case the diagram was not found
*/
Uml::ID::Type SelectDiagramWidget::currentID()
{
QString name = m_editField->currentText();
for (UMLView *view: UMLApp::app()->document()->viewIterator()) {
if (name == view->umlScene()->name())
return view->umlScene()->ID();
}
return Uml::ID::None;
}
| 2,219
|
C++
|
.cpp
| 73
| 26.657534
| 141
| 0.691624
|
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,360
|
umlstereotypewidget.cpp
|
KDE_umbrello/umbrello/dialogs/widgets/umlstereotypewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2014,2019 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlstereotypewidget.h"
#include "basictypes.h"
#include "stereotype.h"
#include "uml.h"
#include "umldoc.h"
#include <KComboBox>
#include <KLocalizedString>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QWidget>
Q_DECLARE_METATYPE(UMLStereotype*);
UMLStereotypeWidget::UMLStereotypeWidget(UMLObject *object, QWidget *parent)
: ComboBoxWidgetBase(i18n("Stereotype &name:"), QString(), parent)
, m_object(object)
{
Q_ASSERT(m_object);
insertItems(m_object->umlStereotype());
}
/**
* Set state if stereotypes could be edited. By default stereotypes could be edited.
* @param state edit state
*/
void UMLStereotypeWidget::setEditable(bool state)
{
m_editField->setEditable(state);
}
/**
* Apply changes to the related UMLObject.
*/
void UMLStereotypeWidget::apply()
{
if (m_editField->currentText().isEmpty()) {
m_object->setUMLStereotype(nullptr);
return;
}
QVariant v = m_editField->itemData(m_editField->currentIndex());
if (v.canConvert<UMLStereotype*>()) {
UMLStereotype *selected = v.value<UMLStereotype*>();
if (m_object->umlStereotype()) {
if (m_object->umlStereotype()->name() != m_editField->currentText())
m_object->setUMLStereotype(selected);
}
else
m_object->setUMLStereotype(selected);
} else {
UMLStereotype *stereotype = new UMLStereotype(m_editField->currentText());
UMLApp::app()->document()->addStereotype(stereotype);
m_object->setUMLStereotype(stereotype);
}
}
/**
* Insert stereotypes into combo box and select the currently used stereotype.
* @param type currently used stereotype
*/
void UMLStereotypeWidget::insertItems(UMLStereotype *type)
{
UMLDoc *umldoc = UMLApp::app()->document();
QMap<QString, UMLStereotype*> types;
for(UMLStereotype* ust : umldoc->stereotypes()) {
types[ust->name()] = ust;
}
// add the given parameter
if (type && !types.keys().contains(type->name())) {
types[type->name()] = type;
}
m_editField->clear();
m_editField->addItem(QStringLiteral(""), QVariant(0));
for(const QString &key : types.keys()) {
m_editField->addItem(key, QVariant::fromValue((types[key])));
}
// select the given parameter
if (type) {
int currentIndex = m_editField->findText(type->name());
if (currentIndex > -1) {
m_editField->setCurrentIndex(currentIndex);
}
m_editField->completionObject()->addItem(type->name());
}
}
| 2,728
|
C++
|
.cpp
| 84
| 27.845238
| 97
| 0.678829
|
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,361
|
pluginloader.cpp
|
KDE_umbrello/umbrello/_unused/pluginloader.cpp
|
/*
SPDX-FileCopyrightText: 2003 Andrew Sutton <ansutton@kent.edu>
SPDX-License-Identifier: GPL-2.0-or-later
*/
// own header
#include "pluginloader.h"
// Qt includes
#include <qstring.h>
// KDE includes
#include <kdebug.h>
#include <klibloader.h>
// u2 includes
#include "plugin.h"
using namespace Umbrello;
// static data
PluginLoader *PluginLoader::_instance = 0;
PluginLoader::PluginLoader() :
_plugins(),
_categories()
{
// proceed the categories
_categories["metamodel"] = PluginList();
_categories["storage"] = PluginList();
_categories["visual"] = PluginList();
}
PluginLoader::~PluginLoader()
{
}
PluginLoader *
PluginLoader::instance()
{
if(!_instance) _instance = new PluginLoader;
return _instance;
}
Plugin *
PluginLoader::loadPlugin(const QString &name)
{
KLibrary *lib = nullptr;
KLibFactory *factory = nullptr;
Plugin *plugin = nullptr;
PluginMap::iterator it;
bool success = true;
// if the plugin has already been loaded, increment
// its reference and return.
if((it = _plugins.find(name)) != _plugins.end()) {
plugin = it.value();
plugin->ref();
return plugin;
}
// use KLibLoader to get a reference to the library
lib = KLibLoader::self()->library(name);
if(!lib) {
kError() << "failed loading plugin library " << name ;
success = false;
}
// get the factory from the library
if(success) {
factory = lib->factory();
if(!factory) {
kError() << "failed to find factory for " << name ;
success = false;
}
}
// use the factory to create the plugin
if(success) {
plugin = dynamic_cast<Plugin *>(factory->create((QObject*)0));
if(!plugin) {
kError() << "failed to create a plugin object for " << name ;
success = false;
}
else {
// we have to register the plugin here, otherwise, we can get
// recursive loads
plugin->setObjectName(name);
_plugins[name] = plugin;
_categories[plugin->category()].append(plugin);
}
}
// initialize the plugin
if(success && plugin) {
success = plugin->init();
if(!success) {
// on failure, delete the plugin. this should cause the
// library to unload.
kError() << "failure initializing " << name ;
_categories[plugin->category()].remove(plugin);
_plugins.remove(name);
delete plugin;
}
}
// finally, finally connect to the destroyed signal and keep a
// reference to it
if(success) {
plugin->ref();
connect(plugin, SIGNAL(destroyed(QObject *)), SLOT(slotDestroyed(QObject *)));
}
return plugin;
}
Plugin *
PluginLoader::findPlugin(const QString &name)
{
PluginMap::iterator it = _plugins.find(name);
if(it != _plugins.end())
return it.value();
return 0;
}
void
PluginLoader::unloadPlugin(const QString &name)
{
KLibLoader::self()->unloadLibrary(name);
}
const PluginLoader::PluginMap &
PluginLoader::plugins() const
{
return _plugins;
}
const PluginLoader::CategoryMap &
PluginLoader::categories() const
{
return _categories;
}
void
PluginLoader::slotDestroyed(QObject *obj)
{
Plugin *plugin = static_cast<Plugin *>(obj);
// we cannot just use the name because it has already been destroyed
// at this point. we have to iterate through and find the reference
// by hand.
PluginMap::iterator end(_plugins.end());
for(PluginMap::iterator i = _plugins.begin(); i != end; ++i) {
Plugin *p = i.value();
if(p == plugin) {
kDebug() << "unloading plugin " << i.key();
// remove it from the mapping
_plugins.erase(i);
break;
}
}
}
| 3,909
|
C++
|
.cpp
| 139
| 22.532374
| 86
| 0.617254
|
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,362
|
plugin.cpp
|
KDE_umbrello/umbrello/_unused/plugin.cpp
|
/*
SPDX-FileCopyrightText: 2003 Andrew Sutton <ansutton@kent.edu>
SPDX-License-Identifier: GPL-2.0-or-later
*/
// own header
#include "plugin.h"
// KDE includes
#include <kdebug.h>
#include <kconfig.h>
#include <kapplication.h>
// app includes
#include "pluginloader.h"
using namespace Umbrello;
Plugin::Plugin(QObject *parent,
const char *name,
const QStringList & /* args */) :
QObject(parent, name),
Configurable(),
_ref(0),
_instanceName(name),
_config(0)
{
}
Plugin::~Plugin()
{
}
void
Plugin::ref()
{
_ref++;
}
void
Plugin::unload()
{
_ref--;
if(_ref == 0) {
// save the name
QString pluginName = _instanceName;
// shutdown and delete
shutdown();
delete this;
// once the object is destroyed, we can have the plugin loader unload
// the library.
PluginLoader::instance()->unloadPlugin(pluginName);
}
}
bool
Plugin::init()
{
bool ret = true;
// initialize this plugin first - then load other plugins
ret = onInit();
if(!ret) {
kError() << "failed to initialize " << instanceName() ;
}
// configure on load plugins
if(ret) {
ret = configure();
if(!ret) {
kError() << "failed configuration " << instanceName() ;
}
}
return true;
}
bool
Plugin::shutdown()
{
bool ret = true;
// always unload plugins, even if things are failing
unloadPlugins();
// shutdown this plugin
ret = onShutdown();
if(!ret) {
kError() << "failed to shutdown " << instanceName() ;
}
return true;
}
QByteArray
Plugin::instanceName() const
{
return _instanceName;
}
KConfig *
Plugin::config()
{
return _config;
}
bool
Plugin::onInit()
{
return true;
}
bool
Plugin::onShutdown()
{
return true;
}
bool
Plugin::configure()
{
bool ret = true;
// grab the OnStartup map
KConfig *conf = config();
if(!conf) {
kDebug() << "no configuration for " << instanceName();
ret = false;
}
if(ret) {
// load standard plugins by default
loadPlugins(conf, "Load Actions", "Load");
// only load GUI plugins if this is not a terminal app
if(KApplication::kApplication()->type() != QApplication::Tty) {
loadPlugins(conf, "Load Actions", "LoadGUI");
}
}
return ret;
}
QString
Plugin::category()
{
return QStringLiteral("miscellaneous");
}
| 2,516
|
C++
|
.cpp
| 122
| 16.122951
| 77
| 0.609725
|
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,363
|
configurable.cpp
|
KDE_umbrello/umbrello/_unused/configurable.cpp
|
/*
SPDX-FileCopyrightText: 2003 Andrew Sutton <ansutton@kent.edu>
SPDX-License-Identifier: GPL-2.0-or-later
*/
// own header
#include "configurable.h"
// Qt includes
#include <qstringlist.h>
// KDE includes
#include <kdebug.h>
#include <kconfig.h>
#include <kconfiggroup.h>
// local includes
#include "pluginloader.h"
#include "plugin.h"
using namespace Umbrello;
Configurable::Configurable() :
_plugins()
{
}
Configurable::~Configurable()
{
unloadPlugins();
}
bool
Configurable::loadPlugins(KConfig *config,
const QString &group,
const QString &key)
{
bool ret = true;
KConfigGroup grp(config, group);
QStringList names = grp.readEntry(key,QStringList());
for (int i = 0; i != names.size(); i++) {
const QString &name = names[i];
kDebug() << "loading plugin " << name;
// load the plugin
Plugin *plugin = PluginLoader::instance()->loadPlugin(name);
// keep the plugin
if(plugin) {
_plugins.append(plugin);
}
}
return ret;
}
bool
Configurable::unloadPlugins()
{
// just iterate through and dereference all the
// plugins.
for(uint i = 0; i != _plugins.count(); i++) {
Plugin *plugin = _plugins.at(i);
plugin->unload();
}
_plugins.clear();
return true;
}
| 1,373
|
C++
|
.cpp
| 56
| 19.607143
| 68
| 0.626728
|
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,364
|
objectsmodel.cpp
|
KDE_umbrello/umbrello/models/objectsmodel.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "objectsmodel.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "folder.h"
#include "operation.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobjectprivate.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QtDebug>
Q_DECLARE_METATYPE(UMLObject*);
ObjectsModel::ObjectsModel()
{
}
bool ObjectsModel::add(UMLObject *o)
{
if (m_allObjects.contains(o))
return false;
int index = m_allObjects.size();
beginInsertRows(QModelIndex(), index, index);
m_allObjects.append(o);
endInsertRows();
return true;
}
bool ObjectsModel::remove(UMLObject *o)
{
int index = m_allObjects.indexOf(o);
if (index == -1)
return false;
beginRemoveRows(QModelIndex(), index, index);
m_allObjects.removeAll(o);
endRemoveRows();
return true;
}
int ObjectsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
int count = m_allObjects.size();
return count;
}
int ObjectsModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 7;
}
QVariant ObjectsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section < 0)
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Vertical)
return section + 1;
if (section == 0)
return QVariant(i18n("Name"));
else if (section == 1)
return QVariant(i18n("Type"));
else if (section == 2)
return QVariant(i18n("Folder"));
else if (section == 3)
return QVariant(i18n("ID"));
else if (section == 4)
return QVariant(i18n("Saved"));
else if (section == 5)
return QVariant(i18n("Parent"));
else if (section == 6)
return QVariant(i18n("Pointer"));
else return QVariant();
}
QVariant ObjectsModel::data(const QModelIndex & index, int role) const
{
if (role == Qt::UserRole && index.column() == 0) {
QVariant v;
v.setValue(m_allObjects.at(index.row()).data());
return v;
}
else if (role != Qt::DisplayRole)
return QVariant();
int cCount = columnCount(index);
if (index.column() >= cCount)
return QVariant();
UMLObject *o = m_allObjects.at(index.row());
// each case needs to return
switch (index.column()) {
case 0:
return o->name();
case 1:
return o->baseTypeStr();
case 2:
if (o->umlPackage())
return o->umlPackage()->name();
else if (o->parent()) {
UMLObject *p = dynamic_cast<UMLObject*>(o->parent());
if (p)
return p->name();
}
return QVariant();
case 3:
return Uml::ID::toString(o->id());
case 4:
return o->m_d->isSaved;
case 5:
if (o->umlPackage()) {
const UMLFolder *f = o->umlPackage()->asUMLFolder();
if (f) {
UMLObjectList content = f->containedObjects();
if (content.contains(o))
return QStringLiteral("package +");
content = f->subordinates();
if (content.contains(o))
return QStringLiteral("list +");
}
else
return QStringLiteral("package -");
} else if (o->umlParent()) {
if (o->isUMLAttribute()) {
const UMLOperation *op = o->umlParent()->asUMLOperation();
if (op && op->getParmList().contains(o->asUMLAttribute()))
return QStringLiteral("parent +");
else
return QStringLiteral("parent -");
} else if (o->isUMLOperation()) {
const UMLClassifier *c = o->umlParent()->asUMLClassifier();
if (c && c->getOpList().contains(o->asUMLOperation()))
return QStringLiteral("parent +");
else
return QStringLiteral("parent -");
}
return QStringLiteral("not implemented");
} else
return QStringLiteral("no parent");
return QVariant();
case 6:
return QString::number((quintptr)o, 16);
default:
return QVariant();
}
}
void ObjectsModel::emitDataChanged(const QModelIndex &index)
{
Q_EMIT dataChanged(index, index);
}
void ObjectsModel::emitDataChanged(int index)
{
QModelIndex mi = createIndex(index,0);
Q_EMIT dataChanged(mi, mi);
}
void ObjectsModel::emitDataChanged(UMLObject *o)
{
int index = m_allObjects.indexOf(o);
emitDataChanged(index);
}
| 4,778
|
C++
|
.cpp
| 159
| 23.188679
| 92
| 0.597911
|
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,365
|
stereotypesmodel.cpp
|
KDE_umbrello/umbrello/models/stereotypesmodel.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2015-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "stereotypesmodel.h"
// app includes
#include "stereotype.h"
#include "uml.h"
#include "umldoc.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QtDebug>
StereotypesModel::StereotypesModel(UMLStereotypeList& stereotypes)
: m_count(0),
m_stereotypes(stereotypes)
{
}
int StereotypesModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
int count = m_stereotypes.count();
return count;
}
int StereotypesModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant StereotypesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section < 0)
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Vertical)
return section + 1;
if (section == 0)
return QVariant(i18n("Name"));
else if (section == 1)
return QVariant(i18n("Usage"));
else return QVariant();
}
QVariant StereotypesModel::data(const QModelIndex & index, int role) const
{
if (role == Qt::UserRole && index.column() == 0) {
QVariant v;
v.setValue(m_stereotypes.at(index.row()));
return v;
}
if (role != Qt::DisplayRole)
return QVariant();
int cCount = columnCount(index);
if (index.column() >= cCount)
return QVariant();
UMLStereotype *s = m_stereotypes.at(index.row());
if (cCount == 1) {
QString a = s->name() + QString(QStringLiteral(" (%1)")).arg(s->refCount());
return a;
}
// table view
if (index.column() == 0)
return s->name();
else
return s->refCount();
}
bool StereotypesModel::addStereotype(UMLStereotype *stereotype)
{
if (m_stereotypes.contains(stereotype))
return false;
for(UMLStereotype *s : m_stereotypes) {
if (s->name() == stereotype->name()) {
return false;
}
}
int index = m_stereotypes.count();
beginInsertRows(QModelIndex(), index, index);
m_stereotypes.append(stereotype);
endInsertRows();
return true;
}
bool StereotypesModel::removeStereotype(UMLStereotype *stereotype)
{
if (!m_stereotypes.contains(stereotype)) {
UMLStereotype *stFound = nullptr;
for(UMLStereotype *s : m_stereotypes) {
if (s->name() == stereotype->name()) {
stFound = s;
break;
}
}
if (stFound == nullptr)
return false;
stereotype = stFound;
}
int index = m_stereotypes.indexOf(stereotype);
beginRemoveRows(QModelIndex(), index, index);
m_stereotypes.removeAll(stereotype);
endRemoveRows();
return true;
}
void StereotypesModel::emitDataChanged(const QModelIndex &index)
{
Q_EMIT dataChanged(index, index);
}
void StereotypesModel::emitDataChanged(int index)
{
QModelIndex mi = createIndex(index,0);
Q_EMIT dataChanged(mi, mi);
}
| 3,116
|
C++
|
.cpp
| 110
| 23.209091
| 95
| 0.653936
|
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,366
|
diagramsmodel.cpp
|
KDE_umbrello/umbrello/models/diagramsmodel.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "diagramsmodel.h"
// app includes
#include "umlscene.h"
#include "umlview.h"
#include "uml.h"
#include "umldoc.h"
#include "folder.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QtDebug>
DiagramsModel::DiagramsModel()
: m_count(0)
{
}
int DiagramsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
int count = m_views.size();
return count;
}
int DiagramsModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 4;
}
QVariant DiagramsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section < 0)
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Vertical)
return section + 1;
if (section == 0)
return QVariant(i18n("Name"));
else if (section == 1)
return QVariant(i18n("Type"));
else if (section == 2)
return QVariant(i18n("Folder"));
else if (section == 3)
return QVariant(i18n("Widgets/Associations"));
else return QVariant();
}
QVariant DiagramsModel::data(const QModelIndex & index, int role) const
{
if (role == Qt::UserRole && index.column() == 0) {
QVariant v;
v.setValue(m_views.at(index.row()).data());
return v;
}
else if (role == Qt::DecorationRole && index.column() == 0) {
UMLView *v = m_views.at(index.row());
return QVariant(Icon_Utils::smallIcon(v->umlScene()->type()));
}
else if (role != Qt::DisplayRole)
return QVariant();
int cCount = columnCount(index);
if (index.column() >= cCount)
return QVariant();
UMLView *v = m_views.at(index.row());
if (index.column() == 0)
return v->umlScene()->name();
else if (index.column() == 1)
return Uml::DiagramType::toStringI18n(v->umlScene()->type());
else if (index.column() == 2)
return v->umlScene()->folder()->name();
else
return QVariant(QString::number(v->umlScene()->widgetList().size())
+ QStringLiteral("/")
+ QString::number(v->umlScene()->associationList().size()));
}
bool DiagramsModel::addDiagram(UMLView *view)
{
if (m_views.contains(view))
return false;
int index = m_views.size();
beginInsertRows(QModelIndex(), index, index);
m_views.append(view);
endInsertRows();
return true;
}
bool DiagramsModel::removeDiagram(UMLView *view)
{
if (!m_views.contains(view))
return false;
int index = m_views.indexOf(view);
beginRemoveRows(QModelIndex(), index, index);
m_views.removeAll(view);
endRemoveRows();
return true;
}
bool DiagramsModel::removeAllDiagrams()
{
if (!m_views.count())
return false;
beginRemoveRows(QModelIndex(), 0, m_views.count() - 1);
m_views.clear();
endRemoveRows();
return true;
}
void DiagramsModel::emitDataChanged(const QModelIndex &index)
{
Q_EMIT dataChanged(index, index);
}
void DiagramsModel::emitDataChanged(int index)
{
QModelIndex mi = createIndex(index,0);
Q_EMIT dataChanged(mi, mi);
}
void DiagramsModel::emitDataChanged(UMLView *view)
{
int index = m_views.indexOf(view);
emitDataChanged(index);
}
| 3,420
|
C++
|
.cpp
| 119
| 24.084034
| 92
| 0.653354
|
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,367
|
objectwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/objectwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header file
#include "objectwidget.h"
// local includes
#include "classpropertiesdialog.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "listpopupmenu.h"
#include "messagewidget.h"
#include "seqlinewidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
#include "umlscene.h"
#include "umlview.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPointer>
#include <QPainter>
#include <QValidator>
#include <QXmlStreamWriter>
#define O_MARGIN 5
#define O_WIDTH 40
#define A_WIDTH 20
#define A_HEIGHT 40
#define A_MARGIN 5
DEBUG_REGISTER_DISABLED(ObjectWidget)
/**
* The number of pixels margin between the lowest message
* and the bottom of the vertical line
*/
static const int sequenceLineMargin = 20;
/**
* Creates an ObjectWidget.
*
* @param scene The parent to this object.
* @param o The object it will be representing.
*/
ObjectWidget::ObjectWidget(UMLScene * scene, UMLObject *o)
: UMLWidget(scene, WidgetBase::wt_Object, o),
m_multipleInstance(false),
m_drawAsActor(false),
m_showDestruction(false),
m_isOnDestructionBox(false)
{
if (m_scene && m_scene->isSequenceDiagram()) {
m_pLine = new SeqLineWidget( m_scene, this );
m_pLine->setStartPoint(x() + width() / 2, y() + height());
} else {
m_pLine = nullptr;
}
}
/**
* Destructor.
*/
ObjectWidget::~ObjectWidget()
{
cleanup();
}
/**
* Sets whether representing a multi-instance object.
*
* @param multiple Object state. true- multi, false - single.
*/
void ObjectWidget::setMultipleInstance(bool multiple)
{
//make sure only calling this in relation to an object on a collab. diagram
if (m_scene && m_scene->isCollaborationDiagram()) {
m_multipleInstance = multiple;
updateGeometry();
update();
}
}
/**
* Returns whether object is representing a multi-object.
*
* @return True if object is representing a multi-object.
*/
bool ObjectWidget::multipleInstance() const
{
return m_multipleInstance;
}
void ObjectWidget::setSelected(bool state)
{
UMLWidget::setSelected(state);
if (m_pLine) {
QPen pen = m_pLine->pen();
int lineWidth = (int)UMLWidget::lineWidth();
if (state)
lineWidth = lineWidth ? lineWidth * 2 : 2;
pen.setWidth(lineWidth);
m_pLine->setPen(pen);
}
}
/**
* Overridden from UMLWidget.
* Moves the widget to a new position using the difference between the
* current position and the new position.
* Y position is ignored, and widget is only moved along X axis.
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position
* (isn't used).
*/
void ObjectWidget::moveWidgetBy(qreal diffX, qreal diffY)
{
setX(x() + diffX);
if (m_scene && (m_scene->type() != Uml::DiagramType::Sequence)) {
setY(y() + diffY);
}
}
/**
* Overridden from UMLWidget.
* Modifies the value of the diffX and diffY variables used to move the widgets.
* All the widgets are constrained to be moved only in X axis (diffY is set to 0).
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void ObjectWidget::constrainMovementForAllWidgets(qreal &diffX, qreal &diffY)
{
Q_UNUSED(diffX);
if (m_scene && m_scene->isSequenceDiagram()) {
diffY = 0;
}
}
/**
* Override default method.
*/
void ObjectWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if (m_drawAsActor)
paintActor(painter);
else
paintObject(painter);
setPenFromSettings(painter);
UMLWidget::paint(painter, option, widget);
}
/**
* Handles a popup menu selection.
*/
void ObjectWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
updateGeometry();
moveEvent(nullptr);
update();
break;
case ListPopupMenu::mt_Up:
tabUp();
break;
case ListPopupMenu::mt_Down:
tabDown();
break;
default:
UMLWidget::slotMenuSelection(action);
break;
}
}
/**
* Overrides method from UMLWidget
*/
QSizeF ObjectWidget::minimumSize() const
{
int width, height;
const QFontMetrics &fm = getFontMetrics(FT_UNDERLINE);
const int fontHeight = fm.lineSpacing();
const QString t = m_instanceName + QStringLiteral(" : ") + name();
const int textWidth = fm.horizontalAdvance(t);
if (m_drawAsActor) {
width = textWidth > A_WIDTH?textWidth:A_WIDTH;
height = A_HEIGHT + fontHeight + A_MARGIN;
width += A_MARGIN * 2;
} else {
width = textWidth > O_WIDTH?textWidth:O_WIDTH;
height = fontHeight + O_MARGIN * 2;
width += O_MARGIN * 2;
if (m_multipleInstance) {
width += 10;
height += 10;
}
}//end else drawasactor
return QSizeF(width, height);
}
/**
* Sets whether to draw as an Actor.
*
* @param drawAsActor True if widget shall be drawn as an actor.
*/
void ObjectWidget::setDrawAsActor(bool drawAsActor)
{
m_drawAsActor = drawAsActor;
updateGeometry();
}
/**
* Returns whether to draw as an Actor or not.
*
* @return True if widget is drawn as an actor.
*/
bool ObjectWidget::drawAsActor() const
{
return m_drawAsActor;
}
/**
* Activate the object after serializing it from a QDataStream
*/
bool ObjectWidget::activate(IDChangeLog *ChangeLog /*= nullptr*/)
{
if (! UMLWidget::activate(ChangeLog))
return false;
if (m_showDestruction && m_pLine)
m_pLine->setupDestructionBox();
moveEvent(nullptr);
return true;
}
/**
* Sets the x-coordinate.
* Reimplements the method from UMLWidget.
*
* @param x The x-coordinate to be set.
*/
void ObjectWidget::setX(qreal x)
{
UMLWidget::setX(x);
moveEvent(nullptr);
}
/**
* Sets the y-coordinate.
* Reimplements the method from UMLWidget.
*
* @param y The y-coordinate to be set.
*/
void ObjectWidget::setY(qreal y)
{
UMLWidget::setY(y);
if (!UMLApp::app()->document()->loading())
moveEvent(nullptr);
}
/**
* Return the x coordinate of the widgets center.
* @return The x-coordinate of the widget center.
*/
qreal ObjectWidget::centerX()
{
return x() + width()/2;
}
/**
* Overrides the standard operation.
*/
void ObjectWidget::moveEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
Q_EMIT sigWidgetMoved(m_nLocalID);
if (m_pLine) {
m_pLine->setStartPoint(x() + width() / 2, y() + height());
}
}
/**
* Overrides the standard operation.
*/
void ObjectWidget::mousePressEvent(QGraphicsSceneMouseEvent *me)
{
UMLWidget::mousePressEvent(me);
m_isOnDestructionBox = false;
if (m_pLine && m_pLine->onDestructionBox(me->scenePos())) {
m_isOnDestructionBox = true;
qreal oldX = x() + width() / 2;
qreal oldY = getEndLineY() - 10;
m_oldPos = QPointF(oldX, oldY);
}
}
/**
* Overrides the standard operation.
*/
void ObjectWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* me)
{
if (m_inResizeArea) {
DEBUG() << "resizing...";
resize(me);
moveEvent(nullptr);
return;
}
if (m_isOnDestructionBox) {
qreal diffY = me->scenePos().y() - m_oldPos.y();
moveDestructionBy(diffY);
}
else {
UMLWidget::mouseMoveEvent(me);
}
}
/**
* Moves the destruction Box to a new position using the difference between the
* current position and the new position.
* The destruction box is only moved along Y axis.
*
* @param diffY The difference between current Y position and new Y position
*/
void ObjectWidget::moveDestructionBy(qreal diffY)
{
// endLine = length of the life line + diffY - 10 to center on the destruction box
qreal endLine = getEndLineY() + diffY - 10;
SeqLineWidget *pLine = sequentialLine();
pLine->setEndOfLine(endLine);
m_oldPos.setY(endLine);
}
/**
* Handles a color change signal.
*/
void ObjectWidget::slotFillColorChanged(Uml::ID::Type /*viewID*/)
{
UMLWidget::setFillColor(m_scene->fillColor());
UMLWidget::setLineColor(m_scene->lineColor());
if(m_pLine)
m_pLine->setPen(QPen(UMLWidget::lineColor(), UMLWidget::lineWidth(), Qt::DashLine));
}
/**
* Used to cleanup any other widget it may need to delete.
*/
void ObjectWidget::cleanup()
{
UMLWidget::cleanup();
if(m_pLine) {
m_pLine->cleanup();
delete m_pLine;
m_pLine = nullptr;
}
}
/**
* Show a properties dialog for an ObjectWidget.
*/
bool ObjectWidget::showPropertiesDialog()
{
bool result = false;
UMLApp::app()->docWindow()->updateDocumentation(false);
QPointer<ClassPropertiesDialog> dlg = new ClassPropertiesDialog((QWidget*)UMLApp::app(), this);
if (dlg->exec()) {
UMLApp::app()->docWindow()->showDocumentation(this, true);
UMLApp::app()->document()->setModified(true);
result = true;
}
dlg->close();
delete dlg;
return result;
}
/**
* Draw the object as an object (default).
*/
void ObjectWidget::paintObject(QPainter *painter)
{
QFont oldFont = painter->font();
QFont font = UMLWidget::font();
font.setUnderline(true);
painter->setFont(font);
setPenFromSettings(painter);
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
else
painter->setBrush(m_scene->backgroundColor());
const int w = width();
const int h = height();
const QString t = m_instanceName + QStringLiteral(" : ") + name();
int multiInstOfst = 0;
if (m_multipleInstance) {
painter->drawRect(10, 10, w - 10, h - 10);
painter->drawRect(5, 5, w - 10, h - 10);
multiInstOfst = 10;
}
painter->drawRect(0, 0, w - multiInstOfst, h - multiInstOfst);
painter->setPen(textColor());
painter->drawText(O_MARGIN, O_MARGIN,
w - O_MARGIN * 2 - multiInstOfst, h - O_MARGIN * 2 - multiInstOfst,
Qt::AlignCenter, t);
painter->setFont(oldFont);
}
/**
* Draw the object as an actor.
*/
void ObjectWidget::paintActor(QPainter *painter)
{
const QFontMetrics &fm = getFontMetrics(FT_UNDERLINE);
setPenFromSettings(painter);
if (UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
const int w = width();
const int textStartY = A_HEIGHT + A_MARGIN;
const int fontHeight = fm.lineSpacing();
const int middleX = w / 2;
const int thirdH = A_HEIGHT / 3;
//draw actor
painter->drawEllipse(middleX - A_WIDTH / 2, 0, A_WIDTH, thirdH);//head
painter->drawLine(middleX, thirdH, middleX, thirdH * 2);//body
painter->drawLine(middleX, 2 * thirdH,
middleX - A_WIDTH / 2, A_HEIGHT);//left leg
painter->drawLine(middleX, 2 * thirdH,
middleX + A_WIDTH / 2, A_HEIGHT);//right leg
painter->drawLine(middleX - A_WIDTH / 2, thirdH + thirdH / 2,
middleX + A_WIDTH / 2, thirdH + thirdH / 2);//arms
//draw text
painter->setPen(textColor());
QString t = m_instanceName + QStringLiteral(" : ") + name();
painter->drawText(A_MARGIN, textStartY,
w - A_MARGIN * 2, fontHeight, Qt::AlignCenter, t);
}
/**
* Move the object up on a sequence diagram.
*/
void ObjectWidget::tabUp()
{
int newY = y() - height();
if (newY < topMargin())
newY = topMargin();
setY(newY);
adjustAssocs(x(), newY);
}
/**
* Move the object down on a sequence diagram.
*/
void ObjectWidget::tabDown()
{
int newY = y() + height();
setY(newY);
adjustAssocs(x(), newY);
}
/**
* Returns the top margin constant (Y axis value)
*
* @return Y coordinate of the space between the diagram top
* and the upper edge of the ObjectWidget.
*/
int ObjectWidget::topMargin()
{
return 80 - height();
}
/**
* Returns whether or not the widget can be moved vertically up.
*
* @return True if widget can be moved upwards vertically.
*/
bool ObjectWidget::canTabUp()
{
return (y() > topMargin());
}
/**
* Sets whether to show deconstruction on sequence line.
*
* @param bShow True if destruction on line shall be shown.
*/
void ObjectWidget::setShowDestruction(bool bShow)
{
m_showDestruction = bShow;
if(m_pLine)
m_pLine->setupDestructionBox();
}
/**
* Returns whether to show deconstruction on sequence line.
*
* @return True if destruction on sequence line is shown.
*/
bool ObjectWidget::showDestruction() const
{
return m_showDestruction;
}
/**
* Sets the y position of the bottom of the vertical line.
*
* @param yPosition The y coordinate for the bottom of the line.
*/
void ObjectWidget::setEndLine(int yPosition)
{
if (m_pLine) {
m_pLine->setEndOfLine(yPosition);
}
}
/**
* Returns the end Y co-ord of the sequence line.
*
* @return Y coordinate of the endpoint of the sequence line.
*/
int ObjectWidget::getEndLineY()
{
int y = this->y() + height();
if(m_pLine)
y += m_pLine->getLineLength();
if (m_showDestruction)
y += 10;
return y;
}
/**
* Add a message widget to the list.
*
* @param message Pointer to the MessageWidget to add.
*/
void ObjectWidget::messageAdded(MessageWidget* message)
{
if (m_messages.count(message)) {
logError1("ObjectWidget::messageAdded(%1) duplicate entry", message->name());
return ;
}
m_messages.append(message);
}
/**
* Remove a message widget from the list.
*
* @param message Pointer to the MessageWidget to remove.
*/
void ObjectWidget::messageRemoved(MessageWidget* message)
{
if (m_messages.removeAll(message) == false) {
logError1("ObjectWidget::messageAdded(%1) missing entry", message->name());
return ;
}
}
/**
* Called when a message widget with an end on this object has
* moved up or down.
* Sets the bottom of the line to a nice position.
*/
void ObjectWidget::slotMessageMoved()
{
if (m_pLine) {
int lowestMessage = 0;
for(MessageWidget* message : m_messages) {
int messageHeight = message->y() + message->height();
if (lowestMessage < messageHeight) {
lowestMessage = messageHeight;
}
}
m_pLine->setEndOfLine(lowestMessage + sequenceLineMargin);
}
}
/**
* Returns whether a message is overlapping with another message.
* Used by MessageWidget::paint() methods.
*
* @param y top of your message
* @param messageWidget pointer to your message so it doesn't check against itself
*/
bool ObjectWidget::messageOverlap(qreal y, MessageWidget* messageWidget)
{
for(MessageWidget* message : m_messages) {
if (message == messageWidget) {
continue;
}
const qreal msgY = message->y();
const qreal msgHeight = msgY + message->height();
if (y >= msgY && y <= msgHeight) {
return true;
}
}
return false;
}
/**
* Overridden from UMLWidget
* Set color of object widget and sequence line on sequence diagrams.
*/
void ObjectWidget::setLineColorCmd(const QColor &color)
{
UMLWidget::setLineColorCmd(color);
if (m_pLine) {
m_pLine->setLineColorCmd(color);
}
}
/**
* Return the SeqLineWidget.
* Returns a non NULL pointer if this ObjectWidget is part of a
* sequence diagram.
*/
SeqLineWidget *ObjectWidget::sequentialLine() const
{
return m_pLine;
}
/**
* Overridden from UMLWidget.
* Returns the cursor to be shown when resizing the widget.
* The cursor shown is KCursor::sizeHorCursor().
*
* @return The cursor to be shown when resizing the widget.
*/
QCursor ObjectWidget::resizeCursor() const
{
return Qt::SizeHorCursor;
}
/**
* Overridden from UMLWidget.
* Resizes the width of the object widget.
* Object widgets can only be resized horizontally, so height isn't modified.
*
* @param newW The new width for the widget.
* @param newH The new height for the widget (isn't used).
*/
void ObjectWidget::resizeWidget(qreal newW, qreal newH)
{
Q_UNUSED(newH);
setSize(newW, height());
}
/**
* Saves to the "objectwidget" XMI element.
*/
void ObjectWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("objectwidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("drawasactor"), QString::number(m_drawAsActor));
writer.writeAttribute(QStringLiteral("multipleinstance"), QString::number(m_multipleInstance));
writer.writeAttribute(QStringLiteral("decon"), QString::number(m_showDestruction));
writer.writeEndElement();
}
/**
* Loads from a "objectwidget" XMI element.
*/
bool ObjectWidget::loadFromXMI(QDomElement& qElement)
{
if(!UMLWidget::loadFromXMI(qElement))
return false;
QString draw = qElement.attribute(QStringLiteral("drawasactor"), QStringLiteral("0"));
QString multi = qElement.attribute(QStringLiteral("multipleinstance"), QStringLiteral("0"));
QString decon = qElement.attribute(QStringLiteral("decon"), QStringLiteral("0"));
m_drawAsActor = (bool)draw.toInt();
m_multipleInstance = (bool)multi.toInt();
m_showDestruction = (bool)decon.toInt();
return true;
}
| 17,729
|
C++
|
.cpp
| 632
| 24.224684
| 100
| 0.676277
|
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,368
|
activitywidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/activitywidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "activitywidget.h"
// app includes
#include "activitydialog.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "dialogspopupmenu.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "widget_utils.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPointer>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(ActivityWidget)
/**
* Creates an Activity widget.
*
* @param scene The parent of the widget.
* @param activityType The type of activity.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
ActivityWidget::ActivityWidget(UMLScene * scene, ActivityType activityType, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Activity, id),
m_activityType(activityType)
{
// Set non zero size to avoid crash on painting.
// We cannot call the reimplemented method minimumSize() in the constructor
// because the vtable is not yet finalized (i.e. dynamic dispatch does not work).
setSize(15, 15);
}
/**
* Destructor.
*/
ActivityWidget::~ActivityWidget()
{
}
/**
* Returns the type of activity.
*/
ActivityWidget::ActivityType ActivityWidget::activityType() const
{
return m_activityType;
}
/**
* Returns the type string of activity.
*/
QString ActivityWidget::activityTypeStr() const
{
return QLatin1String(ENUM_NAME(ActivityWidget, ActivityType, m_activityType));
}
/**
* Sets the type of activity.
*/
void ActivityWidget::setActivityType(ActivityType activityType)
{
m_activityType = activityType;
updateGeometry();
UMLWidget::m_resizable = true;
}
/**
* Determines whether a toolbar button represents an Activity.
* CHECK: currently unused - can this be removed?
*
* @param tbb The toolbar button enum input value.
* @param resultType The ActivityType corresponding to tbb.
* This is only set if tbb is an Activity.
* @return True if tbb represents an Activity.
*/
bool ActivityWidget::isActivity(WorkToolBar::ToolBar_Buttons tbb,
ActivityType& resultType)
{
bool status = true;
switch (tbb) {
case WorkToolBar::tbb_Initial_Activity:
resultType = Initial;
break;
case WorkToolBar::tbb_Activity:
resultType = Normal;
break;
case WorkToolBar::tbb_End_Activity:
resultType = End;
break;
case WorkToolBar::tbb_Final_Activity:
resultType = Final;
break;
case WorkToolBar::tbb_Branch:
resultType = Branch;
break;
default:
status = false;
break;
}
return status;
}
/**
* This method get the name of the preText attribute.
*/
QString ActivityWidget::preconditionText() const
{
return m_preconditionText;
}
/**
* This method set the name of the preText attribute
*/
void ActivityWidget::setPreconditionText(const QString& aPreText)
{
m_preconditionText = aPreText;
updateGeometry();
adjustAssocs(x(), y());
}
/**
* This method get the name of the postText attribute.
*/
QString ActivityWidget::postconditionText() const
{
return m_postconditionText;
}
/**
* This method set the name of the postText attribute
*/
void ActivityWidget::setPostconditionText(const QString& aPostText)
{
m_postconditionText = aPostText;
updateGeometry();
adjustAssocs(x(), y());
}
/**
* Reimplemented from UMLWidget::showPropertiesDialog to show a
* properties dialog for an ActivityWidget.
*/
bool ActivityWidget::showPropertiesDialog()
{
bool result = false;
UMLApp::app()->docWindow()->updateDocumentation(false);
QPointer<ActivityDialog> dialog = new ActivityDialog(umlScene()->activeView(), this);
if (dialog->exec() && dialog->getChangesMade()) {
UMLApp::app()->docWindow()->showDocumentation(this, true);
UMLApp::app()->document()->setModified(true);
result = true;
}
delete dialog;
return result;
}
/**
* Overrides the standard paint event.
*/
void ActivityWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
int w = width();
int h = height();
// Only for the final activity
float x;
float y;
QPen pen = painter->pen();
switch (m_activityType)
{
case Normal:
UMLWidget::setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textStartY = (h / 2) - (fontHeight / 2);
painter->drawRoundRect(0, 0, w, h, (h * 60) / w, 60);
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
painter->drawText(ACTIVITY_MARGIN, textStartY,
w - ACTIVITY_MARGIN * 2, fontHeight, Qt::AlignCenter, name());
}
break;
case Initial:
painter->setPen(QPen(WidgetBase::lineColor(), 1));
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(0, 0, w, h);
break;
case Final:
UMLWidget::setPenFromSettings(painter);
painter->setBrush(Qt::white);
pen.setWidth(2);
pen.setColor (Qt::red);
painter->setPen(pen);
painter->drawEllipse(0, 0, w, h);
x = w/2 ;
y = h/2 ;
{
const float w2 = 0.7071 * (float)w / 2.0;
painter->drawLine((int)(x - w2 + 1), (int)(y - w2 + 1), (int)(x + w2), (int)(y + w2));
painter->drawLine((int)(x + w2 - 1), (int)(y - w2 + 1), (int)(x - w2), (int)(y + w2));
}
break;
case End:
painter->setPen(QPen(WidgetBase::lineColor(), 1));
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(0, 0, w, h);
painter->setBrush(Qt::white);
painter->drawEllipse(1, 1, w - 2, h - 2);
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(3, 3, w - 6, h - 6);
break;
case Branch:
UMLWidget::setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
{
QPolygon array(4);
array[ 0 ] = QPoint(w / 2, 0);
array[ 1 ] = QPoint(w, h / 2);
array[ 2 ] = QPoint(w / 2, h);
array[ 3 ] = QPoint(0, h / 2);
painter->drawPolygon(array);
painter->drawPolyline(array);
}
break;
case Invok:
UMLWidget::setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textStartY = (h / 2) - (fontHeight / 2);
painter->drawRoundRect(0, 0, w, h, (h * 60) / w, 60);
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
painter->drawText(ACTIVITY_MARGIN, textStartY,
w - ACTIVITY_MARGIN * 2, fontHeight, Qt::AlignCenter, name());
}
x = w - (w/5);
y = h - (h/3);
painter->drawLine((int)x, (int) y, (int)x, (int)(y + 20));
painter->drawLine((int)(x - 10), (int)(y + 10), (int)(x + 10), (int)(y + 10));
painter->drawLine((int)(x - 10), (int)(y + 10), (int)(x - 10), (int)(y + 20));
painter->drawLine((int)(x + 10), (int)(y + 10), (int)(x + 10), (int)(y + 20));
break;
case Param:
UMLWidget::setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
QString preCond = Widget_Utils::adornStereo(QStringLiteral("precondition")) + preconditionText();
QString postCond = Widget_Utils::adornStereo(QStringLiteral("postcondition")) + postconditionText();
//int textStartY = (h / 2) - (fontHeight / 2);
painter->drawRoundRect(0, 0, w, h, (h * 60) / w, 60);
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
painter->drawText(ACTIVITY_MARGIN, fontHeight + 10,
w - ACTIVITY_MARGIN * 2, fontHeight, Qt::AlignCenter, preCond);
painter->drawText(ACTIVITY_MARGIN, fontHeight * 2 + 10,
w - ACTIVITY_MARGIN * 2, fontHeight, Qt::AlignCenter, postCond);
painter->drawText(ACTIVITY_MARGIN, (fontHeight / 2),
w - ACTIVITY_MARGIN * 2, fontHeight, Qt::AlignCenter, name());
}
break;
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overridden from UMLWidget due to emission of signal sigActMoved()
*/
void ActivityWidget::moveWidgetBy(qreal diffX, qreal diffY)
{
UMLWidget::moveWidgetBy(diffX, diffY);
Q_EMIT sigActMoved(diffX, diffY);
}
/**
* Loads the widget from the "activitywidget" XMI element.
*/
bool ActivityWidget::loadFromXMI(QDomElement& qElement)
{
if(!UMLWidget::loadFromXMI(qElement))
return false;
setName(qElement.attribute(QStringLiteral("activityname")));
setDocumentation(qElement.attribute(QStringLiteral("documentation")));
setPreconditionText(qElement.attribute(QStringLiteral("precondition")));
setPostconditionText(qElement.attribute(QStringLiteral("postcondition")));
QString type = qElement.attribute(QStringLiteral("activitytype"), QStringLiteral("1"));
setActivityType((ActivityType)type.toInt());
return true;
}
/**
* Saves the widget to the "activitywidget" XMI element.
*/
void ActivityWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("activitywidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("activityname"), name());
writer.writeAttribute(QStringLiteral("documentation"), documentation());
writer.writeAttribute(QStringLiteral("precondition"), preconditionText());
writer.writeAttribute(QStringLiteral("postcondition"), postconditionText());
writer.writeAttribute(QStringLiteral("activitytype"), QString::number(m_activityType));
writer.writeEndElement();
}
/**
* Overrides Method from UMLWidget.
*/
void ActivityWidget::constrain(qreal& width, qreal& height)
{
if (m_activityType == Normal || m_activityType == Invok || m_activityType == Param) {
UMLWidget::constrain(width, height);
return;
}
if (width > height)
width = height;
else if (height > width)
height = width;
UMLWidget::constrain(width, height);
}
/**
* Captures any popup menu signals for menus it created.
*/
void ActivityWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString n = name();
bool ok = Dialog_Utils::askRenameName(WidgetBase::wt_Activity, n);
if (ok && !n.isEmpty()) {
setName(n);
}
}
break;
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Overrides method from UMLWidget
*/
QSizeF ActivityWidget::minimumSize() const
{
if (m_activityType == Normal || m_activityType == Invok || m_activityType == Param) {
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textWidth = fm.width(name());
int height = fontHeight;
height = height > ACTIVITY_HEIGHT ? height : ACTIVITY_HEIGHT;
height += ACTIVITY_MARGIN * 2;
textWidth = textWidth > ACTIVITY_WIDTH ? textWidth : ACTIVITY_WIDTH;
if (m_activityType == Invok) {
height += 40;
} else if (m_activityType == Param) {
QString maxSize;
maxSize = name().length() > postconditionText().length() ? name() : postconditionText();
maxSize = maxSize.length() > preconditionText().length() ? maxSize : preconditionText();
textWidth = fm.width(maxSize);
textWidth = textWidth + 50;
height += 100;
}
int width = textWidth > ACTIVITY_WIDTH ? textWidth : ACTIVITY_WIDTH;
width += ACTIVITY_MARGIN * 4;
return QSizeF(width, height);
}
else if (m_activityType == Branch) {
return QSizeF(20, 20);
}
return QSizeF(15, 15);
}
/**
* Overrides method from UMLWidget
*/
QSizeF ActivityWidget::maximumSize()
{
if (m_activityType == Normal || m_activityType == Invok || m_activityType == Param) {
return UMLWidget::maximumSize();
}
if (m_activityType == Branch) {
return QSizeF(50, 50);
}
return QSizeF(30, 30);
}
| 13,324
|
C++
|
.cpp
| 394
| 27.72335
| 112
| 0.633794
|
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,369
|
associationwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/associationwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "associationwidget.h"
// app includes
#include "association.h"
#include "associationpropertiesdialog.h"
#include "associationwidgetpopupmenu.h"
#include "assocrules.h"
#include "attribute.h"
#include "classifier.h"
#include "classifierwidget.h"
#define DBG_SRC QStringLiteral("AssociationWidget")
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "entity.h"
#include "floatingtextwidget.h"
#include "messagewidget.h"
#include "objectwidget.h"
#include "operation.h"
#include "optionstate.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
#include "widget_utils.h"
#include "instance.h"
#include "instanceattribute.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QColorDialog>
#include <QFontDialog>
#include <QPainterPath>
#include <QPointer>
#include <QApplication>
#include <QXmlStreamWriter>
// system includes
#include <cmath>
DEBUG_REGISTER_DISABLED(AssociationWidget)
// Tolerance by which a point may deviate from the linepath start or end point
// but still be counted as belonging to the start or end point.
// The case that the linepath start/end points are not perfectly on one of the
// widget's edges arises while moving a widget. During the move, the widget
// position is first updated and subsequently, in a separate step, the start/end
// points are updated.
// In between the two update operations the displacement shall be tolerated.
#define PIXEL_TOLERANCE 20
using namespace Uml;
/**
* Constructor is private because the static create() methods shall
* be used for constructing AssociationWidgets.
*
* @param scene The parent view of this widget.
*/
AssociationWidget::AssociationWidget(UMLScene *scene)
: WidgetBase(scene, WidgetBase::wt_Association),
m_activated(false),
m_unNameLineSegment(-1),
m_nLinePathSegmentIndex(-1),
m_pAssocClassLine(nullptr),
m_pAssocClassLineSel0(nullptr),
m_pAssocClassLineSel1(nullptr),
m_associationLine(this),
m_associationClass(nullptr),
m_associationType(Uml::AssociationType::Association),
m_nameWidget(nullptr)
{
m_role[0].setParent(this);
m_role[1].setParent(this);
// propagate line color and width set by base class constructor
// which does not call the virtual methods from this class.
setLineColor(lineColor());
setLineWidth(lineWidth());
setFlag(QGraphicsLineItem::ItemIsSelectable);
setAcceptHoverEvents(true);
}
/**
* This constructor is only for loading from XMI, otherwise it
* should not be used as it creates an incomplete associationwidget.
*
* @param scene The parent view of this widget.
*/
AssociationWidget* AssociationWidget::create(UMLScene *scene)
{
AssociationWidget* instance = new AssociationWidget(scene);
return instance;
}
/**
* Preferred constructor (static factory method.)
*
* @param scene The parent view of this widget.
* @param pWidgetA Pointer to the role A widget for the association.
* @param assocType The AssociationType::Enum for this association.
* @param pWidgetB Pointer to the role B widget for the association.
* @param umlobject Pointer to the underlying UMLObject (if applicable.)
*/
AssociationWidget* AssociationWidget::create
(UMLScene *scene, UMLWidget* pWidgetA,
Uml::AssociationType::Enum assocType, UMLWidget* pWidgetB,
UMLObject *umlobject /* = nullptr */)
{
AssociationWidget* instance = new AssociationWidget(scene);
if (umlobject) {
instance->setUMLObject(umlobject);
} else {
// set up UMLAssociation obj if assoc is represented and both roles are UML objects
if (Uml::AssociationType::hasUMLRepresentation(assocType)) {
UMLObject* umlRoleA = pWidgetA->umlObject();
UMLObject* umlRoleB = pWidgetB->umlObject();
if (umlRoleA != nullptr && umlRoleB != nullptr) {
bool swap;
// Check that we are not attempting to create the same Generalization /
// Dependency / Association_Self / Coll_Mesg_Self / Seq_Message_Self /
// Containment / Realization between the same two objects when such an
// association already exists.
UMLDoc *doc = UMLApp::app()->document();
UMLAssociation *myAssoc = doc->findAssociation(assocType, umlRoleA, umlRoleB, &swap);
if (myAssoc != nullptr) {
switch (assocType) {
case Uml::AssociationType::Generalization:
case Uml::AssociationType::Dependency:
case Uml::AssociationType::Association_Self:
case Uml::AssociationType::Coll_Mesg_Self:
case Uml::AssociationType::Seq_Message_Self:
case Uml::AssociationType::Containment:
case Uml::AssociationType::Realization:
logDebug4("Ignoring second construction of same assoctype %1 between %2 and %3 "
"(swap=%4)", assocType, umlRoleA->name(), umlRoleB->name(), swap);
break;
default:
logDebug4("Constructing a similar or exact same assoctype %1 between %2 and %3 "
"as an already existing assoc (swap=%4)",
assocType, umlRoleA->name(), umlRoleB->name(), swap);
// now, just create a new association anyways
myAssoc = nullptr;
break;
}
}
if (myAssoc == nullptr) {
myAssoc = new UMLAssociation(assocType, umlRoleA, umlRoleB);
// CHECK: myAssoc is not yet inserted at any parent UMLPackage -
// need to check carefully that all callers do this, lest it be
// orphaned.
// ToolBarStateAssociation::addAssociationInViewAndDoc() is
// okay in this regard.
}
instance->setUMLAssociation(myAssoc);
}
}
}
instance->setWidgetForRole(pWidgetA, RoleType::A);
instance->setWidgetForRole(pWidgetB, RoleType::B);
instance->setAssociationType(assocType);
instance->calculateEndingPoints();
instance->associationLine().calculateInitialEndPoints();
instance->associationLine().reconstructSymbols();
//The AssociationWidget is set to Activated because it already has its side widgets
instance->setActivated(true);
// sync UML meta-data to settings here
instance->mergeAssociationDataIntoUMLRepresentation();
// Collaboration messages need a name label because it's that
// which lets operator== distinguish them, which in turn
// permits us to have more than one message between two objects.
if (instance->isCollaboration()) {
// Create a temporary name to bring on setName()
int collabID = instance->m_scene->generateCollaborationId();
instance->setName(QLatin1Char('m') + QString::number(collabID));
}
return instance;
}
/**
* Destructor.
*/
AssociationWidget::~AssociationWidget()
{
}
/**
* Overriding the method from WidgetBase because we need to do
* something extra in case this AssociationWidget represents
* an attribute of a classifier.
* @todo Change WidgetBase::setUMLObject and reimplementers to return bool
* where `false` indicates failure. Currently, if setting the UML
* object fails the callers have no immediate way of knowing.
*/
void AssociationWidget::setUMLObject(UMLObject *obj)
{
UMLObject *umlSave = WidgetBase::umlObject();
WidgetBase::setUMLObject(obj);
if (obj == nullptr)
return;
UMLClassifier *klass = nullptr;
UMLAttribute *attr = nullptr;
UMLEntity *ent = nullptr;
const UMLObject::ObjectType ot = obj->baseType();
switch (ot) {
case UMLObject::ot_Association:
setUMLAssociation(obj->asUMLAssociation());
break;
case UMLObject::ot_Operation:
setOperation(obj->asUMLOperation());
break;
case UMLObject::ot_Attribute:
klass = obj->umlParent()->asUMLClassifier();
connect(klass, SIGNAL(attributeRemoved(UMLClassifierListItem*)),
this, SLOT(slotClassifierListItemRemoved(UMLClassifierListItem*)));
attr = obj->asUMLAttribute();
connect(attr, SIGNAL(attributeChanged()), this, SLOT(slotAttributeChanged()));
break;
case UMLObject::ot_EntityAttribute:
ent = obj->umlParent()->asUMLEntity();
connect(ent, SIGNAL(entityAttributeRemoved(UMLClassifierListItem*)),
this, SLOT(slotClassifierListItemRemoved(UMLClassifierListItem*)));
break;
case UMLObject::ot_ForeignKeyConstraint:
ent = obj->umlParent()->asUMLEntity();
connect(ent, SIGNAL(entityConstraintRemoved(UMLClassifierListItem*)),
this, SLOT(slotClassifierListItemRemoved(UMLClassifierListItem*)));
break;
default:
logError1("AssociationWidget::setUMLObject cannot associate UMLObject of type %1",
UMLObject::toString(ot));
WidgetBase::setUMLObject(umlSave);
break;
}
}
/**
* Set all 'owned' child widgets to this font.
*/
void AssociationWidget::lwSetFont (QFont font)
{
if (m_nameWidget) {
m_nameWidget->setFont(font);
}
m_role[RoleType::A].setFont(font);
m_role[RoleType::B].setFont(font);
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
* @todo Move to LinkWidget.
*/
UMLClassifier *AssociationWidget::operationOwner()
{
Uml::RoleType::Enum role = (isCollaboration() ? Uml::RoleType::B : Uml::RoleType::A);
UMLObject *o = widgetForRole(role)->umlObject();
if (!o) {
return nullptr;
}
UMLClassifier *c = o->asUMLClassifier();
if (!c) {
logError1("AssociationWidget::operationOwner: widgetForRole(%1) is not a classifier",
Uml::RoleType::toString(role));
}
return c;
}
/**
* Implements operation from LinkWidget.
* Motivated by FloatingTextWidget.
*/
UMLOperation *AssociationWidget::operation()
{
return m_umlObject->asUMLOperation();
}
/**
* Implements operation from LinkWidget.
* Motivated by FloatingTextWidget.
*/
void AssociationWidget::setOperation(UMLOperation *op)
{
if (m_umlObject)
disconnect(m_umlObject, SIGNAL(modified()), m_nameWidget, SLOT(setMessageText()));
m_umlObject = op;
if (m_umlObject)
connect(m_umlObject, SIGNAL(modified()), m_nameWidget, SLOT(setMessageText()));
if (m_nameWidget)
m_nameWidget->setMessageText();
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
QString AssociationWidget::customOpText()
{
return name();
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
void AssociationWidget::setCustomOpText(const QString &opText)
{
setName(opText);
}
/**
* Calls setTextPosition on all the labels.
* Overrides operation from LinkWidget.
*/
void AssociationWidget::resetTextPositions()
{
if (m_role[RoleType::A].multiplicityWidget) {
setTextPosition(TextRole::MultiA);
}
if (m_role[RoleType::B].multiplicityWidget) {
setTextPosition(Uml::TextRole::MultiB);
}
if (m_role[RoleType::A].changeabilityWidget) {
setTextPosition(Uml::TextRole::ChangeA);
}
if (m_role[RoleType::B].changeabilityWidget) {
setTextPosition(Uml::TextRole::ChangeB);
}
if (m_nameWidget) {
setTextPosition(Uml::TextRole::Name);
}
if (m_role[RoleType::A].roleWidget) {
setTextPosition(Uml::TextRole::RoleAName);
}
if (m_role[RoleType::B].roleWidget) {
setTextPosition(Uml::TextRole::RoleBName);
}
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*
* @param ft The text widget which to update.
*/
void AssociationWidget::setMessageText(FloatingTextWidget *ft)
{
if (isCollaboration()) {
ft->setSequenceNumber(m_SequenceNumber);
if (m_umlObject != nullptr) {
ft->setText(operationText(m_scene));
} else {
ft->setText(name());
}
} else {
ft->setText(name());
}
}
/**
* Sets the text of the given FloatingTextWidget.
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
void AssociationWidget::setText(FloatingTextWidget *ft, const QString &text)
{
Uml::TextRole::Enum role = ft->textRole();
switch (role) {
case Uml::TextRole::Name:
setName(text);
break;
case Uml::TextRole::RoleAName:
setRoleName(text, RoleType::A);
break;
case Uml::TextRole::RoleBName:
setRoleName(text, RoleType::B);
break;
case Uml::TextRole::MultiA:
setMultiplicity(text, RoleType::A);
break;
case Uml::TextRole::MultiB:
setMultiplicity(text, RoleType::B);
break;
default:
logWarn1("AssociationWidget::setText unhandled TextRole %1", Uml::TextRole::toString(role));
break;
}
}
/**
* Shows the association properties dialog and updates the
* corresponding texts if its execution is successful.
*/
bool AssociationWidget::showPropertiesDialog()
{
bool result = false;
UMLApp::app()->docWindow()->updateDocumentation();
QPointer<AssociationPropertiesDialog> dlg = new AssociationPropertiesDialog(static_cast<QWidget*>(m_scene->activeView()), this);
if (dlg->exec()) {
UMLApp::app()->docWindow()->showDocumentation(this, true);
result = true;
}
delete dlg;
return result;
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
QString AssociationWidget::lwOperationText()
{
return name();
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*
* @return classifier
*/
UMLClassifier* AssociationWidget::lwClassifier()
{
UMLObject *o = widgetForRole(RoleType::B)->umlObject();
UMLClassifier *c = o->asUMLClassifier();
return c;
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*
* @param op The new operation string to set.
*/
void AssociationWidget::setOperationText(const QString &op)
{
if (!op.isEmpty()) {
setName(op);
}
}
/**
* Calculates the m_unNameLineSegment index according to m_nameWidget
* middle point PT.
* It iterates through all AssociationLine's segments and for each one
* calculates the sum of PT's distance to the start point + PT's
* distance to the end point. The segment with the smallest sum will
* be the RoleTextSegment (if this segment moves then the RoleText
* will move with it). It sets m_unNameLineSegment to the start point
* of the chosen segment.
*
* Overrides operation from LinkWidget (i.e. this method is also
* required by FloatingTextWidget.)
*/
void AssociationWidget::calculateNameTextSegment()
{
if (!m_nameWidget) {
return;
}
//changed to use the middle of the text
//i think this will give a better result.
//never know what sort of lines people come up with
//and text could be long to give a false reading
qreal xt = m_nameWidget->x();
qreal yt = m_nameWidget->y();
xt += m_nameWidget->width() / 2;
yt += m_nameWidget->height() / 2;
int size = m_associationLine.count();
//sum of length(PTP1) and length(PTP2)
qreal total_length = 0;
qreal smallest_length = 0;
for (int i = 0; i < size - 1; ++i) {
QPointF pi = m_associationLine.point( i );
QPointF pj = m_associationLine.point( i+1 );
qreal xtiDiff = xt - pi.x();
qreal xtjDiff = xt - pj.x();
qreal ytiDiff = yt - pi.y();
qreal ytjDiff = yt - pj.y();
total_length = sqrt( double(xtiDiff * xtiDiff + ytiDiff * ytiDiff) )
+ sqrt( double(xtjDiff * xtjDiff + ytjDiff * ytjDiff) );
//this gives the closest point
if (total_length < smallest_length || i == 0) {
smallest_length = total_length;
m_unNameLineSegment = i;
}
}
}
/**
* Returns the UMLAssociation representation of this object.
*
* @return Pointer to the UMLAssociation that is represented by
* this AsociationWidget.
*/
UMLAssociation* AssociationWidget::association() const
{
if (m_umlObject == nullptr || umlObject()->baseType() != UMLObject::ot_Association)
return nullptr ;
return m_umlObject->asUMLAssociation();
}
/**
* Returns the UMLAttribute representation of this object.
*
* @return Pointer to the UMLAttribute that is represented by
* this AsociationWidget.
*/
UMLAttribute* AssociationWidget::attribute() const
{
if (m_umlObject == nullptr)
return nullptr;
UMLObject::ObjectType ot = m_umlObject->baseType();
if (ot != UMLObject::ot_Attribute && ot != UMLObject::ot_EntityAttribute && ot != UMLObject::ot_InstanceAttribute)
return nullptr;
return m_umlObject->asUMLAttribute();
}
#if 0 //:TODO:
/**
* Overrides the assignment operator.
*/
AssociationWidget& AssociationWidget::operator=(const AssociationWidget& other)
{
m_associationLine = other.m_associationLine;
if (other.m_nameWidget) {
m_nameWidget = new FloatingTextWidget(m_scene);
*m_nameWidget = *(other.m_nameWidget);
} else {
m_nameWidget = 0;
}
for (unsigned r = (unsigned)A; r <= (unsigned)B; ++r) {
WidgetRole& lhs = m_role[r];
const WidgetRole& rhs = other.m_role[r];
lhs.m_nIndex = rhs.m_nIndex;
lhs.m_nTotalCount = rhs.m_nTotalCount;
if (rhs.multiplicityWidget) {
lhs.multiplicityWidget = new FloatingTextWidget(m_scene);
*(lhs.multiplicityWidget) = *(rhs.multiplicityWidget);
} else {
lhs.multiplicityWidget = 0;
}
if (rhs.roleWidget) {
lhs.roleWidget = new FloatingTextWidget(m_scene);
*(lhs.roleWidget) = *(rhs.roleWidget);
} else {
lhs.roleWidget = 0;
}
if (rhs.changeabilityWidget) {
lhs.changeabilityWidget = new FloatingTextWidget(m_scene);
*(lhs.changeabilityWidget) = *(rhs.changeabilityWidget);
} else {
lhs.changeabilityWidget = 0;
}
lhs.umlWidget = rhs.umlWidget;
lhs.m_WidgetRegion = rhs.m_WidgetRegion;
}
m_activated = other.m_activated;
m_unNameLineSegment = other.m_unNameLineSegment;
setUMLAssociation(other.association());
setSelected(other.isSelected());
return *this;
}
#endif //:TODO:
/**
* Overrides the equality test operator.
*/
bool AssociationWidget::operator==(const AssociationWidget& other) const
{
if (this == &other)
return true;
// if no model representation exists, then the widgets are not equal
if (association() == nullptr && other.association() == nullptr)
return false;
if (!m_umlObject || !other.m_umlObject ) {
if (!other.m_umlObject && m_umlObject)
return false;
if (other.m_umlObject && !m_umlObject)
return false;
} else if (m_umlObject != other.m_umlObject)
return false;
if (associationType() != other.associationType())
return false;
if (widgetIDForRole(RoleType::A) != other.widgetIDForRole(RoleType::A))
return false;
if (widgetIDForRole(RoleType::B) != other.widgetIDForRole(RoleType::B))
return false;
if (widgetForRole(RoleType::A)->isObjectWidget() &&
other.widgetForRole(RoleType::A)->isObjectWidget()) {
if (widgetForRole(RoleType::A)->localID() != other.widgetForRole(RoleType::A)->localID())
return false;
}
if (widgetForRole(RoleType::B)->isObjectWidget() &&
other.widgetForRole(RoleType::B)->isObjectWidget()) {
if (widgetForRole(RoleType::B)->localID() != other.widgetForRole(RoleType::B)->localID())
return false;
}
// Two objects in a collaboration can have multiple messages between each other.
// Here we depend on the messages having names, and the names must be different.
// That is the reason why collaboration messages have strange initial names like
// "m29997" or similar.
return (name() == other.name());
}
/**
* Overrides the != operator.
*/
bool AssociationWidget::operator!=(AssociationWidget& other) const
{
return !(*this == other);
}
/**
* Returns a const reference to the association widget's line path.
*/
const AssociationLine& AssociationWidget::associationLine() const
{
return m_associationLine;
}
/**
* Returns a writable reference to the association widget's line path.
*/
AssociationLine& AssociationWidget::associationLine()
{
return m_associationLine;
}
/**
* Activates the AssociationWidget after a load.
*
* @return true for success
*/
bool AssociationWidget::activate(IDChangeLog *changeLog)
{
Q_UNUSED(changeLog);
if (m_umlObject == nullptr &&
AssociationType::hasUMLRepresentation(m_associationType)) {
UMLObject *myObj = umlDoc()->findObjectById(m_nId);
if (myObj == nullptr) {
logError1("AssociationWidget::activate cannot find UMLObject %1", Uml::ID::toString(m_nId));
return false;
} else {
const UMLObject::ObjectType ot = myObj->baseType();
if (ot == UMLObject::ot_Association) {
UMLAssociation * myAssoc = myObj->asUMLAssociation();
setUMLAssociation(myAssoc);
} else {
setUMLObject(myObj);
setAssociationType(m_associationType);
}
}
}
if (m_activated)
return true;
Uml::AssociationType::Enum type = associationType();
if (m_role[RoleType::A].umlWidget == nullptr)
setWidgetForRole(m_scene->findWidget(widgetIDForRole(RoleType::A)), RoleType::A);
if (m_role[RoleType::B].umlWidget == nullptr)
setWidgetForRole(m_scene->findWidget(widgetIDForRole(RoleType::B)), RoleType::B);
if (!m_role[RoleType::A].umlWidget || !m_role[RoleType::B].umlWidget) {
logDebug0("AssociationWidget::activate: Cannot make association because roleA or roleB widget is NULL");
return false;
}
if (!umlDoc()->loading()) {
// Not calling this during activation after loadFromXMI because
// doing so destroys manual adjustments to associationLine end points.
calculateEndingPoints();
}
if (AssocRules::allowRole(type)) {
for (unsigned r = RoleType::A; r <= RoleType::B; ++r) {
AssociationWidgetRole& robj = m_role[r];
if (robj.roleWidget == nullptr)
continue;
robj.roleWidget->setLink(this);
TextRole::Enum tr = (r == RoleType::A ? TextRole::RoleAName : TextRole::RoleBName);
robj.roleWidget->setTextRole(tr);
Uml::Visibility::Enum vis = visibility(Uml::RoleType::fromInt(r));
robj.roleWidget->setPreText(Uml::Visibility::toString(vis, true));
if (FloatingTextWidget::isTextValid(robj.roleWidget->text()))
robj.roleWidget->show();
else
robj.roleWidget->hide();
if (m_scene->type() == DiagramType::Collaboration)
robj.roleWidget->setUMLObject(robj.umlWidget->umlObject());
robj.roleWidget->activate();
}
}
if (m_nameWidget != nullptr) {
m_nameWidget->setLink(this);
m_nameWidget->setTextRole(calculateNameType(TextRole::Name));
if (FloatingTextWidget::isTextValid(m_nameWidget->text())) {
m_nameWidget->show();
} else {
m_nameWidget->hide();
}
m_nameWidget->activate();
calculateNameTextSegment();
}
for (unsigned r = RoleType::A; r <= RoleType::B; ++r) {
AssociationWidgetRole& robj = m_role[r];
FloatingTextWidget* pMulti = robj.multiplicityWidget;
if (pMulti != nullptr &&
AssocRules::allowMultiplicity(type, robj.umlWidget->baseType())) {
pMulti->setLink(this);
TextRole::Enum tr = (r == RoleType::A ? TextRole::MultiA : TextRole::MultiB);
pMulti->setTextRole(tr);
if (FloatingTextWidget::isTextValid(pMulti->text()))
pMulti->show();
else
pMulti->hide();
pMulti->activate();
}
FloatingTextWidget* pChangeWidget = robj.changeabilityWidget;
if (pChangeWidget != nullptr) {
pChangeWidget->setLink(this);
TextRole::Enum tr = (r == RoleType::A ? TextRole::ChangeA : TextRole::ChangeB);
pChangeWidget->setTextRole(tr);
if (FloatingTextWidget::isTextValid(pChangeWidget->text()))
pChangeWidget->show();
else
pChangeWidget->hide ();
pChangeWidget->activate();
}
}
// Prepare the association class line if needed.
if (m_associationClass && !m_pAssocClassLine) {
createAssocClassLine();
}
m_activated = true;
return true;
}
/**
* Set the widget of the given role.
* Add this AssociationWidget at the widget.
* If this AssociationWidget has an underlying UMLAssociation then set
* the widget's underlying UMLObject at the UMLAssociation's role object.
*
* @param widget Pointer to the UMLWidget.
* @param role Role for which to set the widget.
*/
void AssociationWidget::setWidgetForRole(UMLWidget* widget, Uml::RoleType::Enum role)
{
m_role[role].umlWidget = widget;
if (widget) {
m_role[role].umlWidget->addAssoc(this);
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association)
association()->setObject(widget->umlObject(), role);
}
}
/**
* Return the multiplicity FloatingTextWidget widget of the given role.
*
* @return Pointer to the multiplicity FloatingTextWidget object.
*/
FloatingTextWidget* AssociationWidget::multiplicityWidget(Uml::RoleType::Enum role) const
{
return m_role[role].multiplicityWidget;
}
/**
* Read property of FloatingTextWidget* m_nameWidget.
*
* @return Pointer to the FloatingTextWidget name widget.
*/
FloatingTextWidget* AssociationWidget::nameWidget() const
{
return m_nameWidget;
}
/**
* Return the given role's FloatingTextWidget object.
*
* @return Pointer to the role's FloatingTextWidget widget.
*/
FloatingTextWidget* AssociationWidget::roleWidget(Uml::RoleType::Enum role) const
{
return m_role[role].roleWidget;
}
/**
* Return the given role's changeability FloatingTextWidget widget.
*/
FloatingTextWidget* AssociationWidget::changeabilityWidget(Uml::RoleType::Enum role) const
{
return m_role[role].changeabilityWidget;
}
/**
* Return the FloatingTextWidget object indicated by the given TextRole::Enum.
*
* @return Pointer to the text role's FloatingTextWidget widget.
*/
FloatingTextWidget* AssociationWidget::textWidgetByRole(Uml::TextRole::Enum tr) const
{
switch (tr) {
case Uml::TextRole::MultiA:
return m_role[RoleType::A].multiplicityWidget;
case Uml::TextRole::MultiB:
return m_role[RoleType::B].multiplicityWidget;
case Uml::TextRole::Name:
case Uml::TextRole::Coll_Message:
return m_nameWidget;
case Uml::TextRole::RoleAName:
return m_role[RoleType::A].roleWidget;
case Uml::TextRole::RoleBName:
return m_role[RoleType::B].roleWidget;
case Uml::TextRole::ChangeA:
return m_role[RoleType::A].changeabilityWidget;
case Uml::TextRole::ChangeB:
return m_role[RoleType::B].changeabilityWidget;
default:
break;
}
return nullptr;
}
/**
* Returns the m_nameWidget's text.
*
* @return Text of the FloatingTextWidget name widget.
*/
QString AssociationWidget::name() const
{
if (m_nameWidget == nullptr)
return QString();
return m_nameWidget->text();
}
/**
* Sets the text in the FloatingTextWidget widget representing the Name
* of this association.
*/
void AssociationWidget::setName(const QString &strName)
{
// set attribute of UMLAssociation associated with this associationwidget
UMLAssociation *umla = association();
if (umla)
umla->setName(strName);
bool newLabel = false;
if (!m_nameWidget) {
// Don't construct the FloatingTextWidget if the string is empty.
if (! FloatingTextWidget::isTextValid(strName))
return;
newLabel = true;
m_nameWidget = new FloatingTextWidget(m_scene, calculateNameType(Uml::TextRole::Name), strName);
m_nameWidget->setParentItem(this);
m_nameWidget->setLink(this);
} else {
m_nameWidget->setText(strName);
if (! FloatingTextWidget::isTextValid(strName)) {
//m_nameWidget->hide();
m_scene->removeWidget(m_nameWidget);
m_nameWidget = nullptr;
return;
}
}
setTextPosition(Uml::TextRole::Name);
if (newLabel) {
m_nameWidget->setActivated();
m_scene->addFloatingTextWidget(m_nameWidget);
}
m_nameWidget->show();
}
void AssociationWidget::setStereotype(const QString &stereo) {
UMLAssociation *umlassoc = association();
if (umlassoc) {
umlassoc->setStereotype(stereo);
if (!m_nameWidget) {
QString text = umlassoc->stereotype(true);
// Don't construct the FloatingTextWidget if the string is empty.
if (! FloatingTextWidget::isTextValid(text))
return;
m_nameWidget = new FloatingTextWidget(m_scene, calculateNameType(Uml::TextRole::Name), text);
m_nameWidget->setParentItem(this);
m_nameWidget->setLink(this);
m_nameWidget->activate();
setTextPosition(calculateNameType(Uml::TextRole::Name));
} else {
m_nameWidget->setText(umlassoc->stereotype(true));
}
} else {
logDebug1("AssociationWidget::setStereotype : not setting %1 because association is NULL", stereo);
}
}
/**
* Return the given role's FloatingTextWidget widget text.
*
* @return The name set at the FloatingTextWidget.
*/
QString AssociationWidget::roleName(Uml::RoleType::Enum role) const
{
if (m_role[role].roleWidget == nullptr)
return QString();
return m_role[role].roleWidget->text();
}
/**
* Sets the text to the FloatingTextWidget that display the Role text of this
* association.
* For this function to work properly, the associated widget
* should already be set.
*/
void AssociationWidget::setRoleName(const QString &strRole, Uml::RoleType::Enum role)
{
Uml::AssociationType::Enum type = associationType();
//if the association is not supposed to have a Role FloatingTextWidget
if (!AssocRules::allowRole(type)) {
return;
}
TextRole::Enum tr = (role == RoleType::A ? TextRole::RoleAName : TextRole::RoleBName);
setFloatingText(tr, strRole, m_role[role].roleWidget);
if (m_role[role].roleWidget) {
Uml::Visibility::Enum vis = visibility(role);
if (FloatingTextWidget::isTextValid(m_role[role].roleWidget->text())) {
m_role[role].roleWidget->setPreText(Uml::Visibility::toString(vis, true));
//m_role[role].roleWidget->show();
} else {
m_role[role].roleWidget->setPreText(QString());
//m_role[role].roleWidget->hide();
}
}
// set attribute of UMLAssociation associated with this associationwidget
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association)
association()->setRoleName(strRole, role);
}
/**
* Set the documentation on the given role.
*/
void AssociationWidget::setRoleDocumentation(const QString &doc, Uml::RoleType::Enum role)
{
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association)
association()->setRoleDoc(doc, role);
else
m_role[role].roleDocumentation = doc;
}
/**
* Returns the given role's documentation.
*/
QString AssociationWidget::roleDocumentation(Uml::RoleType::Enum role) const
{
if (m_umlObject == nullptr || m_umlObject->baseType() != UMLObject::ot_Association)
return QString();
const UMLAssociation *umla = m_umlObject->asUMLAssociation();
return umla->getRoleDoc(role);
}
/**
* Change, create, or delete the FloatingTextWidget indicated by the given TextRole::Enum.
*
* @param role TextRole::Enum of the FloatingTextWidget to change or create.
* @param text Text string that controls the action:
* If empty and ft is NULL then setFloatingText() is a no-op.
* If empty and ft is non-NULL then the existing ft is deleted.
* If non-empty and ft is NULL then a new FloatingTextWidget is created
* and returned in ft with the text set.
* If non-empty and ft is non-NULL then the existing ft text is modified.
* @param ft Reference to the pointer to FloatingTextWidget to change or create.
* On creation/deletion, the pointer value will be changed.
*/
void AssociationWidget::setFloatingText(Uml::TextRole::Enum role,
const QString &text,
FloatingTextWidget* &ft)
{
if (! FloatingTextWidget::isTextValid(text)) {
if (ft) {
// Remove preexisting FloatingTextWidget
m_scene->removeWidget(ft); // physically deletes ft
ft = nullptr;
}
return;
}
if (ft == nullptr) {
ft = new FloatingTextWidget(m_scene, role, text);
ft->setParentItem(this);
ft->setLink(this);
ft->activate();
setTextPosition(role);
m_scene->addFloatingTextWidget(ft);
} else {
bool newLabel = ft->text().isEmpty();
ft->setText(text);
if (newLabel)
setTextPosition(role);
}
ft->show();
}
/**
* Return the given role's multiplicity text.
*
* @return Text of the given role's multiplicity widget.
*/
QString AssociationWidget::multiplicity(Uml::RoleType::Enum role) const
{
if (m_role[role].multiplicityWidget == nullptr)
return QString();
return m_role[role].multiplicityWidget->text();
}
/**
* Sets the text in the FloatingTextWidget representing the multiplicity
* at the given side of the association.
*/
void AssociationWidget::setMultiplicity(const QString& text, Uml::RoleType::Enum role)
{
TextRole::Enum tr = (role == RoleType::A ? TextRole::MultiA : TextRole::MultiB);
setFloatingText(tr, text, m_role[role].multiplicityWidget);
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association)
association()->setMultiplicity(text, role);
}
/**
* Gets the visibility on the given role of the association.
*/
Visibility::Enum AssociationWidget::visibility(Uml::RoleType::Enum role) const
{
const UMLAssociation *assoc = association();
if (assoc)
return assoc->visibility(role);
const UMLAttribute *attr = attribute();
if (attr)
return attr->visibility();
return m_role[role].visibility;
}
/**
* Sets the visibility on the given role of the association.
*/
void AssociationWidget::setVisibility(Visibility::Enum value, Uml::RoleType::Enum role)
{
if (value != visibility(role) && m_umlObject) {
// update our model object
const UMLObject::ObjectType ot = m_umlObject->baseType();
if (ot == UMLObject::ot_Association) {
UMLAssociation *a = association();
a->blockSignals(true);
a->setVisibility(value, role);
a->blockSignals(false);
}
else if (ot == UMLObject::ot_Attribute) {
UMLAttribute *a = attribute();
a->blockSignals(true);
a->setVisibility(value);
a->blockSignals(false);
}
}
m_role[role].visibility = value;
// update role pre-text attribute as appropriate
if (m_role[role].roleWidget) {
QString scopeString = Visibility::toString(value, true);
m_role[role].roleWidget->setPreText(scopeString);
}
}
/**
* Gets the changeability on the given end of the Association.
*/
Uml::Changeability::Enum AssociationWidget::changeability(Uml::RoleType::Enum role) const
{
if (m_umlObject == nullptr || m_umlObject->baseType() != UMLObject::ot_Association)
return m_role[role].changeability;
const UMLAssociation *umla = m_umlObject->asUMLAssociation();
return umla->changeability(role);
}
/**
* Sets the changeability on the given end of the Association.
*/
void AssociationWidget::setChangeability(Uml::Changeability::Enum value, Uml::RoleType::Enum role)
{
if (value == changeability(role))
return;
QString changeString = Uml::Changeability::toString(value);
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) // update our model object
association()->setChangeability(value, role);
m_role[role].changeability = value;
// update our string representation
setChangeWidget(changeString, role);
}
/**
* For internal purposes only.
* Other classes/users should use setChangeability() instead.
*/
void AssociationWidget::setChangeWidget(const QString &strChangeWidget, Uml::RoleType::Enum role)
{
bool newLabel = false;
TextRole::Enum tr = (role == RoleType::A ? TextRole::ChangeA : TextRole::ChangeB);
if (!m_role[role].changeabilityWidget) {
// Don't construct the FloatingTextWidget if the string is empty.
if (strChangeWidget.isEmpty())
return;
newLabel = true;
m_role[role].changeabilityWidget = new FloatingTextWidget(m_scene, tr, strChangeWidget);
m_role[role].changeabilityWidget->setParentItem(this);
m_role[role].changeabilityWidget->setLink(this);
m_scene->addFloatingTextWidget(m_role[role].changeabilityWidget);
m_role[role].changeabilityWidget->setPreText(QStringLiteral("{")); // all types have this
m_role[role].changeabilityWidget->setPostText(QStringLiteral("}")); // all types have this
} else {
if (m_role[role].changeabilityWidget->text().isEmpty()) {
newLabel = true;
}
m_role[role].changeabilityWidget->setText(strChangeWidget);
}
m_role[role].changeabilityWidget->setActivated();
if (newLabel) {
setTextPosition(tr);
}
if (FloatingTextWidget::isTextValid(m_role[role].changeabilityWidget->text()))
m_role[role].changeabilityWidget->show();
else
m_role[role].changeabilityWidget->hide();
}
/**
* Returns true if the line path starts at the given widget.
*/
bool AssociationWidget::linePathStartsAt(const UMLWidget* widget) const
{
QPointF lpStart = m_associationLine.point(0);
/*
Calling widget->contains(lpStart) may give incorrect results:
Sometimes the associationline start or end point is outside the widget's
bounding rectangle by just one pixel.
*/
int startX = lpStart.x();
int startY = lpStart.y();
qreal wX = widget->getX();
qreal wY = widget->getY();
int wWidth = widget->width();
int wHeight = widget->height();
bool result = (startX >= wX - PIXEL_TOLERANCE && startX <= wX + wWidth + PIXEL_TOLERANCE &&
startY >= wY - PIXEL_TOLERANCE && startY <= wY + wHeight + PIXEL_TOLERANCE);
logDebug2("AssociationWidget::linePathStartsAt widget=%1 : result=%2", widget->name(), result);
#if defined(VERBOSE_DEBUGGING)
qreal wSceneX = widget->scenePos().x();
qreal wSceneY = widget->scenePos().y();
logDebug4("AssociationWidget::linePathStartsAt(%1) : Returning %2 for candidate (%3,%4)",
widget->name(), result, startX, startY);
logDebug6("... widget (%1,%2 w=%3,h=%4) , wScenePos (%5,%6)",
wX, wY, wWidth, wHeight, wSceneX, wSceneY);
#else
logDebug2("AssociationWidget::linePathStartsAt widget=%1 : result=%2", widget->name(), result);
#endif
return result;
}
/**
* Returns true if the line path ends at the given widget.
*/
bool AssociationWidget::linePathEndsAt(const UMLWidget* widget) const
{
int lastIndex = m_associationLine.count() - 1;
QPointF lpEnd = m_associationLine.point(lastIndex);
int endX = lpEnd.x();
int endY = lpEnd.y();
qreal wX = widget->x();
qreal wY = widget->y();
int wWidth = widget->width();
int wHeight = widget->height();
bool result = (endX >= wX - PIXEL_TOLERANCE && endX <= wX + wWidth + PIXEL_TOLERANCE &&
endY >= wY - PIXEL_TOLERANCE && endY <= wY + wHeight + PIXEL_TOLERANCE);
DEBUG() << "linePathEndsAt widget=" << widget->name() << ": result=" << result;
return result;
}
/**
* This function calculates which role should be set for the m_nameWidget FloatingTextWidget.
*/
Uml::TextRole::Enum AssociationWidget::calculateNameType(Uml::TextRole::Enum defaultRole)
{
TextRole::Enum result = defaultRole;
if (m_scene->type() == DiagramType::Collaboration) {
if (m_role[RoleType::A].umlWidget == m_role[RoleType::B].umlWidget) {
result = TextRole::Coll_Message;//for now same as other Coll_Message
} else {
result = TextRole::Coll_Message;
}
} else if (m_scene->type() == DiagramType::Sequence) {
if (m_role[RoleType::A].umlWidget == m_role[RoleType::B].umlWidget) {
result = TextRole::Seq_Message_Self;
} else {
result = TextRole::Seq_Message;
}
}
return result;
}
/**
* Gets the given role widget.
*
* @return Pointer to the role's UMLWidget.
*/
UMLWidget* AssociationWidget::widgetForRole(Uml::RoleType::Enum role) const
{
return m_role[role].umlWidget;
}
/**
* Cleans up all the association's data in the related widgets.
*/
void AssociationWidget::cleanup()
{
m_role[RoleType::A].cleanup();
m_role[RoleType::B].cleanup();
if (m_nameWidget) {
m_scene->removeWidget(m_nameWidget);
m_nameWidget = nullptr;
}
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) {
/*
We do not remove the UMLAssociation from the document.
Why? - Well, for example we might be in the middle of
a cut/paste. If the UMLAssociation is removed by the cut
then upon pasteing we have a problem.
This is not quite clean yet - there should be a way to
explicitly delete a UMLAssociation. The Right Thing would
be to have a ListView representation for UMLAssociation.
`
IF we are cut n pasting, why are we handling this association as a pointer?
We should be using the XMI representation for a cut and paste. This
allows us to be clean here, AND a choice of recreating the object
w/ same id IF its a "cut", or a new object if its a "copy" operation
(in which case we wouldnt be here, in cleanup()).
*/
setUMLAssociation(nullptr);
}
m_associationLine.cleanup();
removeAssocClassLine();
}
/**
* @brief Return state if the association line point in the vicinity of the last context
* menu event position is addable or not.
* A point is addable if the association is not an Exception and there is no point nearby.
*
* @return true if point is addable
*/
bool AssociationWidget::isPointAddable()
{
if (!isSelected() || associationType() == Uml::AssociationType::Exception)
return false;
int i = m_associationLine.closestPointIndex(m_eventScenePos);
return i == -1;
}
/**
* @brief Return state if the association line point in the vicinity of the last context
* menu event position is removable or not.
* A point is removable if the association is not an Exception and is not the start or end point.
*
* @return true if point is removable
*/
bool AssociationWidget::isPointRemovable()
{
if (!isSelected() || associationType() == Uml::AssociationType::Exception || m_associationLine.count() <= 2)
return false;
int i = m_associationLine.closestPointIndex(m_eventScenePos);
return i > 0 && i < m_associationLine.count() - 1;
}
bool AssociationWidget::isAutoLayouted()
{
if (associationType() == Uml::AssociationType::Exception)
return true;
if (!isSelected() || m_associationLine.count() <= 2)
return false;
return m_associationLine.isAutoLayouted();
}
/**
* if layout of this widget can be changed
* @return true if layout could be changed
* @return false if layout could not be changed
*/
bool AssociationWidget::isLayoutChangeable()
{
return associationType() != Uml::AssociationType::Exception;
}
/**
* Set our internal umlAssociation.
*/
void AssociationWidget::setUMLAssociation (UMLAssociation * assoc)
{
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) {
UMLAssociation *umla = association();
// safety check. Did some num-nuts try to set the existing
// association again? If so, just bail here
if (umla == assoc)
return;
//umla->disconnect(this); //Qt does disconnect automatically upon destruction.
umla->nrof_parent_widgets--;
// ANSWER: This is the wrong treatment of cut and paste. Associations that
// are being cut/n pasted should be serialized to XMI, then reconstituted
// (IF a paste operation) rather than passing around object pointers. Its
// just too hard otherwise to prevent problems in the code. Bottom line: we need to
// delete orphaned associations or we well get code crashes and memory leaks.
if (umla->nrof_parent_widgets <= 0) {
//umla->deleteLater();
}
m_umlObject = nullptr;
}
if (assoc) {
m_umlObject = assoc;
// move counter to "0" from "-1" (which means, no assocwidgets)
if (assoc->nrof_parent_widgets < 0)
assoc->nrof_parent_widgets = 0;
assoc->nrof_parent_widgets++;
connect(assoc, SIGNAL(modified()), this, SLOT(syncToModel()));
}
}
/**
* Returns true if the Widget is either at the starting or ending side of the association.
*/
bool AssociationWidget::containsAsEndpoint(UMLWidget* widget)
{
return (widget == m_role[RoleType::A].umlWidget || widget == m_role[RoleType::B].umlWidget);
}
/**
* Returns true if this AssociationWidget represents a collaboration message.
*/
bool AssociationWidget::isCollaboration() const
{
Uml::AssociationType::Enum at = associationType();
return (at == AssociationType::Coll_Mesg_Sync
|| at == AssociationType::Coll_Mesg_Async
|| at == AssociationType::Coll_Mesg_Self);
}
/**
* Returns true if this AssociationWidget represents a self message.
*/
bool AssociationWidget::isSelf() const
{
return widgetForRole(Uml::RoleType::A) == widgetForRole(Uml::RoleType::B);
}
/**
* Gets the association's type.
*
* @return This AssociationWidget's AssociationType::Enum.
*/
Uml::AssociationType::Enum AssociationWidget::associationType() const
{
if (m_umlObject == nullptr || m_umlObject->baseType() != UMLObject::ot_Association)
return m_associationType;
const UMLAssociation *umla = m_umlObject->asUMLAssociation();
return umla->getAssocType();
}
/**
* Sets the association's type.
*
* @param type The AssociationType::Enum to set.
*/
void AssociationWidget::setAssociationType(Uml::AssociationType::Enum type)
{
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) {
association()->setAssociationType(type);
}
m_associationType = type;
// If the association new type is not supposed to have Multiplicity
// FloatingTexts and a Role FloatingTextWidget then set the texts
// to empty.
// NB We do not physically delete the floatingtext widgets here because
// those widgets are also stored in the UMLView::m_WidgetList.
if (!AssocRules::allowMultiplicity(type, widgetForRole(RoleType::A)->baseType())) {
if (m_role[RoleType::A].multiplicityWidget) {
m_role[RoleType::A].multiplicityWidget->setName(QString());
}
if (m_role[RoleType::B].multiplicityWidget) {
m_role[RoleType::B].multiplicityWidget->setName(QString());
}
}
if (!AssocRules::allowRole(type)) {
if (m_role[RoleType::A].roleWidget) {
m_role[RoleType::A].roleWidget->setName(QString());
}
if (m_role[RoleType::B].roleWidget) {
m_role[RoleType::B].roleWidget->setName(QString());
}
setRoleDocumentation(QString(), RoleType::A);
setRoleDocumentation(QString(), RoleType::B);
}
m_associationLine.reconstructSymbols();
m_associationLine.updatePenStyle();
}
/**
* Gets the ID of the given role widget.
*/
Uml::ID::Type AssociationWidget::widgetIDForRole(Uml::RoleType::Enum role) const
{
if (m_role[role].umlWidget == nullptr) {
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) {
const UMLAssociation *umla = m_umlObject->asUMLAssociation();
return umla->getObjectId(role);
}
logError1("AssociationWidget::widgetIDForRole(%1) : umlWidget is null",
Uml::RoleType::toString(role));
return Uml::ID::None;
}
if (m_role[role].umlWidget->isObjectWidget())
return m_role[role].umlWidget->localID();
Uml::ID::Type id = m_role[role].umlWidget->id();
return id;
}
/**
* Gets the local ID of the given role widget.
*/
Uml::ID::Type AssociationWidget::widgetLocalIDForRole(Uml::RoleType::Enum role) const
{
if (m_role[role].umlWidget == nullptr) {
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) {
const UMLAssociation *umla = m_umlObject->asUMLAssociation();
return umla->getObjectId(role);
}
logError1("AssociationWidget::widgetLocalIDForRole(%1) : umlWidget is null",
Uml::RoleType::toString(role));
return Uml::ID::None;
}
Uml::ID::Type id = m_role[role].umlWidget->localID();
return id;
}
/**
* Returns a QString Object representing this AssociationWidget.
*/
QString AssociationWidget::toString() const
{
QString string;
static const QChar colon(QLatin1Char(':'));
static const QChar space(QLatin1Char(' '));
if (widgetForRole(RoleType::A)) {
string = widgetForRole(RoleType::A)->name();
}
string.append(colon);
if (m_role[RoleType::A].roleWidget) {
string += m_role[RoleType::A].roleWidget->text();
}
string.append(space);
string.append(Uml::AssociationType::toStringI18n(associationType()));
string.append(space);
if (widgetForRole(RoleType::B)) {
string += widgetForRole(RoleType::B)->name();
}
string.append(colon);
if (m_role[RoleType::B].roleWidget) {
string += m_role[RoleType::B].roleWidget->text();
}
return string;
}
/**
* Adds a break point (if left mouse button).
*/
void AssociationWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
logDebug2("AssociationWidget::mouseDoubleClickEvent : widget=%1 / type=%2", name(), baseTypeStr());
showPropertiesDialog();
event->accept();
}
}
/**
* Overrides moveEvent.
*/
void AssociationWidget::moveEvent(QGraphicsSceneMouseEvent *me)
{
// 2004-04-30: Achim Spangler
// Simple Approach to block moveEvent during load of XMI
/// @todo avoid trigger of this event during load
if (umlDoc()->loading()) {
// hmmh - change of position during load of XMI
// -> there is something wrong
// -> avoid movement during opening
// -> print warn and stay at old position
logWarn2("AssociationWidget::moveEvent called during load of XMI for ViewType %1 and BaseType %2",
m_scene->type(), baseType());
return;
}
/*to be here a line segment has moved.
we need to see if the three text widgets needs to be moved.
there are a few things to check first though:
1) Do they exist
2) does it need to move:
2a) for the multi widgets only move if they changed region, otherwise they are close enough
2b) for role name move if the segment it is on moves.
*/
//first see if either the first or last segments moved, else no need to recalculate their point positions
QPointF oldNamePoint = calculateTextPosition(TextRole::Name);
QPointF oldMultiAPoint = calculateTextPosition(TextRole::MultiA);
QPointF oldMultiBPoint = calculateTextPosition(TextRole::MultiB);
QPointF oldChangeAPoint = calculateTextPosition(TextRole::ChangeA);
QPointF oldChangeBPoint = calculateTextPosition(TextRole::ChangeB);
QPointF oldRoleAPoint = calculateTextPosition(TextRole::RoleAName);
QPointF oldRoleBPoint = calculateTextPosition(TextRole::RoleBName);
int movingPoint = m_associationLine.closestPointIndex(me->scenePos());
if (movingPoint != -1)
m_associationLine.setPoint(movingPoint, me->scenePos());
int pos = m_associationLine.count() - 1;//set to last point for widget b
if (movingPoint == 1 || movingPoint == pos-1) {
calculateEndingPoints();
}
if (m_role[RoleType::A].changeabilityWidget && movingPoint == 1) {
setTextPositionRelatively(TextRole::ChangeA, oldChangeAPoint);
}
if (m_role[RoleType::B].changeabilityWidget && movingPoint == pos-1) {
setTextPositionRelatively(TextRole::ChangeB, oldChangeBPoint);
}
if (m_role[RoleType::A].multiplicityWidget && movingPoint == 1) {
setTextPositionRelatively(TextRole::MultiA, oldMultiAPoint);
}
if (m_role[RoleType::B].multiplicityWidget && movingPoint == pos-1) {
setTextPositionRelatively(TextRole::MultiB, oldMultiBPoint);
}
if (m_nameWidget) {
if (movingPoint == m_unNameLineSegment ||
movingPoint - 1 == m_unNameLineSegment) {
setTextPositionRelatively(TextRole::Name, oldNamePoint);
}
}
if (m_role[RoleType::A].roleWidget) {
setTextPositionRelatively(TextRole::RoleAName, oldRoleAPoint);
}
if (m_role[RoleType::B].roleWidget) {
setTextPositionRelatively(TextRole::RoleBName, oldRoleBPoint);
}
if (m_pAssocClassLine) {
computeAssocClassLine();
}
}
/**
* This function acts as delegator to the static method updateAssociations()
* but additionally handles object bound special cases (self association,
* exception association, associationline insufficient points, association class
* connecting line).
*/
void AssociationWidget::calculateEndingPoints()
{
UMLWidget *pWidgetA = m_role[RoleType::A].umlWidget;
UMLWidget *pWidgetB = m_role[RoleType::B].umlWidget;
if (!pWidgetA || !pWidgetB) {
logWarn0("AssociationWidget::calculateEndingPoints: Returning - one of the role widgets is not set.");
return;
}
int size = m_associationLine.count();
if (size < 2) {
QPointF pA = pWidgetA->scenePos();
QPointF pB = pWidgetB->scenePos();
QPolygonF polyA = pWidgetA->shape().toFillPolygon().translated(pA);
QPolygonF polyB = pWidgetB->shape().toFillPolygon().translated(pB);
QLineF nearestPoints = Widget_Utils::closestPoints(polyA, polyB);
if (nearestPoints.isNull()) {
logError0("AssociationWidget::calculateEndingPoints: Widget_Utils::closestPoints failed, "
"falling back to simple widget positions");
} else {
pA = nearestPoints.p1();
pB = nearestPoints.p2();
}
m_associationLine.setEndPoints(pA, pB);
}
// See if an association to self.
// See if it needs to be set up before we continue:
// If self association/message and doesn't have the minimum 4 points
// then create it. Make sure no points are out of bounds of viewing area.
// This only happens on first time through that we are worried about.
if (isSelf() && size < 4) {
createPointsSelfAssociation();
return;
}
if (associationType() == AssociationType::Exception && size < 4) {
createPointsException();
updatePointsException();
return;
}
if (size < 2 || (m_associationLine.startPoint().isNull()
&& m_associationLine.endPoint().isNull())) {
QPointF pA = pWidgetA->scenePos();
QPointF pB = pWidgetB->scenePos();
QPolygonF polyA = pWidgetA->shape().toFillPolygon().translated(pA);
QPolygonF polyB = pWidgetB->shape().toFillPolygon().translated(pB);
QLineF nearestPoints = Widget_Utils::closestPoints(polyA, polyB);
if (nearestPoints.isNull()) {
logError0("AssociationWidget::calculateEndingPoints: Widget_Utils::closestPoints failed, "
"falling back to simple widget positions");
} else {
pA = nearestPoints.p1();
pB = nearestPoints.p2();
}
m_associationLine.setEndPoints(pA, pB);
}
setStartAndEndPoint(this, m_role[RoleType::A].umlWidget);
setStartAndEndPoint(this, m_role[RoleType::B].umlWidget);
AssociationWidgetList assocList(m_scene->associationList());
updateAssociations(m_role[RoleType::A].umlWidget, assocList);
updateAssociations(m_role[RoleType::B].umlWidget, assocList);
computeAssocClassLine();
}
/**
* Read property of bool m_activated.
*/
bool AssociationWidget::isActivated() const
{
return m_activated;
}
/**
* Set the m_activated flag of a widget but does not perform the Activate method.
*/
void AssociationWidget::setActivated(bool active)
{
m_activated = active;
}
/**
* Synchronize this widget from the UMLAssociation.
*/
void AssociationWidget::syncToModel()
{
UMLAssociation *uml = association();
if (uml == nullptr) {
UMLAttribute *attr = attribute();
if (attr == nullptr)
return;
setVisibility(attr->visibility(), RoleType::B);
setRoleName(attr->name(), RoleType::B);
return;
}
// block signals until finished
uml->blockSignals(true);
setName(uml->name());
setRoleName(uml->getRoleName(RoleType::A), RoleType::A);
setRoleName(uml->getRoleName(RoleType::B), RoleType::B);
setVisibility(uml->visibility(RoleType::A), RoleType::A);
setVisibility(uml->visibility(RoleType::B), RoleType::B);
setChangeability(uml->changeability(RoleType::A), RoleType::A);
setChangeability(uml->changeability(RoleType::B), RoleType::B);
setMultiplicity(uml->getMultiplicity(RoleType::A), RoleType::A);
setMultiplicity(uml->getMultiplicity(RoleType::B), RoleType::B);
uml->blockSignals(false);
}
/**
* Merges/syncs the association widget data into UML object
* representation.
* This will synchronize UMLAssociation w/ this new Widget
* CHECK: Can we get rid of this.
*/
void AssociationWidget::mergeAssociationDataIntoUMLRepresentation()
{
UMLAssociation *umlassoc = association();
UMLAttribute *umlattr = attribute();
if (umlassoc == nullptr && umlattr == nullptr)
return;
// block emit modified signal, or we get a horrible loop
m_umlObject->blockSignals(true);
// would be desirable to do the following
// so that we can be sure its back to initial state
// in case we missed something here.
//uml->init();
// floating text widgets
FloatingTextWidget *text = nameWidget();
if (text)
m_umlObject->setName(text->text());
text = roleWidget(RoleType::A);
if (text && umlassoc)
umlassoc->setRoleName(text->text(), RoleType::A);
text = roleWidget(RoleType::B);
if (text) {
if (umlassoc)
umlassoc->setRoleName(text->text(), RoleType::B);
else if (umlattr)
umlattr->setName(text->text());
}
text = multiplicityWidget(RoleType::A);
if (text && umlassoc)
umlassoc->setMultiplicity(text->text(), RoleType::A);
text = multiplicityWidget(RoleType::B);
if (text && umlassoc)
umlassoc->setMultiplicity(text->text(), RoleType::B);
// unblock
m_umlObject->blockSignals(false);
}
/**
* Auxiliary method for widgetMoved():
* Saves all ideally computed floatingtext positions before doing any
* kind of change. This is necessary because a single invocation of
* calculateEndingPoints() modifies the AssociationLine ending points on ALL
* AssociationWidgets. This means that if we don't save the old ideal
* positions then they are irretrievably lost as soon as
* calculateEndingPoints() is invoked.
*/
void AssociationWidget::saveIdealTextPositions()
{
m_oldNamePoint = calculateTextPosition(TextRole::Name);
m_oldMultiAPoint = calculateTextPosition(TextRole::MultiA);
m_oldMultiBPoint = calculateTextPosition(TextRole::MultiB);
m_oldChangeAPoint = calculateTextPosition(TextRole::ChangeA);
m_oldChangeBPoint = calculateTextPosition(TextRole::ChangeB);
m_oldRoleAPoint = calculateTextPosition(TextRole::RoleAName);
m_oldRoleBPoint = calculateTextPosition(TextRole::RoleBName);
}
/**
* Adjusts the ending point of the association that connects to Widget.
*/
void AssociationWidget::widgetMoved(UMLWidget* widget, qreal dx, qreal dy)
{
Q_UNUSED(dx); Q_UNUSED(dy);
// Simple Approach to block moveEvent during load of XMI
/// @todo avoid trigger of this event during load
if (umlDoc()->loading()) {
// change of position during load of XMI
// -> there is something wrong
// -> avoid movement during opening
// -> print warn and stay at old position
logDebug2("AssociationWidget::widgetMoved called during load of XMI for ViewType: %1 / BaseType: %2",
m_scene->type(), baseTypeStr());
return;
}
logDebug1("AssociationWidget::widgetMoved: association type=%1",
Uml::AssociationType::toString(associationType()));
if (associationType() == AssociationType::Exception) {
updatePointsException();
setTextPosition(TextRole::Name);
}
else {
calculateEndingPoints();
computeAssocClassLine();
}
// Assoc to self - move all points:
if (isSelf()) {
updatePointsSelfAssociation();
if (m_nameWidget && !m_nameWidget->isSelected()) {
setTextPositionRelatively(TextRole::Name, m_oldNamePoint);
}
}//end if widgetA = widgetB
else if (m_role[RoleType::A].umlWidget == widget) {
if (m_nameWidget && m_unNameLineSegment == 0 && !m_nameWidget->isSelected() ) {
//only calculate position and move text if the segment it is on is moving
setTextPositionRelatively(TextRole::Name, m_oldNamePoint);
}
if (m_role[RoleType::B].umlWidget && m_role[RoleType::B].umlWidget->changesShape())
m_role[RoleType::B].umlWidget->updateGeometry(false);
}//end if widgetA moved
else if (m_role[RoleType::B].umlWidget == widget) {
const int size = m_associationLine.count();
if (m_nameWidget && (m_unNameLineSegment == size-2) && !m_nameWidget->isSelected() ) {
//only calculate position and move text if the segment it is on is moving
setTextPositionRelatively(TextRole::Name, m_oldNamePoint);
}
if (m_role[RoleType::A].umlWidget && m_role[RoleType::A].umlWidget->changesShape())
m_role[RoleType::A].umlWidget->updateGeometry(false);
}//end if widgetB moved
if (m_role[RoleType::A].roleWidget && !m_role[RoleType::A].roleWidget->isSelected()) {
setTextPositionRelatively(TextRole::RoleAName, m_oldRoleAPoint);
}
if (m_role[RoleType::B].roleWidget && !m_role[RoleType::B].roleWidget->isSelected()) {
setTextPositionRelatively(TextRole::RoleBName, m_oldRoleBPoint);
}
if (m_role[RoleType::A].multiplicityWidget && !m_role[RoleType::A].multiplicityWidget->isSelected()) {
setTextPositionRelatively(TextRole::MultiA, m_oldMultiAPoint);
}
if (m_role[RoleType::B].multiplicityWidget && !m_role[RoleType::B].multiplicityWidget->isSelected()) {
setTextPositionRelatively(TextRole::MultiB, m_oldMultiBPoint);
}
if (m_role[RoleType::A].changeabilityWidget && !m_role[RoleType::A].changeabilityWidget->isSelected()) {
setTextPositionRelatively(TextRole::ChangeA, m_oldChangeAPoint);
}
if (m_role[RoleType::B].changeabilityWidget && !m_role[RoleType::B].changeabilityWidget->isSelected()) {
setTextPositionRelatively(TextRole::ChangeB, m_oldChangeBPoint);
}
}
/**
* Creates the points of the self association.
* Method called when widget end points are calculated by calculateEndingPoints().
*/
void AssociationWidget::createPointsSelfAssociation()
{
UMLWidget *pWidgetA = m_role[RoleType::A].umlWidget;
const int DISTANCE = 50;
qreal x = pWidgetA->x();
qreal y = pWidgetA->y();
qreal h = pWidgetA->height();
qreal w = pWidgetA->width();
// see if above widget ok to start
if (y - DISTANCE > 0) {
m_associationLine.setEndPoints(QPointF(x + w / 4, y) , QPointF(x + w * 3 / 4, y));
m_associationLine.insertPoint(1, QPointF(x + w / 4, y - DISTANCE));
m_associationLine.insertPoint(2, QPointF(x + w * 3 / 4, y - DISTANCE));
m_role[RoleType::A].m_WidgetRegion = m_role[RoleType::B].m_WidgetRegion = Uml::Region::North;
} else {
m_associationLine.setEndPoints(QPointF(x + w / 4, y + h), QPointF(x + w * 3 / 4, y + h));
m_associationLine.insertPoint(1, QPointF(x + w / 4, y + h + DISTANCE));
m_associationLine.insertPoint(2, QPointF(x + w * 3 / 4, y + h + DISTANCE));
m_role[RoleType::A].m_WidgetRegion = m_role[RoleType::B].m_WidgetRegion = Uml::Region::South;
}
}
/**
* Adjusts the points of the self association.
* Method called when a widget was moved by widgetMoved(widget, x, y).
*/
void AssociationWidget::updatePointsSelfAssociation()
{
UMLWidget *pWidgetA = m_role[RoleType::A].umlWidget;
const int DISTANCE = 50;
qreal x = pWidgetA->x();
qreal y = pWidgetA->y();
qreal h = pWidgetA->height();
qreal w = pWidgetA->width();
// see if above widget ok to start
if (y - DISTANCE > 0) {
m_associationLine.setEndPoints(QPointF(x + w / 4, y) , QPointF(x + w * 3 / 4, y));
m_associationLine.setPoint(1, QPointF(x + w / 4, y - DISTANCE));
m_associationLine.setPoint(2, QPointF(x + w * 3 / 4, y - DISTANCE));
m_role[RoleType::A].m_WidgetRegion = m_role[RoleType::B].m_WidgetRegion = Uml::Region::North;
} else {
m_associationLine.setEndPoints(QPointF(x + w / 4, y + h), QPointF(x + w * 3 / 4, y + h));
m_associationLine.setPoint(1, QPointF(x + w / 4, y + h + DISTANCE));
m_associationLine.setPoint(2, QPointF(x + w * 3 / 4, y + h + DISTANCE));
m_role[RoleType::A].m_WidgetRegion = m_role[RoleType::B].m_WidgetRegion = Uml::Region::South;
}
}
/**
* Creates the points of the association exception.
* Method called when a widget end points are calculated by calculateEndingPoints().
*/
void AssociationWidget::createPointsException()
{
UMLWidget *pWidgetA = m_role[RoleType::A].umlWidget;
UMLWidget *pWidgetB = m_role[RoleType::B].umlWidget;
qreal xa = pWidgetA->x();
qreal ya = pWidgetA->y();
qreal ha = pWidgetA->height();
qreal wa = pWidgetA->width();
qreal xb = pWidgetB->x();
qreal yb = pWidgetB->y();
qreal hb = pWidgetB->height();
//qreal wb = pWidgetB->width();
m_associationLine.setEndPoints(QPointF(xa + wa , ya + ha/2) , QPointF(xb , yb + hb/2));
m_associationLine.insertPoint(1, QPointF(xa + wa , ya + ha/2));
m_associationLine.insertPoint(2, QPointF(xb , yb + hb/2));
}
/**
* Adjusts the points of the association exception.
* Method called when a widget was moved by widgetMoved(widget, x, y).
*/
void AssociationWidget::updatePointsException()
{
UMLWidget *pWidgetA = m_role[RoleType::A].umlWidget;
UMLWidget *pWidgetB = m_role[RoleType::B].umlWidget;
qreal xa = pWidgetA->x();
qreal ya = pWidgetA->y();
qreal ha = pWidgetA->height();
qreal wa = pWidgetA->width();
qreal xb = pWidgetB->x();
qreal yb = pWidgetB->y();
qreal hb = pWidgetB->height();
qreal wb = pWidgetB->width();
qreal xmil, ymil;
qreal xdeb, ydeb;
qreal xfin, yfin;
qreal ESPACEX, ESPACEY;
QPointF p1;
QPointF p2;
//calcul des coordonnées au milieu de la flèche eclair
if (xb - xa - wa >= 45) {
ESPACEX = 0;
xdeb = xa + wa;
xfin = xb;
} else if (xa - xb - wb > 45) {
ESPACEX = 0;
xdeb = xa;
xfin = xb + wb;
} else {
ESPACEX = 15;
xdeb = xa + wa/2;
xfin = xb + wb/2;
}
xmil = xdeb + (xfin - xdeb)/2;
if (yb - ya - ha >= 45) {
ESPACEY = 0;
ydeb = ya + ha;
yfin = yb;
} else if (ya - yb - hb > 45) {
ESPACEY = 0;
ydeb = ya;
yfin = yb + hb;
} else {
ESPACEY = 15;
ydeb = ya + ha/2;
yfin = yb + hb/2;
}
ymil = ydeb + (yfin - ydeb)/2;
p1.setX(xmil + (xfin - xmil)*1/2); p1.setY(ymil + (yfin - ymil)*1/3);
p2.setX(xmil - (xmil - xdeb)*1/2); p2.setY(ymil - (ymil - ydeb)*1/3);
if (fabs(p1.x() - p2.x()) <= 10)
ESPACEX = 15;
if (fabs(p1.y() - p2.y()) <= 10)
ESPACEY = 15;
m_associationLine.setEndPoints(QPointF(xdeb, ydeb), QPointF(xfin, yfin));
m_associationLine.setPoint(1, QPointF(p1.x() + ESPACEX, p1.y() + ESPACEY));
m_associationLine.setPoint(2, QPointF(p2.x() - ESPACEX, p2.y() - ESPACEY));
m_role[RoleType::A].m_WidgetRegion = m_role[RoleType::B].m_WidgetRegion = Uml::Region::North;
}
/**
* Finds out which region of rectangle 'rect' contains the point 'pos' and returns the region
* number:
* 1 = Region 1 (West)
* 2 = Region 2 (North)
* 3 = Region 3 (East)
* 4 = Region 4 (South)
* 5 = On diagonal 2 between Region 1 and 2 (NorthWest)
* 6 = On diagonal 1 between Region 2 and 3 (NorthEast)
* 7 = On diagonal 2 between Region 3 and 4 (SouthEast)
* 8 = On diagonal 1 between Region 4 and 1 (SouthWest)
* 9 = On diagonal 1 and on diagonal 2 (Center)
*/
Uml::Region::Enum AssociationWidget::findPointRegion(const QRectF& rect, const QPointF &pos)
{
qreal w = rect.width();
qreal h = rect.height();
qreal x = rect.x();
qreal y = rect.y();
qreal slope2 = w / h;
qreal slope1 = slope2 *(-1.0);
qreal b1 = x + w - (slope1 * y);
qreal b2 = x - (slope2 * y);
qreal eval1 = slope1 * pos.y() + b1;
qreal eval2 = slope2 * pos.y() + b2;
Uml::Region::Enum result = Uml::Region::Error;
//if inside region 1
if (eval1 > pos.x() && eval2 > pos.x()) {
result = Uml::Region::West;
}
//if inside region 2
else if (eval1 > pos.x() && eval2 < pos.x()) {
result = Uml::Region::North;
}
//if inside region 3
else if (eval1 < pos.x() && eval2 < pos.x()) {
result = Uml::Region::East;
}
//if inside region 4
else if (eval1 < pos.x() && eval2 > pos.x()) {
result = Uml::Region::South;
}
//if inside region 5
else if (eval1 == pos.x() && eval2 < pos.x()) {
result = Uml::Region::NorthWest;
}
//if inside region 6
else if (eval1 < pos.x() && eval2 == pos.x()) {
result = Uml::Region::NorthEast;
}
//if inside region 7
else if (eval1 == pos.x() && eval2 > pos.x()) {
result = Uml::Region::SouthEast;
}
//if inside region 8
else if (eval1 > pos.x() && eval2 == pos.x()) {
result = Uml::Region::SouthWest;
}
//if inside region 9
else if (eval1 == pos.x() && eval2 == pos.x()) {
result = Uml::Region::Center;
}
return result;
}
/**
* Returns a point with interchanged X and Y coordinates.
*/
QPointF AssociationWidget::swapXY(const QPointF &p)
{
QPointF swapped( p.y(), p.x() );
return swapped;
}
/**
* Calculates the position of the text widget depending on the role
* that widget is playing.
* Returns the point at which to put the widget.
*/
QPointF AssociationWidget::calculateTextPosition(Uml::TextRole::Enum role)
{
const int SPACE = 2;
QPointF p(-1, -1), q(-1, -1);
// used to find out if association end point (p)
// is at top or bottom edge of widget.
if (role == TextRole::MultiA || role == TextRole::ChangeA || role == TextRole::RoleAName) {
p = m_associationLine.point(0);
q = m_associationLine.point(1);
} else if (role == TextRole::MultiB || role == TextRole::ChangeB || role == TextRole::RoleBName) {
const int lastSegment = m_associationLine.count() - 1;
p = m_associationLine.point(lastSegment);
q = m_associationLine.point(lastSegment - 1);
} else if (role != TextRole::Name) {
logError1("AssociationWidget::calculateTextPosition called with unsupported TextRole %1",
Uml::TextRole::toString(role));
return QPointF(-1, -1);
}
FloatingTextWidget *text = textWidgetByRole(role);
int textW = 0, textH = 0;
if (text) {
textW = text->width();
textH = text->height();
}
qreal x = 0.0, y = 0.0;
if (role == TextRole::MultiA || role == TextRole::MultiB) {
const bool isHorizontal = (p.y() == q.y());
const int atBottom = p.y() + SPACE;
const int atTop = p.y() - SPACE - textH;
const int atLeft = p.x() - SPACE - textW;
const int atRight = p.x() + SPACE;
y = (p.y() > q.y()) == isHorizontal ? atBottom : atTop;
x = (p.x() < q.x()) == isHorizontal ? atRight : atLeft;
} else if (role == TextRole::ChangeA || role == TextRole::ChangeB) {
if (p.y() > q.y())
y = p.y() - SPACE - (textH * 2);
else
y = p.y() + SPACE + textH;
if (p.x() < q.x())
x = p.x() + SPACE;
else
x = p.x() - SPACE - textW;
} else if (role == TextRole::RoleAName || role == TextRole::RoleBName) {
if (p.y() > q.y())
y = p.y() - SPACE - textH;
else
y = p.y() + SPACE;
if (p.x() < q.x())
x = p.x() + SPACE;
else
x = p.x() - SPACE - textW;
} else if (role == TextRole::Name) {
calculateNameTextSegment();
if (m_unNameLineSegment == -1) {
logWarn0("AssociationWidget::calculateTextPosition TODO: negative line segment index");
m_unNameLineSegment = 0;
}
x = ( m_associationLine.point(m_unNameLineSegment).x() +
m_associationLine.point(m_unNameLineSegment + 1).x() ) / 2;
y = ( m_associationLine.point(m_unNameLineSegment).y() +
m_associationLine.point(m_unNameLineSegment + 1).y() ) / 2;
}
if (text) {
constrainTextPos(x, y, textW, textH, role);
}
p = QPointF( x, y );
return p;
}
/**
* Return the mid point between p0 and p1
*/
QPointF AssociationWidget::midPoint(const QPointF& p0, const QPointF& p1)
{
QPointF midP;
if (p0.x() < p1.x())
midP.setX(p0.x() + (p1.x() - p0.x()) / 2);
else
midP.setX(p1.x() + (p0.x() - p1.x()) / 2);
if (p0.y() < p1.y())
midP.setY(p0.y() + (p1.y() - p0.y()) / 2);
else
midP.setY(p1.y() + (p0.y() - p1.y()) / 2);
return midP;
}
/**
* Constrains the FloatingTextWidget X and Y values supplied.
* Implements the abstract operation from LinkWidget.
*
* @param textX Candidate X value (may be modified by the constraint.)
* @param textY Candidate Y value (may be modified by the constraint.)
* @param textWidth Width of the text.
* @param textHeight Height of the text.
* @param tr Uml::Text_Role of the text.
*/
void AssociationWidget::constrainTextPos(qreal &textX, qreal &textY,
qreal textWidth, qreal textHeight,
Uml::TextRole::Enum tr)
{
const int textCenterX = textX + textWidth / 2;
const int textCenterY = textY + textHeight / 2;
const int lastSegment = m_associationLine.count() - 1;
QPointF p0, p1;
switch (tr) {
case TextRole::RoleAName:
case TextRole::MultiA:
case TextRole::ChangeA:
p0 = m_associationLine.point(0);
p1 = m_associationLine.point(1);
// If we are dealing with a single line then tie the
// role label to the proper half of the line, i.e.
// the role label must be closer to the "other"
// role object.
if (lastSegment == 1)
p1 = midPoint(p0, p1);
break;
case TextRole::RoleBName:
case TextRole::MultiB:
case TextRole::ChangeB:
p0 = m_associationLine.point(lastSegment - 1);
p1 = m_associationLine.point(lastSegment);
if (lastSegment == 1)
p0 = midPoint(p0, p1);
break;
case TextRole::Name:
case TextRole::Coll_Message: // CHECK: collab.msg texts seem to be TextRole::Name
case TextRole::State: // CHECK: is this used?
// Find the linepath segment to which the (textX, textY) is closest
// and constrain to the corridor of that segment (see farther below)
{
int minDistSquare = 100000; // utopian initial value
int lpIndex = 0;
for (int i = 0; i < lastSegment; ++i) {
p0 = m_associationLine.point(i);
p1 = m_associationLine.point(i + 1);
QPointF midP = midPoint(p0, p1);
const int deltaX = textCenterX - midP.x();
const int deltaY = textCenterY - midP.y();
const int cSquare = deltaX * deltaX + deltaY * deltaY;
if (cSquare < minDistSquare) {
minDistSquare = cSquare;
lpIndex = i;
}
}
p0 = m_associationLine.point(lpIndex);
p1 = m_associationLine.point(lpIndex + 1);
}
break;
default:
logError1("AssociationWidget::constrainTextPos: unexpected TextRole %1",
Uml::TextRole::toString(tr));
return;
break;
}
/* Constraint:
The midpoint between p0 and p1 is taken to be the center of a circle
with radius D/2 where D is the distance between p0 and p1.
The text center needs to be within this circle else it is constrained
to the nearest point on the circle.
*/
p0 = swapXY(p0); // go to the natural coordinate system
p1 = swapXY(p1); // with (0,0) in the lower left corner
QPointF midP = midPoint(p0, p1);
// If (textX,textY) is not inside the circle around midP then
// constrain (textX,textY) to the nearest point on that circle.
const int x0 = p0.x();
const int y0 = p0.y();
const int x1 = p1.x();
const int y1 = p1.y();
double r = sqrt((double)((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0))) / 2;
if (textWidth > r)
r = textWidth;
// swap textCenter{X,Y} to convert from Qt coord.system.
const QPointF origTextCenter(textCenterY, textCenterX);
const int relX = fabs(origTextCenter.x() - midP.x());
const int relY = fabs(origTextCenter.y() - midP.y());
const double negativeWhenInsideCircle = relX * relX + relY * relY - r * r;
if (negativeWhenInsideCircle <= 0.0) {
return;
}
/*
The original constraint was to snap the text position to the
midpoint but that creates unpleasant visual jitter:
textX = midP.y() - textWidth / 2; // go back to Qt coord.sys.
textY = midP.x() - textHeight / 2; // go back to Qt coord.sys.
Rather, we project the text position onto the closest point
on the circle:
Circle equation:
relX^2 + relY^2 - r^2 = 0, or in other words
relY^2 = r^2 - relX^2, or
relY = sqrt(r^2 - relX^2)
Line equation:
relY = a * relX + b
We can omit "b" because relX and relY are already relative to
the circle origin, therefore we can also write:
a = relY / relX
To obtain the point of intersection between the circle of radius r
and the line connecting the circle origin with the point (relX, relY),
we equate the relY:
a * x = sqrt(r^2 - x^2), or in other words
a^2 * x^2 = r^2 - x^2, or
x^2 * (a^2 + 1) = r^2, or
x^2 = r^2 / (a^2 + 1), or
x = sqrt(r^2 / (a^2 + 1))
and then
y = a * x
The resulting x and y are relative to the circle origin so we just add
the circle origin (X, Y) to obtain the constrained (textX, textY).
*/
// Handle the special case, relX = 0.
if (relX == 0) {
if (origTextCenter.y() > midP.y())
textX = midP.y() + (int)r; // go back to Qt coord.sys.
else
textX = midP.y() - (int)r; // go back to Qt coord.sys.
textX -= textWidth / 2;
return;
}
const double a = (double)relY / (double)relX;
const double x = sqrt(r*r / (a*a + 1));
const double y = a * x;
if (origTextCenter.x() > midP.x())
textY = midP.x() + (int)x; // go back to Qt coord.sys.
else
textY = midP.x() - (int)x; // go back to Qt coord.sys.
textY -= textHeight / 2;
if (origTextCenter.y() > midP.y())
textX = midP.y() + (int)y; // go back to Qt coord.sys.
else
textX = midP.y() - (int)y; // go back to Qt coord.sys.
textX -= textWidth / 2;
}
/**
* Puts the text widget with the given role at a recalculated position.
* This method calls @ref calculateTextPosition to get the needed position.
* I.e. the line segment it is on has moved and its position should move
* the same amount as the line.
*/
void AssociationWidget::setTextPosition(Uml::TextRole::Enum role)
{
bool startMove = false;
if (m_role[RoleType::A].getStartMove())
startMove = true;
else if (m_role[RoleType::B].getStartMove())
startMove = true;
else if (m_nameWidget && m_nameWidget->getStartMove())
startMove = true;
if (startMove) {
return;
}
FloatingTextWidget *ft = textWidgetByRole(role);
if (ft == nullptr)
return;
QPointF pos = calculateTextPosition(role);
ft->setX(pos.x());
ft->setY(pos.y());
}
/**
* Moves the text widget with the given role by the difference between
* the two points.
*/
void AssociationWidget::setTextPositionRelatively(Uml::TextRole::Enum role, const QPointF &oldPosition)
{
bool startMove = false;
if (m_role[RoleType::A].getStartMove())
startMove = true;
else if (m_role[RoleType::B].getStartMove())
startMove = true;
else if (m_nameWidget && m_nameWidget->getStartMove())
startMove = true;
if (startMove) {
return;
}
FloatingTextWidget *ft = textWidgetByRole(role);
if (ft == nullptr)
return;
qreal ftX = ft->x();
qreal ftY = ft->y();
QPointF pos = calculateTextPosition(role);
int relX = pos.x() - oldPosition.x();
int relY = pos.y() - oldPosition.y();
qreal ftNewX = ftX + relX;
qreal ftNewY = ftY + relY;
bool oldIgnoreSnapToGrid = ft->getIgnoreSnapToGrid();
ft->setIgnoreSnapToGrid(true);
ft->setX(ftNewX);
ft->setY(ftNewY);
ft->setIgnoreSnapToGrid(oldIgnoreSnapToGrid);
}
/**
* Remove dashed connecting line for association class.
*/
void AssociationWidget::removeAssocClassLine()
{
delete m_pAssocClassLineSel0;
m_pAssocClassLineSel0 = nullptr;
delete m_pAssocClassLineSel1;
m_pAssocClassLineSel1 = nullptr;
delete m_pAssocClassLine;
m_pAssocClassLine = nullptr;
if (m_associationClass) {
m_associationClass->setClassAssociationWidget(nullptr);
m_associationClass = nullptr;
}
}
/**
* Creates the association class connecting line.
*/
void AssociationWidget::createAssocClassLine()
{
if (m_pAssocClassLine == nullptr) {
m_pAssocClassLine = new QGraphicsLineItem(this);
}
QPen pen(lineColor(), lineWidth(), Qt::DashLine);
m_pAssocClassLine->setPen(pen);
// decoration points
m_pAssocClassLineSel0 = Widget_Utils::decoratePoint(m_pAssocClassLine->line().p1(),
m_pAssocClassLine);
m_pAssocClassLineSel1 = Widget_Utils::decoratePoint(m_pAssocClassLine->line().p2(),
m_pAssocClassLine);
computeAssocClassLine();
selectAssocClassLine(false);
}
/**
* Creates the association class connecting line using the specified
* ClassifierWidget.
*
* @param classifier The ClassifierWidget to use.
* @param linePathSegmentIndex The index of the segment where the
* association class is created.
*/
void AssociationWidget::createAssocClassLine(ClassifierWidget* classifier,
int linePathSegmentIndex)
{
m_nLinePathSegmentIndex = linePathSegmentIndex;
if (m_nLinePathSegmentIndex < 0) {
return;
}
m_associationClass = classifier;
m_associationClass->setClassAssociationWidget(this);
m_associationClass->addAssoc(this); // to get widgetMoved(...) for association classes
createAssocClassLine();
}
/**
* Compute the end points of m_pAssocClassLine in case this
* association has an attached association class.
* TODO: Bring decoration points to life (https://bugs.kde.org/show_bug.cgi?id=447866)
*/
void AssociationWidget::computeAssocClassLine()
{
if (m_associationClass == nullptr || m_pAssocClassLine == nullptr) {
return;
}
if (m_nLinePathSegmentIndex < 0) {
logError0("AssociationWidget::computeAssocClassLine: m_nLinePathSegmentIndex is not set");
return;
}
QPointF segStart = m_associationLine.point(m_nLinePathSegmentIndex);
QPointF segEnd = m_associationLine.point(m_nLinePathSegmentIndex + 1);
const qreal midSegX = segStart.x() + (segEnd.x() - segStart.x()) / 2.0;
const qreal midSegY = segStart.y() + (segEnd.y() - segStart.y()) / 2.0;
QPointF segmentMidPoint(midSegX, midSegY);
QLineF possibleAssocLine = QLineF(segmentMidPoint,
m_associationClass->mapRectToScene(m_associationClass->rect()).center());
QPointF intersectionPoint;
QLineF::IntersectType type = intersect(m_associationClass->mapRectToScene(m_associationClass->boundingRect()),
possibleAssocLine,
&intersectionPoint);
// logDebug2("intersect type=%1 / point=%2", type, intersectionPoint);
if (type == QLineF::BoundedIntersection) {
m_pAssocClassLine->setLine(midSegX, midSegY,
intersectionPoint.x(), intersectionPoint.y());
if (m_pAssocClassLineSel0 && m_pAssocClassLineSel1) {
m_pAssocClassLineSel0->setPos(m_pAssocClassLine->line().p1());
m_pAssocClassLineSel1->setPos(m_pAssocClassLine->line().p2());
}
}
}
/**
* Renders the association class connecting line selected.
*/
void AssociationWidget::selectAssocClassLine(bool sel)
{
if (m_pAssocClassLineSel0 && m_pAssocClassLineSel1) {
m_pAssocClassLineSel0->setVisible(sel);
m_pAssocClassLineSel1->setVisible(sel);
}
}
/**
* Sets the association to be selected.
*/
void AssociationWidget::mousePressEvent(QGraphicsSceneMouseEvent * me)
{
// clear other selected stuff on the screen of ShiftKey
if (me->modifiers() != Qt::ShiftModifier) {
m_scene->clearSelected();
}
if (me->button() == Qt::LeftButton && me->modifiers() == Qt::ControlModifier) {
if (checkRemovePoint(me->scenePos()))
return;
}
// make sure we should be here depending on the button
if (me->button() != Qt::RightButton && me->button() != Qt::LeftButton) {
return;
}
QPointF mep = me->scenePos();
// see if `mep' is on the connecting line to the association class
if (onAssocClassLine(mep)) {
setSelected(true);
selectAssocClassLine();
return;
}
setSelected(!isSelected());
m_associationLine.mousePressEvent(me);
}
/**
* Displays the right mouse buttom menu if right button is pressed.
*/
void AssociationWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent * me)
{
m_associationLine.mouseReleaseEvent(me);
}
/**
* Handles the selection from the popup menu.
*/
void AssociationWidget::slotMenuSelection(QAction* action)
{
QString oldText, newText;
bool ok = false;
Uml::AssociationType::Enum atype = associationType();
Uml::RoleType::Enum r = RoleType::B;
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
logDebug1("AssociationWidget::slotMenuSelection %1", ListPopupMenu::toString(sel));
// if it's a collaboration message we now just use the code in floatingtextwidget
// this means there's some redundant code below but that's better than duplicated code
if (isCollaboration() && sel != ListPopupMenu::mt_Delete) {
m_nameWidget->slotMenuSelection(action);
return;
}
switch(sel) {
case ListPopupMenu::mt_Properties:
if (atype == AssociationType::Seq_Message || atype == AssociationType::Seq_Message_Self) {
// show op dlg for seq. diagram here
// don't worry about here, I don't think it can get here as
// line is widget on seq. diagram
// here just in case - remove later after testing
logDebug1("- mt_Properties: assoctype is %1", atype);
} else { //standard assoc dialog
UMLApp::app()->docWindow()->updateDocumentation(false);
showPropertiesDialog();
}
break;
case ListPopupMenu::mt_Add_Point:
checkAddPoint(m_eventScenePos);
break;
case ListPopupMenu::mt_Delete_Point:
checkRemovePoint(m_eventScenePos);
break;
case ListPopupMenu::mt_Auto_Layout_Spline:
checkAutoLayoutSpline();
break;
case ListPopupMenu::mt_Delete:
if (!Dialog_Utils::askDeleteAssociation())
break;
if (m_pAssocClassLineSel0)
removeAssocClassLine();
else if (association())
m_scene->removeAssocInViewAndDoc(this);
else
m_scene->removeWidgetCmd(this);
break;
case ListPopupMenu::mt_Rename_MultiA:
r = RoleType::A; // fall through
case ListPopupMenu::mt_Rename_MultiB:
if (m_role[r].multiplicityWidget)
oldText = m_role[r].multiplicityWidget->text();
else
oldText = QString();
newText = oldText;
ok = Dialog_Utils::askName(i18n("Multiplicity"),
i18n("Enter multiplicity:"),
newText);
if (ok && newText != oldText) {
if (FloatingTextWidget::isTextValid(newText)) {
setMultiplicity(newText, r);
} else {
m_scene->removeWidget(m_role[r].multiplicityWidget);
m_role[r].multiplicityWidget = nullptr;
}
}
break;
case ListPopupMenu::mt_Rename_Name:
if (m_nameWidget)
oldText = m_nameWidget->text();
else
oldText = QString();
newText = oldText;
ok = Dialog_Utils::askName(i18n("Association Name"),
i18n("Enter association name:"),
newText);
if (ok && newText != oldText) {
if (FloatingTextWidget::isTextValid(newText)) {
setName(newText);
} else if (m_nameWidget) {
m_scene->removeWidget(m_nameWidget);
m_nameWidget = nullptr;
}
}
break;
case ListPopupMenu::mt_Rename_RoleAName:
r = RoleType::A; // fall through
case ListPopupMenu::mt_Rename_RoleBName:
if (m_role[r].roleWidget)
oldText = m_role[r].roleWidget->text();
else
oldText = QString();
newText = oldText;
ok = Dialog_Utils::askName(i18n("Role Name"),
i18n("Enter role name:"),
newText);
if (ok && newText != oldText) {
if (FloatingTextWidget::isTextValid(newText)) {
setRoleName(newText, r);
} else {
m_scene->removeWidget(m_role[r].roleWidget);
m_role[r].roleWidget = nullptr;
}
}
break;
case ListPopupMenu::mt_Change_Font:
{
bool ok = false;
QFont fnt = QFontDialog::getFont(&ok, font(), m_scene->activeView());
if (ok)
lwSetFont(fnt);
}
break;
case ListPopupMenu::mt_Line_Color:
{
QColor newColor = QColorDialog::getColor(lineColor());
if (newColor.isValid() && newColor != lineColor())
{
m_scene->selectionSetLineColor(newColor);
umlDoc()->setModified(true);
}
}
break;
case ListPopupMenu::mt_Cut:
m_scene->setStartedCut();
UMLApp::app()->slotEditCut();
break;
case ListPopupMenu::mt_Copy:
UMLApp::app()->slotEditCopy();
break;
case ListPopupMenu::mt_Paste:
UMLApp::app()->slotEditPaste();
break;
case ListPopupMenu::mt_Reset_Label_Positions:
resetTextPositions();
break;
case ListPopupMenu::mt_LayoutDirect:
m_associationLine.setLayout(Uml::LayoutType::Direct);
break;
case ListPopupMenu::mt_LayoutSpline:
m_associationLine.setLayout(Uml::LayoutType::Spline);
break;
case ListPopupMenu::mt_LayoutOrthogonal:
m_associationLine.setLayout(Uml::LayoutType::Orthogonal);
break;
case ListPopupMenu::mt_LayoutPolyline:
m_associationLine.setLayout(Uml::LayoutType::Polyline);
break;
default:
logDebug1("- MenuType %1 not implemented", ListPopupMenu::toString(sel));
break;
}//end switch
}
/**
* Return the first font found being used by any child widget. (They
* could be different fonts, so this is a slightly misleading method.)
*/
QFont AssociationWidget::font() const
{
//:TODO: find a general font for the association
QFont font;
if (m_role[RoleType::A].roleWidget)
font = m_role[RoleType::A].roleWidget->font();
else if (m_role[RoleType::B].roleWidget)
font = m_role[RoleType::B].roleWidget->font();
else if (m_role[RoleType::A].multiplicityWidget)
font = m_role[RoleType::A].multiplicityWidget->font();
else if (m_role[RoleType::B].multiplicityWidget)
font = m_role[RoleType::B].multiplicityWidget->font();
else if (m_role[RoleType::A].changeabilityWidget)
font = m_role[RoleType::A].changeabilityWidget->font();
else if (m_role[RoleType::B].changeabilityWidget)
font = m_role[RoleType::B].changeabilityWidget->font();
else if (m_nameWidget)
font = m_nameWidget->font();
else
font = m_role[RoleType::A].umlWidget->font();
return font;
}
/**
* Set all 'owned' child widgets to this text color.
*/
void AssociationWidget::setTextColor(const QColor &color)
{
WidgetBase::setTextColor(color);
if (m_nameWidget) {
m_nameWidget->setTextColor(color);
}
if (m_role[RoleType::A].roleWidget) {
m_role[RoleType::A].roleWidget->setTextColor(color);
}
if (m_role[RoleType::B].roleWidget) {
m_role[RoleType::B].roleWidget->setTextColor(color);
}
if (m_role[RoleType::A].multiplicityWidget) {
m_role[RoleType::A].multiplicityWidget->setTextColor(color);
}
if (m_role[RoleType::B].multiplicityWidget) {
m_role[RoleType::B].multiplicityWidget->setTextColor(color);
}
if (m_role[RoleType::A].changeabilityWidget)
m_role[RoleType::A].changeabilityWidget->setTextColor(color);
if (m_role[RoleType::B].changeabilityWidget)
m_role[RoleType::B].changeabilityWidget->setTextColor(color);
}
void AssociationWidget::setLineColor(const QColor &color)
{
WidgetBase::setLineColor(color);
QPen pen = m_associationLine.pen();
pen.setColor(color);
m_associationLine.setPen(pen);
if (m_pAssocClassLine) {
m_pAssocClassLine->setPen(pen);
}
}
void AssociationWidget::setLineWidth(uint width)
{
WidgetBase::setLineWidth(width);
QPen pen = m_associationLine.pen();
pen.setWidth(width);
m_associationLine.setPen(pen);
if (m_pAssocClassLine) {
m_pAssocClassLine->setPen(pen);
}
}
bool AssociationWidget::checkAddPoint(const QPointF &scenePos)
{
if (associationType() == AssociationType::Exception) {
return false;
}
// if there is no point around the mouse pointer, we insert a new one
if (m_associationLine.closestPointIndex(scenePos) < 0) {
int i = m_associationLine.closestSegmentIndex(scenePos);
if (i < 0) {
logDebug0("AssociationWidget::checkAddPoint: no closest segment found");
return false;
}
// switch type to see additional points by default
if (m_associationLine.count() == 2)
m_associationLine.setLayout(Uml::LayoutType::Polyline);
m_associationLine.insertPoint(i + 1, scenePos);
if (m_nLinePathSegmentIndex == i) {
QPointF segStart = m_associationLine.point(i);
QPointF segEnd = m_associationLine.point(i + 2);
const int midSegX = segStart.x() + (segEnd.x() - segStart.x()) / 2;
const int midSegY = segStart.y() + (segEnd.y() - segStart.y()) / 2;
#ifdef VERBOSE_DEBUGGING
logDebug4("segStart=%1, segEnd=%2, midSeg=(%3,%4)",
segStart, segEnd, midSegX, midSegY);
#endif
if (midSegX > scenePos.x() || midSegY < scenePos.y()) {
m_nLinePathSegmentIndex++;
logDebug1("setting m_nLinePathSegmentIndex to %1", m_nLinePathSegmentIndex);
computeAssocClassLine();
}
m_associationLine.update();
calculateNameTextSegment();
umlDoc()->setModified(true);
setSelected(true);
}
return true;
}
else {
logDebug0("found point already close enough");
return false;
}
}
/**
* Remove point close to the given point and redraw the association.
* @param scenePos point which should be removed
* @return success status of the remove action
*/
bool AssociationWidget::checkRemovePoint(const QPointF &scenePos)
{
int i = m_associationLine.closestPointIndex(scenePos);
if (i == -1)
return false;
m_associationLine.setSelected(false);
// there was a point so we remove the point
m_associationLine.removePoint(i);
// switch type back to simple line
if (m_associationLine.count() == 2)
m_associationLine.setLayout(Uml::LayoutType::Direct);
// Maybe reattach association class connecting line
// to different association linepath segment.
const int numberOfLines = m_associationLine.count() - 1;
if (m_nLinePathSegmentIndex >= numberOfLines) {
m_nLinePathSegmentIndex = numberOfLines - 1;
}
calculateEndingPoints();
// select the line path
m_associationLine.setSelected(true);
m_associationLine.update();
calculateNameTextSegment();
umlDoc()->setModified(true);
return true;
}
bool AssociationWidget::checkAutoLayoutSpline() {
m_associationLine.enableAutoLayout();
m_associationLine.update();
return true;
}
/**
* Moves the break point being dragged.
*/
void AssociationWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* me)
{
if (me->buttons() != Qt::LeftButton) {
return;
}
setSelected(true);
m_associationLine.mouseMoveEvent(me);
moveEvent(me);
}
/**
* Returns the Region the widget to line intersection is for the given
* widget in this Association. If the given widget is not in the
* Association then Region::Error is returned.
* Used by @ref calculateEndingPoints to work these positions out for
* another Association - since the number of Associations on the same
* region for the same widget will mean the lines will need to be
* spread out across the region.
*/
//Uml::Region::Enum AssociationWidget::getWidgetRegion(AssociationWidget * widget) const
//{
// if (widget->widgetForRole(RoleType::A) == m_role[RoleType::A].umlWidget)
// return m_role[RoleType::A].m_WidgetRegion;
// if (widget->widgetForRole(RoleType::B) == m_role[RoleType::B].umlWidget)
// return m_role[RoleType::B].m_WidgetRegion;
// return Uml::Region::Error;
//}
/**
* Find the border point of the given rect when a line is drawn from the
* given point to the rect.
* @param rect rect of a classifier
* @param line a line to the rect
* @param intersectionPoint the intercept point on the border of the rect
* @return the QLineF::IntersectType of the intersection
*/
QLineF::IntersectType AssociationWidget::intersect(const QRectF &rect, const QLineF &line,
QPointF* intersectionPoint)
{
QList<QLineF> lines;
lines << QLineF(rect.topLeft(), rect.topRight());
lines << QLineF(rect.topRight(), rect.bottomRight());
lines << QLineF(rect.bottomRight(), rect.bottomLeft());
lines << QLineF(rect.bottomLeft(), rect.topLeft());
for(const QLineF& rectLine: lines) {
QLineF::IntersectType type = rectLine.intersects(line, intersectionPoint);
if (type == QLineF::BoundedIntersection) {
return type;
}
}
return QLineF::NoIntersection;
}
bool AssociationWidget::setStartAndEndPoint(AssociationWidget *assocwidget, UMLWidget *pWidget)
{
const QRectF rect(pWidget->scenePos().x(), pWidget->scenePos().y(),
pWidget->width(), pWidget->height());
AssociationWidgetRole& roleA = assocwidget->m_role[RoleType::A];
AssociationWidgetRole& roleB = assocwidget->m_role[RoleType::B];
UMLWidget *wA = roleA.umlWidget;
UMLWidget *wB = roleB.umlWidget;
// Skip self associations.
if (wA == wB)
return false;
// Now we must find out with which end the assocwidget connects
// to the input widget (pWidget).
if (pWidget != wA && pWidget != wB)
return false;
// Determine intercept position
UMLWidget * otherWidget = (pWidget == wA ? wB : wA);
AssociationLine& linepath = assocwidget->associationLine();
int pointIndex = 0; // start point; will be changed to end point if startsAtOther
QPointF refpoint;
bool startsAtOther = assocwidget->linePathStartsAt(otherWidget);
if (startsAtOther) {
if (!assocwidget->linePathEndsAt(pWidget)) {
logWarn3("AssociationWidget::setStartAndEndPoint : linepath starts at other widget "
"but does not end at own (assocType=%1 pWidget=%2 otherWidget=%3)",
assocwidget->associationType(), pWidget->name(), otherWidget->name());
return false;
}
pointIndex = linepath.count() - 1;
refpoint = linepath.point(pointIndex - 1);
} else if (!assocwidget->linePathStartsAt(pWidget)) {
logWarn3("AssociationWidget::setStartAndEndPoint : linepath starts at neither own "
"nor other widget (assocType=%1 pWidget=%2 otherWidget=%3)",
assocwidget->associationType(), pWidget->name(), otherWidget->name());
return false;
} else if (!assocwidget->linePathEndsAt(otherWidget)) {
logWarn3("AssociationWidget::setStartAndEndPoint : linepath starts at own widget but "
"does not end at other (assocType=%1 pWidget=%2 otherWidget=%3)",
assocwidget->associationType(), pWidget->name(), otherWidget->name());
return false;
} else {
refpoint = linepath.point(1);
}
// The point is authoritative if it is a waypoint on the line path.
bool pointIsAuthoritative = (linepath.count() > 2);
if (! pointIsAuthoritative) {
// If the point is not authoritative then we use the other
// widget's center.
refpoint.setX(otherWidget->scenePos().x() + (otherWidget->width() / 2.0));
refpoint.setY(otherWidget->scenePos().y() + (otherWidget->height() / 2.0));
}
logDebug4("AssociationWidget::setStartAndEndPoint(own=%1) : ownW=%2, ownH=%3, other=%4",
pWidget->name(), pWidget->width(), pWidget->height(), otherWidget->name());
#ifdef VERBOSE_DEBUGGING
logDebug4("- startsAtOther=%1, pointIsAuthoritative=%2, refX=%3, refY=%4",
startsAtOther, pointIsAuthoritative, refpoint.x(), refpoint.y());
#endif
QPointF intercept;
if (! findIntercept(rect, refpoint, intercept)) {
logWarn3("AssociationWidget::setStartAndEndPoint error from findIntercept for "
"assocType=%1 pWidget=%2 otherWidget=%3",
assocwidget->associationType(), pWidget->name(), otherWidget->name());
return false;
}
linepath.setPoint(pointIndex, intercept);
if (pointIsAuthoritative)
return true;
//--------------------------------------------------------------------------------
// Determine intercept at other widget if this is a straight connecting line
// without waypoint (pointIsAuthoritative is false).
const QRectF otherRect(otherWidget->scenePos().x(), otherWidget->scenePos().y(),
otherWidget->width(), otherWidget->height());
int otherPtIndex = linepath.count() - 1;
QPointF otherRefpoint;
if (startsAtOther) {
otherPtIndex = 0;
otherRefpoint = linepath.point(1);
} else {
otherRefpoint = linepath.point(0);
}
if (findIntercept(otherRect, otherRefpoint, intercept)) {
linepath.setPoint(otherPtIndex, intercept);
} else {
logWarn3("AssociationWidget::setStartAndEndPoint error from reverse findIntercept for "
"assocType=%1 pWidget=%2 otherWidget=%3",
assocwidget->associationType(), pWidget->name(), otherWidget->name());
return false;
}
return true;
}
/**
* Used by @ref calculateEndingPoints.
* For all association widgets of the scene, if one of the assocwidget's
* role widgets is the passed in widget then
* - if the AssociationLine starts at the role widget then the AssociationLine
* start point is recalculated and set;
* - if the AssociationLine ends at the role widget then the AssociationLine
* end point is recalculated and set.
*
* @param pWidget Pointer to the widget to seek as the role A or B widget
* in all association widgets of the scene.
* @param list The association widgets to analyze/update
*/
void AssociationWidget::updateAssociations(UMLWidget *pWidget, AssociationWidgetList list)
{
for(AssociationWidget *assocwidget : list) {
setStartAndEndPoint(assocwidget, pWidget);
}
}
/**
* Given a rectangle and a point, compute the connecting line between the
* middle point of the rectangle and the point, and return the intersection
* point of this line with one of the sides of the rectangle.
*
* @param rect rolewidget's rectangle with scene x and y values
* @param point ending point of the line that starts at rect's center
* @param result return value: intersection point with one of rect's sides
* @return false if none of rect's sides intersects with point; in this case,
* \a result will remain at the value passed in.
*/
bool AssociationWidget::findIntercept(const QRectF& rect, const QPointF& point,
QPointF& result)
{
const QPointF rectCenter(rect.center());
const QLineF line(rectCenter, point);
const QLineF eastSide (rect.bottomLeft(), rect.topLeft());
const QLineF northSide(rect.topLeft(), rect.topRight());
const QLineF westSide (rect.topRight(), rect.bottomRight());
const QLineF southSide(rect.bottomRight(), rect.bottomLeft());
QVector<QLineF> edges;
edges << eastSide << northSide << westSide << southSide;
Uml::Region::Enum xSide = Uml::Region::Error;
for (int i = 0; i < 4; i++) {
const QLineF& regionLine = edges.at(i);
QPointF intersectionPoint;
QLineF::IntersectType xType = regionLine.intersects(line, &intersectionPoint);
if (xType == QLineF::BoundedIntersection) {
result = intersectionPoint;
xSide = static_cast<Uml::Region::Enum>(i + 1);
break;
}
}
#ifdef VERBOSE_DEBUGGING
if (xSide != Uml::Region::Error) {
logDebug5("AssociationWidget::findIntercept (rect=%1, center=%2, point=%3) : intercept at %4 %5",
rect, rectCenter, point, result, Uml::Region::toString(xSide));
} else {
logDebug4("AssociationWidget::findIntercept (rect=%1, center=%2, point=%3) : no intercept with %4",
rect, rectCenter, point, edges);
}
#endif
return (xSide != Uml::Region::Error);
}
/**
* Sets the state of whether the widget is selected.
*
* @param _select The state of whether the widget is selected.
*/
void AssociationWidget::setSelected(bool _select /* = true */)
{
WidgetBase::setSelected(_select);
if ( m_nameWidget)
m_nameWidget->setSelected( _select );
m_role[RoleType::A].setSelected(_select);
m_role[RoleType::B].setSelected(_select);
// Update the docwindow for this association.
// This is done last because each of the above setSelected calls
// overwrites the docwindow, but we want the main association doc
// to win.
if (_select) {
UMLApp::app()->docWindow()->showDocumentation(this, false);
} else
UMLApp::app()->docWindow()->updateDocumentation(true);
m_associationLine.setSelected(_select);
if (! _select) {
// For now, if _select is true we don't make the assoc class line
// selected. But that's certainly open for discussion.
// At any rate, we need to deselect the assoc class line
// if _select is false.
selectAssocClassLine(false);
}
UMLApp::app()->document()->writeToStatusBar(_select ? i18n("Press Ctrl with left mouse click to delete a point") : QString());
}
/**
* Reimplement method from WidgetBase in order to check owned floating texts.
*
* @param p Point to be checked.
*
* @return pointer to widget at the provided point
* @return 0 is no widget has been found
*/
UMLWidget* AssociationWidget::onWidget(const QPointF &p)
{
if (m_nameWidget && m_nameWidget->onWidget(p))
return m_nameWidget;
UMLWidget *w = m_role[RoleType::A].onWidget(p);
if (w)
return w;
w = m_role[RoleType::B].onWidget(p);
if (w)
return w;
return nullptr;
}
/**
* Returns true if the given point is on the connecting line to
* the association class. Returns false if there is no association
* class attached, or if the given point is not on the connecting
* line.
*/
bool AssociationWidget::onAssocClassLine(const QPointF &point)
{
bool onLine = false;
if (m_pAssocClassLine) {
//:TODO:
// const QPointF mapped = m_pAssocClassLine->mapFromParent(point);
// bool onLine = m_pAssocClassLine->contains(mapped);
// return onLine;
UMLSceneItemList list = m_scene->collisions(point);
UMLSceneItemList::iterator end(list.end());
for (UMLSceneItemList::iterator item_it(list.begin()); item_it != end; ++item_it) {
if (*item_it == m_pAssocClassLine) {
onLine = true;
break;
}
}
}
logDebug3("AssociationWidget::onAssocClassLine (x=%1, y=%2) : result=%3",
point.x(), point.y(), onLine);
return onLine;
}
/**
* Returns true if the given point is on the association line.
* A circle (rectangle) around the point is used to obtain more tolerance.
* @param point the point to check
* @return flag whether point is on association line
*/
bool AssociationWidget::onAssociation(const QPointF& point)
{
// check the path
const qreal diameter(4.0);
QPainterPath path = m_associationLine.shape();
if (path.contains(point)) {
logDebug2("AssociationWidget::onAssociation (x=%1, y=%2) : on path",
point.x(), point.y());
return true;
}
// check also the points
if (m_associationLine.layout() == Uml::LayoutType::Spline) {
if (m_associationLine.closestPointIndex(point, diameter) > -1) {
logDebug2("AssociationWidget::onAssociation (x=%1, y=%2) : on spline point",
point.x(), point.y());
return true;
}
}
return onAssocClassLine(point);
}
/**
* Set all association points to x coordinate.
*/
void AssociationWidget::setXEntireAssoc(qreal x)
{
for (int i = 0; i < m_associationLine.count(); ++i) {
QPointF p = m_associationLine.point(i);
p.setX(x);
m_associationLine.setPoint(i, p);
}
}
/**
* Set all association points to y coordinate.
*/
void AssociationWidget::setYEntireAssoc(qreal y)
{
for (int i = 0; i < m_associationLine.count(); ++i) {
QPointF p = m_associationLine.point(i);
p.setY(y);
m_associationLine.setPoint(i, p);
}
}
/**
* Moves all the mid points (all except start /end) by the given amount.
*/
void AssociationWidget::moveMidPointsBy(qreal x, qreal y)
{
int pos = m_associationLine.count() - 1;
for (int i = 1; i < (int)pos; ++i) {
QPointF p = m_associationLine.point( i );
qreal newX = p.x() + x;
qreal newY = p.y() + y;
p.setX( newX );
p.setY( newY );
m_associationLine.setPoint( i, p );
}
}
/**
* Moves the entire association by the given offset.
*/
void AssociationWidget::moveEntireAssoc(qreal x, qreal y)
{
//TODO: ADD SUPPORT FOR ASSOC. ON SEQ. DIAGRAMS WHEN NOTES BACK IN.
moveMidPointsBy(x, y);
// multi select
if (umlScene()->selectedCount() > 1) {
QPointF d(x, y);
QPointF s = m_associationLine.startPoint() + d;
QPointF e = m_associationLine.endPoint() + d;
m_associationLine.setEndPoints(s, e);
}
calculateEndingPoints();
calculateNameTextSegment();
resetTextPositions();
}
/**
* Returns the bounding rectangle of all segments of the association.
*/
QRectF AssociationWidget::boundingRect() const
{
return m_associationLine.boundingRect();
}
/**
* Returns the shape of all segments of the association.
*/
QPainterPath AssociationWidget::shape() const
{
return m_associationLine.shape();
}
/**
* Connected to UMLClassifier::attributeRemoved() or UMLEntity::constraintRemoved()
* in case this AssociationWidget is linked to a classifier list item
* (an attribute or a foreign key constraint)
*
* @param obj The UMLClassifierListItem removed.
*/
void AssociationWidget::slotClassifierListItemRemoved(UMLClassifierListItem* obj)
{
if (obj != m_umlObject) {
DEBUG() << "obj=" << obj << ": m_umlObject=" << m_umlObject;
return;
}
m_umlObject = nullptr;
m_scene->removeWidgetCmd(this);
}
/**
* Connected to UMLObject::modified() in case this
* AssociationWidget is linked to a classifer's attribute type.
*/
void AssociationWidget::slotAttributeChanged()
{
UMLAttribute *attr = attribute();
if (attr == nullptr) {
logError0("AssociationWidget::slotAttributeChanged attribute() returns null");
return;
}
setVisibility(attr->visibility(), RoleType::B);
setRoleName(attr->name(), RoleType::B);
}
void AssociationWidget::clipSize()
{
if (m_nameWidget)
m_nameWidget->clipSize();
m_role[RoleType::A].clipSize();
m_role[RoleType::B].clipSize();
if (m_associationClass)
m_associationClass->clipSize();
}
/**
* Event handler for context menu events, called from the line segments.
*/
void AssociationWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
event->accept();
UMLScene *scene = umlScene();
QWidget *parent = nullptr;
if (scene) {
parent = scene->activeView();
}
if (!isSelected() && scene && !scene->selectedItems().isEmpty()) {
Qt::KeyboardModifiers forSelection = (Qt::ControlModifier | Qt::ShiftModifier);
if ((event->modifiers() & forSelection) == 0) {
scene->clearSelection();
}
}
setSelected(true);
m_eventScenePos = event->scenePos();
const Uml::AssociationType::Enum type = onAssocClassLine(event->scenePos()) ? Uml::AssociationType::Anchor : associationType();
AssociationWidgetPopupMenu popup(parent, type, this);
QAction *triggered = popup.exec(event->screenPos());
slotMenuSelection(triggered);
}
/**
* Reimplemented event handler for hover enter events.
*/
void AssociationWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
m_associationLine.hoverEnterEvent(event);
}
/**
* Reimplemented event handler for hover leave events.
*/
void AssociationWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
m_associationLine.hoverLeaveEvent(event);
}
/**
* Reimplemented event handler for hover move events.
*/
void AssociationWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
m_associationLine.hoverMoveEvent(event);
}
/**
* Saves this widget to the "assocwidget" XMI element.
*/
void AssociationWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("assocwidget"));
WidgetBase::saveToXMI(writer);
LinkWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("type"), QString::number(associationType()));
if (!association()) {
writer.writeAttribute(QStringLiteral("visibilityA"), QString::number(visibility(RoleType::A)));
writer.writeAttribute(QStringLiteral("visibilityB"), QString::number(visibility(RoleType::B)));
writer.writeAttribute(QStringLiteral("changeabilityA"), QString::number(changeability(RoleType::A)));
writer.writeAttribute(QStringLiteral("changeabilityB"), QString::number(changeability(RoleType::B)));
if (m_umlObject == nullptr) {
writer.writeAttribute(QStringLiteral("roleAdoc"), roleDocumentation(RoleType::A));
writer.writeAttribute(QStringLiteral("roleBdoc"), roleDocumentation(RoleType::B));
writer.writeAttribute(QStringLiteral("documentation"), documentation());
}
}
writer.writeAttribute(QStringLiteral("widgetaid"), Uml::ID::toString(widgetIDForRole(RoleType::A)));
writer.writeAttribute(QStringLiteral("widgetbid"), Uml::ID::toString(widgetIDForRole(RoleType::B)));
if (m_associationClass) {
QString acid = Uml::ID::toString(m_associationClass->id());
writer.writeAttribute(QStringLiteral("assocclass"), acid);
writer.writeAttribute(QStringLiteral("aclsegindex"), QString::number(m_nLinePathSegmentIndex));
}
// save attributes of m_role[A]
const AssociationWidgetRole& roleA = m_role[RoleType::A];
writer.writeAttribute(QStringLiteral("indexa"), QString::number(roleA.m_nIndex));
writer.writeAttribute(QStringLiteral("totalcounta"), QString::number(roleA.m_nTotalCount));
// save attributes of m_role[B]
const AssociationWidgetRole& roleB = m_role[RoleType::B];
writer.writeAttribute(QStringLiteral("indexb"), QString::number(roleB.m_nIndex));
writer.writeAttribute(QStringLiteral("totalcountb"), QString::number(roleB.m_nTotalCount));
// Save subelements of m_role[A] and m_role[B].
m_role[RoleType::A].saveToXMI(writer);
// This is separated from attributes because attributes may not follow
// elements, i.e. all attributes must be written before the first subelement.
m_role[RoleType::B].saveToXMI(writer);
if (m_nameWidget) {
m_nameWidget->saveToXMI(writer);
}
m_associationLine.saveToXMI(writer);
writer.writeEndElement(); // assocwidget
}
/**
* Uses the supplied widgetList for resolving
* the role A and role B widgets. (The other loadFromXMI() queries
* the UMLScene for these widgets.)
* Required for clipboard operations.
*/
bool AssociationWidget::loadFromXMI(QDomElement& qElement,
const UMLWidgetList& widgets,
const MessageWidgetList* messages)
{
if (!WidgetBase::loadFromXMI(qElement)) {
return false;
}
if (!LinkWidget::loadFromXMI(qElement)) {
return false;
}
// load child widgets first
QString widgetaid = qElement.attribute(QStringLiteral("widgetaid"), QStringLiteral("-1"));
QString widgetbid = qElement.attribute(QStringLiteral("widgetbid"), QStringLiteral("-1"));
Uml::ID::Type aId = Uml::ID::fromString(widgetaid);
Uml::ID::Type bId = Uml::ID::fromString(widgetbid);
UMLWidget *pWidgetA = Widget_Utils::findWidget(aId, widgets, messages);
if (!pWidgetA) {
logError1("AssociationWidget::loadFromXMI cannot find widget for roleA id %1",
Uml::ID::toString(aId));
return false;
}
UMLWidget *pWidgetB = Widget_Utils::findWidget(bId, widgets, messages);
if (!pWidgetB) {
logError1("AssociationWidget::loadFromXMI cannot find widget for roleB id %1",
Uml::ID::toString(bId));
return false;
}
setWidgetForRole(pWidgetA, RoleType::A);
setWidgetForRole(pWidgetB, RoleType::B);
QString type = qElement.attribute(QStringLiteral("type"), QStringLiteral("-1"));
Uml::AssociationType::Enum aType = Uml::AssociationType::fromInt(type.toInt());
bool oldStyleLoad = false;
if (m_nId == Uml::ID::None) {
// xmi.id not present, ergo either a pure widget association,
// or old (pre-1.2) style:
// Everything is loaded from the AssociationWidget.
// UMLAssociation may or may not be saved - if it is, it's a dummy.
// Create the UMLAssociation if both roles are UML objects;
// else load the info locally.
if (Uml::AssociationType::hasUMLRepresentation(aType)) {
// lack of an association in our widget AND presence of
// both uml objects for each role clearly identifies this
// as reading in an old-school file. Note it as such, and
// create, and add, the UMLAssociation for this widget.
// Remove this special code when backwards compatibility
// with older files isn't important anymore. -b.t.
UMLObject* umlRoleA = pWidgetA->umlObject();
UMLObject* umlRoleB = pWidgetB->umlObject();
if (!m_umlObject && umlRoleA && umlRoleB) {
oldStyleLoad = true; // flag for further special config below
if (aType == AssociationType::Aggregation || aType == AssociationType::Composition) {
logWarn0("AssociationWidget::loadFromXMI: Old Style save file? swapping roles on "
"association widget");
// We have to swap the A and B widgets to compensate
// for the long standing bug in AssociationLine of drawing
// the diamond at the wrong end which was fixed
// just before the 1.2 release.
// The logic here is that the user has understood
// that the diamond belongs at the SOURCE end of the
// the association (i.e. at the container, not at the
// contained), and has compensated for this anomaly
// by drawing the aggregations/compositions from
// target to source.
UMLWidget *tmpWidget = pWidgetA;
pWidgetA = pWidgetB;
pWidgetB = tmpWidget;
setWidgetForRole(pWidgetA, RoleType::A);
setWidgetForRole(pWidgetB, RoleType::B);
umlRoleA = pWidgetA->umlObject();
umlRoleB = pWidgetB->umlObject();
}
setUMLAssociation(umlDoc()->createUMLAssociation(umlRoleA, umlRoleB, aType));
}
}
setDocumentation(qElement.attribute(QStringLiteral("documentation")));
setRoleDocumentation(qElement.attribute(QStringLiteral("roleAdoc")), RoleType::A);
setRoleDocumentation(qElement.attribute(QStringLiteral("roleBdoc")), RoleType::B);
// visibility defaults to Public if it cant set it here..
QString visibilityA = qElement.attribute(QStringLiteral("visibilityA"), QStringLiteral("0"));
int vis = visibilityA.toInt();
if (vis >= 200) { // bkwd compat.
vis -= 200;
}
setVisibility((Uml::Visibility::Enum)vis, RoleType::A);
QString visibilityB = qElement.attribute(QStringLiteral("visibilityB"), QStringLiteral("0"));
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 = qElement.attribute(QStringLiteral("changeabilityA"), QStringLiteral("0"));
if (changeabilityA.toInt() > 0)
setChangeability(Uml::Changeability::fromInt(changeabilityA.toInt()), RoleType::A);
QString changeabilityB = qElement.attribute(QStringLiteral("changeabilityB"), QStringLiteral("0"));
if (changeabilityB.toInt() > 0)
setChangeability(Uml::Changeability::fromInt(changeabilityB.toInt()), RoleType::B);
} else {
// we should disconnect any prior association (can this happen??)
if (m_umlObject && m_umlObject->baseType() == UMLObject::ot_Association) {
UMLAssociation *umla = association();
umla->disconnect(this);
umla->nrof_parent_widgets--;
}
// New style: The xmi.id is a reference to the UMLAssociation.
// If the UMLObject is not found right now, we try again later
// during the type resolution pass - see activate().
UMLObject *myObj = umlDoc()->findObjectById(m_nId);
if (myObj) {
const UMLObject::ObjectType ot = myObj->baseType();
if (ot != UMLObject::ot_Association) {
setUMLObject(myObj);
} else {
UMLAssociation * myAssoc = myObj->asUMLAssociation();
setUMLAssociation(myAssoc);
if (type == QStringLiteral("-1"))
aType = myAssoc->getAssocType();
}
}
}
setAssociationType(aType);
m_role[RoleType::A].loadFromXMI(qElement, QStringLiteral("a"));
m_role[RoleType::B].loadFromXMI(qElement, QStringLiteral("b"));
QString assocclassid = qElement.attribute(QStringLiteral("assocclass"));
if (! assocclassid.isEmpty()) {
Uml::ID::Type acid = Uml::ID::fromString(assocclassid);
UMLWidget *w = Widget_Utils::findWidget(acid, widgets);
if (w) {
ClassifierWidget* aclWidget = static_cast<ClassifierWidget*>(w);
QString aclSegIndex = qElement.attribute(QStringLiteral("aclsegindex"), QStringLiteral("0"));
createAssocClassLine(aclWidget, aclSegIndex.toInt());
} else {
logError1("AssociationWidget::loadFromXMI cannot find assocclass %1", assocclassid);
}
}
//now load child elements
QDomNode node = qElement.firstChild();
QDomElement element = node.toElement();
while (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("linepath")) {
if (!m_associationLine.loadFromXMI(element)) {
return false;
}
} else if (tag == QStringLiteral("floatingtext") ||
tag == QStringLiteral("UML:FloatingTextWidget")) { // for bkwd compatibility
QString r = element.attribute(QStringLiteral("role"), QStringLiteral("-1"));
if (r == QStringLiteral("-1"))
return false;
Uml::TextRole::Enum role = Uml::TextRole::fromInt(r.toInt());
FloatingTextWidget *ft = new FloatingTextWidget(m_scene, role, QString(), Uml::ID::Reserved);
if (! ft->loadFromXMI(element)) {
// Most likely cause: The FloatingTextWidget is empty.
delete ft;
node = element.nextSibling();
element = node.toElement();
continue;
}
// always need this
ft->setParentItem(this);
ft->setLink(this);
ft->setSequenceNumber(m_SequenceNumber);
ft->setFontCmd(ft->font());
switch(role) {
case Uml::TextRole::MultiA:
m_role[RoleType::A].multiplicityWidget = ft;
if (oldStyleLoad)
setMultiplicity(m_role[RoleType::A].multiplicityWidget->text(), RoleType::A);
break;
case Uml::TextRole::MultiB:
m_role[RoleType::B].multiplicityWidget = ft;
if (oldStyleLoad)
setMultiplicity(m_role[RoleType::B].multiplicityWidget->text(), RoleType::B);
break;
case Uml::TextRole::ChangeA:
m_role[RoleType::A].changeabilityWidget = ft;
break;
case Uml::TextRole::ChangeB:
m_role[RoleType::B].changeabilityWidget = ft;
break;
case Uml::TextRole::Name:
m_nameWidget = ft;
if (oldStyleLoad)
setName(m_nameWidget->text());
break;
case Uml::TextRole::Coll_Message:
case Uml::TextRole::Coll_Message_Self:
m_nameWidget = ft;
ft->setLink(this);
ft->setActivated();
if (FloatingTextWidget::isTextValid(ft->text()))
ft->show();
else
ft->hide();
break;
case Uml::TextRole::RoleAName:
m_role[RoleType::A].roleWidget = ft;
setRoleName(ft->text(), RoleType::A);
break;
case Uml::TextRole::RoleBName:
m_role[RoleType::B].roleWidget = ft;
setRoleName(ft->text(), RoleType::B);
break;
default:
logDebug1("AssociationWidget::loadFromXMI unexpected FloatingTextWidget (TextRole %1)",
role);
delete ft;
break;
}
}
node = element.nextSibling();
element = node.toElement();
}
return true;
}
/**
* Queries the UMLView for resolving the role A and role B widgets.
* ....
*/
bool AssociationWidget::loadFromXMI(QDomElement& qElement)
{
UMLScene *scene = umlScene();
if (scene == nullptr) {
logDebug0("AssociationWidget::loadFromXMI: This isn't on UMLScene yet, so can neither fetch "
"messages nor widgets on umlscene");
return false;
}
const UMLWidgetList& widgetList = scene->widgetList();
const MessageWidgetList& messageList = scene->messageList();
return loadFromXMI(qElement, widgetList, &messageList);
}
| 132,986
|
C++
|
.cpp
| 3,394
| 32.391868
| 132
| 0.645536
|
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,370
|
seqlinewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/seqlinewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "seqlinewidget.h"
//app includes
#include "debug_utils.h"
#include "messagewidget.h"
#include "objectwidget.h"
#include "umlscene.h"
#include "umlview.h"
#include "widgetbasepopupmenu.h"
//qt includes
#include <QPainter>
DEBUG_REGISTER_DISABLED(SeqLineWidget)
// class members
int const SeqLineWidget::m_nMouseDownEpsilonX = 20;
/**
* Constructor.
*/
SeqLineWidget::SeqLineWidget(UMLScene *scene, ObjectWidget * pObject)
: QGraphicsLineItem(),
m_scene(scene)
{
scene->addItem(this);
m_pObject = pObject;
setPen(QPen(m_pObject->lineColor(), 0, Qt::DashLine));
setZValue(0);
setVisible(true);
m_nLengthY = 250;
setupDestructionBox();
}
/**
* Destructor.
*/
SeqLineWidget::~SeqLineWidget()
{
cleanupDestructionBox();
}
/**
* Return whether point is on sequence line.
* Takes into account destruction box if shown.
*
* @param p The point to investigate.
* @return True if point is on this sequence line.
*/
bool SeqLineWidget::onWidget(const QPointF & p)
{
bool isOnWidget = false;
QPointF sp = line().p1();
QPointF ep = line().p2();
//see if on widget (for message creation)
if (sp.x() - m_nMouseDownEpsilonX < p.x()
&& ep.x() + m_nMouseDownEpsilonX > p.x()
&& sp.y() < p.y() && ep.y() + 3 > p.y())
{
isOnWidget = true;
}
return isOnWidget;
}
/**
* Return whether point is on the destruction box.
*
* @param p The point to investigate.
* @return True if point is on the destruction box of this sequence line.
*/
bool SeqLineWidget::onDestructionBox(const QPointF & p)
{
bool isOnDestructionBox = false;
int x = m_pObject->x() + m_pObject->width() / 2;
int y = m_pObject->y() + m_pObject->height() + m_nLengthY;
//see if on destruction box
if (!m_pObject->showDestruction()) {
return false;
}
if (x - 10 < p.x() && x + 10 > p.x()
&& y - 10 < p.y() && y + 10 > p.y())
{
isOnDestructionBox = true;
}
return isOnDestructionBox;
}
/**
* Clean up anything before deletion.
*/
void SeqLineWidget::cleanup()
{
cleanupDestructionBox();
}
/**
* Set the start point of the line.
*
* @param startX X coordinate of the start point.
* @param startY Y coordinate of the start point.
*/
void SeqLineWidget::setStartPoint(int startX, int startY)
{
int endX = startX;
int endY = startY + m_nLengthY;
QGraphicsLineItem::setLine(startX, startY, endX, endY);
moveDestructionBox();
}
/**
* Clean up destruction box.
*/
void SeqLineWidget::cleanupDestructionBox()
{
if (m_DestructionBox.line1) {
delete m_DestructionBox.line1;
m_DestructionBox.line1 = nullptr;
delete m_DestructionBox.line2;
m_DestructionBox.line2 = nullptr;
}
}
/**
* Set up destruction box.
*/
void SeqLineWidget::setupDestructionBox()
{
cleanupDestructionBox();
if(!m_pObject->showDestruction()) {
return;
}
QRect rect;
rect.setX(m_pObject->x() + m_pObject->width() / 2 - 7);
rect.setY(m_pObject->y() + m_pObject->height() + m_nLengthY - 7);
rect.setWidth(14);
rect.setHeight(14);
m_DestructionBox.line1 = new QGraphicsLineItem;
m_scene->addItem(m_DestructionBox.line1);
m_DestructionBox.setLine1Points(rect);
m_DestructionBox.line1->setVisible(true);
m_DestructionBox.line1->setPen(QPen(m_pObject->lineColor(), 2));
m_DestructionBox.line1->setZValue(3);
m_DestructionBox.line2 = new QGraphicsLineItem;
m_scene->addItem(m_DestructionBox.line2);
m_DestructionBox.setLine2Points(rect);
m_DestructionBox.line2->setVisible(true);
m_DestructionBox.line2->setPen(QPen(m_pObject->lineColor(), 2));
m_DestructionBox.line2->setZValue(3);
}
/**
* Move destruction box.
*/
void SeqLineWidget::moveDestructionBox()
{
if(!m_DestructionBox.line1) {
return;
}
QRect rect;
rect.setX(m_pObject->x() + m_pObject->width() / 2 - 7);
rect.setY(m_pObject->y() + m_pObject->height() + m_nLengthY - 7);
rect.setWidth(14);
rect.setHeight(14);
m_DestructionBox.setLine1Points(rect);
m_DestructionBox.setLine2Points(rect);
}
/**
* Sets the y position of the bottom of the vertical line.
*
* @param yPosition The y coordinate for the bottom of the line.
*/
void SeqLineWidget::setEndOfLine(int yPosition)
{
QPointF sp = line().p1();
int newY = yPosition;
m_nLengthY = yPosition - m_pObject->y() - m_pObject->height();
// normally the managing Objectwidget is responsible for the call of this function
// but to be sure - make a double check _against current position_
if (m_nLengthY < 0) {
m_nLengthY = 0;
newY = m_pObject->y() + m_pObject->height();
}
setLine(sp.x(), sp.y(), sp.x(), newY);
moveDestructionBox();
}
void SeqLineWidget::setLineColorCmd(const QColor &color)
{
QPen pen = this->pen();
pen.setColor(color);
setPen(pen);
m_DestructionBox.setLineColorCmd(color);
}
void SeqLineWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
m_pObject->contextMenuEvent(event);
}
| 5,270
|
C++
|
.cpp
| 188
| 24.404255
| 92
| 0.6774
|
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,371
|
widget_factory.cpp
|
KDE_umbrello/umbrello/umlwidgets/widget_factory.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "widget_factory.h"
// app includes
#include "activitywidget.h"
#include "actor.h"
#include "actorwidget.h"
#include "artifact.h"
#include "artifactwidget.h"
#include "associationwidget.h"
#include "boxwidget.h"
#include "category.h"
#include "categorywidget.h"
#include "classifier.h"
#include "classifierwidget.h"
#include "cmds.h"
#include "combinedfragmentwidget.h"
#include "component.h"
#include "componentwidget.h"
#include "datatypewidget.h"
#define DBG_SRC QStringLiteral("Widget_Factory")
#include "debug_utils.h"
#include "entity.h"
#include "entitywidget.h"
#include "enum.h"
#include "enumwidget.h"
#include "instance.h"
#include "floatingdashlinewidget.h"
#include "floatingtextwidget.h"
#include "folder.h"
#include "forkjoinwidget.h"
#include "interfacewidget.h"
#include "messagewidget.h"
#include "node.h"
#include "nodewidget.h"
#include "notewidget.h"
#include "object_factory.h"
#include "objectnodewidget.h"
#include "objectwidget.h"
#include "package.h"
#include "packagewidget.h"
#include "pinwidget.h"
#include "port.h"
#include "portwidget.h"
#include "preconditionwidget.h"
#include "regionwidget.h"
#include "signalwidget.h"
#include "statewidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "usecase.h"
#include "usecasewidget.h"
DEBUG_REGISTER(Widget_Factory)
namespace Widget_Factory {
/**
* Create a UMLWidget in the given view and representing the given document object.
*/
UMLWidget *createWidget(UMLScene *scene, UMLObject *o)
{
QPointF pos = scene->pos();
int y = pos.y();
Uml::DiagramType::Enum diagramType = scene->type();
UMLObject::ObjectType type = o->baseType();
UMLWidget *newWidget = nullptr;
switch (type) {
case UMLObject::ot_Actor:
if (diagramType == Uml::DiagramType::Sequence) {
ObjectWidget *ow = new ObjectWidget(scene, o);
ow->setDrawAsActor(true);
y = ow->topMargin();
newWidget = ow;
} else
newWidget = new ActorWidget(scene, o->asUMLActor());
break;
case UMLObject::ot_UseCase:
newWidget = new UseCaseWidget(scene, o->asUMLUseCase());
break;
case UMLObject::ot_Folder:
newWidget = new PackageWidget(scene, o->asUMLPackage());
break;
case UMLObject::ot_Package:
newWidget = new ClassifierWidget(scene, o->asUMLPackage());
break;
case UMLObject::ot_Component:
newWidget = new ComponentWidget(scene, o->asUMLComponent());
if (diagramType == Uml::DiagramType::Deployment) {
newWidget->setIsInstance(true);
}
break;
case UMLObject::ot_Port:
{
newWidget = new PortWidget(scene, o->asUMLPort());
}
break;
case UMLObject::ot_Node:
newWidget = new NodeWidget(scene, o->asUMLNode());
break;
case UMLObject::ot_Artifact:
newWidget = new ArtifactWidget(scene, o->asUMLArtifact());
break;
case UMLObject::ot_Datatype:
newWidget = new DatatypeWidget(scene, o->asUMLClassifier());
break;
case UMLObject::ot_Enum:
newWidget = new EnumWidget(scene, o->asUMLEnum());
break;
case UMLObject::ot_Entity:
newWidget = new EntityWidget(scene, o->asUMLEntity());
break;
case UMLObject::ot_Interface:
if (diagramType == Uml::DiagramType::Sequence || diagramType == Uml::DiagramType::Collaboration) {
ObjectWidget *ow = new ObjectWidget(scene, o);
if (diagramType == Uml::DiagramType::Sequence) {
y = ow->topMargin();
}
newWidget = ow;
} else {
UMLClassifier *c = o->asUMLClassifier();
InterfaceWidget* interfaceWidget = new InterfaceWidget(scene, c);
if (diagramType == Uml::DiagramType::Component || diagramType == Uml::DiagramType::Deployment) {
interfaceWidget->setDrawAsCircle(true);
}
newWidget = interfaceWidget;
}
break;
case UMLObject::ot_Class:
if (diagramType == Uml::DiagramType::Object)
break;
//see if we really want an object widget or class widget
if (diagramType == Uml::DiagramType::Class || diagramType == Uml::DiagramType::Component) {
UMLClassifier *c = o->asUMLClassifier();
ClassifierWidget *cw = new ClassifierWidget(scene, c);
if (diagramType == Uml::DiagramType::Component)
cw->setDrawAsCircle(true);
newWidget = cw;
} else {
ObjectWidget *ow = new ObjectWidget(scene, o);
if (diagramType == Uml::DiagramType::Sequence) {
y = ow->topMargin();
}
newWidget = ow;
}
break;
case UMLObject::ot_Instance:
newWidget = new ClassifierWidget(scene, o->asUMLInstance());
break;
case UMLObject::ot_Category:
newWidget = new CategoryWidget(scene, o->asUMLCategory());
break;
default:
logWarn2("Widget_Factory trying to create an invalid widget (%1) for %2",
UMLObject::toString(type), o->name());
}
if (newWidget) {
logDebug1("Widget_Factory::createWidget(%1)", newWidget->baseType());
if (newWidget->baseType() != WidgetBase::wt_Pin &&
newWidget->baseType() != WidgetBase::wt_Port) {
newWidget->setX(pos.x());
newWidget->setY(y);
}
}
return newWidget;
}
bool validateObjType(UMLObject::ObjectType expected, UMLObject* &o, Uml::ID::Type id)
{
if (o == nullptr) {
logDebug1("Widget_Factory::validateObjType: creating new object of type %1",
expected);
QString artificialName = QStringLiteral("LOST_") + Uml::ID::toString(id);
o = Object_Factory::createUMLObject(expected, artificialName, nullptr, false);
if (o == nullptr)
return false;
o->setID(id);
UMLPackage *parentPkg = o->umlPackage();
parentPkg->addObject(o);
return true;
}
UMLObject::ObjectType actual = o->baseType();
if (actual == expected)
return true;
logError3("Widget_Factory::validateObjType(%1): expected type %2, actual type %3",
o->name(), UMLObject::toString(expected), UMLObject::toString(actual));
return false;
}
/**
* Create a UMLWidget according to the given XMI tag.
*/
UMLWidget* makeWidgetFromXMI(const QString& tag,
const QString& idStr, UMLScene *scene)
{
UMLWidget *widget = nullptr;
// Loading of widgets which do NOT represent any UMLObject,
// just graphic stuff with no real model information
//FIXME while boxes and texts are just diagram objects, activities and
// states should be UMLObjects
if (tag == QStringLiteral("statewidget") || tag == QStringLiteral("UML:StateWidget")) {
widget = new StateWidget(scene, StateWidget::Normal, Uml::ID::Reserved);
} else if (tag == QStringLiteral("notewidget") || tag == QStringLiteral("UML:NoteWidget")) {
widget = new NoteWidget(scene, NoteWidget::Normal, Uml::ID::Reserved);
} else if (tag == QStringLiteral("boxwidget")) {
widget = new BoxWidget(scene, Uml::ID::Reserved);
} else if (tag == QStringLiteral("floatingtext") || tag == QStringLiteral("UML:FloatingTextWidget")) {
widget = new FloatingTextWidget(scene, Uml::TextRole::Floating, QString(), Uml::ID::Reserved);
} else if (tag == QStringLiteral("activitywidget") || tag == QStringLiteral("UML:ActivityWidget")) {
widget = new ActivityWidget(scene, ActivityWidget::Initial, Uml::ID::Reserved);
} else if (tag == QStringLiteral("messagewidget")) {
widget = new MessageWidget(scene, Uml::SequenceMessage::Asynchronous, Uml::ID::Reserved);
} else if (tag == QStringLiteral("forkjoin")) {
widget = new ForkJoinWidget(scene, Qt::Vertical, Uml::ID::Reserved);
} else if (tag == QStringLiteral("preconditionwidget")) {
widget = new PreconditionWidget(scene, nullptr, Uml::ID::Reserved);
} else if (tag == QStringLiteral("combinedFragmentwidget")) {
widget = new CombinedFragmentWidget(scene, CombinedFragmentWidget::Ref, Uml::ID::Reserved);
} else if (tag == QStringLiteral("signalwidget")) {
widget = new SignalWidget(scene, SignalWidget::Send, Uml::ID::Reserved);
} else if (tag == QStringLiteral("floatingdashlinewidget")) {
widget = new FloatingDashLineWidget(scene, Uml::ID::Reserved);
} else if (tag == QStringLiteral("objectnodewidget")) {
widget = new ObjectNodeWidget(scene, ObjectNodeWidget::Normal, Uml::ID::Reserved);
} else if (tag == QStringLiteral("regionwidget")) {
widget = new RegionWidget(scene, Uml::ID::Reserved);
} else if (tag == QStringLiteral("pinwidget")) {
widget = new PinWidget(scene, nullptr, Uml::ID::Reserved);
}
else
{
// Loading of widgets which represent a UMLObject
// Find the UMLObject and create the Widget to represent it
Uml::ID::Type id = Uml::ID::fromString(idStr);
UMLDoc *umldoc = UMLApp::app()->document();
UMLObject *o = umldoc->findObjectById(id);
if (o == nullptr) {
logError1("Widget_Factory::makeWidgetFromXMI: cannot find object with id %1",
Uml::ID::toString(id));
delete widget;
return nullptr;
}
if (tag == QStringLiteral("actorwidget") || tag == QStringLiteral("UML:ActorWidget")) {
if (validateObjType(UMLObject::ot_Actor, o, id))
widget = new ActorWidget(scene, o->asUMLActor());
} else if (tag == QStringLiteral("usecasewidget") || tag == QStringLiteral("UML:UseCaseWidget")) {
if (validateObjType(UMLObject::ot_UseCase, o, id))
widget = new UseCaseWidget(scene, o->asUMLUseCase());
} else if (tag == QStringLiteral("classwidget") ||
tag == QStringLiteral("UML:ClassWidget") || tag == QStringLiteral("UML:ConceptWidget")) {
if (validateObjType(UMLObject::ot_Class, o, id) || validateObjType(UMLObject::ot_Package, o, id))
widget = new ClassifierWidget(scene, o->asUMLClassifier());
} else if (tag == QStringLiteral("packagewidget")) {
if (validateObjType(UMLObject::ot_Package, o, id))
widget = new ClassifierWidget(scene, o->asUMLPackage());
} else if (tag == QStringLiteral("componentwidget")) {
if (validateObjType(UMLObject::ot_Component, o, id))
widget = new ComponentWidget(scene, o->asUMLComponent());
} else if (tag == QStringLiteral("portwidget")) {
if (validateObjType(UMLObject::ot_Port, o, id))
widget = new PortWidget(scene, o->asUMLPort());
} else if (tag == QStringLiteral("nodewidget")) {
if (validateObjType(UMLObject::ot_Node, o, id))
widget = new NodeWidget(scene, o->asUMLNode());
} else if (tag == QStringLiteral("artifactwidget")) {
if (validateObjType(UMLObject::ot_Artifact, o, id))
widget = new ArtifactWidget(scene, o->asUMLArtifact());
} else if (tag == QStringLiteral("interfacewidget")) {
if (validateObjType(UMLObject::ot_Interface, o, id))
widget = new InterfaceWidget(scene, o->asUMLClassifier());
} else if (tag == QStringLiteral("datatypewidget")) {
if (validateObjType(UMLObject::ot_Datatype, o, id))
widget = new DatatypeWidget(scene, o->asUMLClassifier());
} else if (tag == QStringLiteral("enumwidget")) {
if (validateObjType(UMLObject::ot_Enum, o, id))
widget = new EnumWidget(scene, o->asUMLEnum());
} else if (tag == QStringLiteral("entitywidget")) {
if (validateObjType(UMLObject::ot_Entity, o, id))
widget = new EntityWidget(scene, o->asUMLEntity());
} else if (tag == QStringLiteral("categorywidget")) {
if (validateObjType(UMLObject::ot_Category, o, id))
widget = new CategoryWidget(scene, o->asUMLCategory());
} else if (tag == QStringLiteral("objectwidget") || tag == QStringLiteral("UML:ObjectWidget")) {
widget = new ObjectWidget(scene, o);
} else if(tag == QStringLiteral("instancewidget") || tag == QStringLiteral("UML:InstanceWidget")) {
if (validateObjType(UMLObject::ot_Instance, o, id))
widget = new ClassifierWidget(scene, o->asUMLInstance());
}
else {
logWarn1("Widget_Factory::makeWidgetFromXMI: Trying to create an unknown widget %1", tag);
}
}
return widget;
}
} // end namespace Widget_Factory
| 13,035
|
C++
|
.cpp
| 295
| 36.450847
| 109
| 0.637142
|
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,372
|
messagewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/messagewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// onw header
#include "messagewidget.h"
//app includes
#include "classifier.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "floatingtextwidget.h"
#include "listpopupmenu.h"
#include "objectwidget.h"
#include "operation.h"
#include "uml.h"
#include "umldoc.h"
#include "messagewidgetpropertiesdialog.h"
#include "umlview.h"
#include "uniqueid.h"
#include "idchangelog.h"
//qt includes
#include <QMoveEvent>
#include <QPainter>
#include <QPolygon>
#include <QResizeEvent>
#include <QXmlStreamWriter>
//kde includes
#include <KLocalizedString>
DEBUG_REGISTER_DISABLED(MessageWidget)
static const int circleWidth = 10;
/**
* Constructs a MessageWidget.
*
* This method is used for creation, synchronous and synchronous message types.
*
* @param scene The parent to this class.
* @param a The role A widget for this message.
* @param b The role B widget for this message.
* @param y The vertical position to display this message.
* @param sequenceMessageType Whether synchronous or asynchronous
* @param id A unique id used for deleting this object cleanly.
* The default (-1) will prompt generation of a new ID.
*/
MessageWidget::MessageWidget(UMLScene * scene, ObjectWidget* a, ObjectWidget* b,
int y, Uml::SequenceMessage::Enum sequenceMessageType,
Uml::ID::Type id /* = Uml::id_None */)
: UMLWidget(scene, WidgetBase::wt_Message, id)
{
init();
m_pOw[Uml::RoleType::A] = a;
m_pOw[Uml::RoleType::B] = b;
m_sequenceMessageType = sequenceMessageType;
if (m_sequenceMessageType == Uml::SequenceMessage::Creation) {
y -= m_pOw[Uml::RoleType::B]->height() / 2;
m_pOw[Uml::RoleType::B]->setY(y);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Destroy)
m_pOw[Uml::RoleType::B]->setShowDestruction(true);
updateResizability();
calculateWidget();
y = y < getMinY() ? getMinY() : y;
if (y > b->getEndLineY())
b->setEndLine(y);
setY(y);
this->activate();
}
/**
* Constructs a MessageWidget.
*
* @param scene The parent to this class.
* @param seqMsgType The Uml::SequenceMessage::Enum of this message widget
* @param id The ID to assign (-1 will prompt a new ID.)
*/
MessageWidget::MessageWidget(UMLScene * scene, Uml::SequenceMessage::Enum seqMsgType,
Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Message, id)
{
init();
m_sequenceMessageType = seqMsgType;
}
/**
* Constructs a Lost or Found MessageWidget.
*
* @param scene The parent to this class.
* @param a The role A widget for this message.
* @param xclick The horizontal position clicked by the user
* @param yclick The vertical position clicked by the user
* @param sequenceMessageType Whether lost or found
* @param id The ID to assign (-1 will prompt a new ID.)
*/
MessageWidget::MessageWidget(UMLScene * scene, ObjectWidget* a, int xclick, int yclick,
Uml::SequenceMessage::Enum sequenceMessageType,
Uml::ID::Type id /*= Uml::id_None*/)
: UMLWidget(scene, WidgetBase::wt_Message, id)
{
init();
m_pOw[Uml::RoleType::A] = a;
m_pOw[Uml::RoleType::B] = a;
m_sequenceMessageType = sequenceMessageType;
m_xclicked = xclick;
m_yclicked = yclick;
updateResizability();
calculateWidget();
yclick = yclick < getMinY() ? getMinY() : yclick;
yclick = yclick > getMaxY() ? getMaxY() : yclick;
setY(yclick);
m_yclicked = yclick;
this->activate();
}
/**
* Initializes key variables of the class.
*/
void MessageWidget::init()
{
m_xclicked = -1;
m_yclicked = -1;
m_ignoreSnapToGrid = true;
m_ignoreSnapComponentSizeToGrid = true;
m_pOw[Uml::RoleType::A] = m_pOw[Uml::RoleType::B] = nullptr;
m_pFText = nullptr;
}
/**
* Standard destructor.
*/
MessageWidget::~MessageWidget()
{
if (m_pOw[Uml::RoleType::B] && m_sequenceMessageType == Uml::SequenceMessage::Destroy)
m_pOw[Uml::RoleType::B]->setShowDestruction(false);
}
/**
* Sets the y-coordinate.
* Reimplemented from UMLWidget.
*
* @param y The y-coordinate to be set.
*/
void MessageWidget::setY(qreal y)
{
if (y < getMinY()) {
DEBUG() << "got out of bounds y position, check the reason" << this->y() << getMinY();
return;
}
UMLWidget::setY(y);
if (m_sequenceMessageType == Uml::SequenceMessage::Creation) {
const qreal objWidgetHalfHeight = m_pOw[Uml::RoleType::B]->height() / 2;
m_pOw[Uml::RoleType::B]->setY(y - objWidgetHalfHeight);
}
if (m_pFText && !UMLApp::app()->document()->loading()) {
setTextPosition();
Q_EMIT sigMessageMoved();
}
}
/**
* Update the UMLWidget::m_resizable flag according to the
* charactersitics of this message.
*/
void MessageWidget::updateResizability()
{
if (m_sequenceMessageType == Uml::SequenceMessage::Synchronous)
UMLWidget::m_resizable = true;
else
UMLWidget::m_resizable = false;
}
/**
* Overridden from UMLWidget.
* Checks if the mouse is in resize area and sets the cursor accordingly.
* The resize area is usually at the right bottom corner of the widget
* except in case of a message widget running from right to left.
* In that case the resize area is at the left bottom corner in order
* to avoid overlap with an execution rectangle at the right.
*
* @param me The QMouseEVent to check.
* @return true if the mouse is in resize area, false otherwise.
*/
bool MessageWidget::isInResizeArea(QGraphicsSceneMouseEvent *me)
{
if (!m_resizable) {
m_scene->activeView()->setCursor(Qt::ArrowCursor);
DEBUG() << "!m_resizable";
return false;
}
qreal m = 7.0;
const qreal w = width();
const qreal h = height();
// If the widget itself is very small then make the resize area small, too.
// Reason: Else it becomes impossible to do a move instead of resize.
if (w - m < m || h - m < m) {
m = 2.0;
}
if (me->scenePos().y() < y() + h - m) {
m_scene->activeView()->setCursor(Qt::ArrowCursor);
DEBUG() << "Y condition not satisfied";
return false;
}
int x1 = m_pOw[Uml::RoleType::A]->x();
int x2 = m_pOw[Uml::RoleType::B]->x();
if ((x1 < x2 && me->scenePos().x() >= x() + w - m) ||
(x1 > x2 && me->scenePos().x() >= x() - m)) {
m_scene->activeView()->setCursor(Qt::SizeVerCursor);
DEBUG() << "X condition is satisfied";
return true;
} else {
m_scene->activeView()->setCursor(Qt::ArrowCursor);
DEBUG() << "X condition not satisfied";
return false;
}
}
/**
* Overridden from UMLWidget.
* Resizes the height of the message widget and emits the message moved signal.
* Message widgets can only be resized vertically, so width isn't modified.
*
* @param newW The new width for the widget (isn't used).
* @param newH The new height for the widget.
*/
void MessageWidget::resizeWidget(qreal newW, qreal newH)
{
if (sequenceMessageType() == Uml::SequenceMessage::Creation)
setSize(width(), newH);
else {
qreal x1 = m_pOw[Uml::RoleType::A]->x();
qreal x2 = getxclicked();
qreal diffX = 0;
if (x1 < x2) {
diffX = x2 + (newW - width());
}
else {
diffX = x2 - (newW - width());
}
if (diffX <= 0 )
diffX = 10;
setxclicked (diffX);
setSize(newW, newH);
calculateWidget();
}
Q_EMIT sigMessageMoved();
}
/**
* Constrains the vertical position of the message widget so it doesn't go
* above the bottom side of the lower object.
* The height of the floating text widget in the message is taken into account
* if there is any and it isn't empty.
*
* @param diffY The difference between current Y position and new Y position.
* @return The new Y position, constrained.
*/
qreal MessageWidget::constrainPositionY(qreal diffY)
{
qreal newY = y() + diffY;
qreal minY = getMinY();
if (m_pFText && !m_pFText->displayText().isEmpty()) {
minY += m_pFText->height();
}
if (newY < minY) {
newY = minY;
}
return newY;
}
/**
* Overridden from UMLWidget.
* Moves the widget to a new position using the difference between the
* current position and the new position. X position is ignored, and widget
* is only moved along Y axis. If message goes upper than the object, it's
* kept at this position until it should be lowered again (the unconstrained
* Y position is saved to know when it's the time to lower it again).
* If the message is a creation message, the object created is also moved to
* the new vertical position.
* @see constrainPositionY
*
* @param diffX The difference between current X position and new X position
* (isn't used).
* @param diffY The difference between current Y position and new Y position.
*/
void MessageWidget::moveWidgetBy(qreal diffX, qreal diffY)
{
Q_UNUSED(diffX);
qreal newY = constrainPositionY(diffY);
setY(newY);
}
/**
* Overridden from UMLWidget.
* Modifies the value of the diffX and diffY variables used to move the widgets.
* All the widgets are constrained to be moved only in Y axis (diffX is set to 0).
* @see constrainPositionY
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void MessageWidget::constrainMovementForAllWidgets(qreal &diffX, qreal &diffY)
{
diffX = 0;
diffY = constrainPositionY(diffY) - y();
}
/**
* Reimplemented from UMLWidget and calls other paint...() methods
* depending on the message type.
*/
void MessageWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if(!m_pOw[Uml::RoleType::A] || !m_pOw[Uml::RoleType::B]) {
return;
}
setPenFromSettings(painter);
if (m_sequenceMessageType == Uml::SequenceMessage::Synchronous) {
paintSynchronous(painter, option);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Asynchronous) {
paintAsynchronous(painter, option);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Creation) {
paintCreation(painter, option);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Destroy) {
paintDestroy(painter, option);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Lost) {
paintLost(painter, option);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Found) {
paintFound(painter, option);
} else {
logWarn1("MessageWidget::paint: Unknown message type %1",
m_sequenceMessageType);
}
}
/**
* Draw a solid (triangular) arrowhead pointing in the given direction.
* The direction can be either Qt::LeftArrow or Qt::RightArrow.
*/
void MessageWidget::paintSolidArrowhead(QPainter *p, int x, int y, Qt::ArrowType direction)
{
int arrowheadExtentX = 4;
if (direction == Qt::RightArrow) {
arrowheadExtentX = -arrowheadExtentX;
}
QPolygon points;
points.putPoints(0, 3, x, y, x + arrowheadExtentX, y - 3, x + arrowheadExtentX, y + 3);
p->setBrush(QBrush(p->pen().color()));
p->drawPolygon(points);
}
/**
* Draw an arrow pointing in the given direction.
* The arrow head is not solid, i.e. it is made up of two lines
* like so: --->
* The direction can be either Qt::LeftArrow or Qt::RightArrow.
*/
void MessageWidget::paintArrow(QPainter *p, int x, int y, int w,
Qt::ArrowType direction, bool useDottedLine /* = false */)
{
if (w > 3) {
int arrowheadStartX = x;
int arrowheadExtentX = 4;
if (direction == Qt::RightArrow) {
arrowheadStartX += w;
arrowheadExtentX = -arrowheadExtentX;
}
// draw upper half of arrowhead
p->drawLine(arrowheadStartX, y, arrowheadStartX + arrowheadExtentX, y - 3);
// draw lower half of arrowhead
p->drawLine(arrowheadStartX, y, arrowheadStartX + arrowheadExtentX, y + 3);
}
// draw arrow line
if (useDottedLine) {
QPen pen = p->pen();
pen.setStyle(Qt::DotLine);
p->setPen(pen);
}
p->drawLine(x, y, x + w, y);
}
/**
* Draws the calling arrow with filled in arrowhead, the
* timeline box and the returning arrow with a dashed line and
* stick arrowhead.
*/
void MessageWidget::paintSynchronous(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int x1 = m_pOw[Uml::RoleType::A]->x();
int x2 = m_pOw[Uml::RoleType::B]->x();
int w = width() - 1;
int h = height();
int offsetX = 0;
int offsetY = 0;
bool messageOverlaps = m_pOw[Uml::RoleType::A]->messageOverlap(y(), this);
const int boxWidth = 17;
const int wr = w < boxWidth ? w : boxWidth;
const int arrowWidth = 4;
if (UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
else
painter->setBrush(m_scene->backgroundColor());
if(isSelf()) {
painter->fillRect(offsetX, offsetY, wr, h, QBrush(Qt::white)); //box
painter->drawRect(offsetX, offsetY, wr, h); //box
offsetX += wr;
w -= wr;
offsetY += 3;
const int lowerLineY = offsetY + h - 6;
// draw upper line segment (leaving the life line)
painter->drawLine(offsetX, offsetY, offsetX + w, offsetY);
// draw line segment parallel to (and at the right of) the life line
painter->drawLine(offsetX + w, offsetY, offsetX + w, lowerLineY);
// draw lower line segment (back to the life line)
paintArrow(painter, offsetX, lowerLineY, w, Qt::LeftArrow);
offsetX -= wr;
offsetY -= 3;
} else if(x1 < x2) {
if (messageOverlaps) {
offsetX += 8;
w -= 8;
}
QPen pen = painter->pen();
int startX = offsetX + w - wr + 1;
painter->fillRect(startX, offsetY, wr, h, QBrush(Qt::white)); //box
painter->drawRect(startX, offsetY, wr, h); //box
painter->drawLine(offsetX, offsetY + arrowWidth, startX, offsetY + arrowWidth); //arrow line
if (w > boxWidth + arrowWidth)
paintSolidArrowhead(painter, startX - 1, offsetY + arrowWidth, Qt::RightArrow);
paintArrow(painter, offsetX, offsetY + h - arrowWidth + 1, w - wr + 1, Qt::LeftArrow, true); // return arrow
if (messageOverlaps) {
offsetX -= 8; //reset for drawSelected()
}
} else {
if (messageOverlaps) {
w -=8;
}
QPen pen = painter->pen();
painter->fillRect(offsetX, offsetY, wr, h, QBrush(Qt::white)); //box
painter->drawRect(offsetX, offsetY, wr, h); //box
painter->drawLine(offsetX + wr + 1, offsetY + arrowWidth, offsetX + w, offsetY + arrowWidth); //arrow line
if (w > boxWidth + arrowWidth)
paintSolidArrowhead(painter, offsetX + wr, offsetY + arrowWidth, Qt::LeftArrow);
paintArrow(painter, offsetX + wr + 1, offsetY + h - arrowWidth + 1, w - wr - 1, Qt::RightArrow, true); // return arrow
}
UMLWidget::paint(painter, option);
}
/**
* Draws a solid arrow line and a stick arrow head.
*/
void MessageWidget::paintAsynchronous(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int x1 = m_pOw[Uml::RoleType::A]->x();
int x2 = m_pOw[Uml::RoleType::B]->x();
int w = width() - 1;
int h = height() - 1;
int offsetX = 0;
int offsetY = 0;
bool messageOverlapsA = m_pOw[Uml::RoleType::A]->messageOverlap(y(), this);
//bool messageOverlapsB = m_pOw[Uml::RoleType::B]->messageOverlap(y(), this);
if(isSelf()) {
if (messageOverlapsA) {
offsetX += 7;
w -= 7;
}
const int lowerLineY = offsetY + h - 3;
// draw upper line segment (leaving the life line)
painter->drawLine(offsetX, offsetY, offsetX + w, offsetY);
// draw line segment parallel to (and at the right of) the life line
painter->drawLine(offsetX + w, offsetY, offsetX + w, lowerLineY);
// draw lower line segment (back to the life line)
paintArrow(painter, offsetX, lowerLineY, w, Qt::LeftArrow);
if (messageOverlapsA) {
offsetX -= 7; //reset for drawSelected()
}
} else if(x1 < x2) {
if (messageOverlapsA) {
offsetX += 7;
w -= 7;
}
paintArrow(painter, offsetX, offsetY + 4, w, Qt::RightArrow);
if (messageOverlapsA) {
offsetX -= 7;
}
} else {
if (messageOverlapsA) {
w -= 7;
}
paintArrow(painter, offsetX, offsetY + 4, w, Qt::LeftArrow);
}
UMLWidget::paint(painter, option);
}
/**
* Draws a solid arrow line and a stick arrow head to the
* edge of the target object widget instead of to the
* sequence line.
*/
void MessageWidget::paintCreation(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int x1 = m_pOw[Uml::RoleType::A]->x();
int x2 = m_pOw[Uml::RoleType::B]->x();
int w = width();
//int h = height() - 1;
int offsetX = 0;
int offsetY = 0;
bool messageOverlapsA = m_pOw[Uml::RoleType::A]->messageOverlap(y(), this);
//bool messageOverlapsB = m_pOw[Uml::RoleType::B]->messageOverlap(y(), this);
const int lineY = offsetY + 4;
if (x1 < x2) {
if (messageOverlapsA) {
offsetX += 7;
w -= 7;
}
paintArrow(painter, offsetX, lineY, w, Qt::RightArrow, true);
if (messageOverlapsA) {
offsetX -= 7;
}
} else {
if (messageOverlapsA) {
w -= 7;
}
paintArrow(painter, offsetX, lineY, w, Qt::LeftArrow, true);
}
UMLWidget::paint(painter, option);
}
void MessageWidget::paintDestroy(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
paintSynchronous(painter, option);
}
/**
* Draws a solid arrow line and a stick arrow head
* and a circle
*/
void MessageWidget::paintLost(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_xclicked;
int w = width();
int h = height();
int offsetX = 0;
int offsetY = 0;
bool messageOverlapsA = m_pOw[Uml::RoleType::A]->messageOverlap(y(), this);
//bool messageOverlapsB = m_pOw[Uml::RoleType::B]->messageOverlap(y(), this);
if(x1 < x2) {
if (messageOverlapsA) {
offsetX += 7;
w -= 7;
}
setPenFromSettings(painter);
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(offsetX + w - h, offsetY, h, h);
paintArrow(painter, offsetX, offsetY + h/2, w - h, Qt::RightArrow);
if (messageOverlapsA) {
offsetX -= 7;
}
} else {
setPenFromSettings(painter);
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(offsetX, offsetY, h, h);
paintArrow(painter, offsetX + h, offsetY + h/2, w - h, Qt::LeftArrow);
}
UMLWidget::paint(painter, option);
}
/**
* Draws a circle and a solid arrow line and a stick arrow head.
*/
void MessageWidget::paintFound(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_xclicked;
int w = width();
int h = height();
int offsetX = 0;
int offsetY = 0;
bool messageOverlapsA = m_pOw[Uml::RoleType::A]->messageOverlap(y(), this);
//bool messageOverlapsB = m_pOw[Uml::RoleType::B]->messageOverlap(y(), this);
if(x1 < x2) {
if (messageOverlapsA) {
offsetX += 7;
w -= 7;
}
setPenFromSettings(painter);
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(offsetX + w - h, offsetY, h, h);
paintArrow(painter, offsetX, offsetY + h/2, w, Qt::LeftArrow);
if (messageOverlapsA) {
offsetX -= 7;
}
} else {
if (messageOverlapsA) {
w -= 7;
}
setPenFromSettings(painter);
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(offsetX, offsetY, h, h);
paintArrow(painter, offsetX, offsetY + h/2, w, Qt::RightArrow);
}
UMLWidget::paint(painter, option);
}
/**
* Overrides operation from UMLWidget.
*
* @param p Point to be checked.
*
* @return 'this' if the point is on a part of the MessageWidget.
* NB In case of a synchronous message, the empty space
* between call line and return line does not count, i.e. if
* the point is located in that space the function returns NULL.
*/
UMLWidget* MessageWidget::onWidget(const QPointF& p)
{
if (m_sequenceMessageType != Uml::SequenceMessage::Synchronous) {
return UMLWidget::onWidget(p);
}
// Synchronous message:
// Consists of top arrow (call) and bottom arrow (return.)
if (p.x() < x() || p.x() > x() + width())
return nullptr;
const int tolerance = 5; // pixels
const int pY = p.y();
const int topArrowY = y() + 3;
const int bottomArrowY = y() + height() - 3;
if (pY < topArrowY - tolerance || pY > bottomArrowY + tolerance)
return nullptr;
if (height() <= 2 * tolerance)
return this;
if (pY > topArrowY + tolerance && pY < bottomArrowY - tolerance)
return nullptr;
return this;
}
/**
* Sets the text position relative to the sequence message.
*/
void MessageWidget::setTextPosition()
{
if (m_pFText == nullptr) {
DEBUG() << "m_pFText is NULL";
return;
}
if (m_pFText->displayText().isEmpty()) {
return;
}
m_pFText->updateGeometry();
int ftX = constrainX(m_pFText->x(), m_pFText->width(), m_pFText->textRole());
int ftY = y() - m_pFText->height();
m_pFText->setX(ftX);
m_pFText->setY(ftY);
}
/**
* Returns the textX arg with constraints applied.
* Auxiliary to setTextPosition() and constrainTextPos().
*/
int MessageWidget::constrainX(int textX, int textWidth, Uml::TextRole::Enum tr)
{
int result = textX;
const int minTextX = x() + 5;
if (textX < minTextX || tr == Uml::TextRole::Seq_Message_Self) {
result = minTextX;
} else {
ObjectWidget *objectAtRight = nullptr;
if (m_pOw[Uml::RoleType::B]->x() > m_pOw[Uml::RoleType::A]->x())
objectAtRight = m_pOw[Uml::RoleType::B];
else
objectAtRight = m_pOw[Uml::RoleType::A];
const int objRight_seqLineX = objectAtRight->centerX();
const int maxTextX = objRight_seqLineX - textWidth - 5;
if (maxTextX <= minTextX)
result = minTextX;
else if (textX > maxTextX)
result = maxTextX;
}
return result;
}
/**
* Constrains the FloatingTextWidget X and Y values supplied.
* Overrides operation from LinkWidget.
*
* @param textX candidate X value (may be modified by the constraint)
* @param textY candidate Y value (may be modified by the constraint)
* @param textWidth width of the text
* @param textHeight height of the text
* @param tr Uml::TextRole::Enum of the text
*/
void MessageWidget::constrainTextPos(qreal &textX, qreal &textY, qreal textWidth, qreal textHeight,
Uml::TextRole::Enum tr)
{
textX = constrainX(textX, textWidth, tr);
// Constrain Y.
const qreal minTextY = getMinY();
const qreal maxTextY = getMaxY() - textHeight - 5;
if (textY < minTextY)
textY = minTextY;
else if (textY > maxTextY)
textY = maxTextY;
// setY(textY + textHeight); // NB: side effect
}
/**
* Shortcut for calling m_pFText->setLink() followed by
* this->setTextPosition().
*/
void MessageWidget::setLinkAndTextPos()
{
if (m_pFText) {
m_pFText->setLink(this);
setTextPosition();
}
}
void MessageWidget::resizeEvent(QResizeEvent* /*re*/)
{
}
/**
* Calculate the geometry of the widget.
*/
void MessageWidget::calculateWidget()
{
setMessageText(m_pFText);
calculateDimensions();
setVisible(true);
}
void MessageWidget::slotWidgetMoved(Uml::ID::Type id)
{
const Uml::ID::Type idA = m_pOw[Uml::RoleType::A]->localID();
const Uml::ID::Type idB = m_pOw[Uml::RoleType::B]->localID();
if (idA != id && idB != id) {
DEBUG() << "id=" << Uml::ID::toString(id) << ": ignoring for idA=" << Uml::ID::toString(idA)
<< ", idB=" << Uml::ID::toString(idB);
return;
}
qreal y = this->y();
if (y < getMinY())
y = getMinY();
if (y > getMaxY())
y = getMaxY();
setPos(x(), y);
calculateWidget();
if(!m_pFText)
return;
if (m_scene->selectedCount(true) > 1)
return;
setTextPosition();
}
/**
* Check to see if the given ObjectWidget is involved in the message.
*
* @param w The ObjectWidget to check for.
* @return true - if is contained, false - not contained.
*/
bool MessageWidget::hasObjectWidget(ObjectWidget * w)
{
if(m_pOw[Uml::RoleType::A] == w || m_pOw[Uml::RoleType::B] == w)
return true;
else
return false;
}
/**
* This method determines whether the message is for "Self" for
* an ObjectWidget.
*
* @retval True If both ObjectWidgets for this widget exists and
* are same.
*/
bool MessageWidget::isSelf() const
{
return (m_pOw[Uml::RoleType::A] && m_pOw[Uml::RoleType::B] &&
m_pOw[Uml::RoleType::A] == m_pOw[Uml::RoleType::B]);
}
void MessageWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
if (sel == ListPopupMenu::mt_Delete) {
if (Dialog_Utils::askDeleteAssociation()) {
// This will clean up this widget and the text widget:
m_scene->removeWidget(this);
}
} else {
UMLWidget::slotMenuSelection(action);
}
}
/**
* Activates a MessageWidget. Connects its m_pOw[] pointers
* to UMLObjects and also send signals about its FloatingTextWidget.
*/
bool MessageWidget::activate(IDChangeLog */*Log = nullptr*/)
{
m_scene->resetPastePoint();
// UMLWidget::activate(Log); CHECK: I don't think we need this ?
if (m_pOw[Uml::RoleType::A] == nullptr) {
UMLWidget *pWA = m_scene->findWidget(m_widgetAId);
if (pWA == nullptr) {
DEBUG() << "role A object " << Uml::ID::toString(m_widgetAId) << " not found";
return false;
}
m_pOw[Uml::RoleType::A] = pWA->asObjectWidget();
if (m_pOw[Uml::RoleType::A] == nullptr) {
DEBUG() << "role A widget " << Uml::ID::toString(m_widgetAId)
<< " is not an ObjectWidget";
return false;
}
}
if (m_pOw[Uml::RoleType::B] == nullptr) {
UMLWidget *pWB = m_scene->findWidget(m_widgetBId);
if (pWB == nullptr) {
DEBUG() << "role B object " << Uml::ID::toString(m_widgetBId) << " not found";
return false;
}
m_pOw[Uml::RoleType::B] = pWB->asObjectWidget();
if (m_pOw[Uml::RoleType::B] == nullptr) {
DEBUG() << "role B widget " << Uml::ID::toString(m_widgetBId)
<< " is not an ObjectWidget";
return false;
}
}
updateResizability();
const UMLClassifier *c = m_pOw[Uml::RoleType::B]->umlObject()->asUMLClassifier();
UMLOperation *op = nullptr;
if (c && !m_CustomOp.isEmpty()) {
Uml::ID::Type opId = Uml::ID::fromString(m_CustomOp);
op = c->findChildObjectById(opId, true)->asUMLOperation();
if (op) {
// If the UMLOperation is set, m_CustomOp isn't used anyway.
// Just setting it empty for the sake of sanity.
m_CustomOp.clear();
}
}
if(!m_pFText) {
Uml::TextRole::Enum tr = Uml::TextRole::Seq_Message;
if (isSelf())
tr = Uml::TextRole::Seq_Message_Self;
m_pFText = new FloatingTextWidget(m_scene, tr, operationText(m_scene));
m_scene->addFloatingTextWidget(m_pFText);
m_pFText->setFontCmd(UMLWidget::font());
}
if (op)
setOperation(op); // This requires a valid m_pFText.
setLinkAndTextPos();
m_pFText->setText(QString());
m_pFText->setActivated();
QString messageText = m_pFText->text();
m_pFText->setVisible(messageText.length() > 1);
connect(m_pOw[Uml::RoleType::A], SIGNAL(sigWidgetMoved(Uml::ID::Type)), this, SLOT(slotWidgetMoved(Uml::ID::Type)));
connect(m_pOw[Uml::RoleType::B], SIGNAL(sigWidgetMoved(Uml::ID::Type)), this, SLOT(slotWidgetMoved(Uml::ID::Type)));
connect(this, SIGNAL(sigMessageMoved()), m_pOw[Uml::RoleType::A], SLOT(slotMessageMoved()));
connect(this, SIGNAL(sigMessageMoved()), m_pOw[Uml::RoleType::B], SLOT(slotMessageMoved()));
m_pOw[Uml::RoleType::A]->messageAdded(this);
if (!isSelf())
m_pOw[Uml::RoleType::B]->messageAdded(this);
// Calculate the size and position of the message widget
calculateDimensions();
// Position the floating text accordingly
setTextPosition();
Q_EMIT sigMessageMoved();
return true;
}
/**
* Resolve references of this message so they reference the correct
* new object widgets after paste.
*/
void MessageWidget::resolveObjectWidget(IDChangeLog* log) {
m_widgetAId = log->findNewID(m_widgetAId);
m_widgetBId = log->findNewID(m_widgetBId);
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*
* @param ft The text widget which to update.
*/
void MessageWidget::setMessageText(FloatingTextWidget *ft)
{
if (ft == nullptr)
return;
ft->setSequenceNumber(m_SequenceNumber);
ft->setText(operationText(m_scene));
setTextPosition();
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*
* @param ft The text widget which to update.
* @param newText The new text to set.
*/
void MessageWidget::setText(FloatingTextWidget *ft, const QString &newText)
{
ft->setText(newText);
UMLApp::app()->document()->setModified(true);
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*
* @param op The new operation string to set.
*/
void MessageWidget::setOperationText(const QString &op)
{
m_CustomOp = op; ///FIXME m_pOperation
}
/**
* Implements operation from LinkWidget.
* Required by FloatingTextWidget.
*/
void MessageWidget::lwSetFont (QFont font)
{
UMLWidget::setFont(font);
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
* @todo Move to LinkWidget.
*/
UMLClassifier *MessageWidget::operationOwner()
{
UMLObject *pObject = m_pOw[Uml::RoleType::B]->umlObject();
if (pObject == nullptr)
return nullptr;
UMLClassifier *c = pObject->asUMLClassifier();
return c;
}
/**
* Implements operation from LinkWidget.
* Motivated by FloatingTextWidget.
*/
UMLOperation *MessageWidget::operation()
{
return m_umlObject->asUMLOperation();
}
/**
* Implements operation from LinkWidget.
* Motivated by FloatingTextWidget.
*/
void MessageWidget::setOperation(UMLOperation *op)
{
if (m_umlObject && m_pFText)
disconnect(m_umlObject, SIGNAL(modified()), m_pFText, SLOT(setMessageText()));
m_umlObject = op;
if (m_umlObject && m_pFText) {
connect(m_umlObject, SIGNAL(modified()), m_pFText, SLOT(setMessageText()));
m_pFText->setMessageText();
}
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
QString MessageWidget::customOpText()
{
return m_CustomOp;
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
void MessageWidget::setCustomOpText(const QString &opText)
{
m_CustomOp = opText;
m_pFText->setMessageText();
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
QString MessageWidget::lwOperationText()
{
UMLOperation *pOperation = operation();
if (pOperation != nullptr) {
return pOperation->toString(Uml::SignatureType::SigNoVis);
} else {
return customOpText();
}
}
/**
* Overrides operation from LinkWidget.
* Required by FloatingTextWidget.
*/
UMLClassifier *MessageWidget::lwClassifier()
{
UMLObject *o = m_pOw[Uml::RoleType::B]->umlObject();
UMLClassifier *c = o->asUMLClassifier();
return c;
}
/**
* Calculates the size of the widget by calling
* calculateDimensionsSynchronous(),
* calculateDimensionsAsynchronous(), or
* calculateDimensionsCreation()
*/
void MessageWidget::calculateDimensions()
{
if (m_sequenceMessageType == Uml::SequenceMessage::Synchronous) {
calculateDimensionsSynchronous();
} else if (m_sequenceMessageType == Uml::SequenceMessage::Asynchronous) {
calculateDimensionsAsynchronous();
} else if (m_sequenceMessageType == Uml::SequenceMessage::Creation) {
calculateDimensionsCreation();
} else if (m_sequenceMessageType == Uml::SequenceMessage::Destroy) {
calculateDimensionsDestroy();
} else if (m_sequenceMessageType == Uml::SequenceMessage::Lost) {
calculateDimensionsLost();
} else if (m_sequenceMessageType == Uml::SequenceMessage::Found) {
calculateDimensionsFound();
} else {
logWarn1("MessageWidget::calculateDimensions: Unknown message type %1",
m_sequenceMessageType);
}
if (! UMLApp::app()->document()->loading()) {
adjustAssocs(x(), y()); // adjust assoc lines
}
}
/**
* Calculates and sets the size of the widget for a synchronous message.
*/
void MessageWidget::calculateDimensionsSynchronous()
{
int x = 0;
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_pOw[Uml::RoleType::B]->centerX();
int widgetWidth = 0;
if(isSelf()) {
widgetWidth = 50;
x = x1 - 2;
} else if(x1 < x2) {
x = x1;
widgetWidth = x2 - x1 + 8;
} else {
x = x2 - 8;
widgetWidth = x1 - x2 + 8;
}
QSizeF minSize = minimumSize();
int widgetHeight = 0;
if (height() < minSize.height()) {
widgetHeight = minSize.height();
} else {
widgetHeight = height();
}
setX(x);
setSize(widgetWidth, widgetHeight);
}
/**
* Calculates and sets the size of the widget for an asynchronous message.
*/
void MessageWidget::calculateDimensionsAsynchronous()
{
int x = 0;
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_pOw[Uml::RoleType::B]->centerX();
int widgetWidth = 0;
if(isSelf()) {
widgetWidth = 50;
x = x1;
} else if(x1 < x2) {
x = x1;
widgetWidth = x2 - x1;
} else {
x = x2;
widgetWidth = x1 - x2;
}
x += 1;
widgetWidth -= 2;
QSizeF minSize = minimumSize();
int widgetHeight = 0;
if (height() < minSize.height()) {
widgetHeight = minSize.height();
} else {
widgetHeight = height();
}
setX(x);
setSize(widgetWidth, widgetHeight);
}
/**
* Calculates and sets the size of the widget for a creation message.
*/
void MessageWidget::calculateDimensionsCreation()
{
int x = 0;
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_pOw[Uml::RoleType::B]->x();
int w2 = m_pOw[Uml::RoleType::B]->width();
if (x1 > x2)
x2 += w2;
int widgetWidth = 0;
if (x1 < x2) {
x = x1;
widgetWidth = x2 - x1;
} else {
x = x2;
widgetWidth = x1 - x2;
}
x += 1;
widgetWidth -= 2;
int widgetHeight = minimumSize().height();
setPos(x, m_pOw[Uml::RoleType::B]->y() + m_pOw[Uml::RoleType::B]->height() / 2);
setSize(widgetWidth, widgetHeight);
}
/**
* Calculates and sets the size of the widget for a destroy message.
*/
void MessageWidget::calculateDimensionsDestroy()
{
calculateDimensionsSynchronous();
}
/**
* Calculates and sets the size of the widget for a lost message.
*/
void MessageWidget::calculateDimensionsLost()
{
int x = 0;
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_xclicked;
int widgetWidth = 0;
if(x1 < x2) {
x = x1;
widgetWidth = x2 - x1 + circleWidth/2;
} else {
x = x2 - circleWidth/2;
widgetWidth = x1 - x2 + circleWidth/2;
}
int widgetHeight = minimumSize().height();
setX(x);
setSize(widgetWidth, widgetHeight);
}
/**
* Calculates and sets the size of the widget for a found message.
*/
void MessageWidget::calculateDimensionsFound()
{
int x = 0;
int x1 = m_pOw[Uml::RoleType::A]->centerX();
int x2 = m_xclicked;
int widgetWidth = 0;
if(x1 < x2) {
x = x1;
widgetWidth = x2 - x1 + circleWidth/2;
} else {
x = x2 - circleWidth/2;
widgetWidth = x1 - x2 + circleWidth/2;
}
int widgetHeight = minimumSize().height();
setX(x);
setSize(widgetWidth, widgetHeight);
}
/**
* Used to cleanup any other widget it may need to delete.
*/
void MessageWidget::cleanup()
{
if (m_pOw[Uml::RoleType::A]) {
disconnect(this, SIGNAL(sigMessageMoved()), m_pOw[Uml::RoleType::A], SLOT(slotMessageMoved()));
m_pOw[Uml::RoleType::A]->messageRemoved(this);
}
if (m_pOw[Uml::RoleType::B]) {
disconnect(this, SIGNAL(sigMessageMoved()), m_pOw[Uml::RoleType::B], SLOT(slotMessageMoved()));
m_pOw[Uml::RoleType::B]->messageRemoved(this);
}
UMLWidget::cleanup();
if (m_pFText) {
m_scene->removeWidgetCmd(m_pFText);
m_pFText = nullptr;
}
}
/**
* Sets the state of whether the widget is selected.
*
* @param _select True if the widget is selected.
*/
void MessageWidget::setSelected(bool _select)
{
UMLWidget::setSelected(_select);
if(!m_pFText || m_pFText->displayText().isEmpty())
return;
if(isSelected() && m_pFText->isSelected())
return;
if(!isSelected() && !m_pFText->isSelected())
return;
m_pFText->setSelected(isSelected());
}
/**
* Returns the minimum height this widget should be set at on
* a sequence diagrams. Takes into account the widget positions
* it is related to.
*/
int MessageWidget::getMinY()
{
if (!m_pOw[Uml::RoleType::A] || !m_pOw[Uml::RoleType::B]) {
return 0;
}
if (m_sequenceMessageType == Uml::SequenceMessage::Creation) {
return m_pOw[Uml::RoleType::A]->y() + m_pOw[Uml::RoleType::A]->height();
}
int heightA = m_pOw[Uml::RoleType::A]->y() + m_pOw[Uml::RoleType::A]->height();
int heightB = m_pOw[Uml::RoleType::B]->y() + m_pOw[Uml::RoleType::B]->height();
int height = heightA;
if(heightA < heightB) {
height = heightB;
}
return height;
}
/**
* Returns the maximum height this widget should be set at on
* a sequence diagrams. Takes into account the widget positions
* it is related to.
*/
int MessageWidget::getMaxY()
{
if(!m_pOw[Uml::RoleType::A] || !m_pOw[Uml::RoleType::B]) {
return 0;
}
int heightA = (int)((ObjectWidget*)m_pOw[Uml::RoleType::A])->getEndLineY();
int heightB = (int)((ObjectWidget*)m_pOw[Uml::RoleType::B])->getEndLineY();
int height = heightA;
if(heightA > heightB) {
height = heightB;
}
return (height - this->height());
}
/**
* Overrides method from UMLWidget.
*/
QSizeF MessageWidget::minimumSize() const
{
if (m_sequenceMessageType == Uml::SequenceMessage::Synchronous) {
return QSizeF(width(), 20);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Asynchronous) {
return isSelf() ? QSizeF(width(), 20) : QSizeF(width(), 8);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Creation) {
return QSizeF(width(), 8);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Destroy) {
return QSizeF(width(), 8);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Lost) {
return QSizeF(width(), 10);
} else if (m_sequenceMessageType == Uml::SequenceMessage::Found) {
return QSizeF(width(), 10);
} else {
logWarn1("MessageWidget::minimumSize: Unknown message type %1",
m_sequenceMessageType);
}
return QSize(width(), height());
}
/**
* Sets the related widget on the given side.
*
* @param ow The ObjectWidget we are related to.
* @param role The Uml::RoleType::Enum to be set for the ObjectWidget
*/
void MessageWidget::setObjectWidget(ObjectWidget * ow, Uml::RoleType::Enum role)
{
m_pOw[role] = ow;
updateResizability();
}
/**
* Returns the related widget on the given side.
*
* @return The ObjectWidget we are related to.
*/
ObjectWidget* MessageWidget::objectWidget(Uml::RoleType::Enum role)
{
return m_pOw[role];
}
/**
* Set the xclicked
*/
void MessageWidget::setxclicked(int xclick)
{
m_xclicked = xclick;
}
/**
* Set the yclicked
*/
void MessageWidget::setyclicked(int yclick)
{
m_yclicked = yclick;
}
/**
* Show a properties dialog for an ObjectWidget.
*/
bool MessageWidget::showPropertiesDialog()
{
if (!lwClassifier()) {
logError0("MessageWidget::showPropertiesDialog: lwClassifier() returns a NULL classifier");
return false;
}
bool result = false;
UMLApp::app()->docWindow()->updateDocumentation(false);
QPointer<MessageWidgetPropertiesDialog> dlg = new MessageWidgetPropertiesDialog(nullptr, this);
if (dlg->exec()) {
m_pFText->setMessageText();
UMLApp::app()->docWindow()->showDocumentation(this, true);
UMLApp::app()->document()->setModified(true);
result = true;
}
delete dlg;
return result;
}
/**
* Saves to the "messagewidget" XMI element.
*/
void MessageWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("messagewidget"));
UMLWidget::saveToXMI(writer);
LinkWidget::saveToXMI(writer);
if (m_pOw[Uml::RoleType::A])
writer.writeAttribute(QStringLiteral("widgetaid"), Uml::ID::toString(m_pOw[Uml::RoleType::A]->localID()));
if (m_pOw[Uml::RoleType::B])
writer.writeAttribute(QStringLiteral("widgetbid"), Uml::ID::toString(m_pOw[Uml::RoleType::B]->localID()));
UMLOperation *pOperation = operation();
if (pOperation)
writer.writeAttribute(QStringLiteral("operation"), Uml::ID::toString(pOperation->id()));
else
writer.writeAttribute(QStringLiteral("operation"), m_CustomOp);
writer.writeAttribute(QStringLiteral("sequencemessagetype"), QString::number(m_sequenceMessageType));
if (m_sequenceMessageType == Uml::SequenceMessage::Lost || m_sequenceMessageType == Uml::SequenceMessage::Found) {
writer.writeAttribute(QStringLiteral("xclicked"), QString::number(m_xclicked));
writer.writeAttribute(QStringLiteral("yclicked"), QString::number(m_yclicked));
}
// save the corresponding message text
if (m_pFText && !m_pFText->text().isEmpty()) {
writer.writeAttribute(QStringLiteral("textid"), Uml::ID::toString(m_pFText->id()));
m_pFText->saveToXMI(writer);
}
writer.writeEndElement();
}
/**
* Loads from the "messagewidget" XMI element.
*/
bool MessageWidget::loadFromXMI(QDomElement& qElement)
{
if (!UMLWidget::loadFromXMI(qElement)) {
return false;
}
if (!LinkWidget::loadFromXMI(qElement)) {
return false;
}
QString textid = qElement.attribute(QStringLiteral("textid"), QStringLiteral("-1"));
QString widgetaid = qElement.attribute(QStringLiteral("widgetaid"), QStringLiteral("-1"));
QString widgetbid = qElement.attribute(QStringLiteral("widgetbid"), QStringLiteral("-1"));
m_CustomOp = qElement.attribute(QStringLiteral("operation"));
QString sequenceMessageType = qElement.attribute(QStringLiteral("sequencemessagetype"), QStringLiteral("1001"));
m_sequenceMessageType = Uml::SequenceMessage::fromInt(sequenceMessageType.toInt());
if (m_sequenceMessageType == Uml::SequenceMessage::Lost || m_sequenceMessageType == Uml::SequenceMessage::Found) {
m_xclicked = qElement.attribute(QStringLiteral("xclicked"), QStringLiteral("-1")).toInt();
m_yclicked = qElement.attribute(QStringLiteral("yclicked"), QStringLiteral("-1")).toInt();
}
m_widgetAId = Uml::ID::fromString(widgetaid);
m_widgetBId = Uml::ID::fromString(widgetbid);
m_textId = Uml::ID::fromString(textid);
Uml::TextRole::Enum tr = Uml::TextRole::Seq_Message;
if (m_widgetAId == m_widgetBId)
tr = Uml::TextRole::Seq_Message_Self;
//now load child elements
QDomNode node = qElement.firstChild();
QDomElement element = node.toElement();
if (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("floatingtext") || tag == QStringLiteral("UML::FloatingTextWidget")) {
m_pFText = new FloatingTextWidget(m_scene, tr, operationText(m_scene), m_textId);
m_scene->addFloatingTextWidget(m_pFText);
if(! m_pFText->loadFromXMI(element)) {
// Most likely cause: The FloatingTextWidget is empty.
delete m_pFText;
m_pFText = nullptr;
}
else
m_pFText->setSequenceNumber(m_SequenceNumber);
} else {
logError1("MessageWidget::loadFromXMI: unknown tag %1", tag);
}
}
return true;
}
| 45,956
|
C++
|
.cpp
| 1,353
| 28.85218
| 126
| 0.641113
|
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,373
|
toolbarstateonewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/toolbarstateonewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstateonewidget.h"
// app includes
#include "activitywidget.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "floatingtextwidget.h"
#include "messagewidget.h"
#include "model_utils.h"
#include "objectwidget.h"
#include "pinwidget.h"
#include "portwidget.h"
#include "preconditionwidget.h"
#include "regionwidget.h"
#include "uml.h"
#include "umldoc.h"
#include "port.h"
#include "umlscene.h"
#include "umlwidget.h"
#include "object_factory.h"
#include "package.h"
#include "widget_factory.h"
#include "widget_utils.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
// using namespace Uml;
/**
* Creates a new ToolBarStateOneWidget.
*
* @param umlScene The UMLScene to use.
*/
ToolBarStateOneWidget::ToolBarStateOneWidget(UMLScene *umlScene)
: ToolBarStatePool(umlScene),
m_firstObject(nullptr),
m_isObjectWidgetLine(false)
{
}
/**
* Destroys this ToolBarStateOneWidget.
*/
ToolBarStateOneWidget::~ToolBarStateOneWidget()
{
}
/**
* Called when the current tool is changed to use another tool.
* Executes base method and cleans the message.
*/
void ToolBarStateOneWidget::cleanBeforeChange()
{
ToolBarStatePool::cleanBeforeChange();
}
/**
* Called when a mouse event happened.
* It executes the base method and then updates the position of the
* message line, if any.
*/
void ToolBarStateOneWidget::mouseMove(QGraphicsSceneMouseEvent* ome)
{
ToolBarStatePool::mouseMove(ome);
}
/**
* A widget was removed from the UMLView.
* If the widget removed was the current widget, the current widget is set
* to 0.
* Also, if it was the first object, the message is cleaned.
*/
void ToolBarStateOneWidget::slotWidgetRemoved(UMLWidget* widget)
{
ToolBarState::slotWidgetRemoved(widget);
}
/**
* Selects only widgets, but no associations.
* Overrides base class method.
* If the press event happened on the line of an object, the object is set
* as current widget. If the press event happened on a widget, the widget is
* set as current widget.
*/
void ToolBarStateOneWidget::setCurrentElement()
{
m_isObjectWidgetLine = false;
ObjectWidget* objectWidgetLine = m_pUMLScene->onWidgetLine(m_pMouseEvent->scenePos());
if (objectWidgetLine) {
setCurrentWidget(objectWidgetLine);
m_isObjectWidgetLine = true;
return;
}
UMLWidget *widget = m_pUMLScene->widgetAt(m_pMouseEvent->scenePos());
if (widget) {
setCurrentWidget(widget);
return;
}
}
/**
* Called when the release event happened on a widget.
* If the button pressed isn't left button or the widget isn't an object
* widget, the message is cleaned.
* If the release event didn't happen on the line of an object and the first
* object wasn't selected, nothing is done. If the first object was already
* selected, a creation message is made.
* If the event happened on the line of an object, the first object or the
* second are set, depending on whether the first object was already set or
* not.
*/
void ToolBarStateOneWidget::mouseReleaseWidget()
{
WidgetBase::WidgetType type = widgetType();
if (type == WidgetBase::wt_Precondition) {
m_firstObject = nullptr;
}
if (type == WidgetBase::wt_Pin || type == WidgetBase::wt_Port) {
m_firstObject = nullptr;
}
if (m_pMouseEvent->button() != Qt::LeftButton) {
return;
}
UMLWidget *currWgt = currentWidget();
// Prevent widget nested in a larger widget from disappearing.
Widget_Utils::ensureNestedVisible(currWgt, m_pUMLScene->widgetList());
if (!currWgt->isObjectWidget() &&
!currWgt->isActivityWidget() &&
!currWgt->isComponentWidget() &&
!currWgt->isRegionWidget()) {
return;
}
if (!m_firstObject && (type == WidgetBase::wt_Pin || type == WidgetBase::wt_Port)) {
setWidget(currWgt);
return;
}
if (!m_isObjectWidgetLine && !m_firstObject) {
return;
}
if (!m_firstObject) {
setWidget(currWgt);
}
}
/**
* Called when the release event happened on an empty space.
* Cleans the message.
* Empty spaces are not only actual empty spaces, but also associations.
*/
void ToolBarStateOneWidget::mouseReleaseEmpty()
{
}
/**
* Sets the first object of the message using the specified object.
* The temporary visual message is created and mouse tracking enabled, so
* mouse events will be delivered.
*
* @param firstObject The first object of the message.
*/
void ToolBarStateOneWidget::setWidget(UMLWidget* firstObject)
{
m_firstObject = firstObject;
UMLWidget *umlwidget = nullptr;
//m_pUMLScene->viewport()->setMouseTracking(true);
if (widgetType() == WidgetBase::wt_Precondition) {
QString name = Widget_Utils::defaultWidgetName(WidgetBase::wt_Precondition);
if (Dialog_Utils::askNewName(WidgetBase::wt_Precondition, name)) {
umlwidget = new PreconditionWidget(m_pUMLScene, firstObject->asObjectWidget());
umlwidget->setName(name);
}
} else if (widgetType() == WidgetBase::wt_Pin && m_firstObject->isActivityWidget()) {
QString name = Widget_Utils::defaultWidgetName(WidgetBase::wt_Pin);
if (Dialog_Utils::askNewName(WidgetBase::wt_Pin, name)) {
umlwidget = new PinWidget(m_pUMLScene, m_firstObject);
umlwidget->setName(name);
}
} else if (widgetType() == WidgetBase::wt_Port && m_firstObject->isComponentWidget()) {
UMLPackage* component = m_firstObject->umlObject()->asUMLPackage();
QString name = Model_Utils::uniqObjectName(UMLObject::ot_Port, component);
if (Dialog_Utils::askNewName(WidgetBase::wt_Port, name)) {
UMLPort *port = Object_Factory::createUMLObject(UMLObject::ot_Port, name, component)->asUMLPort();
PortWidget *widget = new PortWidget(m_pUMLScene, port, m_firstObject);
widget->setInitialPosition(m_pUMLScene->pos());
umlwidget = widget;
}
}
if (umlwidget) {
m_pUMLScene->setupNewWidget(umlwidget);
}
Q_EMIT finished();
}
/**
* Returns the widget type of this tool.
*
* @return The widget type of this tool.
*/
WidgetBase::WidgetType ToolBarStateOneWidget::widgetType()
{
if (getButton() == WorkToolBar::tbb_Seq_Precondition) {
return WidgetBase::wt_Precondition;
}
if (getButton() == WorkToolBar::tbb_Pin) {
return WidgetBase::wt_Pin;
}
if (getButton() == WorkToolBar::tbb_Port) {
return WidgetBase::wt_Port;
}
// Shouldn't happen
Q_ASSERT(0);
return WidgetBase::wt_Pin;
}
/**
* Goes back to the initial state.
*/
void ToolBarStateOneWidget::init()
{
ToolBarStatePool::init();
}
| 6,931
|
C++
|
.cpp
| 215
| 28.265116
| 110
| 0.704862
|
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,374
|
artifactwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/artifactwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "artifactwidget.h"
// app includes
#include "artifact.h"
#include "debug_utils.h"
#include "umlscene.h"
#include "umlview.h"
#include "uml.h" // only needed for log{Warn,Error}
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(ArtifactWidget)
/**
* Constructs an ArtifactWidget.
*
* @param scene The parent of this ArtifactWidget.
* @param a The Artifact this widget will be representing.
*/
ArtifactWidget::ArtifactWidget(UMLScene *scene, UMLArtifact *a)
: UMLWidget(scene, WidgetBase::wt_Artifact, a)
{
setSize(100, 30);
}
/**
* Destructor.
*/
ArtifactWidget::~ArtifactWidget()
{
}
/**
* Reimplemented to paint the artifact widget. Some part of specific
* drawing is delegated to private method like drawAsFile..
*/
void ArtifactWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
UMLWidget::setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
} else {
painter->setBrush(m_scene->backgroundColor());
}
if (umlObject()) {
const UMLArtifact *umlart = m_umlObject->asUMLArtifact();
UMLArtifact::Draw_Type drawType = umlart->getDrawAsType();
switch (drawType) {
case UMLArtifact::defaultDraw:
paintAsNormal(painter, option);
break;
case UMLArtifact::file:
paintAsFile(painter, option);
break;
case UMLArtifact::library:
paintAsLibrary(painter, option);
break;
case UMLArtifact::table:
paintAsTable(painter, option);
break;
default:
logWarn1("ArtifactWidget::paint: Artifact drawn as unknown type %1", drawType);
break;
}
}
else {
logWarn0("ArtifactWidget::paint: Cannot draw as there is no UMLArtifact for this widget.");
}
}
/**
* Reimplemented from WidgetBase::saveToXMI to save the widget to
* the "artifactwidget" XMI element.
*/
void ArtifactWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("artifactwidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Overrides method from UMLWidget.
*/
QSizeF ArtifactWidget::minimumSize() const
{
if (!m_umlObject) {
return UMLWidget::minimumSize();
}
const UMLArtifact *umlart = m_umlObject->asUMLArtifact();
if (umlart->getDrawAsType() == UMLArtifact::defaultDraw) {
return calculateNormalSize();
} else {
return calculateIconSize();
}
}
/**
* calculates the size when drawing as an icon (it's the same size for all icons)
*/
QSize ArtifactWidget::calculateIconSize() const
{
const QFontMetrics &fm = getFontMetrics(FT_BOLD_ITALIC);
const int fontHeight = fm.lineSpacing();
int width = fm.horizontalAdvance(m_umlObject->name());
width = width<50 ? 50 : width;
int height = 50 + fontHeight;
return QSize(width, height);
}
/**
* calculates the size for drawing as a box
*/
QSize ArtifactWidget::calculateNormalSize() const
{
const QFontMetrics &fm = getFontMetrics(FT_BOLD_ITALIC);
const int fontHeight = fm.lineSpacing();
int width = fm.horizontalAdvance(m_umlObject->name());
int tempWidth = 0;
if(!m_umlObject->stereotype().isEmpty()) {
tempWidth = fm.horizontalAdvance(m_umlObject->stereotype(true));
}
width = tempWidth>width ? tempWidth : width;
width += ARTIFACT_MARGIN * 2;
int height = (2*fontHeight) + (ARTIFACT_MARGIN * 2);
return QSize(width, height);
}
/**
* draw as a file icon
*/
void ArtifactWidget::paintAsFile(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
const int w = width();
const int h = height();
QFont font = UMLWidget::font();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int startX = (w/2) - 25;
int iconHeight = h - fontHeight;
QPolygon pointArray(5);
pointArray.setPoint(0, startX, 0);
pointArray.setPoint(1, startX + 40, 0);
pointArray.setPoint(2, startX + 50, 10);
pointArray.setPoint(3, startX + 50, iconHeight);
pointArray.setPoint(4, startX, iconHeight);
painter->drawPolygon(pointArray);
painter->drawLine(startX + 40, 0, startX + 40, 10);
painter->drawLine(startX + 40, 10, startX + 50, 10);
painter->drawLine(startX + 40, 0, startX + 50, 10);
painter->setPen(textColor());
painter->setFont(font);
painter->drawText(0, h - fontHeight,
w, fontHeight, Qt::AlignCenter, name());
UMLWidget::paint(painter, option);
}
/**
* draw as a library file icon
*/
void ArtifactWidget::paintAsLibrary(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
//FIXME this should have gears on it
const int w = width();
const int h = height();
const QFont font = UMLWidget::font();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int startX = (w/2) - 25;
const int iconHeight = h - fontHeight;
QPolygon pointArray(5);
pointArray.setPoint(0, startX, 0);
pointArray.setPoint(1, startX + 40, 0);
pointArray.setPoint(2, startX + 50, 10);
pointArray.setPoint(3, startX + 50, iconHeight);
pointArray.setPoint(4, startX, iconHeight);
painter->drawPolygon(pointArray);
painter->drawLine(startX + 40, 0, startX + 40, 10);
painter->drawLine(startX + 40, 10, startX + 50, 10);
painter->drawLine(startX + 40, 0, startX + 50, 10);
painter->setPen(textColor());
painter->setFont(font);
painter->drawText(0, h - fontHeight,
w, fontHeight, Qt::AlignCenter, name());
UMLWidget::paint(painter, option);
}
/**
* draw as a database table icon
*/
void ArtifactWidget::paintAsTable(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
const int w = width();
const int h = height();
const QFont font = UMLWidget::font();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int startX = (w/2) - 25;
const int iconHeight = h - fontHeight;
painter->drawRect(startX, 0, 50, h - fontHeight + 1);
painter->drawLine(startX + 20, 0, startX + 20, iconHeight);
painter->drawLine(startX + 30, 0, startX + 30, iconHeight);
painter->drawLine(startX + 40, 0, startX + 40, iconHeight);
painter->drawLine(startX, (iconHeight/2), startX + 49, (iconHeight/2));
painter->drawLine(startX, (iconHeight/2) + (iconHeight/4),
startX + 49, (iconHeight/2) + (iconHeight/4));
QPen thickerPen = painter->pen();
thickerPen.setWidth(2);
painter->setPen(thickerPen);
painter->drawLine(startX + 10, 0, startX + 10, iconHeight);
painter->drawLine(startX, (iconHeight/4), startX + 50, (iconHeight/4));
painter->setPen(textColor());
painter->setFont(font);
painter->drawText(0, h - fontHeight,
w, fontHeight, Qt::AlignCenter, name());
UMLWidget::paint(painter, option);
}
/**
* draw as a box
*/
void ArtifactWidget::paintAsNormal(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
int w = width();
int h = height();
QFont font = UMLWidget::font();
font.setBold(true);
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
QString stereotype = m_umlObject->stereotype();
painter->drawRect(0, 0, w, h);
painter->setPen(textColor());
painter->setFont(font);
if (!stereotype.isEmpty()) {
painter->drawText(ARTIFACT_MARGIN, (h/2) - fontHeight,
w, fontHeight, Qt::AlignCenter, m_umlObject->stereotype(true));
}
int lines;
if (!stereotype.isEmpty()) {
lines = 2;
} else {
lines = 1;
}
if (lines == 1) {
painter->drawText(0, (h/2) - (fontHeight/2),
w, fontHeight, Qt::AlignCenter, name());
} else {
painter->drawText(0, (h/2),
w, fontHeight, Qt::AlignCenter, name());
}
UMLWidget::paint(painter, option);
}
| 8,378
|
C++
|
.cpp
| 246
| 29.097561
| 102
| 0.667615
|
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,375
|
linkwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/linkwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "linkwidget.h"
// app includes
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "uml.h"
#include "umlobject.h"
#include "umlview.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(LinkWidget)
LinkWidget::LinkWidget()
{
}
LinkWidget::~LinkWidget()
{
}
/**
* Motivated by FloatingTextWidget::slotMenuSelection(mt_Operation)
*/
UMLClassifier *LinkWidget::operationOwner()
{
UMLOperation *op = operation();
if (op == nullptr)
return nullptr;
return op->umlParent()->asUMLClassifier();
}
/**
* Return the operation text.
* When no scene parameter is given, the scene of the current view
* is taken instead.
* @param scene the given scene
* @return the operation text
*/
QString LinkWidget::operationText(UMLScene *scene)
{
UMLOperation *op = operation();
if (op == nullptr)
return customOpText();
if (scene == nullptr)
scene = UMLApp::app()->currentView()->umlScene();
Uml::SignatureType::Enum sigType;
if (scene && scene->showOpSig())
sigType = Uml::SignatureType::SigNoVis;
else
sigType = Uml::SignatureType::NoSigNoVis;
QString opText = op->toString(sigType);
return opText;
}
/**
* Motivated by FloatingTextWidget::slotMenuSelection(mt_Reset_Label_Positions)
* Only applies to AssociationWidget.
*/
void LinkWidget::resetTextPositions()
{
}
/**
* Motivated by FloatingTextWidget::showPropertiesDialog()
*/
bool LinkWidget::showPropertiesDialog()
{
return false;
}
/**
* Motivated by FloatingTextWidget::setLink().
* Only applies to AssociationWidget.
*/
void LinkWidget::calculateNameTextSegment()
{
}
/**
* Write property of QString m_SequenceNumber.
*/
void LinkWidget::setSequenceNumber(const QString &sequenceNumber)
{
m_SequenceNumber = sequenceNumber;
}
/**
* Read property of QString m_SequenceNumber.
*/
QString LinkWidget::sequenceNumber() const
{
return m_SequenceNumber;
}
/**
* Load data from XMI.
*/
bool LinkWidget::loadFromXMI(QDomElement &qElement)
{
m_SequenceNumber = qElement.attribute(QStringLiteral("seqnum"));
return true;
}
/**
* Save data to XMI.
*/
void LinkWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeAttribute(QStringLiteral("seqnum"), m_SequenceNumber);
}
| 2,466
|
C++
|
.cpp
| 104
| 21.211538
| 92
| 0.736147
|
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,376
|
usecasewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/usecasewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header file
#include "usecasewidget.h"
// app includes
#include "debug_utils.h"
#include "usecase.h"
#include "umlview.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(UseCaseWidget)
/**
* Creates a UseCase widget.
* @param scene The parent of the widget.
* @param o The UMLUseCase to represent.
*/
UseCaseWidget::UseCaseWidget(UMLScene * scene, UMLUseCase *o)
: UMLWidget(scene, WidgetBase::wt_UseCase, o)
{
}
/**
* Destructor.
*/
UseCaseWidget::~UseCaseWidget()
{
}
/**
* Overrides the standard paint event.
*/
void UseCaseWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
if (UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
QFont font = UMLWidget::font();
font.setUnderline(false);
font.setBold(false);
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
const QFontMetricsF &fm = getFontMetrics(FT_NORMAL);
const qreal fontHeight = fm.lineSpacing();
const qreal w = width();
const qreal h = height();
bool drawStereotype = umlObject() && !umlObject()->stereotype().isEmpty();
painter->drawEllipse(QRectF(0, 0, w, h));
painter->setPen(textColor());
QString txt;
if (drawStereotype)
{
// Prepend text of stereotype to other text:
txt = umlObject()->stereotype(true);
}
if (!txt.isEmpty())
txt.append(QStringLiteral("\n"));
QString name_txt = name();
// Replace user-entered "\n" with real line breaks:
name_txt.replace(QStringLiteral("\\n"),QStringLiteral("\n"));
txt += name_txt;
qreal dy = 0.0;
if (drawStereotype)
dy = fontHeight/2.0;
QRectF rectangle(UC_MARGIN, UC_MARGIN - dy, w - UC_MARGIN*2, h - UC_MARGIN*2);
painter->drawText(rectangle, Qt::AlignCenter | Qt::TextWordWrap, txt);
setPenFromSettings(painter);
UMLWidget::paint(painter, option, widget);
}
/**
* Saves this UseCase to file.
*/
void UseCaseWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("usecasewidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Overrides method from UMLWidget
*/
QSizeF UseCaseWidget::minimumSize() const
{
const UMLWidget::FontType ft = (m_umlObject->isAbstract() ? FT_BOLD_ITALIC : FT_BOLD);
const QFontMetrics &fm = UMLWidget::getFontMetrics(ft);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(name());
bool drawStereotype = umlObject() && !umlObject()->stereotype().isEmpty();
int width = (textWidth / 3) > UC_WIDTH ? textWidth / 3 : UC_WIDTH;
int height = UC_HEIGHT + (drawStereotype ? 2 * fontHeight : fontHeight) + UC_MARGIN;
width += UC_MARGIN * 2;
return QSizeF(width, height);
}
| 3,050
|
C++
|
.cpp
| 94
| 28.797872
| 101
| 0.694662
|
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,377
|
forkjoinwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/forkjoinwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "forkjoinwidget.h"
//app includes
#include "debug_utils.h"
#include "umlview.h"
#include "umldoc.h"
#include "listpopupmenu.h"
// qt includes
#include <QColorDialog>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(ForkJoinWidget)
/**
* Constructs a ForkJoinWidget.
*
* @param scene The parent to this widget.
* @param ori Whether to draw the plate horizontally or vertically.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
ForkJoinWidget::ForkJoinWidget(UMLScene * scene, Qt::Orientation ori, Uml::ID::Type id)
: BoxWidget(scene, id, WidgetBase::wt_ForkJoin),
m_orientation(ori)
{
if (ori == Qt::Vertical)
setSize(10, 40);
else
setSize(40, 10);
m_usesDiagramFillColor = false;
setFillColorCmd(QColor("black"));
}
/**
* Destructor.
*/
ForkJoinWidget::~ForkJoinWidget()
{
}
/**
* Get whether to draw the plate vertically or horizontally.
*/
Qt::Orientation ForkJoinWidget::orientation() const
{
return m_orientation;
}
/**
* Set whether to draw the plate vertically or horizontally.
*/
void ForkJoinWidget::setOrientation(Qt::Orientation ori)
{
m_orientation = ori;
updateGeometry();
UMLWidget::adjustAssocs(x(), y());
}
/**
* Reimplemented from UMLWidget::paint to draw the plate of
* fork join.
*/
void ForkJoinWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->fillRect(0, 0, width(), height(), fillColor());
UMLWidget::paint(painter, option, widget);
}
/**
* Reimplemented from UMLWidget::loadFromXMI to load widget
* info from XMI element - 'forkjoin'.
*/
bool ForkJoinWidget::loadFromXMI(QDomElement& qElement)
{
if (!UMLWidget::loadFromXMI(qElement)) {
return false;
}
QString drawVerticalStr = qElement.attribute(QStringLiteral("drawvertical"), QStringLiteral("0"));
bool drawVertical = (bool)drawVerticalStr.toInt();
if (drawVertical) {
setOrientation(Qt::Vertical);
}
else {
setOrientation(Qt::Horizontal);
}
return true;
}
/**
* Reimplemented from UMLWidget::saveToXMI to save widget info
* into XMI element - 'forkjoin'.
*/
void ForkJoinWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("forkjoin"));
UMLWidget::saveToXMI(writer);
bool drawVertical = true;
if (m_orientation == Qt::Horizontal) {
drawVertical = false;
}
writer.writeAttribute(QStringLiteral("drawvertical"), QString::number(drawVertical));
writer.writeEndElement();
}
/**
* Show a properties dialog for a Fork/Join Widget.
*/
bool ForkJoinWidget::showPropertiesDialog()
{
QColor newColor = QColorDialog::getColor(fillColor()); // krazy:exclude=qclasses
if (!newColor.isValid())
return false;
if (newColor != fillColor()) {
setFillColor(newColor);
setUsesDiagramFillColor(false);
umlDoc()->setModified(true);
}
return true;
}
/**
* Reimplemented form UMLWidget::slotMenuSelection to handle
* Flip action.
*/
void ForkJoinWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch (sel) {
case ListPopupMenu::mt_Fill_Color:
showPropertiesDialog();
break;
case ListPopupMenu::mt_FlipHorizontal:
setOrientation(Qt::Horizontal);
break;
case ListPopupMenu::mt_FlipVertical:
setOrientation(Qt::Vertical);
break;
default:
break;
}
}
/**
* Overrides the function from UMLWidget.
*/
QSizeF ForkJoinWidget::minimumSize() const
{
if (m_orientation == Qt::Vertical) {
return QSizeF(4, 40);
} else {
return QSizeF(40, 4);
}
}
/**
* Reimplement method from UMLWidget to suppress the resize corner.
* Although the ForkJoinWidget supports resizing, we suppress the
* resize corner because it is too large for this very slim widget.
*/
void ForkJoinWidget::paintSelected(QPainter * p, int offsetX, int offsetY)
{
Q_UNUSED(p);
Q_UNUSED(offsetX);
Q_UNUSED(offsetY);
}
/**
* Reimplement method from UMLWidget.
*/
void ForkJoinWidget::constrain(qreal& width, qreal& height)
{
if (m_orientation == Qt::Vertical) {
if (width < 4)
width = 4;
else if (width > 10)
width = 10;
if (height < 40)
height = 40;
else if (height > 100)
height = 100;
} else {
if (height < 4)
height = 4;
else if (height > 10)
height = 10;
if (width < 40)
width = 40;
else if (width > 100)
width = 100;
}
}
| 4,879
|
C++
|
.cpp
| 183
| 22.513661
| 102
| 0.678785
|
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,378
|
nodewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/nodewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "nodewidget.h"
// app includes
#include "debug_utils.h"
#include "node.h"
#include "umlscene.h"
#include "umlview.h"
// qt includes
#include <QPainter>
#include <QPolygon>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(NodeWidget)
/**
* Constructs a NodeWidget.
*
* @param scene The parent of this NodeWidget.
* @param n The UMLNode this will be representing.
*/
NodeWidget::NodeWidget(UMLScene * scene, UMLNode *n)
: UMLWidget(scene, WidgetBase::wt_Node, n)
{
setSize(100, 30);
setZValue(1); // above box but below UMLWidget because may embed widgets
}
/**
* Destructor.
*/
NodeWidget::~NodeWidget()
{
}
/**
* Overrides standard method.
*/
void NodeWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
} else {
painter->setBrush(m_scene->backgroundColor());
}
const int w = width();
const int h = height();
const int wDepth = (w/3 > DEPTH ? DEPTH : w/3);
const int hDepth = (h/3 > DEPTH ? DEPTH : h/3);
const int bodyOffsetY = hDepth;
const int bodyWidth = w - wDepth;
const int bodyHeight = h - hDepth;
QFont font = UMLWidget::font();
font.setBold(true);
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
QString nameStr = name();
QPolygon pointArray(5);
pointArray.setPoint(0, 0, bodyOffsetY);
pointArray.setPoint(1, wDepth, 0);
pointArray.setPoint(2, w, 0);
pointArray.setPoint(3, w, bodyHeight);
pointArray.setPoint(4, bodyWidth, h);
painter->drawPolygon(pointArray);
painter->drawRect(0, bodyOffsetY, bodyWidth, bodyHeight);
painter->drawLine(w, 0, bodyWidth, bodyOffsetY);
painter->setPen(textColor());
painter->setFont(font);
int lines = 1;
if (m_umlObject) {
QString stereotype = m_umlObject->stereotype();
if (!stereotype.isEmpty()) {
painter->drawText(0, bodyOffsetY + (bodyHeight/2) - fontHeight,
bodyWidth, fontHeight, Qt::AlignCenter, m_umlObject->stereotype(true));
lines = 2;
}
}
if (UMLWidget::isInstance()) {
font.setUnderline(true);
painter->setFont(font);
nameStr = UMLWidget::instanceName() + QStringLiteral(" : ") + nameStr;
}
if (lines == 1) {
painter->drawText(0, bodyOffsetY + (bodyHeight/2) - (fontHeight/2),
bodyWidth, fontHeight, Qt::AlignCenter, nameStr);
} else {
painter->drawText(0, bodyOffsetY + (bodyHeight/2),
bodyWidth, fontHeight, Qt::AlignCenter, nameStr);
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget.
*/
QSizeF NodeWidget::minimumSize() const
{
if (m_umlObject == nullptr) {
DEBUG() << "m_umlObject is NULL";
return UMLWidget::minimumSize();
}
const QFontMetrics &fm = getFontMetrics(FT_BOLD_ITALIC);
const int fontHeight = fm.lineSpacing();
QString name = m_umlObject->name();
if (UMLWidget::isInstance()) {
name = UMLWidget::instanceName() + QStringLiteral(" : ") + name;
}
int width = fm.horizontalAdvance(name) + 2 * defaultMargin;
int tempWidth = 0;
if (!m_umlObject->stereotype().isEmpty()) {
tempWidth = fm.horizontalAdvance(m_umlObject->stereotype(true));
}
if (tempWidth > width)
width = tempWidth;
width += DEPTH;
int height = (2*fontHeight) + DEPTH;
return QSizeF(width, height);
}
/**
* Saves to the "nodewidget" XMI element.
* Note: For loading we use the method inherited from UMLWidget.
*/
void NodeWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("nodewidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
| 4,135
|
C++
|
.cpp
| 129
| 27.302326
| 98
| 0.664826
|
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,379
|
diagramproxywidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/diagramproxywidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2019-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "diagramproxywidget.h"
#include "cmds/cmdcreatediagram.h"
#include "debug_utils.h"
#include "diagram_utils.h"
#include "dialog_utils.h"
#include "widget_utils.h"
#include "listpopupmenu.h"
#include "statewidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
#include "selectdiagramdialog.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(DiagramProxyWidget)
DiagramProxyWidget::DiagramProxyWidget(UMLWidget *widget, qreal borderWidth)
: m_diagramLinkId(Uml::ID::None)
, m_iconRect(QRectF(0, 0, 10, 10))
, m_widget(widget)
, m_borderWidth(borderWidth)
, m_showLinkedDiagram(true)
{
}
Uml::ID::Type DiagramProxyWidget::diagramLink() const
{
return m_diagramLinkId;
}
UMLScene *DiagramProxyWidget::linkedDiagram() const
{
return m_linkedDiagram;
}
bool DiagramProxyWidget::setDiagramLink(const Uml::ID::Type &id)
{
if (id == Uml::ID::None) {
m_diagramLinkId = id;
m_linkedDiagram = nullptr;
m_widget->updateGeometry(true);
return true;
}
UMLView *view = UMLApp::app()->document()->findView(id);
if (view) {
m_diagramLinkId = id;
m_linkedDiagram = view->umlScene();
m_widget->updateGeometry(true);
}
return view;
}
/**
* Return the area in which the linked diagram is displayed.
*
* @return area in current item coordinates
*/
const QRectF &DiagramProxyWidget::clientRect() const
{
return m_clientRect;
}
/**
* Return scene area of the linked diagram.
*
* @return scene rectangle
*/
const QRectF &DiagramProxyWidget::sceneRect() const
{
return m_sceneRect;
}
/**
* Set the area in which the linked diagram is displayed
*
* @param rect
*/
void DiagramProxyWidget::setClientRect(const QRectF &rect)
{
m_clientRect = rect;
}
bool DiagramProxyWidget::activate(IDChangeLog *changeLog)
{
Q_UNUSED(changeLog);
if (m_diagramLinkId != Uml::ID::None)
setDiagramLink(m_diagramLinkId);
return true;
}
bool DiagramProxyWidget::loadFromXMI(QDomElement &qElement)
{
QString linkID = qElement.attribute(QStringLiteral("diagramlinkid"), QStringLiteral("-1"));
m_diagramLinkId = Uml::ID::fromString(linkID);
return true;
}
void DiagramProxyWidget::saveToXMI(QXmlStreamWriter& writer)
{
if (m_diagramLinkId != Uml::ID::None)
writer.writeAttribute(QStringLiteral("diagramlinkid"), Uml::ID::toString(m_diagramLinkId));
}
bool DiagramProxyWidget::isProxyWidget() const
{
return m_linkedDiagram;
}
UMLWidget *DiagramProxyWidget::getProxiedWidget(const QPointF &p) const
{
QPointF pos = m_widget->mapFromScene(p);
if (!m_linkedDiagram || !m_clientRect.contains(pos))
return nullptr;
QPointF clientPos = mapToClient(pos);
UMLWidget *w = m_linkedDiagram->widgetAt(clientPos);
if (w)
return w;
return nullptr;
}
QPointF DiagramProxyWidget::mapFromClient(const QPointF &pos) const
{
QPointF p1 = pos - m_sceneRect.topLeft();
qreal scaleW = m_sceneRect.width() / (m_clientRect.width() - m_borderWidth);
qreal scaleH = m_sceneRect.height() / m_clientRect.height();
QPointF p2 = QPointF(p1.x() / scaleW, p1.y() / scaleH);
QPointF p3 = p2 + m_clientRect.topLeft();
return m_widget->mapToScene(p3);
}
QRectF DiagramProxyWidget::mapFromClient(const QRectF &r) const
{
return QRectF(mapFromClient(r.topLeft()), mapFromClient(r.bottomRight()));
}
/**
* Maps point from item coordinate to client scene coordinate system.
*
* @param pos item coordinated
* @return point in client scene coordinate system
*/
QPointF DiagramProxyWidget::mapToClient(const QPointF &pos) const
{
QPointF p1 = pos - m_clientRect.topLeft();
qreal scaleW = m_sceneRect.width() / (m_clientRect.width() - m_borderWidth);
qreal scaleH = m_sceneRect.height() / m_clientRect.height();
QPointF p2 = QPointF(p1.x() * scaleW, p1.y() * scaleH);
QPointF p3 = p2 + m_sceneRect.topLeft();
return p3;
}
DiagramProxyWidget &DiagramProxyWidget::operator=(const DiagramProxyWidget &other)
{
m_diagramLinkId = other.m_diagramLinkId;
m_linkedDiagram = other.m_linkedDiagram;
m_widget = other.m_widget;
m_sceneRect = other.m_sceneRect;
m_clientRect = other.m_clientRect;
return *this;
}
/**
* Set up synthetic graphics scene event
*
* @param e event to setup
* @param event event source
* @param pos position in item coordinates
*/
void DiagramProxyWidget::setupEvent(QGraphicsSceneMouseEvent &e,
const QGraphicsSceneMouseEvent *event, const QPointF & pos) const
{
QPointF p = mapToClient(pos);
e.setScenePos(p);
e.setPos(e.scenePos());
QPointF lastPos = m_widget->mapFromScene(event->lastScenePos());
QPointF lp = mapToClient(lastPos);
e.setLastScenePos(lp);
e.setModifiers(event->modifiers());
e.setButtons(event->buttons());
e.setButton(event->button());
}
/**
* Set up synthetic graphics scene context menu event
*
* @param e event to setup
* @param event event source
* @param pos position in item coordinates
*/
void DiagramProxyWidget::setupEvent(QGraphicsSceneContextMenuEvent &e,
const QGraphicsSceneContextMenuEvent *event, const QPointF & pos) const
{
QPointF p = mapToClient(pos);
e.setScenePos(p);
e.setPos(e.scenePos());
QPoint sp = event->screenPos();
e.setScreenPos(sp);
e.setModifiers(event->modifiers());
e.setReason(event->reason());
}
void DiagramProxyWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
{
QPointF pos = m_widget->mapFromScene(event->scenePos());
if (m_linkedDiagram && m_clientRect.contains(pos)) {
QGraphicsSceneContextMenuEvent e(event->type());
setupEvent(e, event, pos);
m_linkedDiagram->contextMenuEvent(&e);
m_widget->update();
event->ignore();
}
}
void DiagramProxyWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (m_showLinkedDiagram) {
QPointF pos = m_widget->mapFromScene(event->scenePos());
if (m_linkedDiagram && m_clientRect.contains(pos)) {
QGraphicsSceneMouseEvent e(event->type());
setupEvent(e, event, pos);
m_linkedDiagram->mouseDoubleClickEvent(&e);
m_widget->update();
event->ignore();
}
} else {
QPointF p = m_widget->mapFromScene(event->scenePos());
if (m_iconRect.contains(p)) {
linkedDiagram()->setWidgetLink(dynamic_cast<WidgetBase *>(this));
UMLApp::app()->document()->changeCurrentView(diagramLink());
event->ignore();
}
}
}
void DiagramProxyWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QPointF pos = m_widget->mapFromScene(event->scenePos());
if (m_linkedDiagram && m_clientRect.contains(pos)) {
QGraphicsSceneMouseEvent e(event->type());
setupEvent(e, event, pos);
m_linkedDiagram->mousePressEvent(&e);
m_widget->update();
event->ignore();
}
}
void DiagramProxyWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QPointF pos = m_widget->mapFromScene(event->scenePos());
if (m_linkedDiagram && m_clientRect.contains(pos)) {
QGraphicsSceneMouseEvent e(event->type());
setupEvent(e, event, pos);
m_linkedDiagram->mouseMoveEvent(&e);
m_widget->update();
event->ignore();
}
}
void DiagramProxyWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QPointF pos = m_widget->mapFromScene(event->scenePos());
if (m_linkedDiagram && m_clientRect.contains(pos)) {
QGraphicsSceneMouseEvent e(event->type());
setupEvent(e, event, pos);
m_linkedDiagram->mouseReleaseEvent(&e);
m_widget->update();
event->ignore();
}
}
/**
* Getter for icon rectangle
* @return icon rectangle
*/
QRectF DiagramProxyWidget::iconRect() const
{
return m_iconRect;
}
/**
* Setter for icon rectangle
* @param iconRect icon rectangle
*/
void DiagramProxyWidget::setIconRect(const QRectF &iconRect)
{
m_iconRect = iconRect;
}
/**
* Return state of 'show linked diagram' attribute
* @return state
*/
bool DiagramProxyWidget::showLinkedDiagram() const
{
return m_showLinkedDiagram;
}
/**
* Set state for 'show linked diagram' attribute
* @param showLinkedDiagram state to set
*/
void DiagramProxyWidget::setShowLinkedDiagram(bool showLinkedDiagram)
{
m_showLinkedDiagram = showLinkedDiagram;
}
/**
* Paint linked diagram into current widget
*
* @param painter painter to paint on
* @param option The option parameter provides style options for the item, such as its state, exposed area and its level-of-detail hints
* @param widget The widget argument is optional. If provided, it points to the widget that is being painted on; otherwise, it is 0
*/
void DiagramProxyWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if (m_showLinkedDiagram) {
m_sceneRect = linkedDiagram()->sceneRect().adjusted(-1,-1, 1, 1);
if (Tracer::instance()->isEnabled(QStringLiteral("DiagramProxyWidget"))) {
painter->setPen(Qt::magenta);
painter->drawRect(m_clientRect);
}
m_linkedDiagram->render(painter, m_clientRect, m_sceneRect);
} else {
QPixmap p = Icon_Utils::smallIcon(Uml::DiagramType::State);
QRectF source(0,0, p.width(), p.height());
painter->drawPixmap(m_iconRect, p, source);
}
}
/**
* Captures any popup menu signals for menus it created.
*
* If the provided action is not handled, it will be forwarded
* to the contained widget.
*
* @param action action to handle
*/
void DiagramProxyWidget::slotMenuSelection(QAction* action)
{
switch(ListPopupMenu::typeFromAction(action)) {
// classifier widget
case ListPopupMenu::mt_State_Diagram:
{
QString name = Widget_Utils::defaultWidgetName(WidgetBase::WidgetType::wt_State);
bool ok;
do {
if (!Diagram_Utils::isUniqueDiagramName(Uml::DiagramType::State, name))
name.append(QStringLiteral("_1"));
ok = Dialog_Utils::askNewName(WidgetBase::WidgetType::wt_State, name);
} while(ok && !Diagram_Utils::isUniqueDiagramName(Uml::DiagramType::State, name));
if (ok) {
Uml::CmdCreateDiagram* d = new Uml::CmdCreateDiagram(UMLApp::app()->document(), Uml::DiagramType::State, name);
UMLScene *scene = d->view()->umlScene();
UMLApp::app()->executeCommand(d);
setShowLinkedDiagram(false);
setDiagramLink(scene->ID());
scene->setWidgetLink(m_widget);
}
}
break;
// state widget
case ListPopupMenu::mt_CombinedState:
{
QString diagramName = UMLApp::app()->document()->createDiagramName(Uml::DiagramType::State);
Uml::CmdCreateDiagram* d = new Uml::CmdCreateDiagram(UMLApp::app()->document(), Uml::DiagramType::State, diagramName);
UMLApp::app()->executeCommand(d);
setDiagramLink(d->view()->umlScene()->ID());
m_widget->asStateWidget()->setStateType(StateWidget::Combined);
}
break;
case ListPopupMenu::mt_SelectStateDiagram:
{
SelectDiagramDialog dlg(nullptr, Uml::DiagramType::State, linkedDiagram() ? linkedDiagram()->name() : QString(), QString());
if (dlg.exec()) {
setDiagramLink(dlg.currentID());
}
break;
}
// classifier widget
case ListPopupMenu::mt_GoToStateDiagram:
// state widget
case ListPopupMenu::mt_EditCombinedState:
if (!linkedDiagram()) {
logError1("DiagramProxyWidget::slotMenuSelection: no diagram id defined at widget id=%1",
Uml::ID::toString(m_widget->id()));
break;
}
linkedDiagram()->setWidgetLink(m_widget);
UMLApp::app()->document()->changeCurrentView(diagramLink());
break;
case ListPopupMenu::mt_RemoveStateDiagram:
setDiagramLink(Uml::ID::None);
break;
default:
m_widget->UMLWidget::slotMenuSelection(action);
break;
}
}
| 12,518
|
C++
|
.cpp
| 377
| 28.114058
| 136
| 0.681514
|
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,380
|
floatingdashlinewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/floatingdashlinewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "floatingdashlinewidget.h"
#include "combinedfragmentwidget.h"
//kde includes
#include <KLocalizedString>
//app includes
#include "debug_utils.h"
#include "dialog_utils.h"
#include "umlview.h"
#include "widget_utils.h"
#include "listpopupmenu.h"
// qt includes
#include <QPainter>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(FloatingDashLineWidget)
/**
* Creates a floating dash line.
* @param scene The parent of the widget
* @param id The ID to assign (-1 will prompt a new ID)
* @param parent The CombinedFragmentWidget which acts as the parent
*/
FloatingDashLineWidget::FloatingDashLineWidget(UMLScene * scene, Uml::ID::Type id, CombinedFragmentWidget *parent)
: UMLWidget(scene, WidgetBase::wt_FloatingDashLine, id),
m_yMin(0),
m_yMax(0),
m_parent(parent)
{
m_resizable = false;
m_Text = QString();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
setSize(10, fontHeight);
}
/**
* Destructor.
*/
FloatingDashLineWidget::~FloatingDashLineWidget()
{
if (m_parent)
m_parent->removeDashLine(this);
}
/**
* Overrides the standard paint event.
*/
void FloatingDashLineWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
painter->drawText(FLOATING_DASH_LINE_TEXT_MARGIN, 0,
width() - FLOATING_DASH_LINE_TEXT_MARGIN * 2, fontHeight,
Qt::AlignLeft, QLatin1Char('[') + m_Text + QLatin1Char(']'));
painter->setPen(QPen(UMLWidget::lineColor(), 0, Qt::DashLine));
painter->drawLine(0, 0, width(), 0);
UMLWidget::paint(painter, option, widget);
}
/**
* Sets m_text.
*/
void FloatingDashLineWidget::setText(const QString& text)
{
m_Text = text;
}
/**
* Returns true if the given point is near the floatingdashline.
*/
bool FloatingDashLineWidget::onLine(const QPointF& point)
{
// check if the given point is the start or end point of the line
if (((abs((long)(y() + height() - point.y()))) <= POINT_DELTA) || (abs((long)(y() - point.y())) <= POINT_DELTA)) {
return true;
}
// check if the given point is the start or end point of the line
return false;
}
void FloatingDashLineWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString name = m_Text;
bool ok = Dialog_Utils::askName(i18n("Enter alternative Name"),
i18n("Enter the alternative:"),
name);
if (ok && name.length() > 0)
m_Text = name;
}
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Overrides the setY method.
*/
void FloatingDashLineWidget::setY(qreal y)
{
if(y >= m_yMin + FLOATING_DASH_LINE_MARGIN && y <= m_yMax - FLOATING_DASH_LINE_MARGIN)
UMLWidget::setY(y);
}
/**
* Sets m_yMin.
*/
void FloatingDashLineWidget::setYMin(qreal yMin)
{
m_yMin = yMin;
}
/**
* Sets m_yMax.
*/
void FloatingDashLineWidget::setYMax(qreal yMax)
{
m_yMax = yMax;
}
/**
* Returns m_yMin.
*/
qreal FloatingDashLineWidget::getYMin() const
{
return m_yMin;
}
/**
* Returns the difference between the y-coordinate of the dash line and m_yMin.
*/
qreal FloatingDashLineWidget::getDiffY() const
{
return (y() - getYMin());
}
/**
* Creates the "floatingdashline" XMI element.
*/
void FloatingDashLineWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("floatingdashlinewidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("text"), m_Text);
writer.writeAttribute(QStringLiteral("minY"), QString::number(m_yMin));
writer.writeAttribute(QStringLiteral("maxY"), QString::number(m_yMax));
writer.writeEndElement();
}
/**
* Loads the "floatingdashline" XMI element.
*/
bool FloatingDashLineWidget::loadFromXMI(QDomElement & qElement)
{
m_yMax = qElement.attribute(QStringLiteral("maxY")).toFloat();
m_yMin = qElement.attribute(QStringLiteral("minY")).toFloat();
m_Text = qElement.attribute(QStringLiteral("text"));
if(!UMLWidget::loadFromXMI(qElement)) {
return false;
}
return true;
}
| 4,733
|
C++
|
.cpp
| 161
| 25.409938
| 118
| 0.685865
|
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,381
|
regionwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/regionwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "regionwidget.h"
// app includes
#include "basictypes.h"
#include "debug_utils.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QXmlStreamWriter>
#define REGION_MARGIN 5
#define REGION_WIDTH 90
#define REGION_HEIGHT 45
DEBUG_REGISTER_DISABLED(RegionWidget)
/**
* Creates a Region widget.
*
* @param scene The parent of the widget.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
RegionWidget::RegionWidget(UMLScene* scene, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Region, id)
{
}
/**
* Destructor.
*/
RegionWidget::~RegionWidget()
{
}
/**
* Overrides the standard paint event.
*/
void RegionWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
const int w = width();
const int h = height();
setPenFromSettings(painter);
QPen pen = painter->pen();
pen.setColor(Qt::red);
pen.setStyle(Qt::DashLine);
painter->setPen(pen);
painter->drawRoundedRect(0, 0, w, h, (h * 60) / w, 60);
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget
*/
QSizeF RegionWidget::minimumSize() const
{
int width = 10, height = 10;
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textWidth = fm.horizontalAdvance(name());
height = fontHeight;
width = textWidth > REGION_WIDTH?textWidth:REGION_WIDTH;
height = height > REGION_HEIGHT ? height : REGION_HEIGHT;
width += REGION_MARGIN * 2;
height += REGION_MARGIN * 2;
return QSizeF(width, height);
}
/**
* Saves region widget to XMI element.
*/
void RegionWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("regionwidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("regionname"), name());
writer.writeAttribute(QStringLiteral("documentation"), documentation());
writer.writeEndElement();
}
/**
* Loads region widget from XMI element.
*/
bool RegionWidget::loadFromXMI(QDomElement& qElement)
{
if (!UMLWidget::loadFromXMI(qElement)) {
return false;
}
setName(qElement.attribute(QStringLiteral("regionname")));
setDocumentation(qElement.attribute(QStringLiteral("documentation")));
return true;
}
| 2,526
|
C++
|
.cpp
| 89
| 25.404494
| 100
| 0.718362
|
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,382
|
pinportbase.cpp
|
KDE_umbrello/umbrello/umlwidgets/pinportbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "pinportbase.h"
// app includes
#include "port.h"
#include "package.h"
#include "debug_utils.h"
#include "listpopupmenu.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "floatingtextwidget.h"
#include "umlwidgets/childwidgetplacementpin.h"
#include "umlwidgets/childwidgetplacementport.h"
// qt includes
#include <QPainter>
#include <QToolTip>
#include <QXmlStreamWriter>
// sys includes
#include <cmath>
DEBUG_REGISTER(PinPortBase)
PinPortBase::PinPortBase(UMLScene *scene, WidgetType type, UMLWidget *owner, UMLObject *o)
: UMLWidget(scene, type, o),
m_childPlacement(createPlacement(type))
{
init(owner);
}
PinPortBase::PinPortBase(UMLScene *scene, WidgetType type, UMLWidget *owner, Uml::ID::Type id)
: UMLWidget(scene, type, id),
m_childPlacement(createPlacement(type))
{
init(owner);
}
/**
* Standard destructor.
*/
PinPortBase::~PinPortBase()
{
}
ChildWidgetPlacement* PinPortBase::createPlacement(WidgetBase::WidgetType type)
{
if (type == wt_Pin) {
return new ChildWidgetPlacementPin(this);
}
else if (type == wt_Port) {
return new ChildWidgetPlacementPort(this);
}
else {
return nullptr;
}
}
/**
* Performs initializations which are common to PinWidget and PortWidget.
*/
void PinPortBase::init(UMLWidget *owner)
{
m_ignoreSnapToGrid = true;
m_ignoreSnapComponentSizeToGrid = true;
m_resizable = false;
setParentItem(owner);
m_pName = nullptr;
const int edgeLength = 15; // old: (m_baseType == wt_Pin ? 10 : 15);
const QSizeF fixedSize(edgeLength, edgeLength);
setMinimumSize(fixedSize);
setMaximumSize(fixedSize);
setSize(fixedSize);
//m_childPlacement->setInitialPosition();
}
UMLWidget* PinPortBase::ownerWidget() const
{
return dynamic_cast<UMLWidget*>(parentItem());
}
void PinPortBase::setInitialPosition(const QPointF &scenePos)
{
m_childPlacement->setInitialPosition(scenePos);
}
qreal PinPortBase::getX() const
{
return parentItem()->x() + UMLWidget::getX();
}
qreal PinPortBase::getY() const
{
return parentItem()->y() + UMLWidget::getY();
}
QPointF PinPortBase::getPos() const
{
return parentItem()->pos() + UMLWidget::getPos();
}
/**
* Overrides method from UMLWidget in order to set a tooltip.
* The tooltip is set to the name().
* The reason for using a tooltip for the name is that the size of this
* widget is not large enough to accommodate the average name.
*/
void PinPortBase::updateWidget()
{
QString strName = name();
logDebug1("PinPortBase::updateWidget: port name is %1", strName);
if (m_pName) {
m_pName->setText(strName);
} else {
setToolTip(strName);
}
}
/**
* Overrides method from UMLWidget to set the name.
*/
void PinPortBase::setName(const QString &strName)
{
UMLWidget::setName(strName);
updateGeometry();
if (m_pName) {
m_pName->setText(strName);
}
}
/**
* Overridden from UMLWidget.
* Moves the widget to a new position using the difference between the
* current position and the new position.
* Movement is constrained such that the port is always attached to its
* owner widget.
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void PinPortBase::moveWidgetBy(qreal diffX, qreal diffY)
{
m_childPlacement->setNewPositionWhenMoved(diffX, diffY);
}
/**
* Receive notification when parent is resized.
* We need to track parent resize to always stay attached to it.
*/
void PinPortBase::notifyParentResize()
{
m_childPlacement->setNewPositionOnParentResize();
}
/**
* Overrides standard method.
*/
void PinPortBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
} else {
painter->setBrush(m_scene->backgroundColor());
}
painter->drawRect(0, 0, width(), height());
UMLWidget::paint(painter, option, widget);
}
QRectF PinPortBase::boundingRect() const
{
return QRectF(0, 0, width(), height());
}
/**
* Captures any popup menu signals for menus it created.
*/
void PinPortBase::slotMenuSelection(QAction* action)
{
logDebug0("PinPortBase::slotMenuSelection");
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_NameAsTooltip:
if (m_pName) {
action->setChecked(true);
delete m_pName;
m_pName = nullptr;
setToolTip(name());
} else {
action->setChecked(false);
m_pName = new FloatingTextWidget(m_scene, Uml::TextRole::Floating, name());
m_pName->setParentItem(this);
m_pName->setText(name()); // to get geometry update
m_pName->activate();
UMLWidget* owner = ownerWidget();
if (owner == nullptr) {
logError0("PinPortBase::slotMenuSelection: ownerWidget() returns null");
setX(x());
setY(y());
} else {
const qreal w = width();
const qreal h = height();
if (x() < owner->x())
m_pName->setX(-m_pName->width());
else if (x() >= owner->x() + owner->width())
m_pName->setX(w);
else
m_pName->setX(-m_pName->width() / 2.0 + w / 2.0);
if (y() < owner->y())
m_pName->setY(-m_pName->height() - 2);
else if (y() >= owner->y() + owner->height())
m_pName->setY(h);
else
m_pName->setY(-m_pName->height() / 2.0 + h / 2.0);
}
m_pName->update();
setToolTip(QString());
QToolTip::hideText();
}
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
FloatingTextWidget *PinPortBase::floatingTextWidget() {
return m_pName;
}
void PinPortBase::setFloatingTextWidget(FloatingTextWidget *ft) {
m_pName = ft;
if (m_pName)
m_pName->setParentItem(this);
}
/**
* Override method from UMLWidget in order to additionally check m_pName.
*
* @param p Point to be checked.
*
* @return 'this' if UMLWidget::onWidget(p) returns non 0;
* m_pName if m_pName is non NULL and m_pName->onWidget(p) returns non 0;
* else NULL.
*/
UMLWidget* PinPortBase::onWidget(const QPointF &p)
{
UMLWidget * onWidget = UMLWidget::onWidget(p);
logDebug4("PinPortBase::onWidget (%1,%2) returns %3 (owner %4)",
p.x(), p.y(), (onWidget != nullptr), ownerWidget()->name());
if (onWidget) {
return this;
}
if (m_pName) {
logDebug1("PinPortBase::onWidget floatingtext: %1", m_pName->text());
return m_pName->onWidget(p);
}
return nullptr;
}
/**
* Reimplement function from UMLWidget
*/
UMLWidget* PinPortBase::widgetWithID(Uml::ID::Type id)
{
if (UMLWidget::widgetWithID(id))
return this;
if (m_pName && m_pName->widgetWithID(id))
return m_pName;
return nullptr;
}
/**
* Saves the widget to the "pinwidget" or "portwidget" XMI element.
*/
void PinPortBase::saveToXMI(QXmlStreamWriter& writer)
{
QString tag = (baseType() == wt_Pin ? QStringLiteral("pinwidget")
: QStringLiteral("portwidget"));
writer.writeStartElement(tag);
Q_ASSERT(ownerWidget() != nullptr);
writer.writeAttribute(QStringLiteral("widgetaid"), Uml::ID::toString(ownerWidget()->id()));
UMLWidget::saveToXMI(writer);
if (m_pName && !m_pName->text().isEmpty()) {
m_pName->saveToXMI(writer);
}
writer.writeEndElement();
}
/**
* Loads from a "pinwidget" or from a "portwidget" XMI element.
*/
bool PinPortBase::loadFromXMI(QDomElement & qElement)
{
if (!UMLWidget::loadFromXMI(qElement))
return false;
QString widgetaid = qElement.attribute(QStringLiteral("widgetaid"), QStringLiteral("-1"));
Uml::ID::Type aId = Uml::ID::fromString(widgetaid);
UMLWidget *owner = m_scene->findWidget(aId);
if(owner == nullptr) {
logDebug1("PinPortBase::loadFromXMI: owner object %1 not found", Uml::ID::toString(aId));
return false;
}
setParentItem(owner);
// Optional child element: floatingtext
QDomNode node = qElement.firstChild();
QDomElement element = node.toElement();
if (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("floatingtext")) {
m_pName = new FloatingTextWidget(m_scene, Uml::TextRole::Floating,
name(), Uml::ID::Reserved);
m_pName->setParentItem(this);
if (!m_pName->loadFromXMI(element)) {
// Most likely cause: The FloatingTextWidget is empty.
// m_scene->removeItem(m_pName); m_pName->deleteLater();
delete m_pName;
m_pName = nullptr;
} else {
m_pName->activate();
m_pName->update();
}
} else {
logError1("PinPortBase::loadFromXMI: unknown tag %1", tag);
}
}
return true;
}
/**
* Reimplementation of method from @ref WidgetBase
*/
bool PinPortBase::activate(IDChangeLog* changeLog)
{
Q_UNUSED(changeLog);
m_childPlacement->detectConnectedSide();
return true;
}
| 9,782
|
C++
|
.cpp
| 315
| 25.574603
| 99
| 0.645175
|
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,383
|
portwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/portwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "portwidget.h"
// app includes
#include "port.h"
#include "package.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "listpopupmenu.h"
#include "uml.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umlscene.h"
#include "componentwidget.h"
#include "floatingtextwidget.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPainter>
#include <QToolTip>
DEBUG_REGISTER_DISABLED(PortWidget)
/**
* Constructs a PortWidget.
*
* @param scene The parent scene of this PortWidget.
* @param d The UMLPort this will be representing.
* @param owner The owning widget to which this PortWidget is attached.
*/
PortWidget::PortWidget(UMLScene *scene, UMLPort *d, UMLWidget *owner)
: PinPortBase(scene, WidgetBase::wt_Port, owner, d)
{
setToolTip(d->name());
}
/**
* Standard deconstructor.
*/
PortWidget::~PortWidget()
{
}
/**
* Override function from PinPortWidget.
*/
UMLWidget* PortWidget::ownerWidget() const
{
return PinPortBase::ownerWidget();
}
/**
* Captures any popup menu signals for menus it created.
*/
void PortWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString newName = name();
if (Dialog_Utils::askNewName(WidgetBase::wt_Port, newName))
setName(newName);
}
break;
default:
PinPortBase::slotMenuSelection(action);
}
}
| 1,680
|
C++
|
.cpp
| 67
| 22.089552
| 92
| 0.71598
|
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,384
|
associationwidgetrole.cpp
|
KDE_umbrello/umbrello/umlwidgets/associationwidgetrole.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "associationwidgetrole.h"
#include "floatingtextwidget.h"
#include "umlwidget.h"
#include "umlscene.h"
#include <QXmlStreamWriter>
AssociationWidgetRole::AssociationWidgetRole()
: multiplicityWidget(nullptr)
, changeabilityWidget(nullptr)
, roleWidget(nullptr)
, umlWidget(nullptr)
, m_WidgetRegion(Uml::Region::Error)
, m_nIndex(0)
, m_nTotalCount(0)
, visibility(Uml::Visibility::Public)
, changeability(Uml::Changeability::Changeable)
, m_q(nullptr)
{
}
void AssociationWidgetRole::cleanup()
{
if (umlWidget) {
umlWidget->removeAssoc(m_q);
umlWidget = nullptr;
}
if (roleWidget) {
roleWidget->umlScene()->removeWidget(roleWidget);
roleWidget = nullptr;
}
if (multiplicityWidget) {
multiplicityWidget->umlScene()->removeWidget(multiplicityWidget);
multiplicityWidget = nullptr;
}
if (changeabilityWidget) {
changeabilityWidget->umlScene()->removeWidget(changeabilityWidget);
changeabilityWidget = nullptr;
}
}
void AssociationWidgetRole::setFont(const QFont &font)
{
if (roleWidget)
roleWidget->setFont(font);
if (multiplicityWidget)
multiplicityWidget->setFont(font);
if (changeabilityWidget)
changeabilityWidget->setFont(font);
}
/**
* Check owned floating texts
*
* @param p Point to be checked
*
* @return pointer to widget at the provided point p
* @return 0 if no widget found
*/
UMLWidget* AssociationWidgetRole::onWidget(const QPointF &p)
{
if (multiplicityWidget && multiplicityWidget->onWidget(p))
return multiplicityWidget;
else if (changeabilityWidget && changeabilityWidget->onWidget(p))
return changeabilityWidget;
else if (roleWidget && roleWidget->onWidget(p))
return roleWidget;
return nullptr;
}
/**
* Sets the state of whether the widget is selected.
*
* @param select The state of whether the widget is selected.
*/
void AssociationWidgetRole::setSelected(bool select)
{
if (roleWidget)
roleWidget->setSelected(select);
if (multiplicityWidget )
multiplicityWidget->setSelected(select);
if (changeabilityWidget)
changeabilityWidget->setSelected(select);
}
void AssociationWidgetRole::clipSize()
{
if (multiplicityWidget)
multiplicityWidget->clipSize();
if (roleWidget)
roleWidget->clipSize();
if (changeabilityWidget)
changeabilityWidget->clipSize();
}
void AssociationWidgetRole::saveToXMI(QXmlStreamWriter& writer)
{
// For attributes index[ab] and totalcount[ab] see AssociationWidget::saveToXMI.
// They are not written here because attributes may not follow elements
// (in particular, attributes of role B may not follow elements of role A)
if (multiplicityWidget)
multiplicityWidget->saveToXMI(writer);
if (roleWidget)
roleWidget->saveToXMI(writer);
if (changeabilityWidget)
changeabilityWidget->saveToXMI(writer);
}
bool AssociationWidgetRole::loadFromXMI(QDomElement &qElement, const QString &suffix)
{
QString index = qElement.attribute(QString(QStringLiteral("index%1")).arg(suffix), QStringLiteral("0"));
QString totalcount = qElement.attribute(QString(QStringLiteral("totalcount%1")).arg(suffix), QStringLiteral("0"));
m_nIndex = index.toInt();
m_nTotalCount = totalcount.toInt();
// for remaining see AssociationWidget::loadFromXMI
return true;
}
bool AssociationWidgetRole::getStartMove()
{
if (multiplicityWidget && multiplicityWidget->getStartMove())
return true;
else if (changeabilityWidget && changeabilityWidget->getStartMove())
return true;
else if (roleWidget && roleWidget->getStartMove())
return true;
return false;
}
| 3,918
|
C++
|
.cpp
| 122
| 27.795082
| 118
| 0.728787
|
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,385
|
entitywidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/entitywidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "entitywidget.h"
// app includes
#include "classifier.h"
#include "classifierlistitem.h"
#include "debug_utils.h"
#include "entity.h"
#include "entityattribute.h"
#include "foreignkeyconstraint.h"
#include "listpopupmenu.h"
#include "object_factory.h"
#include "uml.h"
#include "umlclassifierlistitemlist.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "uniqueconstraint.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(EntityWidget)
/**
* Constructs an EntityWidget.
*
* @param scene The parent of this EntityWidget.
* @param o The UMLObject this will be representing.
*/
EntityWidget::EntityWidget(UMLScene *scene, UMLObject* o)
: UMLWidget(scene, WidgetBase::wt_Entity, o)
{
setSize(100, 30);
}
/**
* Destructor.
*/
EntityWidget::~EntityWidget()
{
}
/**
* calculate content related size of widget.
*
* @return calculated widget size
*/
QSizeF EntityWidget::calculateSize(bool withExtensions /* = true */) const
{
Q_UNUSED(withExtensions)
const QFontMetrics &fm = getFontMetrics(UMLWidget::FT_NORMAL);
const int fontHeight = fm.lineSpacing();
if (!m_umlObject)
return QSizeF(width(), height());
qreal width = 0, height = defaultMargin;
if (showStereotype() && !m_umlObject->stereotype().isEmpty()) {
const QFontMetrics &bfm = UMLWidget::getFontMetrics(UMLWidget::FT_BOLD);
const int stereoWidth = bfm.size(0, m_umlObject->stereotype(true)).width();
if (stereoWidth > width)
width = stereoWidth;
height += fontHeight;
}
const QFontMetrics &bfm = UMLWidget::getFontMetrics(UMLWidget::FT_BOLD);
const int nameWidth = bfm.size(0, name()).width();
if (nameWidth > width)
width = nameWidth;
height += fontHeight;
const UMLClassifier *classifier = m_umlObject->asUMLClassifier();
UMLClassifierListItemList list = classifier->getFilteredList(UMLObject::ot_EntityAttribute);
for(UMLClassifierListItem* entityattribute : list) {
QString text = entityattribute->name();
UMLEntityAttribute* umlEA = entityattribute->asUMLEntityAttribute();
if (showAttributeSignature()) {
text.append(QStringLiteral(" : ") + umlEA->getTypeName());
text.append(QStringLiteral(" [") + umlEA->getAttributes() + QStringLiteral("]"));
}
if (showStereotype()) {
text.append(QStringLiteral(" ") + umlEA->stereotype(true));
}
const int nameWidth = bfm.size(0, text).width();
if (nameWidth > width)
width = nameWidth;
height += fontHeight;
}
return QSizeF(width + 2*defaultMargin, height);
}
/**
* Draws the entity as a rectangle with a box underneith with a list of literals
*/
void EntityWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
else
painter->setBrush(m_scene->backgroundColor());
const int w = width();
const int h = height();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
int fontHeight = fm.lineSpacing();
const QString name = this->name();
painter->drawRect(0, 0, w, h);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(true);
painter->setFont(font);
int y = 0;
if (showStereotype() && !m_umlObject->stereotype().isEmpty()) {
painter->drawText(ENTITY_MARGIN, 0,
w - ENTITY_MARGIN * 2, fontHeight,
Qt::AlignCenter, m_umlObject->stereotype(true));
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
painter->drawText(ENTITY_MARGIN, fontHeight,
w - ENTITY_MARGIN * 2, fontHeight, Qt::AlignCenter, name);
font.setBold(false);
font.setItalic(false);
painter->setFont(font);
y = fontHeight * 2;
} else {
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
painter->drawText(ENTITY_MARGIN, 0,
w - ENTITY_MARGIN * 2, fontHeight, Qt::AlignCenter, name);
font.setBold(false);
font.setItalic(false);
painter->setFont(font);
y = fontHeight;
}
setPenFromSettings(painter);
painter->drawLine(0, y, w, y);
QFontMetrics fontMetrics(font);
const UMLClassifier *classifier = m_umlObject->asUMLClassifier();
UMLClassifierListItemList list = classifier->getFilteredList(UMLObject::ot_EntityAttribute);
for(UMLClassifierListItem *entityattribute: list) {
QString text = entityattribute->name();
painter->setPen(textColor());
const UMLEntityAttribute* umlEA = entityattribute->asUMLEntityAttribute();
if (showAttributeSignature()) {
text.append(QStringLiteral(" : ") + umlEA->getTypeName());
text.append(QStringLiteral(" [") + umlEA->getAttributes() + QStringLiteral("]"));
}
if (showStereotype()) {
text.append(QStringLiteral(" ") + umlEA->stereotype(true));
}
if (umlEA && umlEA->indexType() == UMLEntityAttribute::Primary)
{
font.setUnderline(true);
painter->setFont(font);
font.setUnderline(false);
}
painter->drawText(ENTITY_MARGIN, y,
fontMetrics.horizontalAdvance(text), fontHeight, Qt::AlignVCenter, text);
painter->setFont(font);
y+=fontHeight;
}
UMLWidget::paint(painter, option, widget);
}
bool EntityWidget::loadFromXMI(QDomElement & qElement)
{
if (!UMLWidget::loadFromXMI(qElement))
return false;
QString showAttributeSignatures = qElement.attribute(QStringLiteral("showattsigs"), QStringLiteral("0"));
m_showAttributeSignatures = (bool)showAttributeSignatures.toInt();
return true;
}
/**
* Saves to the "entitywidget" XMI element.
*/
void EntityWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("entitywidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("showattsigs"), QString::number(m_showAttributeSignatures));
writer.writeEndElement();
}
/**
* Will be called when a menu selection has been made from the popup
* menu.
*
* @param action The action that has been selected.
*/
void EntityWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_EntityAttribute:
if (Object_Factory::createChildObject(m_umlObject->asUMLClassifier(),
UMLObject::ot_EntityAttribute)) {
UMLApp::app()->document()->setModified();
}
break;
case ListPopupMenu::mt_PrimaryKeyConstraint:
case ListPopupMenu::mt_UniqueConstraint:
if (UMLObject* obj = Object_Factory::createChildObject(m_umlObject->asUMLEntity(),
UMLObject::ot_UniqueConstraint)) {
UMLApp::app()->document()->setModified();
if (sel == ListPopupMenu::mt_PrimaryKeyConstraint) {
UMLUniqueConstraint* uc = obj->asUMLUniqueConstraint();
m_umlObject->asUMLEntity()->setAsPrimaryKey(uc);
}
}
break;
case ListPopupMenu::mt_ForeignKeyConstraint:
if (Object_Factory::createChildObject(m_umlObject->asUMLEntity(),
UMLObject::ot_ForeignKeyConstraint)) {
UMLApp::app()->document()->setModified();
}
break;
case ListPopupMenu::mt_CheckConstraint:
if (Object_Factory::createChildObject(m_umlObject->asUMLEntity(),
UMLObject::ot_CheckConstraint)) {
UMLApp::app()->document()->setModified();
}
break;
case ListPopupMenu::mt_Show_Attribute_Signature:
setShowAttributeSignature(!showAttributeSignature());
break;
case ListPopupMenu::mt_Show_Stereotypes:
setShowStereotype(showStereotype() == Uml::ShowStereoType::None ?
Uml::ShowStereoType::Tags : Uml::ShowStereoType::None);
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Overrides method from UMLWidget.
*/
QSizeF EntityWidget::minimumSize() const
{
if (!m_umlObject) {
return UMLWidget::minimumSize();
}
return calculateSize();
}
/**
* Set the status of whether to show attributes.
*
* @param flag True if attributes shall be shown.
*/
void EntityWidget::setShowAttributeSignature(bool flag)
{
m_showAttributeSignatures = flag;
updateGeometry();
update();
}
/**
* Returns the status of whether to show attributes.
*
* @return True if attributes are shown.
*/
bool EntityWidget::showAttributeSignature() const
{
return m_showAttributeSignatures;
}
| 9,277
|
C++
|
.cpp
| 257
| 29.48249
| 109
| 0.658572
|
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,386
|
preconditionwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/preconditionwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "preconditionwidget.h"
// app includes
#include "debug_utils.h"
#include "dialog_utils.h"
#include "listpopupmenu.h"
#include "objectwidget.h"
#include "uml.h"
#include "umlscene.h"
#include "uniqueid.h"
#include "idchangelog.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPainter>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(PreconditionWidget)
#define PRECONDITION_MARGIN 5
#define PRECONDITION_WIDTH 30
#define PRECONDITION_HEIGHT 10
/**
* Creates a Precondition widget.
*
* @param scene The parent of the widget.
* @param a The role A widget for this precondition.
* @param id The ID to assign (-1 will prompt a new ID).
*/
PreconditionWidget::PreconditionWidget(UMLScene* scene, ObjectWidget* a, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Precondition, id),
m_objectWidget(a)
{
m_ignoreSnapToGrid = true;
m_ignoreSnapComponentSizeToGrid = true;
m_resizable = true ;
setVisible(true);
//updateResizability();
// calculateWidget();
if (y() < minY())
m_nY = minY();
else if (y() > maxY())
m_nY = maxY();
else
m_nY = y();
connect(m_objectWidget, SIGNAL(sigWidgetMoved(Uml::ID::Type)), this, SLOT(slotWidgetMoved(Uml::ID::Type)));
calculateDimensions();
}
/**
* Destructor.
*/
PreconditionWidget::~PreconditionWidget()
{
}
/**
* Overrides the standard paint event.
*/
void PreconditionWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
int w = width();
int h = height();
if (m_objectWidget) {
int x = m_objectWidget->x() + m_objectWidget->width() / 2;
x -= w/2;
setX(x);
int y = this->y();
//test if y isn't above the object
if (y <= m_objectWidget->y() + m_objectWidget->height()) {
y = m_objectWidget->y() + m_objectWidget->height() + 15;
}
if (y + h >= m_objectWidget->getEndLineY()) {
y = m_objectWidget->getEndLineY() - h;
}
setY(y);
}
setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const QString precondition_value = QStringLiteral("{ ") + name() + QStringLiteral(" }");
//int middleX = w / 2;
int textStartY = (h / 2) - (fontHeight / 2);
painter->drawRoundedRect(0, 0, w, h, (h * 60) / w, 60);
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
painter->drawText(PRECONDITION_MARGIN, textStartY,
w - PRECONDITION_MARGIN * 2, fontHeight, Qt::AlignCenter, precondition_value);
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget.
*/
QSizeF PreconditionWidget::minimumSize() const
{
int width = 10, height = 10;
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(name()) + 25;
height = fontHeight;
width = textWidth > PRECONDITION_WIDTH ? textWidth : PRECONDITION_WIDTH;
height = height > PRECONDITION_HEIGHT ? height : PRECONDITION_HEIGHT;
width += PRECONDITION_MARGIN * 2;
height += PRECONDITION_MARGIN * 2;
return QSizeF(width, height);
}
/**
* Calculate the geometry of the widget.
*/
void PreconditionWidget::calculateWidget()
{
calculateDimensions();
setVisible(true);
setX(m_nPosX);
setY(m_nY);
}
/**
* Activates a PreconditionWidget. Connects the WidgetMoved signal from
* its m_objectWidget pointer so that PreconditionWidget can adjust to the move of
* the object widget.
*/
bool PreconditionWidget::activate(IDChangeLog *Log /*= nullptr*/)
{
m_scene->resetPastePoint();
UMLWidget::activate(Log);
if (m_objectWidget == nullptr &&
!(m_widgetAId.empty() || m_widgetAId == Uml::ID::None || m_widgetAId == Uml::ID::Reserved)) {
UMLWidget *w = umlScene()->findWidget(m_widgetAId);
m_objectWidget = w->asObjectWidget();
if (!m_objectWidget) {
DEBUG() << "role A widget " << Uml::ID::toString(m_widgetAId) << " could not be found";
return false;
}
connect(m_objectWidget, SIGNAL(sigWidgetMoved(Uml::ID::Type)), this, SLOT(slotWidgetMoved(Uml::ID::Type)));
}
calculateDimensions();
return true;
}
/**
* Resolve references of this precondition so it references the correct
* new object widget after paste.
*/
void PreconditionWidget::resolveObjectWidget(IDChangeLog* log)
{
m_widgetAId = log->findNewID(m_widgetAId);
activate(log);
}
/**
* Calculates the size of the widget.
*/
void PreconditionWidget::calculateDimensions()
{
int x = 0;
int w = 0;
int h = 0;
QSizeF q = minimumSize();
w = q.width() > width() ? q.width() : width();
h = q.height() > height() ? q.height() : height();
if (m_objectWidget) {
int x1 = m_objectWidget->x();
int w1 = m_objectWidget->width() / 2;
x1 += w1;
x = x1 - w/2;
m_nPosX = x;
}
setSize(w, h);
}
/**
* Slot when widget is moved.
*/
void PreconditionWidget::slotWidgetMoved(Uml::ID::Type id)
{
const Uml::ID::Type idA = m_objectWidget ? m_objectWidget->localID() : Uml::ID::None;
if (idA != id) {
DEBUG() << "id=" << Uml::ID::toString(id) << ": ignoring for idA=" << Uml::ID::toString(idA);
return;
}
m_nY = y();
if (m_nY < minY())
m_nY = minY();
if (m_nY > maxY())
m_nY = maxY();
calculateDimensions();
if (m_scene->selectedCount(true) > 1)
return;
}
/**
* Returns the minimum height this widget should be set at on
* a sequence diagrams. Takes into account the widget positions
* it is related to.
*/
int PreconditionWidget::minY() const
{
if (m_objectWidget) {
return m_objectWidget->y() + m_objectWidget->height();
}
return 0;
}
/**
* Returns the maximum height this widget should be set at on
* a sequence diagrams. Takes into account the widget positions
* it is related to.
*/
int PreconditionWidget::maxY() const
{
if (m_objectWidget) {
return ((int)m_objectWidget->getEndLineY() - height());
}
return 0;
}
/**
* Captures any popup menu signals for menus it created.
*/
void PreconditionWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString text = name();
bool ok = Dialog_Utils::askNewName(WidgetBase::wt_Precondition, text);
if (ok && !text.isEmpty()) {
setName(text);
}
calculateWidget();
}
break;
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Saves the widget to the "preconditionwidget" XMI element.
*/
void PreconditionWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("preconditionwidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("widgetaid"), Uml::ID::toString(m_objectWidget->localID()));
writer.writeAttribute(QStringLiteral("preconditionname"), name());
writer.writeAttribute(QStringLiteral("documentation"), documentation());
writer.writeEndElement();
}
/**
* Loads the widget from the "preconditionwidget" XMI element.
*/
bool PreconditionWidget::loadFromXMI(QDomElement& qElement)
{
if(!UMLWidget::loadFromXMI(qElement))
return false;
setName(qElement.attribute(QStringLiteral("preconditionname")));
setDocumentation(qElement.attribute(QStringLiteral("documentation")));
QString widgetaid = qElement.attribute(QStringLiteral("widgetaid"), QStringLiteral("-1"));
m_widgetAId = Uml::ID::fromString(widgetaid);
return true;
}
ObjectWidget *PreconditionWidget::objectWidget() const
{
return m_objectWidget;
}
void PreconditionWidget::setObjectWidget(ObjectWidget *objectWidget)
{
m_objectWidget = objectWidget;
}
| 8,492
|
C++
|
.cpp
| 274
| 26.423358
| 115
| 0.661125
|
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,387
|
objectnodewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/objectnodewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "objectnodewidget.h"
// app includes
#include "debug_utils.h"
#include "docwindow.h"
#include "dialog_utils.h"
#include "listpopupmenu.h"
#include "objectnodedialog.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "widget_utils.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPainter>
#include <QPointer>
#include <QXmlStreamWriter>
#define OBJECTNODE_MARGIN 5
#define OBJECTNODE_WIDTH 30
#define OBJECTNODE_HEIGHT 10
DEBUG_REGISTER_DISABLED(ObjectNodeWidget)
/**
* Creates an Object Node widget.
*
* @param scene The parent of the widget.
* @param objectNodeType The type of object node
* @param id The ID to assign (-1 will prompt a new ID.)
*/
ObjectNodeWidget::ObjectNodeWidget(UMLScene * scene, ObjectNodeType objectNodeType, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_ObjectNode, id)
{
setObjectNodeType(objectNodeType);
setState(QString());
}
/**
* Destructor.
*/
ObjectNodeWidget::~ObjectNodeWidget()
{
}
/**
* Overrides the standard paint event.
*/
void ObjectNodeWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
int w = width();
int h = height();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textStartY = (h / 2) - (fontHeight / 2);
setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
painter->drawRect(0, 0, w, h);
painter->setFont(UMLWidget::font());
if (m_objectNodeType == Flow) {
QString objectflow_value;
if (state() == QStringLiteral("-") || state().isEmpty()) {
objectflow_value = QLatin1Char(' ');
} else {
objectflow_value = QLatin1Char('[') + state() + QLatin1Char(']');
}
painter->drawLine(10, h/2, w-10, h/2);
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
painter->drawText(OBJECTNODE_MARGIN, textStartY/2 - OBJECTNODE_MARGIN,
w - OBJECTNODE_MARGIN * 2, fontHeight, Qt::AlignHCenter, name());
painter->drawText(OBJECTNODE_MARGIN, textStartY/2 + textStartY + OBJECTNODE_MARGIN,
w - OBJECTNODE_MARGIN * 2, fontHeight, Qt::AlignHCenter, objectflow_value);
} else {
painter->setPen(textColor());
const QString stereoType = (m_objectNodeType == Normal ? QStringLiteral("object") :
m_objectNodeType == Buffer ? QStringLiteral("centralBuffer")
: QStringLiteral("datastore"));
painter->drawText(OBJECTNODE_MARGIN, textStartY / 2, w - OBJECTNODE_MARGIN * 2, fontHeight,
Qt::AlignHCenter, Widget_Utils::adornStereo(stereoType));
painter->drawText(OBJECTNODE_MARGIN, (textStartY / 2) + fontHeight + 5,
w - OBJECTNODE_MARGIN * 2, fontHeight, Qt::AlignHCenter, name());
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget.
*/
QSizeF ObjectNodeWidget::minimumSize() const
{
int widthtmp = 10, height = 10, width=10;
if (m_objectNodeType == Buffer) {
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(Widget_Utils::adornStereo(QStringLiteral("centralBuffer")));
const int namewidth = fm.horizontalAdvance(name());
height = fontHeight * 2;
widthtmp = textWidth > OBJECTNODE_WIDTH ? textWidth : OBJECTNODE_WIDTH;
width = namewidth > widthtmp ? namewidth : widthtmp;
height = height > OBJECTNODE_HEIGHT ? height : OBJECTNODE_HEIGHT;
width += OBJECTNODE_MARGIN * 2;
height += OBJECTNODE_MARGIN * 2 + 5;
} else if (m_objectNodeType == Data) {
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(Widget_Utils::adornStereo(QStringLiteral("datastore")));
const int namewidth = fm.horizontalAdvance(name());
height = fontHeight * 2;
widthtmp = textWidth > OBJECTNODE_WIDTH ? textWidth : OBJECTNODE_WIDTH;
width = namewidth > widthtmp ? namewidth : widthtmp;
height = height > OBJECTNODE_HEIGHT ? height : OBJECTNODE_HEIGHT;
width += OBJECTNODE_MARGIN * 2;
height += OBJECTNODE_MARGIN * 2 + 5;
} else if (m_objectNodeType == Flow) {
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(QLatin1Char('[') + state() + QLatin1Char(']'));
const int namewidth = fm.horizontalAdvance(name());
height = fontHeight * 2;
widthtmp = textWidth > OBJECTNODE_WIDTH ? textWidth : OBJECTNODE_WIDTH;
width = namewidth > widthtmp ? namewidth : widthtmp;
height = height > OBJECTNODE_HEIGHT ? height : OBJECTNODE_HEIGHT;
width += OBJECTNODE_MARGIN * 2;
height += OBJECTNODE_MARGIN * 4;
}
return QSizeF(width, height);
}
/**
* Returns the type of object node.
*/
ObjectNodeWidget::ObjectNodeType ObjectNodeWidget::objectNodeType() const
{
return m_objectNodeType;
}
/**
* Returns the type of object node.
*/
ObjectNodeWidget::ObjectNodeType ObjectNodeWidget::toObjectNodeType(const QString& type)
{
if (type == QStringLiteral("Central buffer"))
return ObjectNodeWidget::Buffer;
if (type == QStringLiteral("Data store"))
return ObjectNodeWidget::Data;
if (type == QStringLiteral("Object Flow"))
return ObjectNodeWidget::Flow;
// Shouldn't happen
Q_ASSERT(0);
return ObjectNodeWidget::Flow;
}
/**
* Sets the type of object node.
*/
void ObjectNodeWidget::setObjectNodeType(ObjectNodeType objectNodeType)
{
m_objectNodeType = objectNodeType;
UMLWidget::m_resizable = true;
}
/**
* Sets the type of object node.
*/
void ObjectNodeWidget::setObjectNodeType(const QString& type)
{
setObjectNodeType(ObjectNodeWidget::toObjectNodeType(type));
}
/**
* Sets the state of an object node when it's an objectflow.
*/
void ObjectNodeWidget::setState(const QString& state)
{
m_state = state;
updateGeometry();
}
/**
* Returns the state of object node.
*/
QString ObjectNodeWidget::state() const
{
return m_state;
}
/**
* Captures any popup menu signals for menus it created.
*/
void ObjectNodeWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString text = name();
bool ok = Dialog_Utils::askName(i18n("Enter Object Node Name"),
i18n("Enter the name of the object node :"),
text);
if (ok && !text.isEmpty()) {
setName(text);
}
}
break;
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Show a properties dialog for an ObjectNodeWidget.
*/
bool ObjectNodeWidget::showPropertiesDialog()
{
UMLApp::app()->docWindow()->updateDocumentation(false);
bool result = false;
QPointer<ObjectNodeDialog> dialog = new ObjectNodeDialog(UMLApp::app()->currentView(), this);
if (dialog->exec() && dialog->getChangesMade()) {
UMLApp::app()->docWindow()->showDocumentation(this, true);
UMLApp::app()->document()->setModified(true);
result = true;
}
delete dialog;
return result;
}
/**
* Saves the widget to the "objectnodewidget" XMI element.
*/
void ObjectNodeWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("objectnodewidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("objectnodename"), m_Text);
writer.writeAttribute(QStringLiteral("documentation"), m_Doc);
writer.writeAttribute(QStringLiteral("objectnodetype"), QString::number(m_objectNodeType));
writer.writeAttribute(QStringLiteral("objectnodestate"), m_state);
writer.writeEndElement();
}
/**
* Loads the widget from the "objectnodewidget" XMI element.
*/
bool ObjectNodeWidget::loadFromXMI(QDomElement& qElement)
{
if(!UMLWidget::loadFromXMI(qElement) )
return false;
m_Text = qElement.attribute(QStringLiteral("objectnodename"));
m_Doc = qElement.attribute(QStringLiteral("documentation"));
QString type = qElement.attribute(QStringLiteral("objectnodetype"), QStringLiteral("1"));
m_state = qElement.attribute(QStringLiteral("objectnodestate"));
setObjectNodeType((ObjectNodeType)type.toInt());
return true;
}
/**
* Open a dialog box to select the objectNode type (Data, Buffer or Flow).
*/
void ObjectNodeWidget::askForObjectNodeType(UMLWidget* &targetWidget)
{
bool pressedOK = false;
int current = 0;
const QStringList list = QStringList()
<< QStringLiteral("Central buffer")
<< QStringLiteral("Data store")
<< QStringLiteral("Object Flow");
QString type = QInputDialog::getItem (UMLApp::app(),
i18n("Select Object node type"), i18n("Select the object node type"),
list, current, false, &pressedOK);
if (pressedOK) {
targetWidget->asObjectNodeWidget()->setObjectNodeType(type);
if (type == QStringLiteral("Data store"))
Dialog_Utils::askNameForWidget(targetWidget, i18n("Enter the name of the data store node"), i18n("Enter the name of the data store node"), i18n("data store name"));
if (type == QStringLiteral("Central buffer"))
Dialog_Utils::askNameForWidget(targetWidget, i18n("Enter the name of the buffer node"), i18n("Enter the name of the buffer"), i18n("centralBuffer"));
if (type == QStringLiteral("Object Flow")) {
Dialog_Utils::askNameForWidget(targetWidget, i18n("Enter the name of the object flow"), i18n("Enter the name of the object flow"), i18n("object flow"));
askStateForWidget();
}
} else {
targetWidget->cleanup();
delete targetWidget;
targetWidget = nullptr;
}
}
/**
* Open a dialog box to input the state of the widget.
* This box is shown only if m_objectNodeType = Flow.
*/
void ObjectNodeWidget::askStateForWidget()
{
QString state = i18n("-");
bool pressedOK = Dialog_Utils::askName(i18n("Enter Object Flow State"),
i18n("Enter State (keep '-' if there is no state for the object) "),
state);
if (pressedOK) {
setState(state);
} else {
cleanup();
}
}
void ObjectNodeWidget::slotOk()
{
// QDialog::accept();
}
| 11,372
|
C++
|
.cpp
| 302
| 31.324503
| 176
| 0.656545
|
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,388
|
componentwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/componentwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "componentwidget.h"
// app includes
#include "component.h"
#include "debug_utils.h"
#include "umlscene.h"
#include "umlview.h"
#include "optionstate.h"
#include "umldoc.h"
#include "package.h"
#include "portwidget.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(ComponentWidget)
/**
* Constructs a ComponentWidget.
*
* @param scene The parent of this ComponentWidget.
* @param c The UMLComponent this will be representing.
*/
ComponentWidget::ComponentWidget(UMLScene * scene, UMLComponent *c)
: UMLWidget(scene, WidgetBase::wt_Component, c)
{
setSize(100, 30);
//set defaults from m_scene
if (m_scene) {
//check to see if correct
const Settings::OptionState& ops = m_scene->optionState();
m_showStereotype = ops.classState.showStereoType;
}
}
/**
* Destructor.
*/
ComponentWidget::~ComponentWidget()
{
}
/**
* Reimplemented from UMLWidget::paint to paint component
* widget.
*/
void ComponentWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
const UMLComponent *umlcomp = m_umlObject->asUMLComponent();
if (umlcomp == nullptr)
return;
setPenFromSettings(painter);
QPen origPen = painter->pen();
QPen pen = origPen;
if (umlcomp->getExecutable()) {
pen.setWidth(origPen.width() + 2);
painter->setPen(pen);
}
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
} else {
painter->setBrush(m_scene->backgroundColor());
}
const int w = width();
const int h = height();
const int halfHeight = h / 2;
int textXOffset = 0;
QFont font = UMLWidget::font();
font.setBold(true);
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
QString nameStr = name();
const QString stereotype = m_umlObject->stereotype();
if (Settings::optionState().generalState.uml2) {
painter->drawRect(0, 0, w, h);
// draw small component symbol in upper right corner
painter->setPen(origPen);
painter->drawRect(w - 17, 5, 11, 13);
painter->drawRect(w - 19, 7, 2, 2);
painter->drawRect(w - 19, 11, 2, 2);
painter->setPen(pen);
} else {
painter->drawRect(2*COMPONENT_MARGIN, 0, w - 2*COMPONENT_MARGIN, h);
painter->drawRect(0, halfHeight - fontHeight/2 - fontHeight, COMPONENT_MARGIN*4, fontHeight);
painter->drawRect(0, halfHeight + fontHeight/2, COMPONENT_MARGIN*4, fontHeight);
textXOffset = COMPONENT_MARGIN * 4;
}
painter->setPen(textColor());
painter->setFont(font);
int lines = 1;
if (!stereotype.isEmpty()) {
painter->drawText(textXOffset, halfHeight - fontHeight,
w - textXOffset, fontHeight, Qt::AlignCenter,
m_umlObject->stereotype(true));
lines = 2;
}
if (UMLWidget::isInstance()) {
font.setUnderline(true);
painter->setFont(font);
nameStr = UMLWidget::instanceName() + QStringLiteral(" : ") + nameStr;
}
if (lines == 1) {
painter->drawText(textXOffset, halfHeight - (fontHeight/2),
w - textXOffset, fontHeight, Qt::AlignCenter, nameStr);
} else {
painter->drawText(textXOffset, halfHeight,
w - textXOffset, fontHeight, Qt::AlignCenter, nameStr);
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overridden from UMLWidget due to emission of signal sigCompMoved()
*/
void ComponentWidget::moveWidgetBy(qreal diffX, qreal diffY)
{
UMLWidget::moveWidgetBy(diffX, diffY);
Q_EMIT sigCompMoved(diffX, diffY);
}
/**
* Override method from UMLWidget for adjustment of attached PortWidgets.
*/
void ComponentWidget::adjustAssocs(qreal dx, qreal dy)
{
if (m_doc->loading()) {
// don't recalculate the assocs during load of XMI
// -> return immediately without action
return;
}
UMLWidget::adjustAssocs(dx, dy);
const UMLPackage *comp = m_umlObject->asUMLPackage();
for(UMLObject *o: comp->containedObjects()) {
uIgnoreZeroPointer(o);
if (o->baseType() != UMLObject::ot_Port)
continue;
UMLWidget *portW = m_scene->widgetOnDiagram(o->id());
if (portW)
portW->adjustAssocs(dx, dy);
}
}
/**
* Override method from UMLWidget for adjustment of attached PortWidgets.
*/
void ComponentWidget::adjustUnselectedAssocs(qreal dx, qreal dy)
{
if (m_doc->loading()) {
// don't recalculate the assocs during load of XMI
// -> return immediately without action
return;
}
UMLWidget::adjustUnselectedAssocs(dx, dy);
const UMLPackage *comp = m_umlObject->asUMLPackage();
for(UMLObject *o : comp->containedObjects()) {
uIgnoreZeroPointer(o);
if (o->baseType() != UMLObject::ot_Port)
continue;
UMLWidget *portW = m_scene->widgetOnDiagram(o->id());
if (portW)
portW->adjustUnselectedAssocs(dx, dy);
}
}
/**
* Saves to the "componentwidget" XMI element.
*/
void ComponentWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("componentwidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Overrides method from UMLWidget.
*/
QSizeF ComponentWidget::minimumSize() const
{
if (!m_umlObject) {
return QSizeF(70, 70);
}
const QFontMetrics &fm = getFontMetrics(FT_BOLD_ITALIC);
const int fontHeight = fm.lineSpacing();
QString name = m_umlObject->name();
if (UMLWidget::isInstance()) {
name = UMLWidget::instanceName() + QStringLiteral(" : ") + name;
}
int width = fm.horizontalAdvance(name);
int stereoWidth = 0;
if (!m_umlObject->stereotype().isEmpty()) {
stereoWidth = fm.horizontalAdvance(m_umlObject->stereotype(true));
}
if (stereoWidth > width)
width = stereoWidth;
width += COMPONENT_MARGIN * 6;
width = 70>width ? 70 : width; //minumin width of 70
int height = (2*fontHeight) + (COMPONENT_MARGIN * 3);
const UMLComponent *umlcomp = m_umlObject->asUMLComponent();
if (umlcomp && umlcomp->getExecutable()) {
width += 2;
height += 2;
}
return QSizeF(width, height);
}
| 6,558
|
C++
|
.cpp
| 201
| 27.378109
| 103
| 0.65824
|
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,389
|
childwidgetplacementpin.cpp
|
KDE_umbrello/umbrello/umlwidgets/childwidgetplacementpin.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlwidgets/childwidgetplacementpin.h"
#include "umlwidgets/umlwidget.h"
ChildWidgetPlacementPin::ChildWidgetPlacementPin(PinPortBase* widget)
: ChildWidgetPlacement(widget)
{
}
ChildWidgetPlacementPin::~ChildWidgetPlacementPin()
{
}
void ChildWidgetPlacementPin::detectConnectedSide()
{
}
void ChildWidgetPlacementPin::setInitialPosition(const QPointF &scenePos)
{
Q_UNUSED(scenePos);
m_connectedSide = Top;
setPos(0, - height() ); // place above parent
}
void ChildWidgetPlacementPin::setNewPositionWhenMoved(qreal diffX, qreal diffY)
{
const qreal newX = x() + diffX;
const qreal newY = y() + diffY;
UMLWidget* owner = ownerWidget();
if (isAboveParent() || isBelowParent()) {
if (newX < 0.0) {
if (- diffX > width()) {
jumpToLeftOfParent();
}
else {
setX(0);
}
}
else if (newX > owner->width() - width()) {
if (diffX > width()) {
jumpToRightOfParent();
}
else {
setX(owner->width() - width());
}
}
else {
setX(newX);
}
}
else if (isLeftOfParent() || isRightOfParent()) {
if (newY < 0.0) {
if (- diffY > height()) {
jumpToTopOfParent();
}
else {
setY(0);
}
}
else if (newY > owner->height() - height()) {
if (diffY > height()) {
jumpToBottomOfParent();
}
else {
setY(owner->height() - height());
}
}
else {
setY(newY);
}
}
else {
// error: client is not attached to parent
jumpToTopOfParent();
}
}
void ChildWidgetPlacementPin::setNewPositionOnParentResize()
{
UMLWidget* owner = ownerWidget();
if (isRightOfParent()) {
setPos(owner->width(), qMin(y(), owner->height() - height()));
}
else if (isBelowParent()) {
setPos(qMin(x(), owner->width() - width()), owner->height());
}
}
bool ChildWidgetPlacementPin::isAboveParent() const
{
return m_connectedSide == Top;
}
bool ChildWidgetPlacementPin::isBelowParent() const
{
return m_connectedSide == Bottom;
}
bool ChildWidgetPlacementPin::isLeftOfParent() const
{
return m_connectedSide == Left;
}
bool ChildWidgetPlacementPin::isRightOfParent() const
{
return m_connectedSide == Right;
}
qreal ChildWidgetPlacementPin::getNewXOnJumpToTopOrBottom() const
{
return isLeftOfParent() ? 0 : ownerWidget()->width() - width();
}
void ChildWidgetPlacementPin::jumpToTopOfParent()
{
setPos(QPointF(getNewXOnJumpToTopOrBottom(), - height()));
m_connectedSide = Top;
}
void ChildWidgetPlacementPin::jumpToBottomOfParent()
{
setPos(QPointF(getNewXOnJumpToTopOrBottom(), ownerWidget()->height()));
m_connectedSide = Bottom;
}
qreal ChildWidgetPlacementPin::getNewYOnJumpToSide() const
{
return isAboveParent() ? 0 : ownerWidget()->height() - height();
}
void ChildWidgetPlacementPin::jumpToLeftOfParent()
{
setPos(QPointF(-width(), getNewYOnJumpToSide()));
m_connectedSide = Left;
}
void ChildWidgetPlacementPin::jumpToRightOfParent()
{
setPos(QPointF(ownerWidget()->width(), getNewYOnJumpToSide()));
m_connectedSide = Right;
}
| 3,537
|
C++
|
.cpp
| 128
| 21.742188
| 92
| 0.627214
|
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,390
|
childwidgetplacement.cpp
|
KDE_umbrello/umbrello/umlwidgets/childwidgetplacement.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlwidgets/childwidgetplacement.h"
#include "umlwidgets/pinportbase.h"
ChildWidgetPlacement::ChildWidgetPlacement(PinPortBase* widget)
: m_widget(widget), m_connectedSide(Top)
{
}
void ChildWidgetPlacement::setPos(const QPointF& pos)
{
m_widget->setPos(pos);
}
void ChildWidgetPlacement::setPos(qreal x, qreal y)
{
m_widget->setPos(x, y);
}
void ChildWidgetPlacement::setX(qreal x)
{
m_widget->setX(x);
}
void ChildWidgetPlacement::setY(qreal y)
{
m_widget->setY(y);
}
qreal ChildWidgetPlacement::x() const
{
return m_widget->x();
}
qreal ChildWidgetPlacement::y() const
{
return m_widget->y();
}
qreal ChildWidgetPlacement::width() const
{
return m_widget->width();
}
qreal ChildWidgetPlacement::height() const
{
return m_widget->height();
}
UMLWidget* ChildWidgetPlacement::ownerWidget() const
{
return m_widget->ownerWidget();
}
| 1,037
|
C++
|
.cpp
| 46
| 20.282609
| 92
| 0.754601
|
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,391
|
pinwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/pinwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "pinwidget.h"
// app includes
#include "debug_utils.h"
#include "dialog_utils.h"
#include "floatingtextwidget.h"
#include "listpopupmenu.h"
#include "umlscene.h"
#include "activitywidget.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPainter>
DEBUG_REGISTER_DISABLED(PinWidget)
/**
* Creates a Pin widget.
*
* @param scene The parent of the widget.
* @param owner The widget to which this pin is attached.
* @param id The ID to assign (-1 will prompt a new ID).
*/
PinWidget::PinWidget(UMLScene* scene, UMLWidget* owner, Uml::ID::Type id)
: PinPortBase(scene, WidgetBase::wt_Pin, owner, id)
{
// setParent(a);
// m_nY = y() < getMinY() ? getMinY() : y();
m_pName = new FloatingTextWidget(m_scene, Uml::TextRole::Floating, name());
m_pName->setParentItem(this);
m_pName->setText(name()); // to get geometry update
m_pName->activate();
setVisible(true);
}
/**
* Destructor.
*/
PinWidget::~PinWidget()
{
}
/**
* Captures any popup menu signals for menus it created.
*/
void PinWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString name = m_Text;
bool ok = Dialog_Utils::askNewName(WidgetBase::wt_Pin, name);
if (ok) {
setName(name);
}
}
break;
default:
PinPortBase::slotMenuSelection(action);
}
}
| 1,680
|
C++
|
.cpp
| 62
| 23.274194
| 92
| 0.670193
|
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,392
|
classifierwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/classifierwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "classifierwidget.h"
// app includes
#include "floatingtextwidget.h"
#include "associationwidget.h"
#include "associationline.h"
#include "classifier.h"
#include "cmds.h"
#include "debug_utils.h"
#include "diagram_utils.h"
#include "dialog_utils.h"
#include "instance.h"
#include "listpopupmenu.h"
#include "object_factory.h"
#include "operation.h"
#include "optionstate.h"
#include "template.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
#include "widget_utils.h"
// qt includes
#include <QPainter>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(ClassifierWidget)
const int ClassifierWidget::CIRCLE_SIZE = 30;
const int ClassifierWidget::SOCKET_INCREMENT = 10;
/**
* Constructs a ClassifierWidget for a UMLClassifier.
*
* @param scene The parent of this ClassifierWidget.
* @param umlc The UMLClassifier to represent.
*/
ClassifierWidget::ClassifierWidget(UMLScene * scene, UMLClassifier *umlc)
: UMLWidget(scene, WidgetBase::wt_Class, umlc),
m_attributeSignature(Uml::SignatureType::NoSigNoVis),
m_operationSignature(Uml::SignatureType::NoSigNoVis),
m_pAssocWidget(nullptr),
m_pInterfaceName(nullptr)
{
DiagramProxyWidget::setShowLinkedDiagram(false);
const Settings::OptionState& ops = m_scene->optionState();
setVisualPropertyCmd(ShowVisibility, ops.classState.showVisibility);
setVisualPropertyCmd(ShowOperations, ops.classState.showOps);
setVisualPropertyCmd(ShowPublicOnly, ops.classState.showPublicOnly);
setVisualPropertyCmd(ShowPackage, ops.classState.showPackage);
m_attributeSignature = Uml::SignatureType::ShowSig;
/*:TODO:
setVisualProperty(ShowOperationSignature, ops.classState.showOpSig);
Cannot do that because we get "pure virtual method called". Open code:
*/
if(!ops.classState.showOpSig) {
if (visualProperty(ShowVisibility))
m_operationSignature = Uml::SignatureType::NoSig;
else
m_operationSignature = Uml::SignatureType::NoSigNoVis;
} else if (visualProperty(ShowVisibility))
m_operationSignature = Uml::SignatureType::ShowSig;
else
m_operationSignature = Uml::SignatureType::SigNoVis;
setVisualPropertyCmd(ShowAttributes, ops.classState.showAtts);
// Do not call setShowStereotype here, it is a virtual method
// and setup of the vtbl_ptr has not yet been finalized.
m_showStereotype = ops.classState.showStereoType;
if (m_showStereotype != Uml::ShowStereoType::None)
m_visualProperties |= ShowStereotype;
setVisualPropertyCmd(DrawAsCircle, false);
setShowAttSigs(ops.classState.showAttSig);
if (umlc && umlc->isInterface()) {
setBaseType(WidgetBase::wt_Interface);
m_visualProperties = ShowOperations | ShowVisibility;
setShowStereotype(Uml::ShowStereoType::Tags);
updateSignatureTypes();
}
}
/**
* Constructs a ClassifierWidget for a UMLInstance.
*
* @param scene The parent of this ClassifierWidget.
* @param umli The UMLInstance to represent.
*/
ClassifierWidget::ClassifierWidget(UMLScene * scene, UMLInstance * umli)
: UMLWidget(scene, WidgetBase::wt_Instance, umli),
m_pAssocWidget(nullptr),
m_pInterfaceName(nullptr)
{
DiagramProxyWidget::setShowLinkedDiagram(false);
const Settings::OptionState& ops = m_scene->optionState();
setVisualPropertyCmd(ShowVisibility, ops.classState.showVisibility);
setVisualPropertyCmd(ShowPublicOnly, ops.classState.showPublicOnly);
setVisualPropertyCmd(ShowPackage, ops.classState.showPackage);
m_attributeSignature = Uml::SignatureType::ShowSig;
setVisualPropertyCmd(ShowAttributes, ops.classState.showAtts);
setShowAttSigs(ops.classState.showAttSig);
if (umli) {
setBaseType(WidgetBase::wt_Instance);
m_visualProperties = ShowAttributes;
updateSignatureTypes();
}
}
/**
* Constructs a ClassifierWidget for a UMLPackage.
*
* @param scene The parent of this ClassifierWidget.
* @param o The UMLPackage to represent.
*/
ClassifierWidget::ClassifierWidget(UMLScene * scene, UMLPackage *o)
: UMLWidget(scene, WidgetBase::wt_Package, o),
m_pAssocWidget(nullptr),
m_pInterfaceName(nullptr)
{
const Settings::OptionState& ops = m_scene->optionState();
setVisualPropertyCmd(ShowVisibility, ops.classState.showVisibility);
setVisualPropertyCmd(ShowOperations, ops.classState.showOps);
setVisualPropertyCmd(ShowPublicOnly, ops.classState.showPublicOnly);
setVisualPropertyCmd(ShowPackage, ops.classState.showPackage);
m_attributeSignature = Uml::SignatureType::ShowSig;
if(!ops.classState.showOpSig) {
if (visualProperty(ShowVisibility))
m_operationSignature = Uml::SignatureType::NoSig;
else
m_operationSignature = Uml::SignatureType::NoSigNoVis;
} else if (visualProperty(ShowVisibility))
m_operationSignature = Uml::SignatureType::ShowSig;
else
m_operationSignature = Uml::SignatureType::SigNoVis;
setVisualPropertyCmd(ShowAttributes, ops.classState.showAtts);
setShowStereotype(ops.classState.showStereoType);
setVisualPropertyCmd(DrawAsPackage, true);
setShowAttSigs(ops.classState.showAttSig);
}
/**
* Destructor.
*/
ClassifierWidget::~ClassifierWidget()
{
if (m_pAssocWidget)
m_pAssocWidget->removeAssocClassLine();
if (m_pInterfaceName) {
delete m_pInterfaceName;
m_pInterfaceName = nullptr;
}
}
/**
* Return the UMLClassifier which this ClassifierWidget
* represents.
*/
UMLClassifier *ClassifierWidget::classifier() const
{
return m_umlObject->asUMLClassifier();
}
/**
* Reimplement method from UMLWidget.
*/
void ClassifierWidget::setShowStereotype(Uml::ShowStereoType::Enum flag)
{
if (flag == Uml::ShowStereoType::None)
m_visualProperties &= ~ShowStereotype;
else
m_visualProperties |= ShowStereotype;
UMLWidget::setShowStereotype(flag);
}
/**
* @return the visual properties
*/
ClassifierWidget::VisualProperties ClassifierWidget::visualProperties() const
{
return m_visualProperties;
}
/**
* Set an OR combination of properties stored in \a properties on this
* widget.
*/
void ClassifierWidget::setVisualProperties(VisualProperties properties)
{
// Don't do anything if the argument is equal to current status.
if (quint32(m_visualProperties) == quint32(properties)) {
return;
}
m_visualProperties = properties;
updateSignatureTypes();
}
/**
* @return The status of the property passed in.
*
* @note Use @ref attributeSignature() and @ref
* operationSignature() to get signature status. This
* method only indicates whether signature is visible or not.
*/
bool ClassifierWidget::visualProperty(VisualProperty property) const
{
if (property == ShowAttributeSignature) {
return (m_attributeSignature == Uml::SignatureType::ShowSig
|| m_attributeSignature == Uml::SignatureType::SigNoVis);
}
else if (property == ShowOperationSignature) {
return (m_operationSignature == Uml::SignatureType::ShowSig
|| m_operationSignature == Uml::SignatureType::SigNoVis);
}
else if (property == ShowStereotype) {
return (m_showStereotype != Uml::ShowStereoType::None);
}
return m_visualProperties.testFlag(property);
}
/**
* A convenient method to set and reset individual VisualProperty
*
* Undo command.
*
* @param property The property to be set/reset.
* @param enable True/false to set/reset. (default = true)
*
* @note This method handles ShowAttributeSignature and
* ShowOperationSignature specially.
*/
void ClassifierWidget::setVisualProperty(VisualProperty property, bool enable)
{
if (visualProperty(property) != enable) {
UMLApp::app()->executeCommand(new Uml::CmdChangeVisualProperty(this, property, enable));
}
}
/**
* A convenient method to set and reset individual VisualProperty
*
* @param property The property to be set/reset.
* @param enable True/false to set/reset. (default = true)
*
* @note This method handles ShowAttributeSignature and
* ShowOperationSignature specially.
*/
void ClassifierWidget::setVisualPropertyCmd(VisualProperty property, bool enable)
{
// Handle ShowAttributeSignature and ShowOperationSignature
// specially.
if (property == ShowAttributeSignature) {
if (!enable) {
m_attributeSignature = visualProperty(ShowVisibility) ?
Uml::SignatureType::NoSig : Uml::SignatureType::NoSigNoVis;
} else {
m_attributeSignature = visualProperty(ShowVisibility) ?
Uml::SignatureType::ShowSig : Uml::SignatureType::SigNoVis;
}
//:TODO: updateTextItemGroups();
updateSignatureTypes();
}
else if (property == ShowOperationSignature) {
if (!enable) {
m_operationSignature = visualProperty(ShowVisibility) ?
Uml::SignatureType::NoSig : Uml::SignatureType::NoSigNoVis;
} else {
m_operationSignature = visualProperty(ShowVisibility) ?
Uml::SignatureType::ShowSig : Uml::SignatureType::SigNoVis;
}
//:TODO: updateTextItemGroups();
updateSignatureTypes();
}
else if (property == ShowStereotype) {
setShowStereotype(enable ? Uml::ShowStereoType::Tags
: Uml::ShowStereoType::None);
}
else if (property == DrawAsCircle) {
// Don't do anything if the flag status is same.
if (visualProperty(property) == enable)
return;
if (enable) {
m_visualProperties |= property;
} else {
m_visualProperties &= ~property;
}
setDrawAsCircle(enable);
}
// Some other flag.
else {
// Don't do anything if the flag status is same.
if (visualProperty(property) == enable) {
return;
}
// Call setVisualProperties appropriately based on enable.
if (enable) {
setVisualProperties(visualProperties() | property);
} else {
setVisualProperties(visualProperties() & ~property);
}
}
}
/**
* A convenient method to toggle individual VisualProperty of this
* widget.
*
* @param property The property to be toggled.
*
* @note This method handles ShowAttributeSignature and
* ShowOperationSignature specially.
*/
void ClassifierWidget::toggleVisualProperty(VisualProperty property)
{
bool oppositeStatus;
if (property == ShowOperationSignature) {
oppositeStatus = !(m_operationSignature == Uml::SignatureType::ShowSig
|| m_operationSignature == Uml::SignatureType::SigNoVis);
}
else if (property == ShowAttributeSignature) {
oppositeStatus = !(m_attributeSignature == Uml::SignatureType::ShowSig
|| m_attributeSignature == Uml::SignatureType::SigNoVis);
}
else {
oppositeStatus = !visualProperty(property);
}
logDebug2("ClassifierWidget::toggleVisualProperty property: %1 to opposite status: %2",
property, oppositeStatus);
setVisualProperty(property, oppositeStatus);
}
/**
* Updates m_operationSignature to match m_showVisibility.
*/
void ClassifierWidget::updateSignatureTypes()
{
//turn on scope
if (visualProperty(ShowVisibility)) {
if (m_operationSignature == Uml::SignatureType::NoSigNoVis) {
m_operationSignature = Uml::SignatureType::NoSig;
} else if (m_operationSignature == Uml::SignatureType::SigNoVis) {
m_operationSignature = Uml::SignatureType::ShowSig;
}
}
//turn off scope
else {
if (m_operationSignature == Uml::SignatureType::ShowSig) {
m_operationSignature = Uml::SignatureType::SigNoVis;
} else if (m_operationSignature == Uml::SignatureType::NoSig) {
m_operationSignature = Uml::SignatureType::NoSigNoVis;
}
}
if (visualProperty(ShowVisibility)) {
if (m_attributeSignature == Uml::SignatureType::NoSigNoVis)
m_attributeSignature = Uml::SignatureType::NoSig;
else if (m_attributeSignature == Uml::SignatureType::SigNoVis)
m_attributeSignature = Uml::SignatureType::ShowSig;
} else {
if (m_attributeSignature == Uml::SignatureType::ShowSig)
m_attributeSignature = Uml::SignatureType::SigNoVis;
else if(m_attributeSignature == Uml::SignatureType::NoSig)
m_attributeSignature = Uml::SignatureType::NoSigNoVis;
}
updateGeometry();
update();
}
/**
* Returns whether to show attribute signatures.
* Only applies when m_umlObject->getBaseType() is ot_Class.
*
* @return Status of how attribute signatures are shown.
*/
Uml::SignatureType::Enum ClassifierWidget::attributeSignature() const
{
return m_attributeSignature;
}
/**
* Sets the type of signature to display for an attribute.
* Only applies when m_umlObject->getBaseType() is ot_Class.
*
* @param sig Type of signature to display for an attribute.
*/
void ClassifierWidget::setAttributeSignature(Uml::SignatureType::Enum sig)
{
m_attributeSignature = sig;
updateSignatureTypes();
updateGeometry();
update();
}
/**
* @return The Uml::SignatureType::Enum value for the operations.
*/
Uml::SignatureType::Enum ClassifierWidget::operationSignature() const
{
return m_operationSignature;
}
/**
* Set the type of signature to display for an Operation
*
* @param sig Type of signature to display for an operation.
*/
void ClassifierWidget::setOperationSignature(Uml::SignatureType::Enum sig)
{
m_operationSignature = sig;
updateSignatureTypes();
updateGeometry();
update();
}
/**
* Sets whether to show attribute signature
* Only applies when m_umlObject->getBaseType() is ot_Class.
*
* @param _status True if attribute signatures shall be shown.
*/
void ClassifierWidget::setShowAttSigs(bool _status)
{
if(!_status) {
if (visualProperty(ShowVisibility))
m_attributeSignature = Uml::SignatureType::NoSig;
else
m_attributeSignature = Uml::SignatureType::NoSigNoVis;
}
else if (visualProperty(ShowVisibility))
m_attributeSignature = Uml::SignatureType::ShowSig;
else
m_attributeSignature = Uml::SignatureType::SigNoVis;
if (UMLApp::app()->document()->loading())
return;
updateGeometry();
update();
}
/**
* Toggles whether to show attribute signatures.
* Only applies when m_umlObject->getBaseType() is ot_Class.
*/
void ClassifierWidget::toggleShowAttSigs()
{
if (m_attributeSignature == Uml::SignatureType::ShowSig ||
m_attributeSignature == Uml::SignatureType::SigNoVis) {
if (visualProperty(ShowVisibility)) {
m_attributeSignature = Uml::SignatureType::NoSig;
} else {
m_attributeSignature = Uml::SignatureType::NoSigNoVis;
}
} else if (visualProperty(ShowVisibility)) {
m_attributeSignature = Uml::SignatureType::ShowSig;
} else {
m_attributeSignature = Uml::SignatureType::SigNoVis;
}
updateGeometry();
update();
}
/**
* Return the number of displayed members of the given ObjectType.
* Takes into consideration m_showPublicOnly but not other settings.
*/
int ClassifierWidget::displayedMembers(UMLObject::ObjectType ot) const
{
int count = 0;
UMLClassifier *umlc = this->classifier();
if (!umlc && m_umlObject && m_umlObject->isUMLInstance() && ot == UMLObject::ot_Attribute)
umlc = m_umlObject->asUMLInstance()->classifier();
if (!umlc)
return count;
UMLClassifierListItemList list = umlc->getFilteredList(ot);
for(UMLClassifierListItem *m : list) {
if (!(visualProperty(ShowPublicOnly) && m->visibility() != Uml::Visibility::Public))
count++;
}
return count;
}
/**
* Overrides method from UMLWidget.
*/
QSizeF ClassifierWidget::minimumSize() const
{
return calculateSize();
}
/**
* Calculate content related size of widget.
* Overrides method from UMLWidget.
*/
QSizeF ClassifierWidget::calculateSize(bool withExtensions /* = true */) const
{
if (!m_umlObject) {
return UMLWidget::minimumSize();
}
if (m_umlObject->baseType() == UMLObject::ot_Package) {
return calculateAsPackageSize();
}
UMLClassifier *umlc = this->classifier();
if (umlc) {
if (umlc->isInterface() && visualProperty(DrawAsCircle))
return calculateAsCircleSize();
} else if (m_umlObject && m_umlObject->isUMLInstance()) {
umlc = m_umlObject->asUMLInstance()->classifier();
}
const bool showNameOnly = !visualProperty(ShowAttributes) &&
!visualProperty(ShowOperations) &&
!visualProperty(ShowDocumentation);
const QFontMetrics &fm = getFontMetrics(UMLWidget::FT_NORMAL);
const int fontHeight = fm.lineSpacing();
// width is the width of the longest 'word'
int width = 0, height = 0;
// consider stereotype
if (m_showStereotype != Uml::ShowStereoType::None &&
m_umlObject && !m_umlObject->stereotype().isEmpty()) {
height += fontHeight;
QString taggedValues;
if (m_showStereotype == Uml::ShowStereoType::Tags) {
taggedValues = tags();
if (!taggedValues.isEmpty())
height += fontHeight;
}
// ... width
const QFontMetrics &bfm = UMLWidget::getFontMetrics(UMLWidget::FT_BOLD);
const int stereoWidth = bfm.size(0, m_umlObject->stereotype(true)).width();
if (stereoWidth > width)
width = stereoWidth;
if (!taggedValues.isEmpty()) {
const int tagsWidth = bfm.size(0, taggedValues).width();
if (tagsWidth > width)
width = tagsWidth;
}
} else if (showNameOnly) {
height += defaultMargin;
}
// consider name
height += fontHeight;
// ... width
QString name;
UMLObject *o;
if (m_umlObject && m_umlObject->isUMLInstance() && umlc)
o = umlc;
else
o = m_umlObject;
if (!o)
name = m_Text;
else if (visualProperty(ShowPackage))
name = o->fullyQualifiedName();
else
name = o->name();
QString displayedName;
if (m_umlObject && m_umlObject->isUMLInstance())
displayedName = m_umlObject->name() + QStringLiteral(" : ") + name;
else
displayedName = name;
const UMLWidget::FontType nft = (m_umlObject && m_umlObject->isAbstract() ? FT_BOLD_ITALIC : FT_BOLD);
const int nameWidth = UMLWidget::getFontMetrics(nft).size(0, displayedName).width();
if (nameWidth > width)
width = nameWidth;
#ifdef ENABLE_WIDGET_SHOW_DOC
// consider documentation
if (visualProperty(ShowDocumentation)) {
if (!documentation().isEmpty()) {
QRect brect = fm.boundingRect(QRect(0, 0, this->width()-2*defaultMargin, this->height()-height), Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, documentation());
height += brect.height();
if (!visualProperty(ShowOperations) && !visualProperty(ShowAttributes)) {
if (brect.width() >= width)
width = brect.width();
}
}
else
height += fontHeight / 2;
}
#endif
// consider attributes
if (visualProperty(ShowAttributes)) {
const int numAtts = displayedAttributes();
if (numAtts > 0) {
height += fontHeight * numAtts;
// calculate width of the attributes
UMLClassifierListItemList list = umlc->getFilteredList(UMLObject::ot_Attribute);
for(UMLClassifierListItem *a : list) {
if (visualProperty(ShowPublicOnly) && a->visibility() != Uml::Visibility::Public)
continue;
const int attWidth = fm.size(0, a->toString(m_attributeSignature, visualProperty(ShowStereotype))).width();
if (attWidth > width)
width = attWidth;
}
}
else
height += fontHeight / 2;
}
// consider operations
if (visualProperty(ShowOperations)) {
const int numOps = displayedOperations();
if (numOps > 0) {
height += numOps * fontHeight;
// ... width
UMLOperationList list(umlc->getOpList());
for(UMLOperation* op : list) {
if (visualProperty(ShowPublicOnly) && op->visibility() != Uml::Visibility::Public)
continue;
const QString displayedOp = op->toString(m_operationSignature, visualProperty(ShowStereotype));
UMLWidget::FontType oft;
oft = (op->isAbstract() ? UMLWidget::FT_ITALIC : UMLWidget::FT_NORMAL);
const int w = UMLWidget::getFontMetrics(oft).size(0, displayedOp).width();
if (w > width)
width = w;
}
}
else
height += fontHeight / 2;
}
if (withExtensions) {
// consider template box _as last_ !
QSize templatesBoxSize = calculateTemplatesBoxSize();
if (templatesBoxSize.width() != 0) {
// add width to largest 'word'
width += templatesBoxSize.width() / 2;
}
if (templatesBoxSize.height() != 0) {
height += templatesBoxSize.height() - defaultMargin;
}
}
// allow for height margin
if (showNameOnly) {
height += defaultMargin;
}
// allow for width margin
width += defaultMargin * 2;
if (DiagramProxyWidget::linkedDiagram() || DiagramProxyWidget::diagramLink() != Uml::ID::None)
width += 2 * DiagramProxyWidget::iconRect().width();
logDebug5("ClassifierWidget::calculateSize(%1) : "
"rectWidth %2, rectHeight %3 ; calcWidth %4, calcHeight %5",
name, this->width(), this->height(), width, height);
return QSizeF(width, height);
}
/**
* Calculcates the size of the templates box in the top left
* if it exists, returns QSize(0, 0) if it doesn't.
*
* @return QSize of the templates flap.
*/
QSize ClassifierWidget::calculateTemplatesBoxSize() const
{
if (!classifier())
return QSize(0, 0);
UMLTemplateList list = classifier()->getTemplateList();
int count = list.count();
if (count == 0) {
return QSize(0, 0);
}
QFont font = UMLWidget::font();
font.setItalic(false);
font.setUnderline(false);
font.setBold(false);
const QFontMetrics fm(font);
int width = 0;
int height = count * fm.lineSpacing() + (defaultMargin*2);
for(UMLTemplate *t : list) {
int textWidth = fm.size(0, t->toString(Uml::SignatureType::NoSig, visualProperty(ShowStereotype))).width();
if (textWidth > width)
width = textWidth;
}
width += (defaultMargin*2);
return QSize(width, height);
}
/**
* Return the number of displayed attributes.
*/
int ClassifierWidget::displayedAttributes() const
{
if (!visualProperty(ShowAttributes))
return 0;
return displayedMembers(UMLObject::ot_Attribute);
}
/**
* Return the number of displayed operations.
*/
int ClassifierWidget::displayedOperations() const
{
if (!visualProperty(ShowOperations))
return 0;
return displayedMembers(UMLObject::ot_Operation);
}
/**
* Set the AssociationWidget when this ClassWidget acts as
* an association class.
*/
void ClassifierWidget::setClassAssociationWidget(AssociationWidget *assocwidget)
{
if (!classifier()) {
logError0("ClassifierWidget::setClassAssociationWidget: "
"Class association cannot be applied to non classifier");
return;
}
m_pAssocWidget = assocwidget;
}
/**
* Return the AssociationWidget when this classifier acts as
* an association class (else return NULL.)
*/
AssociationWidget *ClassifierWidget::classAssociationWidget() const
{
return m_pAssocWidget;
}
/**
* Overrides standard method.
* Auxiliary to reimplementations in the derived classes.
* @note keep fetching attributes in sync with calculateSize()
*/
void ClassifierWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
if (UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
else {
painter->setBrush(m_scene->backgroundColor());
}
if (m_umlObject->baseType() == UMLObject::ot_Package) {
drawAsPackage(painter, option);
UMLWidget::paint(painter, option, widget);
return;
}
UMLClassifier *umlc = this->classifier();
if (!umlc) {
if (m_umlObject && m_umlObject->isUMLInstance()) {
umlc = m_umlObject->asUMLInstance()->classifier();
} else {
logError0("ClassifierWidget::paint internal error - classifier() returns null");
return;
}
}
if (umlc && umlc->isInterface() && visualProperty(DrawAsCircle)) {
drawAsCircle(painter, option);
UMLWidget::paint(painter, option, widget);
return;
}
// Draw the bounding rectangle
QSize templatesBoxSize = calculateTemplatesBoxSize();
int bodyOffsetY = 0;
if (templatesBoxSize.height() > 0)
bodyOffsetY += templatesBoxSize.height() - defaultMargin;
int w = width();
if (templatesBoxSize.width() > 0)
w -= templatesBoxSize.width() / 2;
int h = height();
if (templatesBoxSize.height() > 0)
h -= templatesBoxSize.height() - defaultMargin;
painter->drawRect(0, bodyOffsetY, w, h);
QFont font = UMLWidget::font();
font.setUnderline(false);
font.setItalic(false);
const QFontMetrics &fm = UMLWidget::getFontMetrics(UMLWidget::FT_NORMAL);
const int fontHeight = fm.lineSpacing();
//If there are any templates then draw them
UMLTemplateList tlist;
if (umlc)
tlist = umlc->getTemplateList();
if (tlist.count() > 0) {
setPenFromSettings(painter);
QPen pen = painter->pen();
pen.setStyle(Qt::DotLine);
painter->setPen(pen);
painter->drawRect(width() - templatesBoxSize.width(), 0,
templatesBoxSize.width(), templatesBoxSize.height());
painter->setPen(QPen(textColor()));
font.setBold(false);
painter->setFont(font);
const int x = width() - templatesBoxSize.width() + defaultMargin;
int y = defaultMargin;
const int templateWidth = templatesBoxSize.width() - 2 * defaultMargin;
for(UMLTemplate *t : tlist) {
QString text = t->toString(Uml::SignatureType::NoSig, m_showStereotype != Uml::ShowStereoType::None);
painter->drawText(x, y, templateWidth, fontHeight, Qt::AlignVCenter, text);
y += fontHeight;
}
}
const int textX = defaultMargin;
const int textWidth = w - defaultMargin * 2;
painter->setPen(QPen(textColor()));
// draw stereotype
font.setBold(true);
const bool showNameOnly = !visualProperty(ShowAttributes) &&
!visualProperty(ShowOperations) &&
!visualProperty(ShowDocumentation);
int nameHeight = fontHeight;
if (m_showStereotype != Uml::ShowStereoType::None && !m_umlObject->stereotype().isEmpty()) {
painter->setFont(font);
painter->drawText(textX, bodyOffsetY, textWidth, fontHeight, Qt::AlignCenter, m_umlObject->stereotype(true));
bodyOffsetY += fontHeight;
if (m_showStereotype == Uml::ShowStereoType::Tags) {
QString taggedValues = tags();
if (!taggedValues.isEmpty()) {
painter->drawText(textX, bodyOffsetY, textWidth, fontHeight, Qt::AlignCenter, taggedValues);
bodyOffsetY += fontHeight;
}
}
} else if (showNameOnly) {
nameHeight = h;
}
// draw name
QString displayedName;
if (!m_umlObject) {
displayedName = m_Text;
} else if (m_umlObject->isUMLInstance()) {
displayedName = m_umlObject->name() + QStringLiteral(" : ");
if (umlc) {
if (visualProperty(ShowPackage))
displayedName.append(umlc->fullyQualifiedName());
else
displayedName.append(umlc->name());
}
} else if (visualProperty(ShowPackage)) {
displayedName = m_umlObject->fullyQualifiedName();
} else {
displayedName = m_umlObject->name();
}
if (baseType() == WidgetBase::wt_Object || baseType() == WidgetBase::wt_Instance)
font.setUnderline(true);
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
painter->drawText(textX, bodyOffsetY, textWidth, nameHeight, Qt::AlignCenter, displayedName);
bodyOffsetY += fontHeight;
font.setBold(false);
font.setItalic(false);
font.setUnderline(false);
painter->setFont(font);
#ifdef ENABLE_WIDGET_SHOW_DOC
// draw documentation
if (visualProperty(ShowDocumentation)) {
setPenFromSettings(painter);
painter->drawLine(0, bodyOffsetY, w, bodyOffsetY);
painter->setPen(textColor());
if (!documentation().isEmpty()) {
QRect brect = fm.boundingRect(QRect(0, 0, w-2*defaultMargin, h-bodyOffsetY), Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, documentation());
if (brect.width() > width() + 2*defaultMargin)
brect.setWidth(width()-2*defaultMargin);
brect.adjust(textX, bodyOffsetY, textX, bodyOffsetY);
painter->drawText(brect, Qt::AlignLeft | Qt::TextWordWrap, documentation());
bodyOffsetY += brect.height();
}
else
bodyOffsetY += fontHeight / 2;
}
#endif
// draw attributes
if (visualProperty(ShowAttributes)) {
// draw dividing line between doc/name and attributes
setPenFromSettings(painter);
painter->drawLine(0, bodyOffsetY, w, bodyOffsetY);
painter->setPen(textColor());
const int numAtts = displayedAttributes();
if (numAtts > 0) {
drawMembers(painter, UMLObject::ot_Attribute, m_attributeSignature, textX,
bodyOffsetY, textWidth, fontHeight);
bodyOffsetY += fontHeight * numAtts;
}
else
bodyOffsetY += fontHeight / 2;
}
// draw operations
if (visualProperty(ShowOperations)) {
// draw dividing line between attributes and operations
setPenFromSettings(painter);
painter->drawLine(0, bodyOffsetY, w, bodyOffsetY);
painter->setPen(QPen(textColor()));
const int numOps = displayedOperations();
if (numOps >= 0) {
drawMembers(painter, UMLObject::ot_Operation, m_operationSignature, textX,
bodyOffsetY, textWidth, fontHeight);
}
}
if (DiagramProxyWidget::linkedDiagram()) {
DiagramProxyWidget::paint(painter, option, widget);
}
UMLWidget::paint(painter, option, widget);
}
/**
* @return The shape of the ClassifierWidget.
*/
QPainterPath ClassifierWidget::shape() const
{
QPainterPath path;
if (classifier() && classifier()->isInterface() && visualProperty(DrawAsCircle)) {
path.addEllipse(QRectF(QPointF(), calculateAsCircleSize()));
return path;
}
QSizeF mainSize = rect().size();
QSize templatesBoxSize = calculateTemplatesBoxSize();
qreal mainY = 0.0;
if (templatesBoxSize.height() > 0) {
mainY += templatesBoxSize.height() - defaultMargin;
path.addRect(QRectF(mainSize.width() - templatesBoxSize.width() / 2, 0.0,
templatesBoxSize.width(), templatesBoxSize.height()));
}
path.addRect(QRectF(0.0, mainY, mainSize.width(), mainSize.height()));
return path;
}
/**
* Draws the interface as a circle.
* Only applies when m_umlObject->getBaseType() is ot_Interface.
*/
void ClassifierWidget::drawAsCircle(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
Q_UNUSED(option);
const int w = width();
bool showProvider = associationWidgetList().size() == 0;
bool showRequired = false;
AssociationWidgetList requiredAssocs;
for(AssociationWidget *aw : associationWidgetList()) {
const Uml::AssociationType::Enum aType = aw->associationType();
UMLWidget *otherEnd = aw->widgetForRole(Uml::RoleType::A);
UMLWidget *thisEnd = aw->widgetForRole(Uml::RoleType::B);
if (aType == Uml::AssociationType::UniAssociation ||
aType == Uml::AssociationType::Association) {
if (otherEnd->baseType() == WidgetBase::wt_Component ||
otherEnd->baseType() == WidgetBase::wt_Port) // provider
showProvider = true;
else if (thisEnd->baseType() == WidgetBase::wt_Component ||
thisEnd->baseType() == WidgetBase::wt_Port) {
showRequired = true;
requiredAssocs.push_back(aw);
}
}
}
if (showProvider || !showRequired)
painter->drawEllipse(w/2 - CIRCLE_SIZE/2, SOCKET_INCREMENT / 2, CIRCLE_SIZE, CIRCLE_SIZE);
if (showRequired) {
// Draw socket for required interface.
const qreal angleSpan = 180; // 360.0 / (m_Assocs.size() + 1.0);
const int arcDiameter = CIRCLE_SIZE + SOCKET_INCREMENT;
QRect requireArc(w/2 - arcDiameter/2, 0, arcDiameter, arcDiameter);
const QPointF center(x() + w/2, y() + arcDiameter/2);
const qreal cX = center.x();
const qreal cY = center.y();
for(AssociationWidget *aw : requiredAssocs) {
const AssociationLine& assocLine = aw->associationLine();
const QPointF p(assocLine.endPoint());
const qreal tolerance = 18.0;
bool drawArc = true;
qreal midAngle;
if (p.x() < cX - tolerance) {
if (p.y() < cY - tolerance)
midAngle = 135;
else if (p.y() > cY + tolerance)
midAngle = 225;
else
midAngle = 180;
} else if (p.x() > cX + tolerance) {
if (p.y() < cY - tolerance)
midAngle = 45;
else if (p.y() > cY + tolerance)
midAngle = 315;
else
midAngle = 0;
} else {
if (p.y() < cY - tolerance)
midAngle = 90;
else if (p.y() > cY + tolerance)
midAngle = 270;
else
drawArc = false;
}
if (drawArc) {
// uDebug() << "number of assocs: " << m_Assocs.size()
// << ", p: " << p << ", center: " << center
// << ", midAngle: " << midAngle << ", angleSpan: " << angleSpan;
painter->drawArc(requireArc, 16 * (midAngle - angleSpan/2), 16 * angleSpan);
} else {
logError4("ClassifierWidget::drawAsCircle socket: assocLine endPoint (%1,%2) is "
"too close to own center (%3,%4)", p.x(), p.y(), cX, cY);
}
}
}
}
/**
* Calculates the size of the object when drawn as a circle.
* Only applies when m_umlObject->getBaseType() is ot_Interface.
*/
QSize ClassifierWidget::calculateAsCircleSize() const
{
int circleSize = CIRCLE_SIZE;
circleSize += SOCKET_INCREMENT;
return QSize(circleSize, circleSize);
}
void ClassifierWidget::drawAsPackage(QPainter *painter, const QStyleOptionGraphicsItem *option)
{
Q_UNUSED(option);
int w = width();
int h = height();
QFont font = UMLWidget::font();
font.setBold(true);
//FIXME italic is true when a package is first created until you click elsewhere, not sure why
font.setItalic(false);
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
painter->drawRect(0, 0, 50, fontHeight);
if (m_umlObject->stereotype() == QStringLiteral("subsystem")) {
const int fHalf = fontHeight / 2;
const int symY = fHalf;
const int symX = 38;
painter->drawLine(symX, symY, symX, symY + fHalf - 2); // left leg
painter->drawLine(symX + 8, symY, symX + 8, symY + fHalf - 2); // right leg
painter->drawLine(symX, symY, symX + 8, symY); // waist
painter->drawLine(symX + 4, symY, symX + 4, symY - fHalf + 2); // head
}
painter->drawRect(0, fontHeight - 1, w, h - fontHeight);
painter->setPen(textColor());
painter->setFont(font);
int lines = 1;
QString stereotype = m_umlObject->stereotype();
if (!stereotype.isEmpty()) {
painter->drawText(0, fontHeight + defaultMargin,
w, fontHeight, Qt::AlignCenter, m_umlObject->stereotype(true));
lines = 2;
}
painter->drawText(0, (fontHeight*lines) + defaultMargin,
w, fontHeight, Qt::AlignCenter, name());
}
QSize ClassifierWidget::calculateAsPackageSize() const
{
const QFontMetrics &fm = getFontMetrics(FT_BOLD_ITALIC);
const int fontHeight = fm.lineSpacing();
int lines = 1;
int width = fm.horizontalAdvance(m_umlObject->name());
int tempWidth = 0;
if (!m_umlObject->stereotype().isEmpty()) {
tempWidth = fm.horizontalAdvance(m_umlObject->stereotype(true));
lines = 2;
}
if (tempWidth > width)
width = tempWidth;
width += defaultMargin * 2;
if (width < 70)
width = 70; // minumin width of 70
int height = (lines*fontHeight) + fontHeight + (defaultMargin * 2);
return QSize(width, height);
}
/**
* Auxiliary method for draw() of child classes:
* Draw the attributes or operations.
*
* @param painter QPainter to paint to.
* @param ot Object type to draw, either ot_Attribute or ot_Operation.
* @param sigType Governs details of the member display.
* @param x X coordinate at which to draw the texts.
* @param y Y coordinate at which text drawing commences.
* @param width The text width.
* @param height The text height.
*/
void ClassifierWidget::drawMembers(QPainter * painter,
UMLObject::ObjectType ot,
Uml::SignatureType::Enum sigType,
int x, int y, int width, int height)
{
UMLClassifier *umlc = classifier();
const bool drawInstanceAttributes = (!umlc && m_umlObject && m_umlObject->isUMLInstance()
&& ot == UMLObject::ot_Attribute);
if (!umlc && !drawInstanceAttributes) {
return;
}
QFont f = UMLWidget::font();
f.setBold(false);
painter->setClipping(true);
painter->setClipRect(rect());
UMLObjectList ialist;
if (drawInstanceAttributes) {
UMLInstance *umlinst = m_umlObject->asUMLInstance();
umlc = umlinst->classifier();
ialist = umlinst->subordinates();
}
UMLClassifierListItemList list = umlc->getFilteredList(ot);
for (int i = 0; i < list.count(); i++) {
UMLClassifierListItem *obj = list.at(i);
uIgnoreZeroPointer(obj);
if (visualProperty(ShowPublicOnly) && obj->visibility() != Uml::Visibility::Public)
continue;
QString text;
if (drawInstanceAttributes) {
UMLInstanceAttribute *iatt = ialist.at(i)->asUMLInstanceAttribute();
if (!iatt) {
logDebug1("ClassifierWidget::drawMembers(%1) : skipping non InstanceAttribute subordinate",
obj->name());
continue;
}
/* CHECK: Do we want visibility indication on instance attributes?
if (sigType == Uml::SignatureType::ShowSig || sigType == Uml::SignatureType::NoSig)
text = Uml::Visibility::toString(iatt->visibility(), true) + QLatin1Char(' ');
*/
text.append(iatt->toString());
} else {
text = obj->toString(sigType, visualProperty(ShowStereotype));
}
f.setItalic(obj->isAbstract());
f.setUnderline(obj->isStatic());
painter->setFont(f);
painter->drawText(x, y, width, height, Qt::AlignVCenter, text);
f.setItalic(false);
f.setUnderline(false);
painter->setFont(f);
y += height;
}
painter->setClipping(false);
}
/**
* Override method from UMLWidget in order to additionally check m_pInterfaceName.
*
* @param p Point to be checked.
*
* @return 'this' if UMLWidget::onWidget(p) returns non 0;
* m_pInterfaceName if m_pName is non NULL and
* m_pInterfaceName->onWidget(p) returns non 0; else NULL.
*/
UMLWidget* ClassifierWidget::onWidget(const QPointF &p)
{
if (UMLWidget::onWidget(p) != nullptr)
return this;
if (getDrawAsCircle() && m_pInterfaceName) {
logDebug1("ClassifierWidget::onWidget: floatingtext %1", m_pInterfaceName->text());
return m_pInterfaceName->onWidget(p);
}
return nullptr;
}
/**
* Reimplement function from UMLWidget.
*/
UMLWidget* ClassifierWidget::widgetWithID(Uml::ID::Type id)
{
if (UMLWidget::widgetWithID(id))
return this;
if (getDrawAsCircle() && m_pInterfaceName && m_pInterfaceName->widgetWithID(id))
return m_pInterfaceName;
return nullptr;
}
void ClassifierWidget::setDocumentation(const QString &doc)
{
WidgetBase::setDocumentation(doc);
updateGeometry();
}
/**
* Sets whether to draw as circle.
* Only applies when m_umlObject->getBaseType() is ot_Interface.
*
* @param drawAsCircle True if widget shall be drawn as circle.
*/
void ClassifierWidget::setDrawAsCircle(bool drawAsCircle)
{
setVisualPropertyCmd(DrawAsCircle, drawAsCircle);
const int circleSize = CIRCLE_SIZE + SOCKET_INCREMENT;
if (drawAsCircle) {
setX(x() + (width()/2 - circleSize/2));
setY(y() + (height()/2 - circleSize/2));
setSize(circleSize, circleSize);
if (m_pInterfaceName) {
m_pInterfaceName->show();
} else {
m_pInterfaceName = new FloatingTextWidget(m_scene, Uml::TextRole::Floating, name());
m_pInterfaceName->setParentItem(this);
m_pInterfaceName->setText(name()); // to get geometry update
m_pInterfaceName->setX(circleSize/2 - m_pInterfaceName->width() / 2);
m_pInterfaceName->setY(circleSize + SOCKET_INCREMENT);
}
m_resizable = false;
} else {
setSize(ClassifierWidget::minimumSize());
setX(x() - (width()/2 - circleSize/2));
setY(y() - (height()/2 - circleSize/2));
if (m_pInterfaceName)
m_pInterfaceName->hide();
m_resizable = true;
}
setChangesShape(drawAsCircle);
updateGeometry();
update();
}
/**
* Returns whether to draw as circle.
* Only applies when m_umlObject->getBaseType() is ot_Interface.
*
* @return True if widget is drawn as circle.
*/
bool ClassifierWidget::getDrawAsCircle() const
{
return visualProperty(DrawAsCircle);
}
/**
* Toggles whether to draw as circle.
* Only applies when m_umlObject->getBaseType() is ot_Interface.
*/
void ClassifierWidget::toggleDrawAsCircle()
{
toggleVisualProperty(DrawAsCircle);
updateSignatureTypes();
updateGeometry();
update();
}
/**
* Changes this classifier from an interface to a class.
* Attributes and stereotype visibility is got from the view OptionState.
* This widget is also updated.
*/
void ClassifierWidget::changeToClass()
{
setBaseType(WidgetBase::wt_Class);
m_umlObject->setBaseType(UMLObject::ot_Class);
setVisualPropertyCmd(DrawAsCircle, false);
const Settings::OptionState& ops = m_scene->optionState();
setVisualProperty(ShowAttributes, ops.classState.showAtts);
setShowStereotype(ops.classState.showStereoType);
updateGeometry();
update();
}
/**
* Changes this classifier from a class to an interface.
* Attributes are hidden and stereotype is shown.
* This widget is also updated.
*/
void ClassifierWidget::changeToInterface()
{
setBaseType(WidgetBase::wt_Interface);
m_umlObject->setBaseType(UMLObject::ot_Interface);
setVisualProperty(ShowAttributes, false);
setShowStereotype(Settings::optionState().classState.showStereoType);
updateGeometry();
update();
}
/**
* Changes this classifier from an "class-or-package" to a package.
* This widget is also updated.
*/
void ClassifierWidget::changeToPackage()
{
setBaseType(WidgetBase::wt_Package);
m_umlObject->setBaseType(UMLObject::ot_Package);
setVisualProperty(ShowAttributes, false);
setShowStereotype(Uml::ShowStereoType::Name);
updateGeometry();
update();
}
/**
* Loads the "classwidget" or "interfacewidget" XML element.
*/
bool ClassifierWidget::loadFromXMI(QDomElement & qElement)
{
if (!UMLWidget::loadFromXMI(qElement)) {
return false;
}
if (DiagramProxyWidget::linkedDiagram())
DiagramProxyWidget::setShowLinkedDiagram(false);
bool loadShowAttributes = true;
if (umlObject() && (umlObject()->isUMLPackage() || umlObject()->isUMLInstance())) {
loadShowAttributes = false;
}
if (loadShowAttributes) {
QString showatts = qElement.attribute(QStringLiteral("showattributes"), QStringLiteral("0"));
QString showops = qElement.attribute(QStringLiteral("showoperations"), QStringLiteral("1"));
QString showpubliconly = qElement.attribute(QStringLiteral("showpubliconly"), QStringLiteral("0"));
QString showattsigs = qElement.attribute(QStringLiteral("showattsigs"), QStringLiteral("600"));
QString showopsigs = qElement.attribute(QStringLiteral("showopsigs"), QStringLiteral("600"));
QString showpackage = qElement.attribute(QStringLiteral("showpackage"), QStringLiteral("0"));
QString showscope = qElement.attribute(QStringLiteral("showscope"), QStringLiteral("0"));
QString drawascircle = qElement.attribute(QStringLiteral("drawascircle"), QStringLiteral("0"));
QString showstereotype = qElement.attribute(QStringLiteral("showstereotype"), QStringLiteral("1"));
setVisualPropertyCmd(ShowAttributes, (bool)showatts.toInt());
setVisualPropertyCmd(ShowOperations, (bool)showops.toInt());
setVisualPropertyCmd(ShowPublicOnly, (bool)showpubliconly.toInt());
setVisualPropertyCmd(ShowPackage, (bool)showpackage.toInt());
setVisualPropertyCmd(ShowVisibility, (bool)showscope.toInt());
setVisualPropertyCmd(DrawAsCircle, (bool)drawascircle.toInt());
setShowStereotype((Uml::ShowStereoType::Enum)showstereotype.toInt());
m_attributeSignature = Uml::SignatureType::fromInt(showattsigs.toInt());
m_operationSignature = Uml::SignatureType::fromInt(showopsigs.toInt());
}
#ifdef ENABLE_WIDGET_SHOW_DOC
QString showDocumentation = qElement.attribute(QStringLiteral("showdocumentation"), QStringLiteral("0"));
setVisualPropertyCmd(ShowDocumentation, (bool)showDocumentation.toInt());
#endif
if (!getDrawAsCircle())
return true;
// Optional child element: floatingtext
QDomNode node = qElement.firstChild();
QDomElement element = node.toElement();
if (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("floatingtext")) {
if (m_pInterfaceName == nullptr) {
m_pInterfaceName = new FloatingTextWidget(m_scene,
Uml::TextRole::Floating,
name(), Uml::ID::Reserved);
m_pInterfaceName->setParentItem(this);
}
if (!m_pInterfaceName->loadFromXMI(element)) {
// Most likely cause: The FloatingTextWidget is empty.
delete m_pInterfaceName;
m_pInterfaceName = nullptr;
} else {
m_pInterfaceName->activate();
m_pInterfaceName->update();
}
} else {
logError1("ClassifierWidget::loadFromXMI: unknown tag %1", tag);
}
}
return true;
}
/**
* Creates the "classwidget" or "interfacewidget" XML element.
*/
void ClassifierWidget::saveToXMI(QXmlStreamWriter& writer)
{
bool saveShowAttributes = true;
UMLClassifier *umlc = classifier();
QString tag;
if (umlObject()->baseType() == UMLObject::ot_Package) {
tag = QStringLiteral("packagewidget");
saveShowAttributes = false;
} else if (umlObject()->baseType() == UMLObject::ot_Instance) {
tag = QStringLiteral("instancewidget");
saveShowAttributes = false;
} else if (umlc && umlc->isInterface()) {
tag = QStringLiteral("interfacewidget");
} else {
tag = QStringLiteral("classwidget");
}
writer.writeStartElement(tag);
UMLWidget::saveToXMI(writer);
if (saveShowAttributes) {
writer.writeAttribute(QStringLiteral("showoperations"), QString::number(visualProperty(ShowOperations)));
writer.writeAttribute(QStringLiteral("showpubliconly"), QString::number(visualProperty(ShowPublicOnly)));
writer.writeAttribute(QStringLiteral("showopsigs"), QString::number(m_operationSignature));
writer.writeAttribute(QStringLiteral("showpackage"), QString::number(visualProperty(ShowPackage)));
writer.writeAttribute(QStringLiteral("showscope"), QString::number(visualProperty(ShowVisibility)));
writer.writeAttribute(QStringLiteral("showattributes"), QString::number(visualProperty(ShowAttributes)));
writer.writeAttribute(QStringLiteral("showattsigs"), QString::number(m_attributeSignature));
}
#ifdef ENABLE_WIDGET_SHOW_DOC
writer.writeAttribute(QStringLiteral("showdocumentation"), QString::number(visualProperty(ShowDocumentation)));
#endif
if (umlc && (umlc->isInterface() || umlc->isAbstract())) {
writer.writeAttribute(QStringLiteral("drawascircle"), QString::number(visualProperty(DrawAsCircle)));
if (visualProperty(DrawAsCircle) && m_pInterfaceName) {
m_pInterfaceName->saveToXMI(writer);
}
}
writer.writeEndElement();
}
/**
* Will be called when a menu selection has been made from the
* popup menu.
*
* @param action The action that has been selected.
*/
void ClassifierWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
logDebug1("ClassifierWidget::slotMenuSelection sel = %1", sel);
switch (sel) {
case ListPopupMenu::mt_Attribute:
case ListPopupMenu::mt_Operation:
case ListPopupMenu::mt_Template:
{
UMLObject::ObjectType ot = ListPopupMenu::convert_MT_OT(sel);
UMLClassifier *umlc = classifier();
if (!umlc) {
logError1("ClassifierWidget::slotMenuSelection(%1) internal error - classifier() returns null",
sel);
return;
}
if (Object_Factory::createChildObject(umlc, ot)) {
updateGeometry();
update();
UMLApp::app()->document()->setModified();
}
break;
}
case ListPopupMenu::mt_Class:
case ListPopupMenu::mt_Datatype:
case ListPopupMenu::mt_Enum:
case ListPopupMenu::mt_Interface:
{
UMLObject::ObjectType ot = ListPopupMenu::convert_MT_OT(sel);
UMLClassifier *umlc = classifier();
if (!umlc) {
logError1("ClassifierWidget::slotMenuSelection(%1) internal error - classifier() returns null",
sel);
return;
}
umlScene()->setCreateObject(true);
if (Object_Factory::createUMLObject(ot, QString(), umlc)) {
updateGeometry();
update();
UMLApp::app()->document()->setModified();
}
break;
}
case ListPopupMenu::mt_Show_Operations:
toggleVisualProperty(ShowOperations);
break;
case ListPopupMenu::mt_Show_Attributes:
toggleVisualProperty(ShowAttributes);
break;
case ListPopupMenu::mt_Show_Documentation:
toggleVisualProperty(ShowDocumentation);
break;
case ListPopupMenu::mt_Show_Public_Only:
toggleVisualProperty(ShowPublicOnly);
break;
case ListPopupMenu::mt_Show_Operation_Signature:
toggleVisualProperty(ShowOperationSignature);
break;
case ListPopupMenu::mt_Show_Attribute_Signature:
toggleVisualProperty(ShowAttributeSignature);
break;
case ListPopupMenu::mt_Visibility:
toggleVisualProperty(ShowVisibility);
break;
case ListPopupMenu::mt_Show_Packages:
toggleVisualProperty(ShowPackage);
break;
case ListPopupMenu::mt_Show_Stereotypes:
toggleVisualProperty(ShowStereotype);
break;
case ListPopupMenu::mt_DrawAsCircle:
toggleVisualProperty(DrawAsCircle);
break;
case ListPopupMenu::mt_ChangeToClass:
changeToClass();
break;
case ListPopupMenu::mt_ChangeToInterface:
changeToInterface();
break;
case ListPopupMenu::mt_ChangeToPackage:
changeToPackage();
break;
default:
DiagramProxyWidget::slotMenuSelection(action);
break;
}
}
/**
* Slot to show/hide attributes based on \a state.
*/
void ClassifierWidget::slotShowAttributes(bool state)
{
setVisualProperty(ShowAttributes, state);
}
/**
* Slot to show/hide operations based on \a state.
*/
void ClassifierWidget::slotShowOperations(bool state)
{
setVisualProperty(ShowOperations, state);
}
void ClassifierWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (linkedDiagram())
DiagramProxyWidget::mouseDoubleClickEvent(event);
if (event->isAccepted())
UMLWidget::mouseDoubleClickEvent(event);
}
/**
* Show a properties dialog for a ClassifierWidget
*/
bool ClassifierWidget::showPropertiesDialog()
{
if (UMLWidget::showPropertiesDialog()) {
if (isInterfaceWidget() && visualProperty(DrawAsCircle))
m_pInterfaceName->setText(name());
return true;
}
return false;
}
/**
* Overriding the method from WidgetBase because we need to do
* something extra in case this ClassifierWidget represents
* an interface widget used in component diagrams.
*/
void ClassifierWidget::setUMLObject(UMLObject *obj)
{
WidgetBase::setUMLObject(obj);
if (isInterfaceWidget() && visualProperty(DrawAsCircle))
m_pInterfaceName->setText(obj->name());
}
| 55,376
|
C++
|
.cpp
| 1,463
| 30.984279
| 175
| 0.656026
|
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,393
|
actorwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/actorwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header file
#include "actorwidget.h"
// local includes
#include "actor.h"
#include "debug_utils.h"
#include "umlview.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(ActorWidget)
/**
* Constructs an ActorWidget.
*
* @param scene The parent of this ActorWidget.
* @param a The Actor class this ActorWidget will display.
*/
ActorWidget::ActorWidget(UMLScene * scene, UMLActor *a)
: UMLWidget(scene, WidgetBase::wt_Actor, a)
{
setFixedAspectRatio(true);
}
/**
* Destructor.
*/
ActorWidget::~ActorWidget()
{
}
/**
* Overrides the standard paint event.
*/
void ActorWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
UMLWidget::setPenFromSettings(painter);
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
const int w = width();
const int h = height();
painter->setFont(UMLWidget::font());
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
bool drawStereotype = umlObject() && !umlObject()->stereotype().isEmpty();
const int a_height = h - (drawStereotype ? 2 * fontHeight : fontHeight) - A_MARGIN;
const int h2 = a_height / 2;
const int a_width = (h2);
const int middleX = w / 2;
const int thirdY = a_height / 3;
//draw actor
painter->drawEllipse(middleX - a_width / 2, 0, a_width, thirdY); //head
painter->drawLine(middleX, thirdY,
middleX, thirdY * 2); //body
painter->drawLine(middleX, 2 * thirdY,
middleX - a_width / 2, a_height); //left leg
painter->drawLine(middleX, 2 * thirdY,
middleX + a_width / 2, a_height); //right leg
painter->drawLine(middleX - a_width / 2, thirdY + thirdY / 2,
middleX + a_width / 2, thirdY + thirdY / 2); //arms
//draw text
painter->setPen(textColor());
if (drawStereotype)
painter->drawText(A_MARGIN, h - 2 * fontHeight, w - A_MARGIN * 2, fontHeight, Qt::AlignCenter, umlObject()->stereotype(true));
painter->drawText(A_MARGIN, h - fontHeight,
w - A_MARGIN * 2, fontHeight, Qt::AlignCenter, name());
UMLWidget::paint(painter, option, widget);
}
/**
* Saves the widget to the "actorwidget" XMI element.
* Note: For loading from XMI, the inherited parent method is used.
*/
void ActorWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("actorwidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Overrides method from UMLWidget.
*/
QSizeF ActorWidget::minimumSize() const
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(name());
bool drawStereotype = umlObject() && !umlObject()->stereotype().isEmpty();
int width = textWidth > A_WIDTH ? textWidth : A_WIDTH;
int height = A_HEIGHT + (drawStereotype ? 2 * fontHeight : fontHeight) + A_MARGIN;
width += A_MARGIN * 2;
return QSizeF(width, height);
}
| 3,267
|
C++
|
.cpp
| 93
| 31.129032
| 134
| 0.681847
|
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,394
|
enumwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/enumwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "enumwidget.h"
// app includes
#include "classifier.h"
#include "classifierlistitem.h"
#include "debug_utils.h"
#include "enum.h"
#include "enumliteral.h"
#include "listpopupmenu.h"
#include "object_factory.h"
#include "uml.h"
#include "umlclassifierlistitemlist.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
// qt includes
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(EnumWidget)
/**
* Constructs an instance of EnumWidget.
*
* @param scene The parent of this EnumWidget.
* @param o The UMLObject this will be representing.
*/
EnumWidget::EnumWidget(UMLScene *scene, UMLObject* o)
: UMLWidget(scene, WidgetBase::wt_Enum, o),
m_showPackage(false)
{
setSize(100, 30);
//set defaults from m_scene
if (m_scene) {
//check to see if correct
const Settings::OptionState& ops = m_scene->optionState();
m_showPackage = ops.classState.showPackage;
} else {
// For completeness only. Not supposed to happen.
m_showPackage = false;
}
}
/**
* Destructor.
*/
EnumWidget::~EnumWidget()
{
}
/**
* Returns the status of whether to show Package.
*
* @return True if package is shown.
*/
bool EnumWidget::showPackage() const
{
return m_showPackage;
}
/**
* Set the status of whether to show Package.
*
* @param _status True if package shall be shown.
*/
void EnumWidget::setShowPackage(bool _status)
{
m_showPackage = _status;
updateGeometry();
update();
}
/**
* Toggles the status of whether to show package.
*/
void EnumWidget::toggleShowPackage()
{
m_showPackage = !m_showPackage;
updateGeometry();
update();
}
/**
* Draws the enum as a rectangle with a box underneith with a list of literals
* Reimplemented from UMLWidget::paint
*/
void EnumWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
else
painter->setBrush(m_scene->backgroundColor());
const int w = width();
const int h = height();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
QString name;
if (m_showPackage) {
name = m_umlObject->fullyQualifiedName();
} else {
name = this->name();
}
painter->drawRect(0, 0, w, h);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(true);
painter->setFont(font);
painter->drawText(ENUM_MARGIN, 0,
w - ENUM_MARGIN * 2, fontHeight,
Qt::AlignCenter, m_umlObject->stereotype(true));
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
painter->drawText(ENUM_MARGIN, fontHeight,
w - ENUM_MARGIN * 2, fontHeight, Qt::AlignCenter, name);
font.setBold(false);
font.setItalic(false);
painter->setFont(font);
int y = fontHeight * 2;
setPenFromSettings(painter);
painter->drawLine(0, y, w, y);
QFontMetrics fontMetrics(font);
const UMLClassifier *classifier = m_umlObject->asUMLClassifier();
UMLClassifierListItemList list = classifier->getFilteredList(UMLObject::ot_EnumLiteral);
for(UMLClassifierListItem *enumLiteral: list) {
QString text = enumLiteral->toString();
painter->setPen(textColor());
painter->drawText(ENUM_MARGIN, y,
fontMetrics.horizontalAdvance(text), fontHeight, Qt::AlignVCenter, text);
y+=fontHeight;
}
UMLWidget::paint(painter, option, widget);
}
/**
* Loads from an "enumwidget" XMI element.
*/
bool EnumWidget::loadFromXMI(QDomElement & qElement)
{
if (!UMLWidget::loadFromXMI(qElement)) {
return false;
}
QString showpackage = qElement.attribute(QStringLiteral("showpackage"), QStringLiteral("0"));
m_showPackage = (bool)showpackage.toInt();
return true;
}
/**
* Saves to the "enumwidget" XMI element.
*/
void EnumWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("enumwidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("showpackage"), QString::number(m_showPackage));
writer.writeEndElement();
}
/**
* Will be called when a menu selection has been made from the
* popup menu.
*
* @param action The action that has been selected.
*/
void EnumWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
if (sel == ListPopupMenu::mt_EnumLiteral) {
if (Object_Factory::createChildObject(m_umlObject->asUMLClassifier(),
UMLObject::ot_EnumLiteral)) {
/* I don't know why it works without these calls:
updateComponentSize();
update();
*/
UMLApp::app()->document()->setModified();
}
return;
}
UMLWidget::slotMenuSelection(action);
}
/**
* Overrides method from UMLWidget.
*/
QSizeF EnumWidget::minimumSize() const
{
if (!m_umlObject) {
return UMLWidget::minimumSize();
}
int width, height;
QFont font = UMLWidget::font();
font.setItalic(false);
font.setUnderline(false);
font.setBold(false);
const QFontMetrics fm(font);
const int fontHeight = fm.lineSpacing();
int lines = 1;//always have one line - for name
lines++; //for the stereotype
const int numberOfEnumLiterals = m_umlObject->asUMLEnum()->enumLiterals();
height = width = 0;
//set the height of the enum
lines += numberOfEnumLiterals;
if (numberOfEnumLiterals == 0) {
height += fontHeight / 2; //no enum literals, so just add a bit of space
}
height += lines * fontHeight;
//now set the width of the classifier
//set width to name to start with
if (m_showPackage) {
width = getFontMetrics(FT_BOLD_ITALIC).boundingRect(m_umlObject->fullyQualifiedName()).width();
} else {
width = getFontMetrics(FT_BOLD_ITALIC).boundingRect(name()).width();
}
int w = getFontMetrics(FT_BOLD).boundingRect(m_umlObject->stereotype(true)).width();
width = w > width?w:width;
const UMLClassifier *classifier = m_umlObject->asUMLClassifier();
UMLClassifierListItemList list = classifier->getFilteredList(UMLObject::ot_EnumLiteral);
for(UMLClassifierListItem *listItem: list) {
int w = fm.horizontalAdvance(listItem->toString());
width = w > width?w:width;
}
//allow for width margin
width += ENUM_MARGIN * 2;
return QSizeF(width, height);
}
| 6,869
|
C++
|
.cpp
| 219
| 26.684932
| 103
| 0.680085
|
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,395
|
boxwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/boxwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "boxwidget.h"
// app includes
#include "debug_utils.h"
#include "uml.h"
#include "umldoc.h"
// qt includes
#include <QColorDialog>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(BoxWidget)
/**
* Constructs a BoxWidget.
*
* @param scene The parent to this widget.
* @param id The ID to assign (-1 will prompt a new ID.)
* @param type The WidgetType (wt_Box.)
*/
BoxWidget::BoxWidget(UMLScene * scene, Uml::ID::Type id, WidgetType type)
: UMLWidget(scene, type, id)
{
setSize(100, 80);
m_usesDiagramLineColor = false; // boxes be black
setLineColor(QColor("black"));
setZValue(-10);
}
/**
* Destructor.
*/
BoxWidget::~BoxWidget()
{
}
/**
* Draws a rectangle.
*/
void BoxWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
painter->drawRect(0, 0, width(), height());
UMLWidget::paint(painter, option, widget);
}
/**
* Saves the widget to the "boxwidget" XMI element.
* Note: For loading from XMI, the inherited parent method is used.
*/
void BoxWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("boxwidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Show a properties dialog for a BoxWidget.
*/
bool BoxWidget::showPropertiesDialog()
{
QColor newColor = QColorDialog::getColor(lineColor()); // krazy:exclude=qclasses
if (!newColor.isValid())
return false;
if (newColor != lineColor()) {
setLineColor(newColor);
setUsesDiagramLineColor(false);
umlDoc()->setModified(true);
}
return true;
}
void BoxWidget::toForeground()
{
}
| 1,898
|
C++
|
.cpp
| 74
| 22.810811
| 97
| 0.70877
|
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,396
|
umlwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/umlwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlwidget.h"
// local includes
#include "artifact.h"
#include "artifactwidget.h"
#include "activitywidget.h"
#include "actor.h"
#include "actorwidget.h"
#include "associationwidget.h"
#include "classifier.h"
#include "classpropertiesdialog.h"
#include "cmds.h"
#include "component.h"
#include "componentwidget.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "floatingtextwidget.h"
#include "forkjoinwidget.h"
#include "interfacewidget.h"
#include "notewidget.h"
#include "messagewidget.h"
#include "objectwidget.h"
#include "object_factory.h"
#include "idchangelog.h"
#include "menus/listpopupmenu.h"
#include "objectnodewidget.h"
#include "pinwidget.h"
#include "port.h"
#include "portwidget.h"
#include "regionwidget.h"
#include "signalwidget.h"
#include "settingsdialog.h"
#include "statewidget.h"
#include "stereotype.h"
#include "uml.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umlobject.h"
#include "umlscene.h"
#include "umlview.h"
#include "usecase.h"
#include "usecasewidget.h"
#include "uniqueid.h"
#include "widget_factory.h"
#include "widget_utils.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QApplication>
#include <QColor>
#include <QPainter>
#include <QPointer>
#include <QXmlStreamWriter>
using namespace Uml;
DEBUG_REGISTER_DISABLED(UMLWidget)
#define I18N_NEXT_RELEASE(a,b) QString(QStringLiteral(a)).arg(b))
const QSizeF UMLWidget::DefaultMinimumSize(50, 20);
const QSizeF UMLWidget::DefaultMaximumSize(5000, 5000);
const int UMLWidget::defaultMargin = 5;
const int UMLWidget::selectionMarkerSize = 4;
const int UMLWidget::resizeMarkerLineCount = 3;
/**
* Creates a UMLWidget object.
*
* @param scene The view to be displayed on.
* @param type The WidgetType to construct.
* This must be set to the appropriate value by the constructors of inheriting classes.
* @param o The UMLObject to represent.
* @note Although a pointer to the scene is required, the widget is not added to the scene by default.
*/
UMLWidget::UMLWidget(UMLScene * scene, WidgetType type, UMLObject * o)
: WidgetBase(scene, type, o ? o->id() : Uml::ID::None)
, DiagramProxyWidget(this)
{
init();
m_umlObject = o;
if (m_umlObject) {
// TODO: calling WidgetBase::setUMLObject does not add this connection
connect(m_umlObject, SIGNAL(modified()), this, SLOT(updateWidget()));
}
}
/**
* Creates a UMLWidget object.
*
* @param scene The view to be displayed on.
* @param type The WidgetType to construct.
* This must be set to the appropriate value by the constructors of inheriting classes.
* @param id The id of the widget.
* The default value (id_None) will prompt generation of a new ID.
*/
UMLWidget::UMLWidget(UMLScene *scene, WidgetType type, Uml::ID::Type id)
: WidgetBase(scene, type, id)
, DiagramProxyWidget(this)
{
init();
}
/**
* Destructor.
*/
UMLWidget::~UMLWidget()
{
cleanup();
}
/**
* Assignment operator
*/
UMLWidget& UMLWidget::operator=(const UMLWidget & other)
{
if (this == &other)
return *this;
WidgetBase::operator=(other);
DiagramProxyWidget::operator=(other);
// assign members loaded/saved
m_useFillColor = other.m_useFillColor;
m_usesDiagramFillColor = other.m_usesDiagramFillColor;
m_usesDiagramUseFillColor = other.m_usesDiagramUseFillColor;
m_fillColor = other.m_fillColor;
m_Assocs = other.m_Assocs;
m_isInstance = other.m_isInstance;
m_instanceName = other.m_instanceName;
m_instanceName = other.m_instanceName;
m_showStereotype = other.m_showStereotype;
setX(other.x());
setY(other.y());
setRect(rect().x(), rect().y(), other.width(), other.height());
// assign volatile (non-saved) members
m_startMove = other.m_startMove;
m_nPosX = other.m_nPosX;
m_doc = other.m_doc; //new
m_resizable = other.m_resizable;
for (unsigned i = 0; i < FT_INVALID; ++i)
m_pFontMetrics[i] = other.m_pFontMetrics[i];
m_activated = other.m_activated;
m_ignoreSnapToGrid = other.m_ignoreSnapToGrid;
m_ignoreSnapComponentSizeToGrid = other.m_ignoreSnapComponentSizeToGrid;
return *this;
}
/**
* Overload '==' operator
*/
bool UMLWidget::operator==(const UMLWidget& other) const
{
if (this == &other)
return true;
if (baseType() != other.baseType()) {
return false;
}
if (id() != other.id())
return false;
/* Testing the associations is already an exaggeration, no?
The type and ID should uniquely identify a UMLWidget.
*/
if (m_Assocs.count() != other.m_Assocs.count()) {
return false;
}
// if(getBaseType() != wt_Text) // DON'T do this for floatingtext widgets, an infinite loop will result
// {
AssociationWidgetListIt assoc_it(m_Assocs);
AssociationWidgetListIt assoc_it2(other.m_Assocs);
AssociationWidget *assoc = nullptr, *assoc2 = nullptr;
while (assoc_it.hasNext() && assoc_it2.hasNext()) {
assoc = assoc_it.next();
assoc2 = assoc_it2.next();
if (!(*assoc == *assoc2)) {
return false;
}
}
// }
return true;
// NOTE: In the comparison tests we are going to do, we don't need these values.
// They will actually stop things functioning correctly so if you change these, be aware of that.
/*
if(m_useFillColor != other.m_useFillColor)
return false;
if(m_nId != other.m_nId)
return false;
if(m_nX != other.m_nX)
return false;
if(m_nY != other.m_nY)
return false;
*/
}
/**
* Compute the minimum possible width and height.
*
* @return QSizeF(mininum_width, minimum_height)
*/
QSizeF UMLWidget::minimumSize() const
{
return m_minimumSize;
}
/**
* This method is used to set the minimum size variable for this
* widget.
*
* @param newSize The size being set as minimum.
*/
void UMLWidget::setMinimumSize(const QSizeF& newSize)
{
m_minimumSize = newSize;
}
/**
* Compute the maximum possible width and height.
*
* @return maximum size
*/
QSizeF UMLWidget::maximumSize()
{
return m_maximumSize;
}
/**
* This method is used to set the maximum size variable for this
* widget.
*
* @param newSize The size being set as maximum.
*/
void UMLWidget::setMaximumSize(const QSizeF& newSize)
{
m_maximumSize = newSize;
}
/**
* Event handler for context menu events.
*/
void UMLWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
WidgetBase::contextMenuEvent(event);
}
/**
* Moves the widget to a new position using the difference between the
* current position and the new position.
* This method doesn't adjust associations. It only moves the widget.
*
* It can be overridden to constrain movement only in one axis even when
* the user isn't constraining the movement with shift or control buttons, for example.
* The movement policy set here is applied whenever the widget is moved, being it
* moving it explicitly, or as a part of a selection but not receiving directly the
* mouse events.
*
* Default behaviour is move the widget to the new position using the diffs.
* @see constrainMovementForAllWidgets
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void UMLWidget::moveWidgetBy(qreal diffX, qreal diffY)
{
setX(x() + diffX);
setY(y() + diffY);
}
/**
* Modifies the value of the diffX and diffY variables used to move the widgets.
*
* It can be overridden to constrain movement of all the selected widgets only in one
* axis even when the user isn't constraining the movement with shift or control
* buttons, for example.
* The difference with moveWidgetBy is that the diff positions used here are
* applied to all the selected widgets instead of only to m_widget, and that
* moveWidgetBy, in fact, moves the widget, and here simply the diff positions
* are modified.
*
* Default behaviour is do nothing.
* @see moveWidgetBy
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void UMLWidget::constrainMovementForAllWidgets(qreal &diffX, qreal &diffY)
{
Q_UNUSED(diffX) Q_UNUSED(diffY)
}
/**
* Bring the widget at the pressed position to the foreground.
*/
void UMLWidget::toForeground()
{
QRectF rect = QRectF(scenePos(), QSizeF(width(), height()));
QList<QGraphicsItem*> items = scene()->items(rect, Qt::IntersectsItemShape, Qt::DescendingOrder);
logDebug2("UMLWidget %1 toForeground: items at rect = %2", name(), items.count());
if (items.count() > 1) {
for(QGraphicsItem *i : items) {
UMLWidget* w = dynamic_cast<UMLWidget*>(i);
if (w) {
logDebug2("- item=%1 with zValue=%2", w->name(), w->zValue());
if (w->name() != name()) {
if (w->zValue() >= zValue()) {
setZValue(w->zValue() + 1.0);
logDebug1("-- bring to foreground with zValue: %1", zValue());
}
}
}
}
}
else {
setZValue(0.0);
}
logDebug2("UMLWidget %1 toForeground: zValue is %2", name(), zValue());
}
/**
* Handles a mouse press event.
* It'll select the widget (or mark it to be deselected) and prepare it to
* be moved or resized. Go on reading for more info about this.
*
* Widget values and message bar status are saved.
*
* If shift or control buttons are pressed, we're in move area no matter
* where the button was pressed in the widget. Moreover, if the widget
* wasn't already selected, it's added to the selection. If already selected,
* it's marked to be deselected when releasing the button (provided it isn't
* moved).
* Also, if the widget is already selected with other widgets but shift nor
* control buttons are pressed, we're in move area. If finally we don't move
* the widget, it's selected and the other widgets deselected when releasing
* the left button.
*
* If shift nor control buttons are pressed, we're facing a single selection.
* Depending on the position of the cursor, we're in move or in resize area.
* If the widget wasn't selected (both when there are no widgets selected, or
* when there're other widgets selected but not the one receiving the press
* event) it's selected and the others deselected, if any. If already selected,
* it's marked to be deselected when releasing the button (provided it wasn't
* moved or resized).
*
* @param event The QGraphicsSceneMouseEvent event.
*/
void UMLWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() != Qt::LeftButton) {
event->ignore();
return;
}
/*
logDebug4("UMLWidget::mousePressEvent: widget=%1 / type=%2 / event->scenePos=%3 / pos=%4",
name(), baseTypeStr(), event->scenePos(), pos());
*/
event->accept();
logDebug2("UMLWidget::mousePressEvent: widget = %1 / type = %2", name(), baseTypeStr());
toForeground();
m_startMovePostion = pos();
m_startResizeSize = QSizeF(width(), height());
// saving the values of the widget
m_pressOffset = event->scenePos() - pos();
logDebug2("UMLWidget::mousePressEvent: press offset x=%1, y=%2", m_pressOffset.x(), m_pressOffset.y());
m_oldStatusBarMsg = UMLApp::app()->statusBarMsg();
if (event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) {
m_shiftPressed = true;
if (event->button() == Qt::LeftButton) {
m_inMoveArea = true;
}
if (!isSelected()) {
selectMultiple(event);
}
return;
}
m_shiftPressed = false;
int count = m_scene->selectedCount();
if (event->button() == Qt::LeftButton) {
if (isSelected() && count > 1) {
// single selection is made in release event if the widget wasn't moved
m_inMoveArea = true;
m_oldPos = pos();
return;
}
if (isInResizeArea(event)) {
m_inResizeArea = true;
m_oldW = width();
m_oldH = height();
} else {
m_inMoveArea = true;
}
}
// if widget wasn't selected, or it was selected but with other widgets also selected
if (!isSelected() || count > 1) {
selectSingle(event);
}
}
/**
* Handles a mouse move event.
* It resizes or moves the widget, depending on where the cursor is pressed
* on the widget. Go on reading for more info about this.
*
* If resizing, the widget is resized using UMLWidget::resizeWidget (where specific
* widget resize constraint can be applied), and then the associations are
* adjusted.
* The resizing can be constrained also to a specific axis using control
* and shift buttons. If one or another is pressed, it's constrained to X axis.
* If both are pressed, it's constrained to Y axis.
*
* If not resizing, the widget is being moved. If the move is being started,
* the selection bounds are set (which includes updating the list of selected
* widgets).
* The difference between the previous position of the selection and the new
* one is calculated (taking in account the selection bounds so widgets don't go
* beyond the scene limits). Then, it's constrained to X or Y axis depending
* on shift and control buttons.
* A further constraint is made using constrainMovementForAllWidgets (for example,
* if the widget that receives the event can only be moved in Y axis, with this
* method the movement of all the widgets in the selection can be constrained to
* be moved only in Y axis).
* Then, all the selected widgets are moved using moveWidgetBy (where specific
* widget movement constraint can be applied) and, if a certain amount of time
* passed from the last move event, the associations are also updated (they're
* not updated always to be easy on the CPU). Finally, the scene is resized,
* and selection bounds updated.
*
* @param event The QGraphicsSceneMouseEvent event.
*/
void UMLWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (m_inResizeArea) {
resize(event);
return;
}
if (!m_moved) {
UMLApp::app()->document()->writeToStatusBar
(i18n("Hold shift or ctrl to move in X axis. Hold shift and control to move in Y axis. Right button click to cancel move."));
m_moved = true;
//Maybe needed by AssociationWidget
m_startMove = true;
setSelectionBounds();
}
QPointF position = event->scenePos() - m_pressOffset;
qreal diffX = position.x() - x();
qreal diffY = position.y() - y();
if ((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::ControlModifier)) {
// move only in Y axis
diffX = 0;
} else if ((event->modifiers() & Qt::ShiftModifier) || (event->modifiers() & Qt::ControlModifier)) {
// move only in X axis
diffY = 0;
}
constrainMovementForAllWidgets(diffX, diffY);
// nothing to move
if (diffX == 0 && diffY == 0) {
return;
}
QPointF delta = event->scenePos() - event->lastScenePos();
logDebug2("UMLWidget::mouseMoveEvent: diffX=%1 / diffY=%2", diffX, diffY);
for(UMLWidget *widget : umlScene()->selectedWidgets()) {
if ((widget->parentItem() == nullptr) || (!widget->parentItem()->isSelected())) {
widget->moveWidgetBy(diffX, diffY);
widget->adjustUnselectedAssocs(delta.x(), delta.y());
widget->slotSnapToGrid();
}
}
// Move any selected associations.
for(AssociationWidget *aw : m_scene->selectedAssocs()) {
if (aw->isSelected()) {
aw->moveEntireAssoc(diffX, diffY);
}
}
}
/**
* Handles a mouse release event.
* It selects or deselects the widget and cancels or confirms the move or
* resize. Go on reading for more info about this.
* No matter which tool is selected, Z position of widget is updated.
*
* Middle button release resets the selection.
* Left button release, if it wasn't moved nor resized, selects the widget
* and deselect the others if it wasn't selected and there were other widgets
* selected. If the widget was marked to be deselected, deselects it.
* If it was moved or resized, the document is set to modified if position
* or size changed. Also, if moved, all the associations are adjusted because
* the timer could have prevented the adjustment in the last move event before
* the release.
* If mouse was pressed in resize area, cursor is set again to normal cursor
* Right button release if right button was pressed shows the pop up menu for
* the widget.
* If left button was pressed, it cancels the move or resize with a mouse move
* event at the same position than the cursor was when pressed. Another left
* button release is also sent.
*
* @param event The QGraphicsSceneMouseEvent event.
*/
void UMLWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
logDebug0("UMLWidget::mouseReleaseEvent");
if (!m_moved && !m_resized) {
if (!m_shiftPressed && (m_scene->selectedCount() > 1)) {
selectSingle(event);
} else if (!isSelected()) {
deselect(event);
} else {
Widget_Utils::ensureNestedVisible(this, umlScene()->widgetList());
}
} else {
// Commands
if (m_moved) {
UMLWidgetList selectedWidgets = umlScene()->selectedWidgets();
int selectionCount = selectedWidgets.count();
if (selectionCount > 1) {
UMLApp::app()->beginMacro(i18n("Move widgets"));
}
for(UMLWidget *widget : selectedWidgets) {
UMLApp::app()->executeCommand(new Uml::CmdMoveWidget(widget));
Widget_Utils::ensureNestedVisible(widget, umlScene()->widgetList());
}
if (selectionCount > 1) {
UMLApp::app()->endMacro();
}
m_moved = false;
} else {
UMLApp::app()->executeCommand(new Uml::CmdResizeWidget(this));
m_autoResize = false;
m_resized = false;
deselect(event);
}
if ((m_inMoveArea && wasPositionChanged()) ||
(m_inResizeArea && wasSizeChanged())) {
umlDoc()->setModified(true);
umlScene()->invalidate();
}
UMLApp::app()->document()->writeToStatusBar(m_oldStatusBarMsg);
}
if (m_inResizeArea) {
m_inResizeArea = false;
m_scene->activeView()->setCursor(Qt::ArrowCursor);
} else {
m_inMoveArea = false;
}
m_startMove = false;
}
/**
* Event handler for mouse double click events.
* @param event the QGraphicsSceneMouseEvent event.
*/
void UMLWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
logDebug2("UMLWidget::mouseDoubleClickEvent: widget = %1 / type = %2", name(), baseTypeStr());
showPropertiesDialog();
event->accept();
}
}
/**
* Return the start position of the move action.
* @return point where the move began
*/
QPointF UMLWidget::startMovePosition() const
{
return m_startMovePostion;
}
/**
* Set the start position of the move action.
* @param position point where the move began
*/
void UMLWidget::setStartMovePosition(const QPointF &position)
{
m_startMovePostion = position;
}
/**
* Return the start size of the resize action.
* @return size where the resize began
*/
QSizeF UMLWidget::startResizeSize() const
{
return m_startResizeSize;
}
/**
* Resizes the widget.
* It's called from resize, after the values are constrained and before
* the associations are adjusted.
*
* Default behaviour is resize the widget using the new size values.
* @see resize
*
* @param newW The new width for the widget.
* @param newH The new height for the widget.
*/
void UMLWidget::resizeWidget(qreal newW, qreal newH)
{
setSize(newW, newH);
}
/**
* Notify child widget about parent resizes.
* Child widgets can override this function to move when their parent is resized.
*/
void UMLWidget::notifyParentResize()
{
}
/**
* When a widget changes this slot captures that signal.
*/
void UMLWidget::updateWidget()
{
updateGeometry();
switch (baseType()) {
case WidgetBase::wt_Class:
m_scene->createAutoAttributeAssociations(this);
break;
case WidgetBase::wt_Entity:
m_scene->createAutoConstraintAssociations(this);
break;
default:
break;
}
if (isVisible())
update();
}
/**
* Apply possible constraints to the given candidate width and height.
* The default implementation limits input values to the bounds returned
* by minimumSize()/maximumSize().
*
* @param width input value, may be modified by the constraint
* @param height input value, may be modified by the constraint
*/
void UMLWidget::constrain(qreal& width, qreal& height)
{
QSizeF minSize = minimumSize();
if (width < minSize.width())
width = minSize.width();
if (height < minSize.height())
height = minSize.height();
QSizeF maxSize = maximumSize();
if (width > maxSize.width())
width = maxSize.width();
if (height > maxSize.height())
height = maxSize.height();
if (fixedAspectRatio()) {
QSizeF size = rect().size();
float aspectRatio = size.width() > 0 ? (float)size.height()/size.width() : 1;
logDebug3("UMLWidget::constrain(%1) : Changing input height %2 to %3 due to fixedAspectRatio",
name(), height, (width * aspectRatio));
height = width * aspectRatio;
}
}
/**
* Initializes key attributes of the class.
*/
void UMLWidget::init()
{
m_isInstance = false;
setMinimumSize(DefaultMinimumSize);
setMaximumSize(DefaultMaximumSize);
m_font = QApplication::font();
for (int i = (int)FT_INVALID - 1; i >= 0; --i) {
FontType fontType = (FontType)i;
setupFontType(m_font, fontType);
m_pFontMetrics[fontType] = new QFontMetrics(m_font);
}
if (m_scene) {
m_useFillColor = true;
m_usesDiagramFillColor = true;
m_usesDiagramUseFillColor = true;
const Settings::OptionState& optionState = m_scene->optionState();
m_fillColor = optionState.uiState.fillColor;
m_showStereotype = optionState.classState.showStereoType;
} else {
logError0("UMLWidget::init SERIOUS PROBLEM - m_scene is null");
m_useFillColor = false;
m_usesDiagramFillColor = false;
m_usesDiagramUseFillColor = false;
m_showStereotype = Uml::ShowStereoType::None;
}
m_resizable = true;
m_fixedAspectRatio = false;
m_startMove = false;
m_activated = false;
m_ignoreSnapToGrid = false;
m_ignoreSnapComponentSizeToGrid = false;
m_doc = UMLApp::app()->document();
m_nPosX = 0;
connect(m_scene, SIGNAL(sigFillColorChanged(Uml::ID::Type)), this, SLOT(slotFillColorChanged(Uml::ID::Type)));
connect(m_scene, SIGNAL(sigLineColorChanged(Uml::ID::Type)), this, SLOT(slotLineColorChanged(Uml::ID::Type)));
connect(m_scene, SIGNAL(sigTextColorChanged(Uml::ID::Type)), this, SLOT(slotTextColorChanged(Uml::ID::Type)));
connect(m_scene, SIGNAL(sigLineWidthChanged(Uml::ID::Type)), this, SLOT(slotLineWidthChanged(Uml::ID::Type)));
m_umlObject = nullptr;
m_oldPos = QPointF();
m_pressOffset = QPointF();
m_oldW = 0;
m_oldH = 0;
m_shiftPressed = false;
m_inMoveArea = false;
m_inResizeArea = false;
m_moved = false;
m_resized = false;
// propagate line color set by base class constructor
// which does not call the virtual methods from this class.
setLineColor(lineColor());
setZValue(2.0); // default for most widgets
}
/**
* This is usually called synchronously after menu.exec() and \a
* trigger's parent is always the ListPopupMenu which can be used to
* get the type of action of \a trigger.
*
* @note Subclasses can reimplement to handle specific actions and
* leave the rest to WidgetBase::slotMenuSelection.
*/
void UMLWidget::slotMenuSelection(QAction *trigger)
{
if (!trigger) {
return;
}
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(trigger);
switch (sel) {
case ListPopupMenu::mt_Resize:
umlScene()->resizeSelection();
break;
case ListPopupMenu::mt_AutoResize:
setAutoResize(trigger->isChecked());
updateGeometry();
break;
case ListPopupMenu::mt_Rename_Object: {
QString name = m_instanceName;
bool ok = Dialog_Utils::askName(i18n("Rename Object"),
i18n("Enter object name:"),
name);
if (ok) {
m_instanceName = name;
updateGeometry();
moveEvent(nullptr);
update();
UMLApp::app()->document()->setModified(true);
}
break;
}
case ListPopupMenu::mt_FloatText: {
FloatingTextWidget* ft = new FloatingTextWidget(umlScene());
ft->showChangeTextDialog();
//if no text entered delete
if (!FloatingTextWidget::isTextValid(ft->text())) {
delete ft;
} else {
ft->setID(UniqueID::gen());
addWidget(ft, false);
}
break;
}
case ListPopupMenu::mt_Actor: {
UMLActor *actor = new UMLActor;
UMLWidget *widget = new ActorWidget(umlScene(), actor);
addConnectedWidget(widget, Uml::AssociationType::Association);
break;
}
case ListPopupMenu::mt_Artifact: {
UMLArtifact *a = new UMLArtifact();
ArtifactWidget *widget = new ArtifactWidget(umlScene(), a);
addConnectedWidget(widget, Uml::AssociationType::Association);
break;
}
case ListPopupMenu::mt_Component: {
UMLComponent *c = new UMLComponent();
ComponentWidget *widget = new ComponentWidget(umlScene(), c);
addConnectedWidget(widget, Uml::AssociationType::Association, SetupSize);
break;
}
case ListPopupMenu::mt_Hide_Destruction_Box: {
ObjectWidget *w = asObjectWidget();
if (w)
w->setShowDestruction(false);
break;
}
case ListPopupMenu::mt_Show_Destruction_Box: {
ObjectWidget *w = asObjectWidget();
if (w)
w->setShowDestruction(true);
break;
}
case ListPopupMenu::mt_Interface: {
UMLPackage* component = umlObject()->asUMLPackage();
QString name = Model_Utils::uniqObjectName(UMLObject::ot_Interface, component);
if (Dialog_Utils::askNewName(WidgetBase::wt_Interface, name)) {
UMLClassifier *c = new UMLClassifier();
c->setBaseType(UMLObject::ot_Interface);
ClassifierWidget *widget = new ClassifierWidget(umlScene(), c);
addConnectedWidget(widget, Uml::AssociationType::Association);
}
break;
}
case ListPopupMenu::mt_InterfaceComponent:
case ListPopupMenu::mt_InterfaceProvided: {
UMLObject *o = Object_Factory::createUMLObject(UMLObject::ot_Interface);
InterfaceWidget *w = new InterfaceWidget(umlScene(), o->asUMLClassifier());
w->setDrawAsCircle(true);
addConnectedWidget(w, Uml::AssociationType::Association, SetupSize);
break;
}
case ListPopupMenu::mt_InterfaceRequired: {
UMLObject *o = Object_Factory::createUMLObject(UMLObject::ot_Interface);
InterfaceWidget *w = new InterfaceWidget(umlScene(), o->asUMLClassifier());
w->setDrawAsCircle(true);
addConnectedWidget(w, Uml::AssociationType::Association, SetupSize | SwitchDirection);
break;
}
case ListPopupMenu::mt_Note: {
NoteWidget *widget = new NoteWidget(umlScene());
addConnectedWidget(widget, Uml::AssociationType::Anchor);
break;
}
case ListPopupMenu::mt_Port: {
// TODO: merge with ToolbarStateOneWidget::setWidget()
UMLPackage* component = umlObject()->asUMLPackage();
QString name = Model_Utils::uniqObjectName(UMLObject::ot_Port, component);
if (Dialog_Utils::askNewName(WidgetBase::wt_Port, name)) {
UMLPort *port = Object_Factory::createUMLObject(UMLObject::ot_Port, name, component)->asUMLPort();
UMLWidget *umlWidget = Widget_Factory::createWidget(umlScene(), port);
umlWidget->setParentItem(this);
QPointF p = mapFromScene(umlScene()->pos());
umlWidget->setPos(p);
umlScene()->setupNewWidget(umlWidget, false);
}
break;
}
case ListPopupMenu::mt_UseCase: {
UMLUseCase *useCase = new UMLUseCase;
UMLWidget *widget = new UseCaseWidget(umlScene(), useCase);
addConnectedWidget(widget, Uml::AssociationType::Association);
break;
}
case ListPopupMenu::mt_MessageCreation:
case ListPopupMenu::mt_MessageDestroy:
case ListPopupMenu::mt_MessageSynchronous:
// MessageWidget *widget = new MessageWidget(umlScene(), this);
// addConnectedWidget(widget, Uml::AssociationType::Coll_Mesg_Sync);
case ListPopupMenu::mt_MessageAsynchronous:
case ListPopupMenu::mt_MessageFound:
case ListPopupMenu::mt_MessageLost:
break;
// activity diagrams
case ListPopupMenu::mt_Accept_Signal:
addConnectedWidget(new SignalWidget(umlScene(), SignalWidget::Accept), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Accept_Time_Event:
addConnectedWidget(new SignalWidget(umlScene(), SignalWidget::Time), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Activity:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Normal), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Activity_Transition:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Final), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Branch:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Branch), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Exception:
umlScene()->triggerToolbarButton(WorkToolBar::tbb_Exception);
break;
case ListPopupMenu::mt_Final_Activity:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Final), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Fork:
addConnectedWidget(new ForkJoinWidget(umlScene()), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_End_Activity:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::End), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Initial_Activity:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Initial), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Invoke_Activity:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Invok), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Object_Node:
addConnectedWidget(new ObjectNodeWidget(umlScene(), ObjectNodeWidget::Data), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Pin:
umlScene()->triggerToolbarButton(WorkToolBar::tbb_Pin);
break;
case ListPopupMenu::mt_Param_Activity:
addConnectedWidget(new ActivityWidget(umlScene(), ActivityWidget::Param), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_PrePostCondition:
addConnectedWidget(new NoteWidget(umlScene(), NoteWidget::Normal), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Region:
addConnectedWidget(new RegionWidget(umlScene()), Uml::AssociationType::Activity, NoOption);
break;
case ListPopupMenu::mt_Send_Signal:
addConnectedWidget(new SignalWidget(umlScene(), SignalWidget::Send), Uml::AssociationType::Activity, NoOption);
break;
// state diagrams
case ListPopupMenu::mt_Choice:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::Choice), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_DeepHistory:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::DeepHistory), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_End_State:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::End), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_Junction:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::Junction), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_ShallowHistory:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::ShallowHistory), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_State:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::Normal), Uml::AssociationType::State, ShowProperties);
break;
case ListPopupMenu::mt_StateFork:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::Fork), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_StateJoin:
addConnectedWidget(new StateWidget(umlScene(), StateWidget::Join), Uml::AssociationType::State, NoOption);
break;
case ListPopupMenu::mt_StateTransition:
umlScene()->triggerToolbarButton(WorkToolBar::tbb_State_Transition);
break;
default:
WidgetBase::slotMenuSelection(trigger);
break;
}
}
/**
* Captures when another widget moves if this widget is linked to it.
* @see sigWidgetMoved
*
* @param id The id of object behind the widget.
*/
void UMLWidget::slotWidgetMoved(Uml::ID::Type /*id*/)
{
}
/**
* Captures a color change signal.
*
* @param viewID The id of the UMLScene behind the widget.
*/
void UMLWidget::slotFillColorChanged(Uml::ID::Type viewID)
{
//only change if on the diagram concerned
if (m_scene->ID() != viewID) {
return;
}
if (m_usesDiagramFillColor) {
WidgetBase::setFillColor(m_scene->fillColor());
}
if (m_usesDiagramUseFillColor) {
WidgetBase::setUseFillColor(m_scene->useFillColor());
}
update();
}
/**
* Captures a text color change signal.
*
* @param viewID The id of the UMLScene behind the widget.
*/
void UMLWidget::slotTextColorChanged(Uml::ID::Type viewID)
{
//only change if on the diagram concerned
if (m_scene->ID() != viewID)
return;
WidgetBase::setTextColor(m_scene->textColor());
update();
}
/**
* Captures a line color change signal.
*
* @param viewID The id of the UMLScene behind the widget.
*/
void UMLWidget::slotLineColorChanged(Uml::ID::Type viewID)
{
//only change if on the diagram concerned
if (m_scene->ID() != viewID)
return;
if (m_usesDiagramLineColor) {
WidgetBase::setLineColor(m_scene->lineColor());
}
update();
}
/**
* Captures a linewidth change signal.
*
* @param viewID The id of the UMLScene behind the widget.
*/
void UMLWidget::slotLineWidthChanged(Uml::ID::Type viewID)
{
//only change if on the diagram concerned
if (m_scene->ID() != viewID) {
return;
}
if (m_usesDiagramLineWidth) {
WidgetBase::setLineWidth(m_scene->lineWidth());
}
update();
}
/**
* Set the status of using fill color (undo action)
*
* @param fc the status of using fill color.
*/
void UMLWidget::setUseFillColor(bool fc)
{
if (useFillColor() != fc) {
UMLApp::app()->executeCommand(new CmdChangeUseFillColor(this, fc));
}
}
/**
* Set the status of using fill color.
*
* @param fc the status of using fill color.
*/
void UMLWidget::setUseFillColorCmd(bool fc)
{
WidgetBase::setUseFillColor(fc);
update();
}
/**
* Overrides the method from WidgetBase.
*/
void UMLWidget::setTextColorCmd(const QColor &color)
{
WidgetBase::setTextColor(color);
update();
}
/**
* Overrides the method from WidgetBase.
*/
void UMLWidget::setTextColor(const QColor &color)
{
if (textColor() != color) {
UMLApp::app()->executeCommand(new CmdChangeTextColor(this, color));
update();
}
}
/**
* Overrides the method from WidgetBase.
*/
void UMLWidget::setLineColorCmd(const QColor &color)
{
WidgetBase::setLineColor(color);
update();
}
/**
* Overrides the method from WidgetBase.
*/
void UMLWidget::setLineColor(const QColor &color)
{
if (lineColor() != color) {
UMLApp::app()->executeCommand(new CmdChangeLineColor(this, color));
}
}
/**
* Overrides the method from WidgetBase, execute CmdChangeLineWidth
*/
void UMLWidget::setLineWidth(uint width)
{
if (lineWidth() != width) {
UMLApp::app()->executeCommand(new CmdChangeLineWidth(this, width));
}
}
/**
* Overrides the method from WidgetBase.
*/
void UMLWidget::setLineWidthCmd(uint width)
{
WidgetBase::setLineWidth(width);
update();
}
/**
* Sets the background fill color
*
* @param color the new fill color
*/
void UMLWidget::setFillColor(const QColor &color)
{
if (fillColor() != color) {
UMLApp::app()->executeCommand(new CmdChangeFillColor(this, color));
}
}
/**
* Sets the background fill color
*
* @param color the new fill color
*/
void UMLWidget::setFillColorCmd(const QColor &color)
{
WidgetBase::setFillColor(color);
update();
}
/**
* Reimplemented from @ref WidgetBase
*/
bool UMLWidget::activate(IDChangeLog* changeLog)
{
if (!WidgetBase::activate(changeLog))
return false;
DiagramProxyWidget::activate(changeLog);
setFontCmd(m_font);
setSize(width(), height());
m_activated = true;
updateGeometry();
if (m_scene->getPaste()) {
FloatingTextWidget *ft = nullptr;
QPointF point = m_scene->getPastePoint();
int x = point.x() + this->x();
int y = point.y() + this->y();
if (m_scene->isSequenceDiagram()) {
switch (baseType()) {
case WidgetBase::wt_Object:
case WidgetBase::wt_Precondition :
setY(this->y());
setX(x);
break;
case WidgetBase::wt_Message:
setY(this->y());
setX(x);
break;
case WidgetBase::wt_Text:
ft = static_cast<FloatingTextWidget *>(this);
if (ft->textRole() == Uml::TextRole::Seq_Message) {
setX(x);
setY(this->y());
} else {
setX(this->x());
setY(this->y());
}
break;
default:
setY(y);
break;
}//end switch base type
}//end if sequence
else {
setX(x);
setY(y);
}
}//end if pastepoint
else {
setX(this->x());
setY(this->y());
}
if (m_scene->getPaste())
m_scene->createAutoAssociations(this);
updateGeometry();
return true;
}
/**
* Returns true if the Activate method has been called for this instance
*
* @return The activate status.
*/
bool UMLWidget::isActivated() const
{
return m_activated;
}
/**
* Set the m_activated flag of a widget but does not perform the Activate method
*
* @param active Status of activation is to be set.
*/
void UMLWidget::setActivated(bool active /*=true*/)
{
m_activated = active;
}
/**
* Reimplemented from class WidgetBase
*/
void UMLWidget::addAssoc(AssociationWidget* pAssoc)
{
if (pAssoc && !associationWidgetList().contains(pAssoc)) {
associationWidgetList().append(pAssoc);
}
}
/**
* Returns the list of associations connected to this widget.
*/
AssociationWidgetList &UMLWidget::associationWidgetList() const
{
m_Assocs.removeAll(nullptr);
return m_Assocs;
}
/**
* Reimplemented from class WidgetBase
*/
void UMLWidget::removeAssoc(AssociationWidget* pAssoc)
{
if (pAssoc) {
associationWidgetList().removeAll(pAssoc);
}
if (changesShape() && !UMLApp::app()->shuttingDown()) {
updateGeometry();
}
}
/**
* Adjusts associations with the given co-ordinates
*
* @param dx The amount by which the widget moved in X direction.
* @param dy The amount by which the widget moved in Y direction.
*/
void UMLWidget::adjustAssocs(qreal dx, qreal dy)
{
logDebug3("UMLWidget::adjustAssocs(%1) : w=%2, h=%3", name(), width(), height());
// don't adjust Assocs on file load, as
// the original positions, which are stored in XMI
// should be reproduced exactly
// (don't try to reposition assocs as long
// as file is only partly loaded -> reposition
// could be misguided)
/// @todo avoid trigger of this event during load
if (m_doc->loading() || (qFuzzyIsNull(dx) && qFuzzyIsNull(dy))) {
// don't recalculate the assocs during load of XMI
// -> return immediately without action
return;
}
for(AssociationWidget *assocwidget : associationWidgetList()) {
assocwidget->saveIdealTextPositions();
}
for(AssociationWidget *assocwidget : associationWidgetList()) {
assocwidget->widgetMoved(this, dx, dy);
}
}
/**
* Adjusts all unselected associations with the given co-ordinates
*
* @param dx The amount by which the widget moved in X direction.
* @param dy The amount by which the widget moved in Y direction.
*/
void UMLWidget::adjustUnselectedAssocs(qreal dx, qreal dy)
{
for(AssociationWidget *assocwidget : associationWidgetList()) {
if (!assocwidget->isSelected())
assocwidget->saveIdealTextPositions();
}
for(AssociationWidget *assocwidget : associationWidgetList()) {
if (!assocwidget->isSelected() &&
(this == assocwidget->widgetForRole(Uml::RoleType::A) ||
this == assocwidget->widgetForRole(Uml::RoleType::B))) {
assocwidget->widgetMoved(this, dx, dy);
}
}
}
/**
* Show a properties dialog for a UMLWidget.
*/
bool UMLWidget::showPropertiesDialog()
{
bool result = false;
// will already be selected so make sure docWindow updates the doc
// back it the widget
UMLApp::app()->docWindow()->updateDocumentation(false);
QPointer<ClassPropertiesDialog> dlg = new ClassPropertiesDialog((QWidget*)UMLApp::app(), this);
if (dlg->exec()) {
UMLApp::app()->docWindow()->showDocumentation(umlObject(), true);
m_doc->setModified(true);
result = true;
}
dlg->close(); //wipe from memory
delete dlg;
return result;
}
/**
* Move the widget by an X and Y offset relative to
* the current position.
*/
void UMLWidget::moveByLocal(qreal dx, qreal dy)
{
qreal newX = x() + dx;
qreal newY = y() + dy;
setX(newX);
setY(newY);
adjustAssocs(dx, dy);
}
/**
* Set the pen.
*/
void UMLWidget::setPenFromSettings(QPainter & p)
{
p.setPen(QPen(m_lineColor, m_lineWidth));
}
/**
* Set the pen.
*/
void UMLWidget::setPenFromSettings(QPainter *p)
{
p->setPen(QPen(m_lineColor, m_lineWidth));
}
/**
* Return true if `this' is located in the bounding rectangle of `other'.
*/
bool UMLWidget::isLocatedIn(const UMLWidget *other) const
{
const QPointF pos = scenePos();
const QPointF otherPos = other->scenePos();
const QString msgProlog = QStringLiteral("UMLWidget ") + name() +
QStringLiteral(" isLocatedIn(") + other->name() + QStringLiteral(")");
if (otherPos.x() > pos.x() || otherPos.y() > pos.y()) {
logDebug1("%1 returns false due to x or y out of range", msgProlog);
return false;
}
const int endX = pos.x() + width();
const int endY = pos.y() + height();
if (otherPos.x() > endX || otherPos.y() > endY) {
logDebug1("%1 returns false due to endX or endY out of range", msgProlog);
return false;
}
const int otherEndX = otherPos.x() + other->width();
if (otherEndX < pos.x() || otherEndX < endX) {
logDebug1("%1 returns false due to otherEndX out of range", msgProlog);
return false;
}
const int otherEndY = otherPos.y() + other->height();
if (otherEndY < pos.y() || otherEndY < endY) {
logDebug1("%1 returns false due to otherEndY out of range", msgProlog);
return false;
}
logDebug2("UMLWidget %1 isLocatedIn(%2) returns true", name(), other->name());
return true;
}
/**
* Returns the cursor to be shown when resizing the widget.
* Default cursor is KCursor::sizeFDiagCursor().
*
* @return The cursor to be shown when resizing the widget.
*/
QCursor UMLWidget::resizeCursor() const
{
return Qt::SizeFDiagCursor;
}
/**
* Checks if the mouse is in resize area (right bottom corner), and sets
* the cursor depending on that.
* The cursor used when resizing is gotten from resizeCursor().
*
* @param me The QMouseEVent to check.
* @return true if the mouse is in resize area, false otherwise.
*/
bool UMLWidget::isInResizeArea(QGraphicsSceneMouseEvent *me)
{
qreal m = 10.0;
const qreal w = width();
const qreal h = height();
// If the widget itself is very small then make the resize area small, too.
// Reason: Else it becomes impossible to do a move instead of resize.
if (w - m < m || h - m < m) {
m = 2.0;
}
if (m_resizable &&
me->scenePos().x() >= (x() + w - m) &&
me->scenePos().y() >= (y() + h - m)) {
m_scene->activeView()->setCursor(resizeCursor());
return true;
} else {
m_scene->activeView()->setCursor(Qt::ArrowCursor);
return false;
}
}
/**
* calculate content related size of widget.
*
* @return calculated widget size
*/
QSizeF UMLWidget::calculateSize(bool withExtensions /* = true */) const
{
Q_UNUSED(withExtensions)
const QFontMetrics &fm = getFontMetrics(UMLWidget::FT_NORMAL);
const int fontHeight = fm.lineSpacing();
if (m_umlObject) {
qreal width = 0, height = defaultMargin;
if (!m_umlObject->stereotype().isEmpty()) {
height += fontHeight;
const QFontMetrics &bfm = UMLWidget::getFontMetrics(UMLWidget::FT_BOLD);
const int stereoWidth = bfm.size(0, m_umlObject->stereotype(true)).width();
if (stereoWidth > width)
width = stereoWidth;
}
height += fontHeight;
const QFontMetrics &bfm = UMLWidget::getFontMetrics(UMLWidget::FT_BOLD);
const int nameWidth = bfm.size(0, m_umlObject->name()).width();
if (nameWidth > width)
width = nameWidth;
return QSizeF(width + 2*defaultMargin, height);
}
else
return QSizeF(width(), height());
}
/**
* Resize widget to minimum size.
*/
void UMLWidget::resize()
{
qreal oldW = width();
qreal oldH = height();
// @TODO minimumSize() do not work in all cases, we need a dedicated autoResize() method
QSizeF size = minimumSize();
setSize(size.width(), size.height());
logDebug3("UMLWidget::resize(%1) w=%2, h=%3", name(), size.width(), size.height());
adjustAssocs(size.width()-oldW, size.height()-oldH);
}
/**
* Resizes the widget and adjusts the associations.
* It's called when a mouse move event happens and the cursor was
* in resize area when pressed.
* Resizing can be constrained to an specific axis using control and shift buttons.
*
* @param me The QGraphicsSceneMouseEvent to get the values from.
*/
void UMLWidget::resize(QGraphicsSceneMouseEvent *me)
{
QString msgX = i18n("Hold shift or control to move in X axis.");
QString msgY = i18n("Hold shift and control to move in Y axis.");
QString msg;
if (isMessageWidget())
msg = msgY;
else if (isObjectWidget())
msg = msgX;
else
msg = QString(QStringLiteral("%1 %2")).arg(msgX, msgY);
UMLApp::app()->document()->writeToStatusBar(msg);
m_resized = true;
qreal newW = m_oldW + me->scenePos().x() - x() - m_pressOffset.x();
qreal newH = m_oldH + me->scenePos().y() - y() - m_pressOffset.y();
if ((me->modifiers() & Qt::ShiftModifier) && (me->modifiers() & Qt::ControlModifier)) {
//Move in Y axis
newW = m_oldW;
} else if ((me->modifiers() & Qt::ShiftModifier) || (me->modifiers() & Qt::ControlModifier)) {
//Move in X axis
newH = m_oldH;
}
constrain(newW, newH);
resizeWidget(newW, newH);
DEBUG() << "event=" << me->scenePos() << "/ pos=" << pos() << " / newW=" << newW << " / newH=" << newH;
QPointF delta = me->scenePos() - me->lastScenePos();
adjustAssocs(delta.x(), delta.y());
}
/**
* Checks if the size of the widget changed respect to the size that
* it had when press event was fired.
*
* @return true if was resized, false otherwise.
*/
bool UMLWidget::wasSizeChanged()
{
return m_oldW != width() || m_oldH != height();
}
/**
* Checks if the position of the widget changed respect to the position that
* it had when press event was fired.
*
* @return true if was moved, false otherwise.
*/
bool UMLWidget::wasPositionChanged()
{
return m_oldPos != pos();
}
/**
* Fills m_selectedWidgetsList and sets the selection bounds ((m_min/m_max)X/Y attributes).
*/
void UMLWidget::setSelectionBounds()
{
}
void UMLWidget::setSelectedFlag(bool _select)
{
WidgetBase::setSelected(_select);
}
/**
* Sets the state of whether the widget is selected.
*
* @param _select The state of whether the widget is selected.
*/
void UMLWidget::setSelected(bool _select)
{
const WidgetBase::WidgetType wt = baseType();
if (_select) {
if (m_scene->selectedCount() == 0) {
if (widgetHasUMLObject(wt)) {
UMLApp::app()->docWindow()->showDocumentation(m_umlObject, false);
} else {
UMLApp::app()->docWindow()->showDocumentation(this, false);
}
}//end if
/* if (wt != wt_Text && wt != wt_Box) {
setZ(9);//keep text on top and boxes behind so don't touch Z value
} */
} else {
/* if (wt != wt_Text && wt != wt_Box) {
setZ(m_origZ);
} */
if (isSelected())
UMLApp::app()->docWindow()->updateDocumentation(true);
}
WidgetBase::setSelected(_select);
logDebug1("UMLWidget::setSelected(%1) : Prevent obscuring", _select);
Widget_Utils::ensureNestedVisible(this, umlScene()->widgetList());
update();
// selection changed, we have to make sure the copy and paste items
// are correctly enabled/disabled
UMLApp::app()->slotCopyChanged();
// select in tree view as done for diagrams
if (_select) {
UMLListViewItem * item = UMLApp::app()->listView()->findItem(id());
if (item)
UMLApp::app()->listView()->setCurrentItem(item);
else
UMLApp::app()->listView()->clearSelection();
}
}
/**
* Selects the widget and clears the other selected widgets, if any.
*
* @param me The QGraphicsSceneMouseEvent which made the selection.
*/
void UMLWidget::selectSingle(QGraphicsSceneMouseEvent *me)
{
m_scene->clearSelected();
// Adds the widget to the selected widgets list, but as it has been cleared
// only the current widget is selected.
selectMultiple(me);
}
/**
* Selects the widget and adds it to the list of selected widgets.
*
* @param me The QGraphicsSceneMouseEvent which made the selection.
*/
void UMLWidget::selectMultiple(QGraphicsSceneMouseEvent *me)
{
Q_UNUSED(me);
setSelected(true);
}
/**
* Deselects the widget and removes it from the list of selected widgets.
*
* @param me The QGraphicsSceneMouseEvent which made the selection.
*/
void UMLWidget::deselect(QGraphicsSceneMouseEvent *me)
{
Q_UNUSED(me);
setSelected(false);
}
/**
* Clears the selection, resets the toolbar and deselects the widget.
*/
//void UMLWidget::resetSelection()
//{
// m_scene->clearSelected();
// m_scene->resetToolbar();
// setSelected(false);
//}
/**
* Sets the view the widget is on.
*
* @param scene The UMLScene the widget is on.
*/
void UMLWidget::setScene(UMLScene *scene)
{
//remove signals from old view - was probably 0 anyway
disconnect(m_scene, SIGNAL(sigFillColorChanged(Uml::ID::Type)), this, SLOT(slotFillColorChanged(Uml::ID::Type)));
disconnect(m_scene, SIGNAL(sigTextColorChanged(Uml::ID::Type)), this, SLOT(slotTextColorChanged(Uml::ID::Type)));
disconnect(m_scene, SIGNAL(sigLineWidthChanged(Uml::ID::Type)), this, SLOT(slotLineWidthChanged(Uml::ID::Type)));
m_scene = scene;
connect(m_scene, SIGNAL(sigFillColorChanged(Uml::ID::Type)), this, SLOT(slotFillColorChanged(Uml::ID::Type)));
connect(m_scene, SIGNAL(sigTextColorChanged(Uml::ID::Type)), this, SLOT(slotTextColorChanged(Uml::ID::Type)));
connect(m_scene, SIGNAL(sigLineWidthChanged(Uml::ID::Type)), this, SLOT(slotLineWidthChanged(Uml::ID::Type)));
}
/**
* Gets the x-coordinate.
* Currently, the only class that reimplements this method is PinPortBase.
*
* @return The x-coordinate.
*/
qreal UMLWidget::getX() const
{
return QGraphicsObjectWrapper::x();
}
/**
* Gets the y-coordinate.
* Currently, the only class that reimplements this method is PinPortBase.
*
* @return The y-coordinate.
*/
qreal UMLWidget::getY() const
{
return QGraphicsObjectWrapper::y();
}
/**
* Gets the position.
* Currently, the only class that reimplements this method is PinPortBase.
*
* @return The QGraphicsObject position.
*/
QPointF UMLWidget::getPos() const
{
return QGraphicsObjectWrapper::pos();
}
/**
* Sets the x-coordinate.
* Currently, the only class that reimplements this method is
* ObjectWidget.
*
* @param x The x-coordinate to be set.
*/
void UMLWidget::setX(qreal x)
{
if (x < -UMLScene::maxCanvasSize() || x > UMLScene::maxCanvasSize())
logError1("UMLWidget::setX refusing to set X to %1", x);
else
QGraphicsObjectWrapper::setX(x);
}
/**
* Sets the y-coordinate.
* Currently, the only class that reimplements this method is
* ObjectWidget.
*
* @param y The y-coordinate to be set.
*/
void UMLWidget::setY(qreal y)
{
if (y < -UMLScene::maxCanvasSize() || y > UMLScene::maxCanvasSize())
logError1("UMLWidget::setY refusing to set Y to %1", y);
else
QGraphicsObjectWrapper::setY(y);
}
/**
* Used to cleanup any other widget it may need to delete.
* Used by child classes. This should be called before deleting a widget of a diagram.
*/
void UMLWidget::cleanup()
{
}
/**
* Tells the widget to snap to grid.
* Will use the grid settings of the @ref UMLView it belongs to.
*/
void UMLWidget::slotSnapToGrid()
{
if (!m_ignoreSnapToGrid) {
qreal newX = m_scene->snappedX(x());
setX(newX);
qreal newY = m_scene->snappedY(y());
setY(newY);
}
}
/**
* Set m_ignoreSnapToGrid.
*/
void UMLWidget::setIgnoreSnapToGrid(bool to)
{
m_ignoreSnapToGrid = to;
}
/**
* Return the value of m_ignoreSnapToGrid.
*/
bool UMLWidget::getIgnoreSnapToGrid() const
{
return m_ignoreSnapToGrid;
}
/**
* Sets the size.
* If m_scene->snapComponentSizeToGrid() is true then
* set the next larger size that snaps to the grid.
*/
void UMLWidget::setSize(qreal width, qreal height)
{
// snap to the next larger size that is a multiple of the grid
if (!m_ignoreSnapComponentSizeToGrid && m_scene
&& m_scene->snapComponentSizeToGrid()) {
// integer divisions
int numX = width / m_scene->snapX();
int numY = height / m_scene->snapY();
// snap to the next larger valid value
if (width > numX * m_scene->snapX())
width = (numX + 1) * m_scene->snapX();
if (height > numY * m_scene->snapY())
height = (numY + 1) * m_scene->snapY();
}
const QRectF newRect(rect().x(), rect().y(), width, height);
logDebug3("UMLWidget::setSize(%1): setting w=%2, h=%3", name(), newRect.width(), newRect.height());
setRect(newRect);
for(QGraphicsItem *child : childItems()) {
UMLWidget* umlChild = static_cast<UMLWidget*>(child);
umlChild->notifyParentResize();
}
}
/**
* Sets the size with another size.
*/
void UMLWidget::setSize(const QSizeF& size)
{
setSize(size.width(), size.height());
}
/**
* Update the size of this widget.
*
* @param withAssocs true - update associations too
*/
void UMLWidget::updateGeometry(bool withAssocs)
{
if (m_doc->loading()) {
return;
}
if (!m_autoResize)
return;
qreal oldW = width();
qreal oldH = height();
QSizeF size = calculateSize();
qreal clipWidth = size.width();
qreal clipHeight = size.height();
constrain(clipWidth, clipHeight);
logDebug5("UMLWidget::updateGeometry(%1) : oldW=%2, oldH=%3, clipWidth=%4, clipHeight=%5",
name(), oldW, oldH, clipWidth, clipHeight);
setSize(clipWidth, clipHeight);
slotSnapToGrid();
if (withAssocs)
adjustAssocs(size.width()-oldW, size.height()-oldH);
update();
}
/**
* clip the size of this widget against the
* minimal and maximal limits.
*/
void UMLWidget::clipSize()
{
qreal clipWidth = width();
qreal clipHeight = height();
constrain(clipWidth, clipHeight);
setSize(clipWidth, clipHeight);
}
/**
* Template Method, override this to set the default font metric.
*/
void UMLWidget::setDefaultFontMetrics(QFont &font, UMLWidget::FontType fontType)
{
setupFontType(font, fontType);
setFontMetrics(fontType, QFontMetrics(font));
}
void UMLWidget::setupFontType(QFont &font, UMLWidget::FontType fontType)
{
switch (fontType) {
case FT_NORMAL:
font.setBold(false);
font.setItalic(false);
font.setUnderline(false);
break;
case FT_BOLD:
font.setBold(true);
font.setItalic(false);
font.setUnderline(false);
break;
case FT_ITALIC:
font.setBold(false);
font.setItalic(true);
font.setUnderline(false);
break;
case FT_UNDERLINE:
font.setBold(false);
font.setItalic(false);
font.setUnderline(true);
break;
case FT_BOLD_ITALIC:
font.setBold(true);
font.setItalic(true);
font.setUnderline(false);
break;
case FT_BOLD_UNDERLINE:
font.setBold(true);
font.setItalic(false);
font.setUnderline(true);
break;
case FT_ITALIC_UNDERLINE:
font.setBold(false);
font.setItalic(true);
font.setUnderline(true);
break;
case FT_BOLD_ITALIC_UNDERLINE:
font.setBold(true);
font.setItalic(true);
font.setUnderline(true);
break;
default: return;
}
}
void UMLWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if (option->state & QStyle::State_Selected) {
const qreal w = width();
const qreal h = height();
const qreal s = selectionMarkerSize;
QBrush brush(Qt::blue);
painter->fillRect(0, 0, s, s, brush);
painter->fillRect(0, 0 + h - s, s, s, brush);
painter->fillRect(0 + w - s, 0, s, s, brush);
// Draw the resize anchor in the lower right corner.
// Don't draw it if the widget is so small that the
// resize anchor would cover up most of the widget.
if (m_resizable && w >= s+8 && h >= s+8) {
brush.setColor(Qt::red);
const int bottom = 0 + h;
int horSide = w; // horizontal side default: right side
if (baseType() == wt_Message) {
MessageWidget *msg = asMessageWidget();
int x1 = msg->objectWidget(Uml::RoleType::A)->x();
int x2 = msg->objectWidget(Uml::RoleType::B)->x();
if (x1 > x2) {
// On messages running right to left we use the left side for
// placing the resize anchor because the message's execution
// specification as at the left in this case. Furthermore,
// the right side may be covered up by another message's
// execution specification.
horSide = 17; // execution box width
}
}
painter->drawLine(horSide - s, 0 + h - 1, 0 + w - 1, 0 + h - s);
painter->drawLine(horSide - (s*2), bottom - 1, horSide - 1, bottom - (s*2));
painter->drawLine(horSide - (s*3), bottom - 1, horSide - 1, bottom - (s*3));
} else {
painter->fillRect(0 + w - s, 0 + h - s, s, s, brush);
}
// debug info
if (Tracer::instance()->isEnabled(QLatin1String(metaObject()->className()))) {
QPen p(Qt::green);
p.setWidthF(1.0);
painter->setPen(p);
painter->setBrush(Qt::NoBrush);
painter->drawPath(shape());
painter->setPen(Qt::blue);
painter->drawRect(boundingRect());
// origin
painter->drawLine(-10, 0, 10, 0);
painter->drawLine(0, -10, 0, 10);
}
}
if (umlScene()->isShowDocumentationIndicator() && hasDocumentation()) {
const qreal h = height();
const qreal d = 8;
QPolygonF p;
p << QPointF(0, h - d) << QPointF(d, h) << QPointF(0, h);
painter->setPen(Qt::blue);
painter->setBrush(Qt::red);
painter->drawPolygon(p);
}
}
/**
* Template Method, override this to set the default font metric.
*/
void UMLWidget::setDefaultFontMetrics(QFont &font, UMLWidget::FontType fontType, QPainter &painter)
{
setupFontType(font, fontType);
painter.setFont(font);
setFontMetrics(fontType, painter.fontMetrics());
}
/**
* Returns the font metric used by this object for Text
* which uses bold/italic fonts.
*/
QFontMetrics &UMLWidget::getFontMetrics(UMLWidget::FontType fontType) const
{
return *m_pFontMetrics[fontType];
}
/**
* Set the font metric to use.
*/
void UMLWidget::setFontMetrics(UMLWidget::FontType fontType, QFontMetrics fm)
{
delete m_pFontMetrics[fontType];
m_pFontMetrics[fontType] = new QFontMetrics(fm);
}
/**
* Sets the font the widget is to use.
*
* @param font Font to be set.
*/
void UMLWidget::setFont(const QFont &font)
{
QFont newFont = font;
forceUpdateFontMetrics(newFont, nullptr);
if (m_font != newFont) {
UMLApp::app()->executeCommand(new CmdChangeFont(this, font));
}
}
/**
* Sets the font the widget is to use.
*
* @param font Font to be set.
*/
void UMLWidget::setFontCmd(const QFont &font)
{
WidgetBase::setFont(font);
forceUpdateFontMetrics(nullptr);
if (m_doc->loading())
return;
update();
}
/**
* Updates font metrics for widgets current m_font
*/
void UMLWidget::forceUpdateFontMetrics(QPainter *painter)
{
forceUpdateFontMetrics(m_font, painter);
}
/**
* @note For performance Reasons, only FontMetrics for already used
* font types are updated. Not yet used font types will not get a font metric
* and will get the same font metric as if painter was zero.
* This behaviour is acceptable, because diagrams will always be shown on Display
* first before a special painter like a printer device is used.
*/
void UMLWidget::forceUpdateFontMetrics(QFont& font, QPainter *painter)
{
if (painter == nullptr) {
for (int i = (int)FT_INVALID - 1; i >= 0; --i) {
if (m_pFontMetrics[(UMLWidget::FontType)i] != nullptr)
setDefaultFontMetrics(font, (UMLWidget::FontType)i);
}
} else {
for (int i2 = (int)FT_INVALID - 1; i2 >= 0; --i2) {
if (m_pFontMetrics[(UMLWidget::FontType)i2] != nullptr)
setDefaultFontMetrics(font, (UMLWidget::FontType)i2, *painter);
}
}
if (m_doc->loading())
return;
// calculate the size, based on the new font metric
updateGeometry();
}
/**
* Set the status of whether to show Stereotype.
*
* @param flag Value of type Uml::ShowStereoType::Enum
*/
void UMLWidget::setShowStereotype(Uml::ShowStereoType::Enum flag)
{
m_showStereotype = flag;
updateGeometry();
update();
}
/**
* Return stereotype concrete attributes concatenated into single string
* with the attribute name given before each value and delimited by "{"
* at start and "}" at end.
* Example:
* For a stereotype with attribute 'foo' of type Double and attribute 'bar'
* of type String and concrete values 1.0 for 'foo' and "hello" for 'bar',
* the result is: {foo=1.0,bar="hello"}
*/
QString UMLWidget::tags() const
{
if (m_umlObject == nullptr)
return QString();
UMLStereotype *s = m_umlObject->umlStereotype();
if (s == nullptr)
return QString();
UMLStereotype::AttributeDefs adefs = s->getAttributeDefs();
if (adefs.isEmpty())
return QString();
const QStringList& umlTags = m_umlObject->tags();
QString taggedValues(QStringLiteral("{"));
for (int i = 0; i < adefs.size(); i++) {
UMLStereotype::AttributeDef ad = adefs.at(i);
taggedValues.append(ad.name);
taggedValues.append(QStringLiteral("="));
QString value = ad.defaultVal;
if (i < umlTags.size()) {
QString umlTag = umlTags.at(i);
if (!umlTag.isEmpty())
value = umlTag;
}
if (ad.type == Uml::PrimitiveTypes::String)
value = QStringLiteral("\"") + value + QStringLiteral("\"");
taggedValues.append(value);
if (i < adefs.size() - 1)
taggedValues.append(QStringLiteral(","));
}
taggedValues.append(QStringLiteral("}"));
return taggedValues;
}
/**
* Returns the status of whether to show Stereotype.
*
* @return True if stereotype is shown.
*/
Uml::ShowStereoType::Enum UMLWidget::showStereotype() const
{
return m_showStereotype;
}
/**
* Overrides the standard operation.
*
* @param me The move event.
*/
void UMLWidget::moveEvent(QGraphicsSceneMouseEvent* me)
{
Q_UNUSED(me)
}
void UMLWidget::saveToXMI(QXmlStreamWriter& writer)
{
/*
When calling this from child classes bear in mind that the call
must precede terminated XML subelements.
Type must be set in the child class.
*/
WidgetBase::saveToXMI(writer);
DiagramProxyWidget::saveToXMI(writer);
qreal dpiScale = UMLApp::app()->document()->dpiScale();
writer.writeAttribute(QStringLiteral("x"), QString::number(x() / dpiScale));
writer.writeAttribute(QStringLiteral("y"), QString::number(y() / dpiScale));
writer.writeAttribute(QStringLiteral("width"), QString::number(width() / dpiScale));
writer.writeAttribute(QStringLiteral("height"), QString::number(height() / dpiScale));
writer.writeAttribute(QStringLiteral("isinstance"), QString::number(m_isInstance));
if (!m_instanceName.isEmpty())
writer.writeAttribute(QStringLiteral("instancename"), m_instanceName);
writer.writeAttribute(QStringLiteral("showstereotype"), QString::number(m_showStereotype));
}
bool UMLWidget::loadFromXMI(QDomElement & qElement)
{
WidgetBase::loadFromXMI(qElement);
DiagramProxyWidget::loadFromXMI(qElement);
QString x = qElement.attribute(QStringLiteral("x"), QStringLiteral("0"));
QString y = qElement.attribute(QStringLiteral("y"), QStringLiteral("0"));
QString h = qElement.attribute(QStringLiteral("height"), QStringLiteral("0"));
QString w = qElement.attribute(QStringLiteral("width"), QStringLiteral("0"));
const qreal dpiScale = UMLApp::app()->document()->dpiScale();
const qreal scaledW = toDoubleFromAnyLocale(w) * dpiScale;
const qreal scaledH = toDoubleFromAnyLocale(h) * dpiScale;
setSize(scaledW, scaledH);
qreal nX = toDoubleFromAnyLocale(x);
qreal nY = toDoubleFromAnyLocale(y);
bool applyOffsetCorrection = true;
if (nX < -UMLScene::maxCanvasSize() || nX > UMLScene::maxCanvasSize()) {
logWarn2("UMLWidget::loadFromXMI: widget of type %1 has illegal X value %2, setting to default position 10",
baseType(), nX);
nX = 10.0;
applyOffsetCorrection = false;
}
if (nY < -UMLScene::maxCanvasSize() || nY > UMLScene::maxCanvasSize()) {
logWarn2("UMLWidget::loadFromXMI: widget of type %1 has illegal Y value %2, setting to default position 10",
baseType(), nY);
nY = 10.0;
applyOffsetCorrection = false;
}
qreal fixedX = nX;
qreal fixedY = nY;
bool usesRelativeCoords = (baseType() == wt_Pin || baseType() == wt_Port);
if (!usesRelativeCoords && baseType() == wt_Text) {
UMLWidget *parent = dynamic_cast<UMLWidget*>(parentItem());
usesRelativeCoords = (parent != nullptr);
}
if (applyOffsetCorrection && !usesRelativeCoords) {
fixedX += umlScene()->fixX(); // bug 449622
fixedY += umlScene()->fixY();
}
const qreal scaledX = fixedX * dpiScale;
const qreal scaledY = fixedY * dpiScale;
if (applyOffsetCorrection && !usesRelativeCoords) {
umlScene()->updateCanvasSizeEstimate(scaledX, scaledY, scaledW, scaledH);
}
setX(scaledX);
setY(scaledY);
QString isinstance = qElement.attribute(QStringLiteral("isinstance"), QStringLiteral("0"));
m_isInstance = (bool)isinstance.toInt();
m_instanceName = qElement.attribute(QStringLiteral("instancename"));
QString showstereo = qElement.attribute(QStringLiteral("showstereotype"), QStringLiteral("0"));
m_showStereotype = (Uml::ShowStereoType::Enum)showstereo.toInt();
return true;
}
/**
* Adds a widget to the diagram, which is connected to the current widget
* @param widget widget instance to add to diagram
* @param type association type
* @param options widget options
*/
void UMLWidget::addConnectedWidget(UMLWidget *widget, Uml::AssociationType::Enum type, AddWidgetOptions options)
{
QString name = Widget_Utils::defaultWidgetName(widget->baseType());
widget->setName(name);
if (options & ShowProperties) {
if (!widget->showPropertiesDialog()) {
delete widget;
return;
}
}
umlScene()->addItem(widget);
widget->setX(x() + rect().width() + 100);
widget->setY(y());
if (options & SetupSize) {
widget->setSize(100, 40);
QSizeF size = widget->minimumSize();
widget->setSize(size);
}
AssociationWidget* assoc = options & SwitchDirection ? AssociationWidget::create(umlScene(), widget, type, this)
: AssociationWidget::create(umlScene(), this, type, widget);
umlScene()->addAssociation(assoc);
umlScene()->clearSelected();
umlScene()->selectWidget(widget);
UMLApp::app()->beginMacro(I18N_NEXT_RELEASE("Adding connected '%1'", widget->baseTypeStrWithoutPrefix());
UMLApp::app()->executeCommand(new CmdCreateWidget(widget));
UMLApp::app()->executeCommand(new CmdCreateWidget(assoc));
UMLApp::app()->endMacro();
m_doc->setModified();
}
/**
* Adds a widget to the diagram, which is connected to the current widget
* @param widget widget instance to add to diagram
* @param showProperties whether to show properties of the widget
*/
void UMLWidget::addWidget(UMLWidget *widget, bool showProperties)
{
umlScene()->addItem(widget);
widget->setX(x() + rect().width() + 100);
widget->setY(y());
widget->setSize(100, 40);
if (showProperties)
widget->showPropertiesDialog();
QSizeF size = widget->minimumSize();
widget->setSize(size);
}
| 72,438
|
C++
|
.cpp
| 2,103
| 29.266286
| 135
| 0.66458
|
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,397
|
widgetbase.cpp
|
KDE_umbrello/umbrello/umlwidgets/widgetbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "widgetbase.h"
#include "classifier.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "floatingtextwidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umlobject.h"
#include "umlscene.h"
#include "widgetbasepopupmenu.h"
#include "uniqueid.h"
#include <KLocalizedString>
#include <QAction>
#include <QColorDialog>
#include <QFontDialog>
#include <QPointer>
#include <QXmlStreamWriter>
DEBUG_REGISTER(WidgetBase)
static unsigned eventCnt = 0;
void QGraphicsObjectWrapper::setSelected(bool state)
{
if (!m_calledFromItemChange)
QGraphicsObject::setSelected(state);
QString info;
WidgetBase *wb = dynamic_cast<WidgetBase*>(this);
if (wb)
info = wb->name();
if (info.isEmpty()) {
DEBUG()
<< ++eventCnt << " new state=" << state << ", fromItemChange=" << m_calledFromItemChange << " " << this;
} else { // @todo convert DEBUG() stream to logDebug3 macro (uml.h)
DEBUG()
<< ++eventCnt << " new state=" << state << ", fromItemChange=" << m_calledFromItemChange << " " << info;
}
m_calledFromItemChange = false;
}
QVariant QGraphicsObjectWrapper::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedChange && scene()) {
bool state = value.toBool();
m_calledFromItemChange = true;
setSelected(state);
}
return QGraphicsItem::itemChange(change, value);
}
/**
* Creates a WidgetBase object.
*
* @param scene The view to be displayed on.
* @param type The WidgetType to construct. This must be set to the appropriate
* value by the constructors of inheriting classes.
* @param id The XMI ID to use. The value Uml::ID::None will trigger generation of a new ID.
*/
WidgetBase::WidgetBase(UMLScene *scene, WidgetType type, Uml::ID::Type id)
: QGraphicsObjectWrapper(),
m_baseType(type),
m_scene(scene),
m_umlObject(nullptr),
m_nId(id == Uml::ID::None ? UniqueID::gen() : id),
m_nLocalID(UniqueID::gen()),
m_textColor(QColor("black")),
m_fillColor(QColor("yellow")),
m_brush(m_fillColor),
m_lineWidth(0), // initialize with 0 to have valid start condition
m_useFillColor(true),
m_usesDiagramFillColor(true),
m_usesDiagramLineColor(true),
m_usesDiagramLineWidth(true),
m_usesDiagramTextColor(true),
m_usesDiagramUseFillColor(true),
m_autoResize(true),
m_changesShape(false)
{
Q_ASSERT(m_baseType > wt_Min && m_baseType < wt_Max);
setFlags(ItemIsSelectable);
//setFlags(ItemIsSelectable | ItemIsMovable |ItemSendsGeometryChanges);
// Note: no virtual methods from derived classes available,
// this operation need to be finished in derived class constructor.
setLineColor(QColor("black"));
setSelected(false);
if (m_scene) {
m_usesDiagramLineColor = true;
m_usesDiagramLineWidth = true;
m_usesDiagramTextColor = true;
const Settings::OptionState& optionState = m_scene->optionState();
m_textColor = optionState.uiState.textColor;
setLineColor(optionState.uiState.lineColor);
setLineWidth(optionState.uiState.lineWidth);
m_font = optionState.uiState.font;
} else {
logError0("WidgetBase constructor: SERIOUS PROBLEM - m_scene is NULL");
}
}
/**
* Destructor.
*/
WidgetBase::~WidgetBase()
{
}
/**
* Read property of m_baseType.
*/
WidgetBase::WidgetType WidgetBase::baseType() const
{
Q_ASSERT(m_baseType > wt_Min && m_baseType < wt_Max);
return m_baseType;
}
/**
* Set property m_baseType. Used for types changing their types during runtime.
*/
void WidgetBase::setBaseType(const WidgetType& baseType)
{
Q_ASSERT(baseType > wt_Min && baseType < wt_Max);
m_baseType = baseType;
}
/**
* @return The type used for rtti as string.
*/
QLatin1String WidgetBase::baseTypeStr() const
{
Q_ASSERT(m_baseType > wt_Min && m_baseType < wt_Max);
return QLatin1String(ENUM_NAME(WidgetBase, WidgetType, m_baseType));
}
/**
* @return The type as string without 'wt_' prefix.
*/
QString WidgetBase::baseTypeStrWithoutPrefix() const
{
QString rawType = baseTypeStr();
return rawType.remove(QStringLiteral("wt_"));
}
/*
* Sets the state of whether the widget is selected.
*
* @param select The state of whether the widget is selected.
*/
void WidgetBase::setSelected(bool select)
{
QGraphicsObjectWrapper::setSelected(select);
}
/**
* Deliver a pointer to the connected UMLView
* (needed esp. by event handling of AssociationLine).
*/
UMLScene* WidgetBase::umlScene() const
{
return m_scene;
}
/**
* This is shortcut method for UMLApp::app()->document().
*
* @return Pointer to the UMLDoc object.
*/
UMLDoc* WidgetBase::umlDoc() const
{
return UMLApp::app()->document();
}
/**
* Returns the @ref UMLObject set to represent.
*
* @return the UMLObject to represent.
*/
UMLObject* WidgetBase::umlObject() const
{
return m_umlObject;
}
/**
* Sets the @ref UMLObject to represent.
*
* @param obj The object to represent.
*/
void WidgetBase::setUMLObject(UMLObject *obj)
{
m_umlObject = obj;
}
/**
* Write property of m_nId.
*/
void WidgetBase::setID(Uml::ID::Type id)
{
if (m_umlObject) {
if (m_umlObject->id() != Uml::ID::None)
logWarn2("WidgetBase::setID changing old UMLObject %1 to %2",
Uml::ID::toString(m_umlObject->id()), Uml::ID::toString(id));
m_umlObject->setID(id);
}
m_nId = id;
}
/**
* Read property of m_nId.
*/
Uml::ID::Type WidgetBase::id() const
{
if (m_umlObject)
return m_umlObject->id();
return m_nId;
}
/**
* Sets the local id of the object.
*
* @param id The local id of the object.
*/
void WidgetBase::setLocalID(Uml::ID::Type id)
{
m_nLocalID = id;
}
/**
* Returns the local ID for this object. This ID is used so that
* many objects of the same @ref UMLObject instance can be on the
* same diagram.
*
* @return The local ID.
*/
Uml::ID::Type WidgetBase::localID() const
{
return m_nLocalID;
}
/**
* Returns the widget with the given ID.
* The default implementation tests the following IDs:
* - m_nLocalID
* - if m_umlObject is non NULL: m_umlObject->id()
* - m_nID
* Composite widgets override this function to test further owned widgets.
*
* @param id The ID to test this widget against.
* @return 'this' if id is either of m_nLocalID, m_umlObject->id(), or m_nId;
* else NULL.
*/
UMLWidget* WidgetBase::widgetWithID(Uml::ID::Type id)
{
if (id == m_nLocalID ||
(m_umlObject != nullptr && id == m_umlObject->id()) ||
id == m_nId)
return this->asUMLWidget();
return nullptr;
}
/**
* Used by some child classes to get documentation.
*
* @return The documentation from the UMLObject (if m_umlObject is set.)
*/
QString WidgetBase::documentation() const
{
if (m_umlObject)
return m_umlObject->doc();
return m_Doc;
}
/**
* Returns state of documentation for the widget.
*
* @return false if documentation is empty
*/
bool WidgetBase::hasDocumentation() const
{
if (m_umlObject)
return m_umlObject->hasDoc();
return !m_Doc.isEmpty();
}
/**
* Used by some child classes to set documentation.
*
* @param doc The documentation to be set in the UMLObject
* (if m_umlObject is set.)
*/
void WidgetBase::setDocumentation(const QString& doc)
{
if (m_umlObject)
m_umlObject->setDoc(doc);
else
m_Doc = doc;
}
/**
* Gets the name from the corresponding UMLObject if this widget has an
* underlying UMLObject; if it does not then it returns the local
* m_Text (notably the case for FloatingTextWidget.)
*
* @return the currently set name
*/
QString WidgetBase::name() const
{
if (m_umlObject)
return m_umlObject->name();
return m_Text;
}
/**
* Sets the name in the corresponding UMLObject.
* Sets the local m_Text if m_umlObject is NULL.
*
* @param strName The name to be set.
*/
void WidgetBase::setName(const QString &strName)
{
if (m_umlObject)
m_umlObject->setName(strName);
else
m_Text = strName;
}
/**
* Returns text color
*
* @return currently used text color
*/
QColor WidgetBase::textColor() const
{
return m_textColor;
}
/**
* Sets the text color
*
* @param color the new text color
*/
void WidgetBase::setTextColor(const QColor &color)
{
m_textColor = color;
m_usesDiagramTextColor = false;
}
/**
* Returns line color
*
* @return currently used line color
*/
QColor WidgetBase::lineColor() const
{
return m_lineColor;
}
/**
* Sets the line color
*
* @param color The new line color
*/
void WidgetBase::setLineColor(const QColor &color)
{
m_lineColor = color;
m_usesDiagramLineColor = false;
}
/**
* Returns fill color
*
* @return currently used fill color
*/
QColor WidgetBase::fillColor() const
{
return m_fillColor;
}
/**
* Sets the fill color
*
* @param color The new fill color
*/
void WidgetBase::setFillColor(const QColor &color)
{
m_fillColor = color;
m_usesDiagramFillColor = false;
}
/**
* Returns line width
*
* @return currently used line with
*/
uint WidgetBase::lineWidth() const
{
return m_lineWidth;
}
/**
* Sets the line width
*
* @param width The new line width
*/
void WidgetBase::setLineWidth(uint width)
{
m_lineWidth = width;
m_usesDiagramLineWidth = false;
}
/**
* Return state of fill color usage
*
* @return True if fill color is used
*/
bool WidgetBase::useFillColor() const
{
return m_useFillColor;
}
/**
* Set state if fill color is used
*
* @param state The state to set
*/
void WidgetBase::setUseFillColor(bool state)
{
m_useFillColor = state;
m_usesDiagramUseFillColor = false;
}
/**
* Returns state if diagram text color is used
*
* @return True means diagram text color is used
*/
bool WidgetBase::usesDiagramTextColor() const
{
return m_usesDiagramTextColor;
}
/**
* Set state if diagram text color is used
*
* @param state The state to set
*/
void WidgetBase::setUsesDiagramTextColor(bool state)
{
if (m_usesDiagramTextColor == state) {
return;
}
m_usesDiagramTextColor = state;
setTextColor(m_textColor);
}
/**
* Returns state of diagram line color is used
*
* @return True means diagrams line color is used
*/
bool WidgetBase::usesDiagramLineColor() const
{
return m_usesDiagramLineColor;
}
/**
* Set state of diagram line color is used
*
* @param state The state to set
*/
void WidgetBase::setUsesDiagramLineColor(bool state)
{
m_usesDiagramLineColor = state;
}
/**
* Returns state of diagram fill color is used
*
* @return True means diagrams fill color is used
*/
bool WidgetBase::usesDiagramFillColor() const
{
return m_usesDiagramFillColor;
}
/**
* Set state if diagram fill color is used
*
* @param state The state to set
*/
void WidgetBase::setUsesDiagramFillColor(bool state)
{
m_usesDiagramFillColor = state;
}
/**
* Returns state of diagram use fill color is used
*
* @return True means diagrams fill color is used
*/
bool WidgetBase::usesDiagramUseFillColor() const
{
return m_usesDiagramUseFillColor;
}
/**
* Set state of diagram use fill color is used
*
* @param state The state to set
*/
void WidgetBase::setUsesDiagramUseFillColor(bool state)
{
m_usesDiagramUseFillColor = state;
}
/**
* Returns state of diagram line width is used
*
* @return True means diagrams line width is used
*/
bool WidgetBase::usesDiagramLineWidth() const
{
return m_usesDiagramLineWidth;
}
/**
* Set state of diagram line width is used
*
* @param state The state to set
*/
void WidgetBase::setUsesDiagramLineWidth(bool state)
{
m_usesDiagramLineWidth = state;
}
/**
* Returns the font used for displaying any text.
* @return the font
*/
QFont WidgetBase::font() const
{
return m_font;
}
/**
* Set the font used to display text inside this widget.
*/
void WidgetBase::setFont(const QFont& font)
{
m_font = font;
}
/**
* Return state of auto resize property
* @return the auto resize state
*/
bool WidgetBase::autoResize() const
{
return m_autoResize;
}
/**
* set auto resize state
* @param state
*/
void WidgetBase::setAutoResize(bool state)
{
m_autoResize = state;
}
/**
* Return changes state property
* @return the changes shape state
*/
bool WidgetBase::changesShape() const
{
return m_changesShape;
}
/**
* set changes shape property
* @param state
*/
void WidgetBase::setChangesShape(bool state)
{
m_changesShape = state;
}
/**
* A virtual method for the widget to display a property dialog box.
* Subclasses should reimplement this appropriately.
* In case the user cancels the dialog or there are some requirements
* not fulfilled the method returns false; true otherwise.
*
* @return true - properties has been applyed
* @return false - properties has not been applied
*
*/
bool WidgetBase::showPropertiesDialog()
{
return false;
}
/**
* A virtual method to save the properties of this widget into a
* QXmlStreamWriter i.e. XML.
*
* Subclasses should first create a new dedicated element as the child
* of \a qElement parameter passed. Then this base method should be
* called to save basic widget properties.
*
* @param writer The QXmlStreamWriter to write to.
*/
void WidgetBase::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeAttribute(QStringLiteral("xmi.id"), Uml::ID::toString(id()));
// Unique identifier for widget (todo: id() should be unique, new attribute
// should indicate the UMLObject's ID it belongs to)
writer.writeAttribute(QStringLiteral("localid"), Uml::ID::toString(m_nLocalID));
writer.writeAttribute(QStringLiteral("textcolor"), m_usesDiagramTextColor ? QStringLiteral("none")
: m_textColor.name());
if (m_usesDiagramLineColor) {
writer.writeAttribute(QStringLiteral("linecolor"), QStringLiteral("none"));
} else {
writer.writeAttribute(QStringLiteral("linecolor"), m_lineColor.name());
}
if (m_usesDiagramLineWidth) {
writer.writeAttribute(QStringLiteral("linewidth"), QStringLiteral("none"));
} else {
writer.writeAttribute(QStringLiteral("linewidth"), QString::number(m_lineWidth));
}
writer.writeAttribute(QStringLiteral("usefillcolor"), QString::number(m_useFillColor));
// for consistency the following attributes now use american spelling for "color"
writer.writeAttribute(QStringLiteral("usesdiagramfillcolor"), QString::number(m_usesDiagramFillColor));
writer.writeAttribute(QStringLiteral("usesdiagramusefillcolor"), QString::number(m_usesDiagramUseFillColor));
if (m_usesDiagramFillColor) {
writer.writeAttribute(QStringLiteral("fillcolor"), QStringLiteral("none"));
} else {
writer.writeAttribute(QStringLiteral("fillcolor"), m_fillColor.name());
}
writer.writeAttribute(QStringLiteral("font"), m_font.toString());
writer.writeAttribute(QStringLiteral("autoresize"), QString::number(m_autoResize ? 1 : 0));
}
/**
* Returns whether the widget type has an associated UMLObject
*/
bool WidgetBase::widgetHasUMLObject(WidgetBase::WidgetType type)
{
if (type == WidgetBase::wt_Actor ||
type == WidgetBase::wt_UseCase ||
type == WidgetBase::wt_Class ||
type == WidgetBase::wt_Interface ||
type == WidgetBase::wt_Enum ||
type == WidgetBase::wt_Datatype ||
type == WidgetBase::wt_Package ||
type == WidgetBase::wt_Component ||
type == WidgetBase::wt_Port ||
type == WidgetBase::wt_Node ||
type == WidgetBase::wt_Artifact ||
type == WidgetBase::wt_Object) {
return true;
} else {
return false;
}
}
/**
* Activate the object after deserializing it from XMI
*
* @param changeLog optional pointer to IDChangeLog object
* @return true for success
*/
bool WidgetBase::activate(IDChangeLog* changeLog)
{
Q_UNUSED(changeLog);
if (widgetHasUMLObject(baseType()) && m_umlObject == nullptr) {
m_umlObject = UMLApp::app()->document()->findObjectById(m_nId);
if (m_umlObject == nullptr) {
logError1("WidgetBase::activate: cannot find UMLObject with id=%1",
Uml::ID::toString(m_nId));
return false;
}
}
return true;
}
/**
* Adds an already created association to the list of
* associations that include this UMLWidget
*/
void WidgetBase::addAssoc(AssociationWidget *pAssoc)
{
Q_UNUSED(pAssoc);
}
/**
* Removes an already created association from the list of
* associations that include this UMLWidget
*/
void WidgetBase::removeAssoc(AssociationWidget *pAssoc)
{
Q_UNUSED(pAssoc);
}
/**
* A virtual method to load the properties of this widget from a
* QDomElement into this widget.
*
* Subclasses should reimplement this to load additional properties
* required, calling this base method to load the basic properties of
* the widget.
*
* @param qElement A QDomElement which contains xml info for this widget.
*
* @todo Add support to load older version.
*/
bool WidgetBase::loadFromXMI(QDomElement& qElement)
{
QString id = qElement.attribute(QStringLiteral("xmi.id"), QStringLiteral("-1"));
m_nId = Uml::ID::fromString(id);
QString localid = qElement.attribute(QStringLiteral("localid"), QStringLiteral("0"));
if (localid != QStringLiteral("0")) {
m_nLocalID = Uml::ID::fromString(localid);
}
// first load from "linecolour" and then overwrite with the "linecolor"
// attribute if that one is present. The "linecolour" name was a "typo" in
// earlier versions of Umbrello
QString lineColor = qElement.attribute(QStringLiteral("linecolour"), QStringLiteral("none"));
lineColor = qElement.attribute(QStringLiteral("linecolor"), lineColor);
if (lineColor != QStringLiteral("none")) {
setLineColor(QColor(lineColor));
m_usesDiagramLineColor = false;
} else if (m_baseType != WidgetBase::wt_Box && m_scene != nullptr) {
setLineColor(m_scene->lineColor());
m_usesDiagramLineColor = true;
}
QString lineWidth = qElement.attribute(QStringLiteral("linewidth"), QStringLiteral("none"));
if (lineWidth != QStringLiteral("none")) {
setLineWidth(lineWidth.toInt());
m_usesDiagramLineWidth = false;
} else if (m_scene) {
setLineWidth(m_scene->lineWidth());
m_usesDiagramLineWidth = true;
}
QString textColor = qElement.attribute(QStringLiteral("textcolor"), QStringLiteral("none"));
if (textColor != QStringLiteral("none")) {
m_textColor = QColor(textColor);
m_usesDiagramTextColor = false;
} else if (m_scene) {
m_textColor = m_scene->textColor();
m_usesDiagramTextColor = true;
}
QString usefillcolor = qElement.attribute(QStringLiteral("usefillcolor"), QStringLiteral("1"));
m_useFillColor = (bool)usefillcolor.toInt();
/*
For the next three *color attributes, there was a mixup of american and english spelling for "color".
So first we need to keep backward compatibility and try to retrieve the *colour attribute.
Next we overwrite this value if we find a *color, otherwise the former *colour is kept.
*/
QString fillColor = qElement.attribute(QStringLiteral("fillcolour"), QStringLiteral("none"));
fillColor = qElement.attribute(QStringLiteral("fillcolor"), fillColor);
if (fillColor != QStringLiteral("none")) {
m_fillColor = QColor(fillColor);
}
QString usesDiagramFillColor = qElement.attribute(QStringLiteral("usesdiagramfillcolour"), QStringLiteral("1"));
usesDiagramFillColor = qElement.attribute(QStringLiteral("usesdiagramfillcolor"), usesDiagramFillColor);
m_usesDiagramFillColor = (bool)usesDiagramFillColor.toInt();
QString usesDiagramUseFillColor = qElement.attribute(QStringLiteral("usesdiagramusefillcolour"), QStringLiteral("1"));
usesDiagramUseFillColor = qElement.attribute(QStringLiteral("usesdiagramusefillcolor"), usesDiagramUseFillColor);
m_usesDiagramUseFillColor = (bool)usesDiagramUseFillColor.toInt();
QString font = qElement.attribute(QStringLiteral("font"));
if (!font.isEmpty()) {
QFont newFont;
newFont.fromString(font);
m_font = newFont;
} else {
logWarn2("WidgetBase::loadFromXMI: Using default font %1 for widget with xmi.id %2",
m_font.toString(), Uml::ID::toString(m_nId));
}
QString autoResize = qElement.attribute(QStringLiteral("autoresize"), QStringLiteral("1"));
m_autoResize = (bool)autoResize.toInt();
return true;
}
/**
* Assignment operator
*/
WidgetBase& WidgetBase::operator=(const WidgetBase& other)
{
if (&other == this)
return *this;
m_baseType = other.m_baseType;
m_scene = other.m_scene;
m_umlObject = other.m_umlObject;
m_Doc = other.m_Doc;
m_Text = other.m_Text;
m_nId = other.m_nId;
m_nLocalID = other.m_nLocalID;
m_textColor = other.m_textColor;
setLineColor(other.lineColor());
m_fillColor = other.m_fillColor;
m_brush = other.m_brush;
m_font = other.m_font;
m_lineWidth = other.m_lineWidth;
m_useFillColor = other.m_useFillColor;
m_usesDiagramTextColor = other.m_usesDiagramTextColor;
m_usesDiagramLineColor = other.m_usesDiagramLineColor;
m_usesDiagramFillColor = other.m_usesDiagramFillColor;
m_usesDiagramLineWidth = other.m_usesDiagramLineWidth;
setSelected(other.isSelected());
return *this;
}
/**
* return drawing rectangle of widget in local coordinates
*/
QRectF WidgetBase::rect() const
{
return m_rect;
}
/**
* set widget rectangle in item coordinates
*/
void WidgetBase::setRect(const QRectF& rect)
{
if (m_rect == rect)
return;
logDebug3("WidgetBase::setRect(%1) : setting w=%2, h=%3", name(), rect.width(), rect.height());
prepareGeometryChange();
m_rect = rect;
update();
}
/**
* set widget rectangle in item coordinates
*/
void WidgetBase::setRect(qreal x, qreal y, qreal width, qreal height)
{
setRect(QRectF(x, y, width, height));
}
/**
* @return The bounding rectangle for this widget.
* @see setRect
*/
QRectF WidgetBase::boundingRect() const
{
qreal halfWidth = lineWidth() / 2.0;
return m_rect.adjusted(-halfWidth, -halfWidth, halfWidth, halfWidth);
}
/**
* Test if point is inside the bounding rectangle of the widget.
* Inheriting classes may reimplement this to test possible child widgets.
*
* @param p Point to be checked.
*
* @return 'this' if the given point is in the boundaries of the widget;
* else NULL.
*/
UMLWidget* WidgetBase::onWidget(const QPointF &p)
{
UMLWidget *uw = this->asUMLWidget();
if (uw == nullptr)
return nullptr;
const qreal w = m_rect.width();
const qreal h = m_rect.height();
const qreal left = x(); // don't use m_rect.x() for this, it is always 0
const qreal right = left + w;
const qreal top = y(); // don't use m_rect.y() for this, it is always 0
const qreal bottom = top + h;
// uDebug() << "p=(" << p.x() << "," << p.y()
// << "), x=" << left << ", y=" << top << ", w=" << w << ", h=" << h
// << "; right=" << right << ", bottom=" << bottom;
if (p.x() < left || p.x() > right ||
p.y() < top || p.y() > bottom) { // Qt coord.sys. origin in top left corner
// uDebug() << "returning NULL";
return nullptr;
}
// uDebug() << "returning this";
return uw;
}
/**
* Draws the UMLWidget on the given paint device
*
* @param painter The painter for the drawing device
* @param option Painting related options
* @param widget Background widget on which to paint (optional)
*
*/
void WidgetBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(painter); Q_UNUSED(option); Q_UNUSED(widget);
}
/**
* Reimplemented to show appropriate context menu.
*/
void WidgetBase::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
event->accept();
logDebug2("WidgetBase::contextMenuEvent: widget = %1 / type = %2", name(), baseTypeStr());
UMLScene *scene = umlScene();
// If right-click was done on a widget that was not selected, clear the
// current selection and select the new widget. The context menu is shown
// with actions for that single widget.
// If a keyboard modifier was used, add the widget to the current selection
// and show the menu with actions for the whole selection.
if (!isSelected()) {
Qt::KeyboardModifiers forSelection = (Qt::ControlModifier | Qt::ShiftModifier);
if ((event->modifiers() & forSelection) == 0) {
scene->clearSelected();
}
if (umlObject() != nullptr) {
scene->selectWidget(this->asUMLWidget());
} else {
setSelected(true);
}
}
int count = scene->selectedCount(true);
// Determine multi state
bool multi = (isSelected() && count > 1);
WidgetBasePopupMenu popup(nullptr, this, multi, scene->getUniqueSelectionType());
// Disable the "view code" menu for simple code generators
if (UMLApp::app()->isSimpleCodeGeneratorActive()) {
popup.setActionEnabled(ListPopupMenu::mt_ViewCode, false);
}
QAction *triggered = popup.exec(event->screenPos());
slotMenuSelection(triggered);
}
/**
* This is usually called synchronously after menu.exec() and \a
* trigger's parent is always the ListPopupMenu which can be used to
* get the type of action of \a trigger.
*
* @note Subclasses can reimplement to handle specific actions and
* leave the rest to WidgetBase::slotMenuSelection.
*/
void WidgetBase::slotMenuSelection(QAction *trigger)
{
if (!trigger) {
return;
}
QColor newColor;
const WidgetType wt = m_baseType; // short hand name
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(trigger);
switch (sel) {
case ListPopupMenu::mt_Rename:
umlDoc()->renameUMLObject(umlObject());
break;
case ListPopupMenu::mt_Properties:
if (wt == WidgetBase::wt_Actor || wt == WidgetBase::wt_UseCase ||
wt == WidgetBase::wt_Package || wt == WidgetBase::wt_Interface ||
wt == WidgetBase::wt_Datatype || wt == WidgetBase::wt_Node ||
wt == WidgetBase::wt_Component || wt == WidgetBase::wt_Artifact ||
wt == WidgetBase::wt_Enum || wt == WidgetBase::wt_Entity ||
wt == WidgetBase::wt_Port || wt == WidgetBase::wt_Instance ||
(wt == WidgetBase::wt_Class && umlScene()->isClassDiagram())) {
showPropertiesDialog();
} else if (wt == WidgetBase::wt_Object) {
m_umlObject->showPropertiesDialog();
} else {
logWarn1("WidgetBase::slotMenuSelection: making properties dialog for unknown widget type %1", sel);
}
break;
case ListPopupMenu::mt_Line_Color:
case ListPopupMenu::mt_Line_Color_Selection:
newColor = QColorDialog::getColor(lineColor());
if (newColor.isValid() && newColor != lineColor())
{
if (sel == ListPopupMenu::mt_Line_Color_Selection) {
umlScene()->selectionSetLineColor(newColor);
} else {
setLineColor(newColor);
}
setUsesDiagramLineColor(false);
umlDoc()->setModified(true);
}
break;
case ListPopupMenu::mt_Fill_Color:
case ListPopupMenu::mt_Fill_Color_Selection:
newColor = QColorDialog::getColor(fillColor());
if (newColor.isValid() && newColor != fillColor())
{
if (sel == ListPopupMenu::mt_Fill_Color_Selection) {
umlScene()->selectionSetFillColor(newColor);
} else {
setFillColor(newColor);
}
umlDoc()->setModified(true);
}
break;
case ListPopupMenu::mt_Use_Fill_Color:
setUseFillColor(!m_useFillColor);
break;
case ListPopupMenu::mt_Set_Use_Fill_Color_Selection:
umlScene()->selectionUseFillColor(true);
break;
case ListPopupMenu::mt_Unset_Use_Fill_Color_Selection:
umlScene()->selectionUseFillColor(false);
break;
case ListPopupMenu::mt_Show_Attributes_Selection:
case ListPopupMenu::mt_Hide_Attributes_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowAttributes, sel != ListPopupMenu::mt_Hide_Attributes_Selection
);
break;
case ListPopupMenu::mt_Show_Operations_Selection:
case ListPopupMenu::mt_Hide_Operations_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowOperations, sel != ListPopupMenu::mt_Hide_Operations_Selection
);
break;
case ListPopupMenu::mt_Show_Visibility_Selection:
case ListPopupMenu::mt_Hide_Visibility_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowVisibility, sel != ListPopupMenu::mt_Hide_Visibility_Selection
);
break;
case ListPopupMenu::mt_Show_Operation_Signature_Selection:
case ListPopupMenu::mt_Hide_Operation_Signature_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowOperationSignature, sel != ListPopupMenu::mt_Hide_Operation_Signature_Selection
);
break;
case ListPopupMenu::mt_Show_Attribute_Signature_Selection:
case ListPopupMenu::mt_Hide_Attribute_Signature_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowAttributeSignature, sel != ListPopupMenu::mt_Hide_Attribute_Signature_Selection
);
break;
case ListPopupMenu::mt_Show_Packages_Selection:
case ListPopupMenu::mt_Hide_Packages_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowPackage, sel != ListPopupMenu::mt_Hide_Packages_Selection
);
break;
case ListPopupMenu::mt_Show_Stereotypes_Selection:
case ListPopupMenu::mt_Hide_Stereotypes_Selection:
// Bug73847 - ClassifierWidget::ShowStereotype boolean value is DEPRECATED
// TODO - handle this differently, then delete ClassifierWidget::ShowStereotype
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowStereotype, sel != ListPopupMenu::mt_Hide_Stereotypes_Selection
);
break;
case ListPopupMenu::mt_Hide_NonPublic_Selection:
case ListPopupMenu::mt_Show_NonPublic_Selection:
umlScene()->selectionSetVisualProperty(
ClassifierWidget::ShowPublicOnly, sel != ListPopupMenu::mt_Show_NonPublic_Selection
);
break;
case ListPopupMenu::mt_ViewCode: {
UMLClassifier *c = umlObject()->asUMLClassifier();
if (c) {
UMLApp::app()->viewCodeDocument(c);
}
break;
}
case ListPopupMenu::mt_Remove:
umlScene()->deleteSelection();
break;
case ListPopupMenu::mt_Delete:
if (!Dialog_Utils::askDeleteAssociation())
break;
umlScene()->deleteSelection();
break;
case ListPopupMenu::mt_Change_Font:
case ListPopupMenu::mt_Change_Font_Selection: {
bool ok = false;
QFont newFont = QFontDialog::getFont(&ok, font());
if (ok)
{
if (sel == ListPopupMenu::mt_Change_Font_Selection) {
m_scene->selectionSetFont(newFont);
} else {
setFont(newFont);
}
}
}
break;
case ListPopupMenu::mt_Cut:
umlScene()->setStartedCut();
UMLApp::app()->slotEditCut();
break;
case ListPopupMenu::mt_Copy:
UMLApp::app()->slotEditCopy();
break;
case ListPopupMenu::mt_Paste:
UMLApp::app()->slotEditPaste();
break;
case ListPopupMenu::mt_Refactoring:
//check if we are operating on a classifier, or some other kind of UMLObject
if (umlObject()->asUMLClassifier()) {
UMLApp::app()->refactor(umlObject()->asUMLClassifier());
}
break;
case ListPopupMenu::mt_Clone:
{
for(UMLWidget* widget : umlScene()->selectedWidgets()) {
if (Model_Utils::isCloneable(widget->baseType())) {
UMLObject *clone = widget->umlObject()->clone();
umlScene()->addObject(clone);
}
}
}
break;
case ListPopupMenu::mt_Rename_MultiA:
case ListPopupMenu::mt_Rename_MultiB:
case ListPopupMenu::mt_Rename_Name:
case ListPopupMenu::mt_Rename_RoleAName:
case ListPopupMenu::mt_Rename_RoleBName: {
FloatingTextWidget *ft = static_cast<FloatingTextWidget*>(this);
ft->handleRename();
break;
}
case ListPopupMenu::mt_Align_Right:
umlScene()->alignRight();
break;
case ListPopupMenu::mt_Align_Left:
umlScene()->alignLeft();
break;
case ListPopupMenu::mt_Align_Top:
umlScene()->alignTop();
break;
case ListPopupMenu::mt_Align_Bottom:
umlScene()->alignBottom();
break;
case ListPopupMenu::mt_Align_VerticalMiddle:
umlScene()->alignVerticalMiddle();
break;
case ListPopupMenu::mt_Align_HorizontalMiddle:
umlScene()->alignHorizontalMiddle();
break;
case ListPopupMenu::mt_Align_VerticalDistribute:
umlScene()->alignVerticalDistribute();
break;
case ListPopupMenu::mt_Align_HorizontalDistribute:
umlScene()->alignHorizontalDistribute();
break;
default:
logDebug1("WidgetBase::slotMenuSelection: MenuType %1 not implemented",
ListPopupMenu::toString(sel));
break;
}
}
/**
* Helper function for debug output.
* Returns the given enum value as string.
* @param wt WidgetType of which a string representation is wanted
* @return the WidgetType as string
*/
QString WidgetBase::toString(WidgetType wt)
{
return QLatin1String(ENUM_NAME(WidgetBase, WidgetType, wt));
}
/**
* Returns the given enum value as localized string.
* @param wt WidgetType of which a string representation is wanted
* @return the WidgetType as localized string
*/
QString WidgetBase::toI18nString(WidgetType wt)
{
QString name;
switch (wt) {
case wt_Activity:
name = i18n("Activity");
break;
case wt_Actor:
name = i18n("Actor");
break;
case wt_Artifact:
name = i18n("Artifact");
break;
case wt_Association:
name = i18n("Association");
break;
case wt_Box:
name = i18n("Box");
break;
case wt_Category:
name = i18n("Category");
break;
case wt_CombinedFragment:
name = i18n("CombinedFragment");
break;
case wt_Component:
name = i18n("Component");
break;
case wt_Class:
name = i18n("Class");
break;
case wt_Datatype:
name = i18n("Datatype");
break;
case wt_Entity:
name = i18n("Entity");
break;
case wt_Enum:
name = i18n("Enum");
break;
case wt_FloatingDashLine:
name = i18n("FloatingDashLine");
break;
case wt_ForkJoin:
name = i18n("ForkJoin");
break;
case wt_Interface:
name = i18n("Interface");
break;
case wt_Message:
name = i18n("Message");
break;
case wt_Node:
name = i18n("Node");
break;
case wt_Note:
name = i18n("Note");
break;
case wt_Object:
name = i18n("Object");
break;
case wt_ObjectNode:
name = i18n("ObjectNode");
break;
case wt_Package:
name = i18n("Package");
break;
case wt_Pin:
name = i18n("Pin");
break;
case wt_Port:
name = i18n("Port");
break;
case wt_Precondition:
name = i18n("Precondition");
break;
case wt_Region:
name = i18n("Region");
break;
case wt_Signal:
name = i18n("Signal");
break;
case wt_State:
name = i18n("State");
break;
case wt_Text:
name = i18n("Text");
break;
case wt_UseCase:
name = i18n("UseCase");
break;
case wt_Instance:
name = i18n("Instance");
break;
default:
name = QStringLiteral("<unknown> &name:");
logWarn1("WidgetBase::toI18nString: unknown widget type %1", wt);
break;
}
return name;
}
/**
* Returns the given enum value as icon type.
* @param wt WidgetType of which an icon type representation is wanted
* @return the WidgetType as icon type
*/
Icon_Utils::IconType WidgetBase::toIcon(WidgetBase::WidgetType wt)
{
Icon_Utils::IconType icon;
switch (wt) {
case wt_Activity:
icon = Icon_Utils::it_Activity;
break;
case wt_Actor:
icon = Icon_Utils::it_Actor;
break;
case wt_Artifact:
icon = Icon_Utils::it_Artifact;
break;
case wt_Association:
icon = Icon_Utils::it_Association;
break;
case wt_Box:
icon = Icon_Utils::it_Box;
break;
case wt_Category:
icon = Icon_Utils::it_Category;
break;
case wt_CombinedFragment:
icon = Icon_Utils::it_Combined_Fragment;
break;
case wt_Component:
icon = Icon_Utils::it_Component;
break;
case wt_Class:
icon = Icon_Utils::it_Class;
break;
case wt_Datatype:
icon = Icon_Utils::it_Datatype;
break;
case wt_Entity:
icon = Icon_Utils::it_Entity;
break;
case wt_Enum:
icon = Icon_Utils::it_Enum;
break;
case wt_FloatingDashLine:
icon = Icon_Utils::it_Association;
break;
case wt_ForkJoin:
icon = Icon_Utils::it_Fork_Join;
break;
case wt_Instance:
icon = Icon_Utils::it_Instance;
break;
case wt_Interface:
icon = Icon_Utils::it_Interface;
break;
case wt_Message:
icon = Icon_Utils::it_Message_Synchronous;
break;
case wt_Node:
icon = Icon_Utils::it_Node;
break;
case wt_Note:
icon = Icon_Utils::it_Note;
break;
case wt_Object:
icon = Icon_Utils::it_Object;
break;
case wt_ObjectNode:
icon = Icon_Utils::it_Object_Node;
break;
case wt_Package:
icon = Icon_Utils::it_Package;
break;
case wt_Pin:
icon = Icon_Utils::it_Pin;
break;
case wt_Port:
icon = Icon_Utils::it_Port;
break;
case wt_Precondition:
icon = Icon_Utils::it_Precondition;
break;
case wt_Region:
icon = Icon_Utils::it_Region;
break;
case wt_Signal:
icon = Icon_Utils::it_Send_Signal;
break;
case wt_State:
icon = Icon_Utils::it_State;
break;
case wt_Text:
icon = Icon_Utils::it_Text;
break;
case wt_UseCase:
icon = Icon_Utils::it_UseCase;
break;
default:
icon = Icon_Utils::it_Home;
logWarn1("WidgetBase::toIcon: unknown widget type %1", wt);
break;
}
return icon;
}
#include "activitywidget.h"
#include "actorwidget.h"
#include "artifactwidget.h"
#include "associationwidget.h"
#include "boxwidget.h"
#include "categorywidget.h"
//#include "classwidget.h"
#include "combinedfragmentwidget.h"
#include "componentwidget.h"
#include "datatypewidget.h"
#include "entitywidget.h"
#include "enumwidget.h"
#include "floatingdashlinewidget.h"
#include "forkjoinwidget.h"
#include "interfacewidget.h"
#include "messagewidget.h"
#include "nodewidget.h"
#include "notewidget.h"
#include "objectnodewidget.h"
#include "objectwidget.h"
#include "packagewidget.h"
#include "pinwidget.h"
#include "portwidget.h"
#include "preconditionwidget.h"
#include "regionwidget.h"
#include "signalwidget.h"
#include "statewidget.h"
#include "usecasewidget.h"
ActivityWidget* WidgetBase::asActivityWidget() { return dynamic_cast<ActivityWidget* > (this); }
ActorWidget* WidgetBase::asActorWidget() { return dynamic_cast<ActorWidget* > (this); }
ArtifactWidget* WidgetBase::asArtifactWidget() { return dynamic_cast<ArtifactWidget* > (this); }
AssociationWidget* WidgetBase::asAssociationWidget() { return dynamic_cast<AssociationWidget* > (this); }
BoxWidget* WidgetBase::asBoxWidget() { return dynamic_cast<BoxWidget* > (this); }
CategoryWidget* WidgetBase::asCategoryWidget() { return dynamic_cast<CategoryWidget* > (this); }
ClassifierWidget* WidgetBase::asClassifierWidget() { return dynamic_cast<ClassifierWidget* > (this); }
CombinedFragmentWidget* WidgetBase::asCombinedFragmentWidget() { return dynamic_cast<CombinedFragmentWidget*>(this); }
ComponentWidget* WidgetBase::asComponentWidget() { return dynamic_cast<ComponentWidget* > (this); }
DatatypeWidget* WidgetBase::asDatatypeWidget() { return dynamic_cast<DatatypeWidget* > (this); }
EntityWidget* WidgetBase::asEntityWidget() { return dynamic_cast<EntityWidget* > (this); }
EnumWidget* WidgetBase::asEnumWidget() { return dynamic_cast<EnumWidget* > (this); }
FloatingDashLineWidget* WidgetBase::asFloatingDashLineWidget() { return dynamic_cast<FloatingDashLineWidget*>(this); }
ForkJoinWidget* WidgetBase::asForkJoinWidget() { return dynamic_cast<ForkJoinWidget* > (this); }
InterfaceWidget* WidgetBase::asInterfaceWidget() { return dynamic_cast<InterfaceWidget* > (this); }
MessageWidget* WidgetBase::asMessageWidget() { return dynamic_cast<MessageWidget* > (this); }
NodeWidget* WidgetBase::asNodeWidget() { return dynamic_cast<NodeWidget* > (this); }
NoteWidget* WidgetBase::asNoteWidget() { return dynamic_cast<NoteWidget* > (this); }
ObjectNodeWidget* WidgetBase::asObjectNodeWidget() { return dynamic_cast<ObjectNodeWidget* > (this); }
ObjectWidget* WidgetBase::asObjectWidget() { return dynamic_cast<ObjectWidget* > (this); }
PackageWidget* WidgetBase::asPackageWidget() { return dynamic_cast<PackageWidget* > (this); }
PinWidget* WidgetBase::asPinWidget() { return dynamic_cast<PinWidget* > (this); }
PinPortBase* WidgetBase::asPinPortBase() { return dynamic_cast<PinPortBase*> (this); }
PortWidget* WidgetBase::asPortWidget() { return dynamic_cast<PortWidget* > (this); }
PreconditionWidget* WidgetBase::asPreconditionWidget() { return dynamic_cast<PreconditionWidget* > (this); }
RegionWidget* WidgetBase::asRegionWidget() { return dynamic_cast<RegionWidget* > (this); }
SignalWidget* WidgetBase::asSignalWidget() { return dynamic_cast<SignalWidget* > (this); }
StateWidget* WidgetBase::asStateWidget() { return dynamic_cast<StateWidget* > (this); }
FloatingTextWidget* WidgetBase::asFloatingTextWidget() { return dynamic_cast<FloatingTextWidget* > (this); }
//TextWidget* WidgetBase::asTextWidget() { return dynamic_cast<TextWidget* > (this); }
UseCaseWidget* WidgetBase::asUseCaseWidget() { return dynamic_cast<UseCaseWidget* > (this); }
UMLWidget* WidgetBase::asUMLWidget() { return dynamic_cast<UMLWidget*> (this); }
const ActivityWidget* WidgetBase::asActivityWidget() const { return dynamic_cast<const ActivityWidget* > (this); }
const ActorWidget* WidgetBase::asActorWidget() const { return dynamic_cast<const ActorWidget* > (this); }
const ArtifactWidget* WidgetBase::asArtifactWidget() const { return dynamic_cast<const ArtifactWidget* > (this); }
const AssociationWidget* WidgetBase::asAssociationWidget() const { return dynamic_cast<const AssociationWidget* > (this); }
const BoxWidget* WidgetBase::asBoxWidget() const { return dynamic_cast<const BoxWidget* > (this); }
const CategoryWidget* WidgetBase::asCategoryWidget() const { return dynamic_cast<const CategoryWidget* > (this); }
const ClassifierWidget* WidgetBase::asClassifierWidget() const { return dynamic_cast<const ClassifierWidget* > (this); }
const CombinedFragmentWidget* WidgetBase::asCombinedFragmentWidget() const { return dynamic_cast<const CombinedFragmentWidget*>(this); }
const ComponentWidget* WidgetBase::asComponentWidget() const { return dynamic_cast<const ComponentWidget* > (this); }
const DatatypeWidget* WidgetBase::asDatatypeWidget() const { return dynamic_cast<const DatatypeWidget* > (this); }
const EntityWidget* WidgetBase::asEntityWidget() const { return dynamic_cast<const EntityWidget* > (this); }
const EnumWidget* WidgetBase::asEnumWidget() const { return dynamic_cast<const EnumWidget* > (this); }
const FloatingDashLineWidget* WidgetBase::asFloatingDashLineWidget() const { return dynamic_cast<const FloatingDashLineWidget*>(this); }
const ForkJoinWidget* WidgetBase::asForkJoinWidget() const { return dynamic_cast<const ForkJoinWidget* > (this); }
const InterfaceWidget* WidgetBase::asInterfaceWidget() const { return dynamic_cast<const InterfaceWidget* > (this); }
const MessageWidget* WidgetBase::asMessageWidget() const { return dynamic_cast<const MessageWidget* > (this); }
const NodeWidget* WidgetBase::asNodeWidget() const { return dynamic_cast<const NodeWidget* > (this); }
const NoteWidget* WidgetBase::asNoteWidget() const { return dynamic_cast<const NoteWidget* > (this); }
const ObjectNodeWidget* WidgetBase::asObjectNodeWidget() const { return dynamic_cast<const ObjectNodeWidget* > (this); }
const ObjectWidget* WidgetBase::asObjectWidget() const { return dynamic_cast<const ObjectWidget* > (this); }
const PackageWidget* WidgetBase::asPackageWidget() const { return dynamic_cast<const PackageWidget* > (this); }
const PinWidget* WidgetBase::asPinWidget() const { return dynamic_cast<const PinWidget* > (this); }
const PinPortBase* WidgetBase::asPinPortBase() const { return dynamic_cast<const PinPortBase*> (this); }
const PortWidget* WidgetBase::asPortWidget() const { return dynamic_cast<const PortWidget* > (this); }
const PreconditionWidget* WidgetBase::asPreconditionWidget() const { return dynamic_cast<const PreconditionWidget* > (this); }
const RegionWidget* WidgetBase::asRegionWidget() const { return dynamic_cast<const RegionWidget* > (this); }
const SignalWidget* WidgetBase::asSignalWidget() const { return dynamic_cast<const SignalWidget* > (this); }
const StateWidget* WidgetBase::asStateWidget() const { return dynamic_cast<const StateWidget* > (this); }
const FloatingTextWidget* WidgetBase::asFloatingTextWidget() const { return dynamic_cast<const FloatingTextWidget* > (this); }
//const TextWidget* WidgetBase::asTextWidget() const { return dynamic_cast<const TextWidget* > (this); }
const UseCaseWidget* WidgetBase::asUseCaseWidget() const { return dynamic_cast<const UseCaseWidget* > (this); }
const UMLWidget* WidgetBase::asUMLWidget() const { return dynamic_cast<const UMLWidget*> (this); }
| 48,851
|
C++
|
.cpp
| 1,399
| 30.152252
| 138
| 0.658742
|
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,398
|
datatypewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/datatypewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "datatypewidget.h"
// app includes
#include "classifier.h"
#include "classifierlistitem.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
// qt includes
#include <QPainter>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(DatatypeWidget)
/**
* Constructs an DatatypeWidget.
*
* @param scene The parent of this DatatypeWidget.
* @param d The UMLClassifier this will be representing.
*/
DatatypeWidget::DatatypeWidget(UMLScene *scene, UMLClassifier *d)
: UMLWidget(scene, WidgetBase::wt_Datatype, d)
{
setSize(100, 30);
}
/**
* Standard deconstructor.
*/
DatatypeWidget::~DatatypeWidget()
{
}
/**
* Overrides standard method.
*/
void DatatypeWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
} else {
painter->setBrush(m_scene->backgroundColor());
}
int w = width();
int h = height();
QFontMetrics &fm = getFontMetrics(FT_NORMAL);
int fontHeight = fm.lineSpacing();
painter->drawRect(0, 0, w, h);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(true);
painter->setFont(font);
painter->drawText(DATATYPE_MARGIN, 0,
w - DATATYPE_MARGIN* 2, fontHeight,
Qt::AlignCenter, m_umlObject->stereotype(true));
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
painter->drawText(DATATYPE_MARGIN, fontHeight,
w - DATATYPE_MARGIN * 2, fontHeight, Qt::AlignCenter, name());
UMLWidget::paint(painter, option, widget);
}
/**
* Loads from a "datatypewidget" XMI element.
*/
bool DatatypeWidget::loadFromXMI(QDomElement & qElement)
{
return UMLWidget::loadFromXMI(qElement);
}
/**
* Saves to the "datatypewidget" XMI element.
*/
void DatatypeWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("datatypewidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Overrides method from UMLWidget.
*/
QSizeF DatatypeWidget::minimumSize() const
{
if (!m_umlObject) {
return UMLWidget::minimumSize();
}
int width, height;
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int lines = 1;//always have one line - for name
lines++; //for the stereotype
height = width = 0;
height += lines * fontHeight;
//now set the width of the classifier
//set width to name to start with
//set width to name to start with
width = getFontMetrics(FT_BOLD_ITALIC).boundingRect(m_umlObject->fullyQualifiedName()).width();
int w = getFontMetrics(FT_BOLD).boundingRect(m_umlObject->stereotype(true)).width();
width = w > width?w:width;
//allow for width margin
width += DATATYPE_MARGIN * 2;
return QSizeF(width, height);
}
| 3,178
|
C++
|
.cpp
| 105
| 26.590476
| 102
| 0.705015
|
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,399
|
associationline.cpp
|
KDE_umbrello/umbrello/umlwidgets/associationline.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "associationline.h"
// application includes
#include "associationwidget.h"
#include "debug_utils.h"
#include "optionstate.h"
#include "uml.h"
#include "umldoc.h"
#include "umlwidget.h"
// qt includes
#include <QDomDocument>
#include <QPainter>
#include <QXmlStreamWriter>
// system includes
#include <cstdlib>
#include <cmath>
DEBUG_REGISTER_DISABLED(AssociationLine)
// Initialize static variables.
const qreal AssociationLine::Delta = 5;
const qreal AssociationLine::SelectedPointDiameter = 4;
const qreal AssociationLine::SelfAssociationMinimumHeight = 30;
/**
* Constructor.
* Constructs an AssociationLine item slaved to the given AssociationWidget.
*/
AssociationLine::AssociationLine(AssociationWidget *association)
: QGraphicsObject(association),
m_associationWidget(association),
m_activePointIndex(-1),
m_activeSegmentIndex(-1),
m_startSymbol(nullptr),
m_endSymbol(nullptr),
m_subsetSymbol(nullptr),
m_collaborationLineItem(nullptr),
m_collaborationLineHead(nullptr),
m_layout(Settings::optionState().generalState.layoutType),
m_autoLayoutSpline(true)
{
Q_ASSERT(association);
setFlag(QGraphicsLineItem::ItemIsSelectable);
setAcceptHoverEvents(true);
setZValue(3);
}
/**
* Destructor.
*/
AssociationLine::~AssociationLine()
{
delete m_startSymbol;
delete m_endSymbol;
delete m_subsetSymbol;
removeCollaborationLine();
}
/**
* Returns the point at the point index.
* @return point at given index
*/
QPointF AssociationLine::point(int index) const
{
if ((index < 0) || (index >= m_points.size())) {
logWarn2("AssociationLine::point: Index %1 out of range [0..%2]",
index, m_points.size() - 1);
return QPointF(-1.0, -1.0);
}
return m_points.at(index);
}
/**
* Sets the point value at given index to \a point.
*/
bool AssociationLine::setPoint(int index, const QPointF &point)
{
if ((index < 0) | (index >= m_points.size())) {
logWarn2("AssociationLine::setPoint: Index %1 out of range [0..%2]",
index, m_points.size() - 1);
return false;
}
if (m_points.at(index) == point) {
return false; // nothing to change
}
prepareGeometryChange();
m_points[index] = point;
alignSymbols();
return true;
}
/**
* Shortcut for point(0).
*/
QPointF AssociationLine::startPoint() const
{
return m_points.at(0);
}
/**
* Shortcut for end point.
*/
QPointF AssociationLine::endPoint() const
{
return m_points.at(m_points.size()-1);
}
void AssociationLine::addPoint(const QPointF &point)
{
m_points.append(point);
}
/**
* Inserts the passed in \a point at the \a index passed in and
* recalculates the bounding rect.
*/
void AssociationLine::insertPoint(int index, const QPointF &point)
{
prepareGeometryChange();
m_points.insert(index, point);
alignSymbols();
}
/**
* Removes the point at \a index passed in.
* @see removeNonEndPoint
*/
void AssociationLine::removePoint(int index)
{
prepareGeometryChange();
m_points.remove(index);
m_activePointIndex = -1;
m_activeSegmentIndex = -1;
alignSymbols();
}
/**
* Returns the amount of POINTS on the line.
* Includes start and end points.
* @return number of points in the AssociationLine
*/
int AssociationLine::count() const
{
return m_points.size();
}
/**
* Removes all the points and signals a geometry update.
*/
void AssociationLine::cleanup()
{
if (!m_points.isEmpty()) {
prepareGeometryChange();
m_points.clear();
alignSymbols();
}
}
/**
* This method optimizes the number of points in the
* AssociationLine. This can be used to reduce the clutter caused
* due to too many points.
* TODO: Use delta comparison 'closestPointIndex' instead of exact comparison.
* TODO: Not used anywhere.
*/
void AssociationLine::optimizeLinePoints()
{
int i = 1;
prepareGeometryChange();
while (i < m_points.size()) {
if (m_points.at(i) == m_points.at(i-1)) {
m_points.remove(i);
}
else {
++i;
}
}
m_activePointIndex = -1;
m_activeSegmentIndex = -1;
alignSymbols();
}
/**
* Return index of point closer a given delta.
*
* @param point The point which is to be tested for closeness.
* @param delta The distance the point should be closer to.
*
* @retval "Index" of the first line point closer to the \a point passed.
* @retval -1 If no line point is closer to passed in \a point.
*/
int AssociationLine::closestPointIndex(const QPointF &point, qreal delta) const
{
for(int i = 0; i < m_points.size(); ++i) {
const QPointF& linePoint = m_points.at(i);
// Apply distance formula to see point closeness.
qreal deltaXSquare = (point.x() - linePoint.x()) * (point.x() - linePoint.x());
qreal deltaYSquare = (point.y() - linePoint.y()) * (point.y() - linePoint.y());
qreal lhs = deltaXSquare + deltaYSquare;
qreal rhs = delta * delta;
if (lhs <= rhs) {
return i;
}
}
return -1;
}
/**
* Return index of closest segment.
*
* @param point The point which is to be tested for closeness.
* @param delta The distance in pixels that the point may be removed from
* a segment but is still considered to be on the segment.
*
* @return Index of the line segment closest to the \a point passed;
* -1 if no line segment is closer to passed in \a point.
*/
int AssociationLine::closestSegmentIndex(const QPointF &point, qreal delta) const
{
QPainterPathStroker stroker;
stroker.setWidth(delta);
for(int i = 1; i < m_points.size(); ++i) {
QLineF segment(m_points[i-1], m_points[i]);
QPainterPath path;
path.moveTo(segment.p1());
path.lineTo(segment.p2());
path = stroker.createStroke(path);
if (path.contains(point)) {
return i-1;
}
}
return -1;
}
/**
* Retval True If point at \a index is start or end.
*/
bool AssociationLine::isEndPointIndex(int index) const
{
const int size = m_points.size();
Q_ASSERT(index >= 0 && index < size);
return (index == 0 || index == (size - 1));
}
/**
* Retval True If segment at \a index is start or end.
*/
bool AssociationLine::isEndSegmentIndex(int index) const
{
// num of seg = num of points - 1
const int size = m_points.size() - 1;
Q_ASSERT(index >= 0 && index < size);
return (index == 0 || index == (size - 1));
}
bool AssociationLine::isAutoLayouted() const
{
return m_autoLayoutSpline;
}
bool AssociationLine::enableAutoLayout()
{
m_autoLayoutSpline = true;
createSplinePoints();
path();
createSplinePoints();
path();
update();
return true;
}
/**
* Sets the start and end points.
*/
bool AssociationLine::setEndPoints(const QPointF &start, const QPointF &end)
{
const int size = m_points.size();
prepareGeometryChange();
if (size == 0) {
m_points.insert(0, start);
m_points.insert(1, end);
}
else if (size == 1) {
m_points[0] = start;
m_points.insert(1, end);
}
else {
m_points[0] = start;
m_points[size-1] = end;
}
alignSymbols();
return true;
}
/**
* Debug helper method to write out the points.
*/
void AssociationLine::dumpPoints()
{
for (int i = 1; i < m_points.size(); ++i) {
QPointF p = m_points.at(i);
DEBUG() << i << ". point x:" << p.x() << " / y:" << p.y();
}
}
/**
* Loads AssociationLine information saved in \a qElement XMI element.
*/
bool AssociationLine::loadFromXMI(QDomElement &qElement)
{
QString layout = qElement.attribute(QStringLiteral("layout"), QStringLiteral("polyline"));
m_layout = Uml::LayoutType::fromString(layout);
QDomNode node = qElement.firstChild();
m_points.clear();
QDomElement startElement = node.toElement();
if(startElement.isNull() || startElement.tagName() != QStringLiteral("startpoint")) {
return false;
}
UMLScene* umlScene = m_associationWidget->umlScene();
qreal dpiScale = UMLApp::app()->document()->dpiScale();
QString x = startElement.attribute(QStringLiteral("startx"), QStringLiteral("0"));
qreal nX = toDoubleFromAnyLocale(x) + umlScene->fixX();
QString y = startElement.attribute(QStringLiteral("starty"), QStringLiteral("0"));
qreal nY = toDoubleFromAnyLocale(y) + umlScene->fixY();
QPointF startPoint(nX, nY);
node = startElement.nextSibling();
QDomElement endElement = node.toElement();
if(endElement.isNull() || endElement.tagName() != QStringLiteral("endpoint")) {
return false;
}
x = endElement.attribute(QStringLiteral("endx"), QStringLiteral("0"));
nX = toDoubleFromAnyLocale(x) + umlScene->fixX();
y = endElement.attribute(QStringLiteral("endy"), QStringLiteral("0"));
nY = toDoubleFromAnyLocale(y) + umlScene->fixY();
QPointF endPoint(nX, nY);
setEndPoints(startPoint * dpiScale, endPoint * dpiScale);
QPointF point;
node = endElement.nextSibling();
QDomElement element = node.toElement();
int i = 1;
while (!element.isNull()) {
if (element.tagName() == QStringLiteral("point")) {
x = element.attribute(QStringLiteral("x"), QStringLiteral("0"));
y = element.attribute(QStringLiteral("y"), QStringLiteral("0"));
point.setX(toDoubleFromAnyLocale(x) + umlScene->fixX());
point.setY(toDoubleFromAnyLocale(y) + umlScene->fixY());
insertPoint(i++, point * dpiScale);
}
node = element.nextSibling();
element = node.toElement();
}
return true;
}
/**
* Saves association line information into XMI element named "linepath".
* @note Stored as linepath for backward compatibility
*/
void AssociationLine::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("linepath"));
writer.writeAttribute(QStringLiteral("layout"), Uml::LayoutType::toString(m_layout));
writer.writeStartElement(QStringLiteral("startpoint"));
qreal dpiScale = UMLApp::app()->document()->dpiScale();
QPointF point = m_associationWidget->mapToScene(startPoint());
point /= dpiScale;
writer.writeAttribute(QStringLiteral("startx"), QString::number(point.x()));
writer.writeAttribute(QStringLiteral("starty"), QString::number(point.y()));
writer.writeEndElement(); // startpoint
writer.writeStartElement(QStringLiteral("endpoint"));
point = m_associationWidget->mapToScene(endPoint());
point /= dpiScale;
writer.writeAttribute(QStringLiteral("endx"), QString::number(point.x()));
writer.writeAttribute(QStringLiteral("endy"), QString::number(point.y()));
writer.writeEndElement(); // endpoint
for(int i = 1; i < count()-1; ++i) {
writer.writeStartElement(QStringLiteral("point"));
point = m_associationWidget->mapToScene(this->point(i));
point /= dpiScale;
writer.writeAttribute(QStringLiteral("x"), QString::number(point.x()));
writer.writeAttribute(QStringLiteral("y"), QString::number(point.y()));
writer.writeEndElement(); // point
}
writer.writeEndElement(); // linepath
}
/**
* Returns the type of brush to use depending on the type of Association.
*/
QBrush AssociationLine::brush() const
{
QBrush brush(Qt::SolidPattern);
Uml::AssociationType::Enum type = m_associationWidget->associationType();
if (type == Uml::AssociationType::Aggregation ||
type == Uml::AssociationType::Generalization ||
type == Uml::AssociationType::Realization) {
brush.setColor(Qt::white);
}
if (type == Uml::AssociationType::Composition) {
brush.setColor(m_associationWidget->lineColor());
}
return brush;
}
/**
* Returns the pen used for drawing.
*/
QPen AssociationLine::pen() const
{
return m_pen;
}
/**
* Setup new pen.
*/
void AssociationLine::setPen(const QPen &pen)
{
if (m_startSymbol) {
m_startSymbol->setPen(pen);
// update brush fill color
m_startSymbol->setBrush(brush());
}
if (m_subsetSymbol) {
m_subsetSymbol->setPen(pen);
m_subsetSymbol->setBrush(brush());
}
if (m_endSymbol) {
m_endSymbol->setPen(pen);
m_endSymbol->setBrush(brush());
}
prepareGeometryChange();
m_pen = pen;
m_pen.setCapStyle(Qt::RoundCap);
m_pen.setJoinStyle(Qt::RoundJoin);
updatePenStyle();
}
/**
* Update pen style depending on the association type of the related AssociationWidget instance.
*/
void AssociationLine::updatePenStyle()
{
Uml::AssociationType::Enum type = m_associationWidget->associationType();
if (type == Uml::AssociationType::Dependency ||
type == Uml::AssociationType::Realization ||
type == Uml::AssociationType::Anchor) {
m_pen.setStyle(Qt::DashLine);
}
else {
m_pen.setStyle(Qt::SolidLine);
}
}
/**
* This method simply ensures presence of two points and
* adds the needed points for self associations.
*/
void AssociationLine::calculateInitialEndPoints()
{
if (m_associationWidget->isSelf() && count() < 4) {
for (int i = count(); i < 4; ++i) {
insertPoint(i, QPointF());
}
UMLWidget *wid = m_associationWidget->widgetForRole(Uml::RoleType::B);
if (!wid) {
logError0("AssociationLine::calculateInitialEndPoints: "
"AssociationWidget is partially constructed."
"UMLWidget for role B is null.");
return;
}
const QRectF rect = m_associationWidget->mapFromScene(
mapToScene(wid->rect()).boundingRect()).boundingRect();
qreal l = rect.left() + .25 * rect.width();
qreal r = rect.left() + .75 * rect.width();
bool drawAbove = rect.top() >= SelfAssociationMinimumHeight;
qreal y = drawAbove ? rect.top() : rect.bottom();
qreal yOffset = SelfAssociationMinimumHeight;
if (drawAbove) {
yOffset *= -1.0;
}
setPoint(0, QPointF(l, y));
setPoint(1, QPointF(l, y + yOffset));
setPoint(2, QPointF(r, y + yOffset));
setPoint(3, QPointF(r, y));
} else if (!m_associationWidget->isSelf() && count() < 2) {
setEndPoints(QPointF(), QPointF());
}
if (m_layout == Uml::LayoutType::Spline)
createSplinePoints();
}
/**
* This method creates, deletes symbols and collaboration lines based on
* m_associationWidget->associationType().
*
* Call this method when associationType of m_associationWidget changes.
*/
void AssociationLine::reconstructSymbols()
{
switch( m_associationWidget->associationType() ) {
case Uml::AssociationType::Exception:
setLayout(Uml::LayoutType::Polyline);
// fall through
case Uml::AssociationType::State:
case Uml::AssociationType::Activity:
case Uml::AssociationType::UniAssociation:
case Uml::AssociationType::Dependency:
setStartSymbol(Symbol::None);
setEndSymbol(Symbol::OpenArrow);
removeSubsetSymbol();
removeCollaborationLine();
break;
case Uml::AssociationType::Relationship:
setStartSymbol(Symbol::None);
setEndSymbol(Symbol::CrowFeet);
removeSubsetSymbol();
removeCollaborationLine();
break;
case Uml::AssociationType::Generalization:
case Uml::AssociationType::Realization:
setStartSymbol(Symbol::None);
setEndSymbol(Symbol::ClosedArrow);
removeSubsetSymbol();
removeCollaborationLine();
break;
case Uml::AssociationType::Composition:
case Uml::AssociationType::Aggregation:
setStartSymbol(Symbol::Diamond);
setEndSymbol(Symbol::None);
removeSubsetSymbol();
removeCollaborationLine();
break;
case Uml::AssociationType::Containment:
setStartSymbol(Symbol::Circle);
setEndSymbol(Symbol::None);
removeSubsetSymbol();
removeCollaborationLine();
break;
case Uml::AssociationType::Child2Category:
setStartSymbol(Symbol::None);
setEndSymbol(Symbol::None);
createSubsetSymbol();
removeCollaborationLine();
break;
case Uml::AssociationType::Coll_Mesg_Sync:
case Uml::AssociationType::Coll_Mesg_Async:
case Uml::AssociationType::Coll_Mesg_Self:
setStartSymbol(Symbol::None);
setEndSymbol(Symbol::None);
removeSubsetSymbol();
createCollaborationLine();
break;
default:
break;
}
alignSymbols();
}
/**
* Sets the Symbol to appear at the first line segment to \a symbol.
*
* If symbol == Symbol::None , then it deletes the symbol item.
*/
void AssociationLine::setStartSymbol(Symbol::SymbolType symbolType)
{
Q_ASSERT(symbolType != Symbol::Count);
if (symbolType == Symbol::None) {
delete m_startSymbol;
m_startSymbol = nullptr;
return;
}
if (m_startSymbol) {
m_startSymbol->setSymbolType(symbolType);
}
else {
m_startSymbol = new Symbol(symbolType, m_associationWidget);
}
m_startSymbol->setPen(pen());
m_startSymbol->setBrush(brush());
}
/**
* Sets the Symbol to appear at the last line segment to \a symbol.
*
* If symbol == Symbol::None , then it deletes the symbol item.
*/
void AssociationLine::setEndSymbol(Symbol::SymbolType symbolType)
{
Q_ASSERT(symbolType != Symbol::Count);
if (symbolType == Symbol::None) {
delete m_endSymbol;
m_endSymbol = nullptr;
return;
}
if (m_endSymbol) {
m_endSymbol->setSymbolType(symbolType);
}
else {
m_endSymbol = new Symbol(symbolType, m_associationWidget);
}
m_endSymbol->setPen(pen());
m_endSymbol->setBrush(brush());
}
/**
* Constructs a new subset symbol.
*/
void AssociationLine::createSubsetSymbol()
{
delete m_subsetSymbol; // recreate
m_subsetSymbol = new Symbol(Symbol::Subset, m_associationWidget);
m_subsetSymbol->setPen(pen());
m_subsetSymbol->setBrush(brush());
}
/**
* Removes the subset symbol if it existed by deleting appropriate items.
*/
void AssociationLine::removeSubsetSymbol()
{
delete m_subsetSymbol;
m_subsetSymbol = nullptr;
}
/**
* Constructs the open arrow symbol and arrow line, that would represent Collaboration line.
*/
void AssociationLine::createCollaborationLine()
{
const QPen p = pen();
//recreate
removeCollaborationLine();
m_collaborationLineItem = new QGraphicsLineItem(m_associationWidget);
m_collaborationLineItem->setPen(p);
if (m_associationWidget->associationType() == Uml::AssociationType::Coll_Mesg_Sync) {
m_collaborationLineHead = new Symbol(Symbol::ClosedArrow, m_associationWidget);
m_collaborationLineHead->setBrush(p.color());
}
else
m_collaborationLineHead = new Symbol(Symbol::OpenArrow, m_associationWidget);
m_collaborationLineHead->setPen(p);
}
/**
* Removes collaboration line by deleting the head and line item.
*/
void AssociationLine::removeCollaborationLine()
{
delete m_collaborationLineItem;
m_collaborationLineItem = nullptr;
delete m_collaborationLineHead;
m_collaborationLineHead = nullptr;
}
/**
* This method aligns both the \b "start" and \b "end" symbols to
* the current angles of the \b "first" and the \b "last" line
* segment respectively.
*/
void AssociationLine::alignSymbols()
{
const int sz = m_points.size();
if (sz < 2) {
// cannot align if there is no line (one line = 2 points)
return;
}
QList<QPolygonF> polygons = path().toSubpathPolygons();
if (m_startSymbol && polygons.size() > 0) {
QPolygonF firstLine = polygons.first();
QLineF segment(firstLine.at(1), firstLine.at(0));
m_startSymbol->alignTo(segment);
}
if (m_endSymbol && polygons.size() > 0) {
QPolygonF lastLine = polygons.last();
int maxIndex = lastLine.size();
QLineF segment(lastLine.at(maxIndex-2), lastLine.at(maxIndex-1));
m_endSymbol->alignTo(segment);
}
if (m_subsetSymbol) {
QPointF p1 = path().pointAtPercent(0.4);
QPointF p2 = path().pointAtPercent(0.5);
QLineF segment(p1, p2);
m_subsetSymbol->alignTo(segment);
}
if (m_collaborationLineItem) {
const qreal distance = 10;
const int midSegmentIndex = (sz - 1) / 2;
const QPointF a = m_points.at(midSegmentIndex);
const QPointF b = m_points.at(midSegmentIndex + 1);
if (a == b)
return;
const QPointF p1 = (a + b) / 2.0;
const QPointF p2 = (p1 + b) / 2.0;
// Reversed line as we want normal in opposite direction.
QLineF segment(p2, p1);
QLineF normal = segment.normalVector().unitVector();
normal.setLength(distance);
QLineF actualLine;
actualLine.setP2(normal.p2());
normal.translate(p1 - p2);
actualLine.setP1(normal.p2());
m_collaborationLineItem->setLine(actualLine);
m_collaborationLineHead->alignTo(actualLine);
}
}
/**
* @return The path of the AssociationLine.
*/
QPainterPath AssociationLine::path() const
{
if (m_points.count() == 0) {
return QPainterPath();
}
QPainterPath path;
switch (m_layout) {
case Uml::LayoutType::Direct:
path.moveTo(m_points.first());
path.lineTo(m_points.last());
break;
case Uml::LayoutType::Spline:
path = createBezierCurve(m_points);
break;
case Uml::LayoutType::Orthogonal:
path = createOrthogonalPath(m_points);
break;
case Uml::LayoutType::Polyline:
default:
QPolygonF polygon(m_points);
path.addPolygon(polygon);
break;
}
return path;
}
/**
* The points are used for the bounding rect. The reason is,
* that for splines the control points are further away from the path.
* @return The bounding rectangle for the AssociationLine.
*/
QRectF AssociationLine::boundingRect() const
{
QPolygonF polygon(m_points);
QRectF rect = polygon.boundingRect();
const qreal margin(5.0);
rect.adjust(-margin, -margin, margin, margin);
return rect;
}
/**
* @return The shape of the AssociationLine.
*/
QPainterPath AssociationLine::shape() const
{
QPainterPathStroker stroker;
stroker.setWidth(qMax<qreal>(2*SelectedPointDiameter, pen().widthF()) + 2.0); // allow delta region
stroker.setCapStyle(Qt::FlatCap);
return stroker.createStroke(path());
}
/**
* Convert enum LayoutType to string.
*/
QString AssociationLine::toString(Uml::LayoutType::Enum layout)
{
return Uml::LayoutType::toString(layout);
}
/**
* Convert string to enum LayoutType.
*/
Uml::LayoutType::Enum AssociationLine::fromString(const QString &layout)
{
if (layout == QStringLiteral("Direct"))
return Uml::LayoutType::Direct;
if (layout == QStringLiteral("Spline"))
return Uml::LayoutType::Spline;
if (layout == QStringLiteral("Orthogonal"))
return Uml::LayoutType::Orthogonal;
return Uml::LayoutType::Polyline;
}
/**
* Return the layout type of the association line.
* @return the currently used layout
*/
Uml::LayoutType::Enum AssociationLine::layout() const
{
return m_layout;
}
/**
* Set the layout type of the association line.
* @param layout the desired layout to set
*/
void AssociationLine::setLayout(Uml::LayoutType::Enum layout)
{
prepareGeometryChange();
m_layout = layout;
DEBUG() << "new layout = " << Uml::LayoutType::toString(m_layout);
if (m_layout == Uml::LayoutType::Spline) {
createSplinePoints();
}
alignSymbols();
}
/**
* For a cubic Bezier curve at least four points are needed.
* If there are less, the missing points will be created.
* Note: Implementation is only for two points.
*/
void AssociationLine::createSplinePoints()
{
QPointF c1, c2;
QPointF p1 = m_points.first(); // start point
QPointF p2 = m_points.last(); // end point
if (m_autoLayoutSpline) {
qreal dx = p2.x() - p1.x();
qreal dy = p2.y() - p1.y();
/*qreal oneThirdX = 0.33 * dx;
qreal oneThirdY = 0.33 * dy;
QPointF c1(p1.x() + oneThirdX, // control point 1
p1.y() - oneThirdY);
QPointF c2(p2.x() - oneThirdX, // control point 2
p2.y() + oneThirdY);*/
qreal oneHalfX = 0.5 * dx;
qreal oneHalfY = 0.5 * dy;
if (dx > dy) {
m_c1dx = oneHalfX;
m_c1dy = 0;
m_c2dx = -oneHalfX;
m_c2dy = 0;
}
else {
m_c1dx = 0;
m_c1dy = oneHalfY;
m_c2dx = 0;
m_c2dy = -oneHalfY;
}
c1 = QPointF(p1.x() + m_c1dx, // control point 1
p1.y() + m_c1dy);
c2 = QPointF(p2.x() + m_c2dx, // control point 2
p2.y() + m_c2dy);
} else {
//c1 = m_points[1];
//c2 = m_points[2];
//m_c1dx = c1.x() - p1.x();
//m_c1dy = c1.y() - p1.y();
//m_c2dx = c2.x() - p2.x();
//m_c2dy = c2.y() - p2.y();
c1 = QPointF(p1.x() + m_c1dx, // control point 1
p1.y() + m_c1dy);
c2 = QPointF(p2.x() + m_c2dx, // control point 2
p2.y() + m_c2dy);
}
if (m_points.size() == 2) { // create two points
insertPoint(1, c1);
insertPoint(2, c2);
}
if (m_points.size() == 4) { // change bezier points
setPoint(1, c1);
setPoint(2, c2);
}
if (m_points.size() == 3) { // create one point
// insertPoint(1 or 2, );
// Note: For now we use a quadratic Bezier curve in createBezierCurve(...).
}
}
/**
* Returns a Bézier path from given points.
* @param points points which define the Bézier curve
* @return cubic Bézier spline
*/
QPainterPath AssociationLine::createBezierCurve(QVector<QPointF> points)
{
std::string autoLayout;
QPainterPath path;
if (points.size() > 3) { // cubic Bezier curve(s)
path.moveTo(points.at(0));
int i = 1;
while (i + 2 < points.size()) {
path.cubicTo(points.at(i), points.at(i+1), points.at(i+2));
i += 3;
}
while (i < points.size()) { // draw a line if points are not modulo 3
path.lineTo(points.at(i));
++i;
}
}
else {
if (points.size() == 3) { // quadratic Bezier curve
path.moveTo(points.at(0));
path.quadTo(points.at(1), points.at(2));
}
else { // should not be reached
QPolygonF polygon(points);
path.addPolygon(polygon);
}
}
return path;
}
/**
* Returns an orthogonal path constructed of vertical and horizontal segments
* through the given points.
* @param points base points for the path
* @return orthogonal path
*/
QPainterPath AssociationLine::createOrthogonalPath(QVector<QPointF> points)
{
QPainterPath path;
if (points.size() > 1) {
QPointF start = points.first();
QPointF end = points.last();
qreal deltaX = fabs(start.x() - end.x());
qreal deltaY = fabs(start.y() - end.y());
// DEBUG() << "start=" << start << " / end=" << end
// << " / deltaX=" << deltaX << " / deltaY=" << deltaY;
QVector<QPointF> vector;
for (int i = 0; i < points.size() - 1; ++i) {
QPointF curr = points.at(i);
QPointF next = points.at(i+1);
QPointF center = (next + curr)/2.0;
vector.append(curr);
if (deltaX < deltaY) {
// go vertical first
vector.append(QPointF(curr.x(), center.y()));
vector.append(QPointF(next.x(), center.y()));
}
else {
// go horizontal first
vector.append(QPointF(center.x(), curr.y()));
vector.append(QPointF(center.x(), next.y()));
}
vector.append(next);
}
QPolygonF rectLine(vector);
path.addPolygon(rectLine);
}
else {
QPolygonF polygon(points);
path.addPolygon(polygon);
}
return path;
}
/**
* Reimplemented from QGraphicsItem::paint.
* Draws the AssociationLine and also takes care of highlighting active point or line.
*/
void AssociationLine::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(widget)
QPen _pen = pen();
const QColor orig = _pen.color().lighter();
QColor invertedColor(orig.green(), orig.blue(), orig.red());
if (invertedColor == _pen.color()) {
// Ensure different color.
invertedColor.setRed((invertedColor.red() + 50) % 256);
}
invertedColor.setAlpha(150);
int sz = m_points.size();
if (sz < 1) {
// not enough points - do nothing
return;
}
QPointF savedStart = m_points.first();
QPointF savedEnd = m_points.last();
// modify the m_points array not to include the Symbol, the value depends on Symbol
if (m_startSymbol) {
QPointF newStart = m_startSymbol->mapToParent(m_startSymbol->symbolEndPoints().first);
m_points[0] = newStart;
}
if (m_endSymbol) {
QPointF newEnd = m_endSymbol->mapToParent(m_endSymbol->symbolEndPoints().first);
m_points[sz - 1] = newEnd;
}
painter->setPen(_pen);
painter->setBrush(Qt::NoBrush);
painter->drawPath(path());
if (option->state & QStyle::State_Selected) {
// make the association broader in the selected state
QPainterPathStroker stroker;
stroker.setWidth(3.0);
QPainterPath outline = stroker.createStroke(path());
QColor shadowColor(Qt::lightGray);
shadowColor.setAlpha(80);
QBrush shadowBrush(shadowColor);
painter->setBrush(shadowBrush);
painter->setPen(Qt::NoPen);
painter->drawPath(outline);
// set color for selected painting
_pen.setColor(Qt::blue);
QRectF circle(0, 0, SelectedPointDiameter, SelectedPointDiameter);
painter->setBrush(_pen.color());
painter->setPen(Qt::NoPen);
// draw points
circle.moveCenter(savedStart);
painter->drawRect(circle);
for (int i = 1; i < sz-1; ++i) {
if (i != m_activePointIndex) {
circle.moveCenter(m_points.at(i));
painter->drawRect(circle);
}
}
//circle.moveCenter(savedStart);
//painter->drawRect(circle);
// draw bezier handles
if (m_layout == Uml::LayoutType::Spline) {
for (int i = 2; i < sz-1; ++i) {
painter->setPen(QPen(invertedColor, _pen.widthF() + 1));
// if(m_layout == Uml::LayoutType::Spline) {
QLineF mysegmentLine(savedStart, m_points[i-1]);
painter->drawLine(mysegmentLine);
QLineF mysegmentLine2(m_points[i], savedEnd);
painter->drawLine(mysegmentLine2);
}
}
circle.moveCenter(savedEnd);
painter->drawRect(circle);
if (m_activePointIndex != -1) {
painter->setBrush(invertedColor);
painter->setPen(Qt::NoPen);
circle.setWidth(1.5*SelectedPointDiameter);
circle.setHeight(1.5*SelectedPointDiameter);
circle.moveCenter(m_points.at(m_activePointIndex));
painter->drawEllipse(circle);
}
else if (m_activeSegmentIndex != -1) {
if (m_layout == Uml::LayoutType::Polyline) {
painter->setPen(QPen(invertedColor, _pen.widthF() + 1));
painter->setBrush(Qt::NoBrush);
QLineF segmentLine(m_points[m_activeSegmentIndex], m_points[m_activeSegmentIndex + 1]);
painter->drawLine(segmentLine);
}
}
// debug info
if (Tracer::instance()->isEnabled(QString::fromLatin1(metaObject()->className()))) {
QPen p(Qt::green);
p.setWidthF(1.0);
painter->setPen(p);
painter->setBrush(Qt::NoBrush);
painter->drawPath(shape());
painter->setPen(Qt::blue);
painter->drawRect(boundingRect());
// origin
painter->drawLine(-10, 0, 10, 0);
painter->drawLine(0, -10, 0, 10);
}
}
// now restore the points array
m_points[0] = savedStart;
m_points[sz - 1] = savedEnd;
}
/**
* Determines the active point or segment, the latter being given more priority.
*/
void AssociationLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
DEBUG() << "at " << event->scenePos();
if (event->buttons() & Qt::LeftButton) {
m_activePointIndex = closestPointIndex(event->scenePos());
// calculate only if active point index is -1
m_activeSegmentIndex = (m_activePointIndex != -1) ? -1 : closestSegmentIndex(event->scenePos());
}
else if (event->buttons() & Qt::RightButton) {
DEBUG() << "call context menu of association widget at " << event->scenePos();
}
else {
m_activePointIndex = -1;
m_activeSegmentIndex = -1;
}
}
/**
* Moves the point or line if active.
*/
void AssociationLine::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
UMLScene* scene = m_associationWidget->umlScene();
QPointF unsnappedPos = event->scenePos();
QPointF newPos(
scene->snappedX(unsnappedPos.x()),
scene->snappedY(unsnappedPos.y())
);
// Prevent the moving vertex from disappearing underneath a widget
// (else there's no way to get it back.)
UMLWidget *onW = scene->widgetAt(newPos);
if (onW && !onW->isBoxWidget()) { // boxes are transparent
const qreal pX = newPos.x();
const qreal pY = newPos.y();
const qreal wX = onW->x();
const qreal wY = onW->y();
const qreal wWidth = onW->width();
const qreal wHeight = onW->height();
if (pX > wX && pX < wX + wWidth) {
const qreal midX = wX + wWidth / 2.0;
if (pX <= midX)
newPos.setX(wX);
else
newPos.setX(wX + wWidth);
}
if (pY > wY && pY < wY + wHeight) {
const qreal midY = wY + wHeight / 2.0;
if (pY <= midY)
newPos.setY(wY);
else
newPos.setY(wY + wHeight);
}
}
if (m_activePointIndex != -1) {
const int nPoints = m_points.size();
// Move a single point (snap behaviour)
if (m_activePointIndex == 1) {
m_c1dx = newPos.x() - m_points.at(0).x();
m_c1dy = newPos.y() - m_points.at(0).y();
} else if (nPoints > 3 && m_activePointIndex == nPoints - 2) {
m_c2dx = newPos.x() - m_points.at(nPoints-1).x();
m_c2dy = newPos.y() - m_points.at(nPoints-1).y();
}
setPoint(m_activePointIndex, newPos);
m_autoLayoutSpline = false;
}
else if (m_activeSegmentIndex != -1 && !isEndSegmentIndex(m_activeSegmentIndex)) {
// Move a segment (between two points, snap behaviour not implemented)
QPointF delta = event->scenePos() - event->lastScenePos();
setPoint(m_activeSegmentIndex, m_points[m_activeSegmentIndex] + delta);
setPoint(m_activeSegmentIndex + 1, m_points[m_activeSegmentIndex + 1] + delta);
}
}
/**
* Reset active indices and also push undo command.
*/
void AssociationLine::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
m_activeSegmentIndex = -1;
m_activePointIndex = -1;
}
}
/**
* Calculates the "to be highlighted" point and segment indices
* and updates if necessary.
*/
void AssociationLine::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
DEBUG() << "at " << event->scenePos();
int oldPointIndex = m_activePointIndex;
int oldSegmentIndex = m_activeSegmentIndex;
m_activePointIndex = closestPointIndex(event->scenePos());
// End points are not drawn and hence not active.
if (m_activePointIndex != -1 && isEndPointIndex(m_activePointIndex)) {
m_activePointIndex = -1;
}
// Activate segment index only if point index is -1
m_activeSegmentIndex = (m_activePointIndex != -1) ? -1 : closestSegmentIndex(event->scenePos());
bool isChanged = (oldSegmentIndex != m_activeSegmentIndex || oldPointIndex != m_activePointIndex);
if (isChanged) {
m_associationWidget->update();
}
}
/**
* Calculates the "to be highlighted" point and segment indices
* and updates if necessary.
*/
void AssociationLine::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
int oldPointIndex = m_activePointIndex;
int oldSegmentIndex = m_activeSegmentIndex;
m_activePointIndex = closestPointIndex(event->scenePos());
// End points are not drawn and hence not active.
if (m_activePointIndex != -1 && isEndPointIndex(m_activePointIndex)) {
m_activePointIndex = -1;
}
// Activate segment index only if point index is -1
m_activeSegmentIndex = (m_activePointIndex != -1) ? -1 : closestSegmentIndex(event->scenePos());
bool isChanged = (oldSegmentIndex != m_activeSegmentIndex || oldPointIndex != m_activePointIndex);
if (isChanged) {
m_associationWidget->update();
}
}
/**
* Reset active indices and updates.
*/
void AssociationLine::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
DEBUG() << "at " << event->scenePos();
//Q_UNUSED(event)
m_activePointIndex = -1;
m_activeSegmentIndex = -1;
m_associationWidget->update();
}
//-----------------------------------------------------------------------------
/**
* Auxiliary struct for Symbol::SymbolProperty in C Plain Old Data format
* avoids danger of "C++ static initialization order fiasco", see
* https://en.cppreference.com/w/cpp/language/siof
*/
struct SymbolPropertyPOD {
int boundRectX, boundRectY, boundRectW, boundRectH;
int axisLineStartX, axisLineStartY, axisLineEndX, axisLineEndY;
int endPoint0x, endPoint0y, endPoint1x, endPoint1y;
};
static const SymbolPropertyPOD symPropData[] =
{
{
-6, 0, 12, 10,
0, 0, 0, 10,
0, 10, 0, 10
},
{
-6, 0, 12, 10,
0, 0, 0, 10,
0, 0, 0, 10
},
{
-6, 0, 12, 10,
0, 0, 0, 10,
0, 10, 0, 10
},
{
-5, -10, 10, 20,
0, -10, 0, 10,
0, -10, 0, 10
},
{
-15, -10, 30, 20,
-10, 0, 0, 0,
0, 0, 0, 0
},
{
-8, -8, 16, 16,
0, -8, 0, 8,
0, -8, 0, 8
}
};
/**
* SymbolEndPoints:
* The first point is where the AssociationLine's visible line is
* supposed to end.
* The second points is where the actual symbol part is to appear.
*/
Symbol::SymbolProperty *Symbol::symbolTable;
/**
* @internal A convenience method to setup shapes of all symbols.
*/
void Symbol::setupSymbolTable()
{
if (symbolTable)
return;
symbolTable = new SymbolProperty[Count];
// Copy C symPropData to C++ symbolTable
for (int i = 0; i < Count; i++) {
const SymbolPropertyPOD& c = symPropData[i];
SymbolProperty& prop = symbolTable[i];
prop.boundRect = QRectF(c.boundRectX, c.boundRectY, c.boundRectW, c.boundRectH);
prop.axisLine = QLineF(c.axisLineStartX, c.axisLineStartY, c.axisLineEndX, c.axisLineEndY);
prop.endPoints = SymbolEndPoints(QPointF(c.endPoint0x, c.endPoint0y),
QPointF(c.endPoint1x, c.endPoint1y));
}
SymbolProperty &openArrow = symbolTable[OpenArrow];
if (openArrow.shape.isEmpty()) {
QRectF rect = openArrow.boundRect;
// Defines a 'V' shape arrow fitting in the bound rect.
openArrow.shape.moveTo(rect.topLeft());
openArrow.shape.lineTo(rect.center().x(), rect.bottom());
openArrow.shape.lineTo(rect.topRight());
}
SymbolProperty &closedArrow = symbolTable[ClosedArrow];
if (closedArrow.shape.isEmpty()) {
QRectF rect = closedArrow.boundRect;
// Defines a 'V' shape arrow fitting in the bound rect.
closedArrow.shape.moveTo(rect.topLeft());
closedArrow.shape.lineTo(rect.center().x(), rect.bottom());
closedArrow.shape.lineTo(rect.topRight());
closedArrow.shape.lineTo(rect.topLeft());
}
SymbolProperty &crowFeet = symbolTable[CrowFeet];
if (crowFeet.shape.isEmpty()) {
QRectF rect = crowFeet.boundRect;
// Defines a crowFeet fitting in the bound rect.
QPointF topMid(rect.center().x(), rect.top());
// left leg
crowFeet.shape.moveTo(rect.bottomLeft());
crowFeet.shape.lineTo(topMid);
// middle leg
crowFeet.shape.moveTo(rect.center().x(), rect.bottom());
crowFeet.shape.lineTo(topMid);
// right leg
crowFeet.shape.moveTo(rect.bottomRight());
crowFeet.shape.lineTo(topMid);
}
SymbolProperty &diamond = symbolTable[Diamond];
if (diamond.shape.isEmpty()) {
QRectF rect = diamond.boundRect;
// Defines a 'diamond' shape fitting in the bound rect.
diamond.shape.moveTo(rect.center().x(), rect.top());
diamond.shape.lineTo(rect.left(), rect.center().y());
diamond.shape.lineTo(rect.center().x(), rect.bottom());
diamond.shape.lineTo(rect.right(), rect.center().y());
diamond.shape.lineTo(rect.center().x(), rect.top());
}
SymbolProperty &subset = symbolTable[Subset];
if (subset.shape.isEmpty()) {
QRectF rect = subset.boundRect;
// Defines an arc fitting in bound rect.
qreal start = 90, span = 180;
subset.shape.arcMoveTo(rect, start);
subset.shape.arcTo(rect, start, span);
}
SymbolProperty &circle = symbolTable[Circle];
if (circle.shape.isEmpty()) {
QRectF rect = circle.boundRect;
// Defines a circle with a horizontal-vertical cross lines.
circle.shape.addEllipse(rect);
circle.shape.moveTo(rect.center().x(), rect.top());
circle.shape.lineTo(rect.center().x(), rect.bottom());
circle.shape.moveTo(rect.left(), rect.center().y());
circle.shape.lineTo(rect.right(), rect.center().y());
}
}
/**
* Constructs a Symbol with current symbol being \a symbol and
* parented to \a parent.
*/
Symbol::Symbol(SymbolType symbolType, QGraphicsItem *parent)
: QGraphicsItem(parent),
m_symbolType(symbolType)
{
// ensure SymbolTable is validly initialized
setupSymbolTable();
}
/**
* Destructor.
*/
Symbol::~Symbol()
{
}
/**
* @return The current symbol being represented.
*/
Symbol::SymbolType Symbol::symbolType() const
{
return m_symbolType;
}
/**
* Sets the current symbol type to \a symbol and updates the geometry.
*/
void Symbol::setSymbolType(SymbolType symbolType)
{
prepareGeometryChange(); // calls update implicitly
m_symbolType = symbolType;
}
/**
* Draws the current symbol using the QPainterPath stored for the current
* symbol.
*/
void Symbol::paint(QPainter *painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
Q_UNUSED(option) Q_UNUSED(widget)
painter->setPen(m_pen);
switch (m_symbolType) {
case ClosedArrow:
case CrowFeet:
case Diamond:
painter->setBrush(m_brush);
break;
default:
break;
}
painter->drawPath(symbolTable[m_symbolType].shape);
}
/**
* @return The bound rectangle for this based on current symbol.
*/
QRectF Symbol::boundingRect() const
{
const qreal adj = .5 * m_pen.widthF();
return symbolTable[m_symbolType].boundRect.
adjusted(-adj, -adj, adj, adj);
}
/**
* @return The path for this based on current symbol.
*/
QPainterPath Symbol::shape() const
{
QPainterPath path;
path.addRect(boundingRect());
return path;
}
/**
* This method aligns *this* Symbol to the line being
* passed. That is, it ensures that the axis of this symbol aligns
* exactly with the \a "to" line passed.
*
* Also this item is moved such that the second end point of the
* SymbolEndPoints for the current symbol *collides* with the second end
* point of \a "to" line.
*/
void Symbol::alignTo(const QLineF& to)
{
QLineF toMapped(mapFromParent(to.p1()), mapFromParent(to.p2()));
QLineF origAxis = symbolTable[m_symbolType].axisLine;
QLineF translatedAxis = origAxis.translated(toMapped.p2() - origAxis.p2());
qreal angle = translatedAxis.angleTo(toMapped);
setRotation(rotation() - angle);
QPointF delta = to.p2() - mapToParent(symbolEndPoints().second);
moveBy(delta.x(), delta.y());
}
/**
* @return The end points for the symbol.
*/
Symbol::SymbolEndPoints Symbol::symbolEndPoints() const
{
return symbolTable[m_symbolType].endPoints;
}
/**
* @return The pen used to draw symbol.
*/
QPen Symbol::pen() const
{
return m_pen;
}
/**
* Sets the pen used to draw the symbol.
*/
void Symbol::setPen(const QPen& pen)
{
prepareGeometryChange();
m_pen = pen;
m_pen.setStyle(Qt::SolidLine);
}
/**
* @return The brush used to fill symbol.
*/
QBrush Symbol::brush() const
{
return m_brush;
}
/**
* Sets the brush used to fill symbol.
*/
void Symbol::setBrush(const QBrush &brush)
{
m_brush = brush;
update();
}
| 46,291
|
C++
|
.cpp
| 1,403
| 27.034212
| 104
| 0.632948
|
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,400
|
floatingtextwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/floatingtextwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "floatingtextwidget.h"
// local includes
#include "association.h"
#include "associationwidget.h"
#include "associationpropertiesdialog.h"
#include "classifier.h"
#include "cmds.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "linkwidget.h"
#include "classifierwidget.h"
#include "listpopupmenu.h"
#include "messagewidget.h"
#include "model_utils.h"
#include "object_factory.h"
#include "operation.h"
#include "selectoperationdialog.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QFontDialog>
#include <QPointer>
#include <QRegularExpression>
#include <QPainter>
#include <QValidator>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(FloatingTextWidget)
/**
* Constructs a FloatingTextWidget instance.
*
* @param scene The parent of this FloatingTextWidget.
* @param role The role this FloatingTextWidget will take up.
* @param text The main text to display.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
FloatingTextWidget::FloatingTextWidget(UMLScene * scene, Uml::TextRole::Enum role, const QString& text, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Text, id),
m_linkWidget(nullptr),
m_preText(QString()),
m_postText(QString()),
m_textRole(role),
m_unconstrainedPositionX(0),
m_unconstrainedPositionY(0),
m_movementDirectionX(0),
m_movementDirectionY(0)
{
m_Text = text;
m_resizable = false;
setZValue(10); //make sure always on top.
}
/**
* Destructor.
*/
FloatingTextWidget::~FloatingTextWidget()
{
}
/**
* Use to get the _main body_ of text (e.g. prepended and appended
* text is omitted) as currently displayed by the widget.
*
* @return The main text currently being displayed by the widget.
*/
QString FloatingTextWidget::text() const
{
// test to make sure not just the ":" between the seq number and
// the actual message widget
// hmm. this section looks like it could have been avoided by
// using pre-, post- text instead of storing in the main body of
// the text -b.t.
if (m_textRole == Uml::TextRole::Seq_Message || m_textRole == Uml::TextRole::Seq_Message_Self ||
m_textRole == Uml::TextRole::Coll_Message || m_textRole == Uml::TextRole::Coll_Message_Self) {
if (m_Text.length() <= 1 || m_Text == QStringLiteral(": "))
return QString();
}
return m_Text;
}
/**
* Set the main body of text to display.
*
* @param t The text to display.
*/
void FloatingTextWidget::setText(const QString &t)
{
if (m_textRole == Uml::TextRole::Seq_Message || m_textRole == Uml::TextRole::Seq_Message_Self) {
QString op;
if (m_linkWidget)
op = m_linkWidget->lwOperationText();
if (op.length() > 0) {
if (!m_scene->showOpSig())
op.replace(QRegularExpression(QStringLiteral("\\(.*\\)")), QStringLiteral("()"));
m_Text = op;
}
else
m_Text = t;
}
else {
m_Text = t;
}
QSizeF s = minimumSize();
setSize(s.width(), s.height());
updateGeometry();
update();
}
/**
* Set some text to be prepended to the main body of text.
* @param t The text to prepend to main body which is displayed.
*/
void FloatingTextWidget::setPreText(const QString &t)
{
m_preText = t;
updateGeometry();
update();
}
/**
* Set some text to be appended to the main body of text.
* @param t The text to append to main body which is displayed.
*/
void FloatingTextWidget::setPostText(const QString &t)
{
m_postText = t;
updateGeometry();
update();
}
/**
* Use to get the total text (prepended + main body + appended)
* currently displayed by the widget.
*
* @return The text currently being displayed by the widget.
*/
QString FloatingTextWidget::displayText() const
{
QString displayText;
if (!m_SequenceNumber.isEmpty())
displayText = m_SequenceNumber + QStringLiteral(": ") + m_Text;
else
displayText = m_Text;
displayText.prepend(m_preText);
displayText.append(m_postText);
return displayText;
}
/**
* Return state if no pre, post and main text is empty
* @return true if widget contains no text
*/
bool FloatingTextWidget::isEmpty()
{
return m_Text.isEmpty() && m_preText.isEmpty() && m_postText.isEmpty();
}
/**
* Overrides method from UMLWidget.
*/
QSizeF FloatingTextWidget::minimumSize() const
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
int h = fm.lineSpacing();
int w = fm.horizontalAdvance(displayText());
return QSizeF(w + 8, h + 4); // give a small margin
}
/**
* Method used by setText: its called by cmdsetTxt, Don't use it!
*
* @param t The text to display.
*/
void FloatingTextWidget::setTextcmd(const QString &t)
{
UMLApp::app()->executeCommand(new Uml::CmdSetTxt(this, t));
}
/**
* Displays a dialog box to change the text.
*/
void FloatingTextWidget::showChangeTextDialog()
{
QString newText = text();
bool ok = Dialog_Utils::askName(i18n("Change Text"),
i18n("Enter new text:"),
newText);
if (ok && newText != text() && isTextValid(newText)) {
setText(newText);
setVisible(!text().isEmpty());
updateGeometry();
update();
}
if (!isTextValid(newText))
hide();
}
/**
* Shows an operation dialog box.
*
* @param enableAutoIncrement Enable auto increment checkbox
*/
bool FloatingTextWidget::showOperationDialog(bool enableAutoIncrement)
{
if (!m_linkWidget) {
logError0("FloatingTextWidget::showOperationDialog: m_linkWidget is NULL");
return false;
}
if (!m_linkWidget->lwClassifier()) {
logError0("FloatingTextWidget::showOperationDialog: m_linkWidget->lwClassifier() returns a NULL classifier");
return false;
}
bool result = false;
QPointer<SelectOperationDialog> selectDialog = new SelectOperationDialog(m_scene->activeView(), m_linkWidget->lwClassifier(), m_linkWidget, enableAutoIncrement);
if (selectDialog->exec()) {
selectDialog->apply();
setMessageText();
result = true;
}
delete selectDialog;
return result;
}
/**
* Show the properties for a FloatingTextWidget.
* Depending on the role of the floating text widget, the options dialog
* for the floating text widget, the rename dialog for floating text or
* the options dialog for the link widget are shown.
*/
bool FloatingTextWidget::showPropertiesDialog()
{
UMLWidget *p = dynamic_cast<UMLWidget*>(parentItem());
if (p && p->isInterfaceWidget()) {
if (p->showPropertiesDialog())
setText(p->name());
} else if (m_textRole == Uml::TextRole::Coll_Message || m_textRole == Uml::TextRole::Coll_Message_Self ||
m_textRole == Uml::TextRole::Seq_Message || m_textRole == Uml::TextRole::Seq_Message_Self) {
return showOperationDialog(false);
} else if (m_textRole == Uml::TextRole::Floating) {
// double clicking on a text line opens the dialog to change the text
return handleRename();
} else if (m_linkWidget) {
return m_linkWidget->showPropertiesDialog();
}
return false;
}
/**
* Use to get the pre-text which is prepended to the main body of
* text to be displayed.
*
* @return The pre-text currently displayed by the widget.
*/
QString FloatingTextWidget::preText() const
{
return m_preText;
}
/**
* Use to get the post-text which is appended to the main body of
* text to be displayed.
*
* @return The post-text currently displayed by the widget.
*/
QString FloatingTextWidget::postText() const
{
return m_postText;
}
/**
* Activate the FloatingTextWidget after the saved data has been loaded
*
* @param ChangeLog Pointer to the IDChangeLog.
* @return true for success
*/
bool FloatingTextWidget::activate(IDChangeLog *ChangeLog /*= nullptr */)
{
if (! UMLWidget::activate(ChangeLog))
return false;
update();
return true;
}
/**
* Set the LinkWidget that this FloatingTextWidget is related to.
*
* @param l The related LinkWidget.
*/
void FloatingTextWidget::setLink(LinkWidget * l)
{
m_linkWidget = l;
}
/**
* Returns the LinkWidget this floating text is related to.
*
* @return The LinkWidget this floating text is related to.
*/
LinkWidget * FloatingTextWidget::link() const
{
return m_linkWidget;
}
/**
* Sets the role type of this FloatingTextWidget.
*
* @param role The TextRole::Enum of this FloatingTextWidget.
*/
void FloatingTextWidget::setTextRole(Uml::TextRole::Enum role)
{
m_textRole = role;
}
/**
* Return the role of the text widget
* @return The TextRole::Enum of this FloatingTextWidget.
*/
Uml::TextRole::Enum FloatingTextWidget::textRole() const
{
return m_textRole;
}
/**
* Handle the ListPopupMenu::mt_Rename case of the slotMenuSelection.
* Given an own method because it requires rather lengthy code.
*/
bool FloatingTextWidget::handleRename()
{
QString t;
if (m_textRole == Uml::TextRole::RoleAName || m_textRole == Uml::TextRole::RoleBName) {
t = i18n("Enter role name:");
} else if (m_textRole == Uml::TextRole::MultiA || m_textRole == Uml::TextRole::MultiB) {
t = i18n("Enter multiplicity:");
/*
// NO! shouldn't be allowed
} else if (m_textRole == Uml::TextRole::ChangeA || m_textRole == Uml::TextRole::ChangeB) {
t = i18n("Enter changeability");
*/
} else if (m_textRole == Uml::TextRole::Name) {
t = i18n("Enter association name:");
} else if (m_textRole == Uml::TextRole::Floating) {
t = i18n("Enter new text:");
} else {
t = i18n("ERROR");
}
QString newText = text();
bool ok = Dialog_Utils::askName(i18n("Rename"), t, newText);
if (!ok || newText == text()) {
return false;
}
UMLApp::app()->executeCommand(new Uml::CmdHandleRename(this, newText));
return true;
}
/**
* Changes the text of linked widget.
* @param newText the new text
*/
void FloatingTextWidget::changeName(const QString& newText)
{
if (m_linkWidget && !isTextValid(newText)) {
AssociationWidget *assoc = dynamic_cast<AssociationWidget*>(m_linkWidget);
if (assoc) {
switch (m_textRole) {
case Uml::TextRole::MultiA:
assoc->setMultiplicity(QString(), Uml::RoleType::A);
break;
case Uml::TextRole::MultiB:
assoc->setMultiplicity(QString(), Uml::RoleType::B);
break;
case Uml::TextRole::RoleAName:
assoc->setRoleName(QString(), Uml::RoleType::A);
break;
case Uml::TextRole::RoleBName:
assoc->setRoleName(QString(), Uml::RoleType::B);
break;
case Uml::TextRole::ChangeA:
assoc->setChangeability(Uml::Changeability::Changeable, Uml::RoleType::A);
break;
case Uml::TextRole::ChangeB:
assoc->setChangeability(Uml::Changeability::Changeable, Uml::RoleType::B);
break;
default:
assoc->setName(QString());
break;
}
}
else {
MessageWidget *msg = dynamic_cast<MessageWidget*>(m_linkWidget);
if (msg) {
msg->setName(QString());
m_scene->removeWidget(this);
}
}
return;
}
if (m_linkWidget && m_textRole != Uml::TextRole::Seq_Message
&& m_textRole != Uml::TextRole::Seq_Message_Self) {
m_linkWidget->setText(this, newText);
}
else {
setText(newText);
UMLApp::app()->document()->setModified(true);
}
setVisible(true);
updateGeometry();
update();
}
/**
* Write property of QString m_SequenceNumber.
*/
void FloatingTextWidget::setSequenceNumber(const QString &sequenceNumber)
{
m_SequenceNumber = sequenceNumber;
}
/**
* Read property of QString m_SequenceNumber.
*/
QString FloatingTextWidget::sequenceNumber() const
{
return m_SequenceNumber;
}
/**
* For a text to be valid it must be non-empty, i.e. have a length
* larger than zero, and have at least one non whitespace character.
*
* @param text The string to analyze.
* @return True if the given text is valid.
*/
bool FloatingTextWidget::isTextValid(const QString &text)
{
int length = text.length();
if(length < 1)
return false;
for(int i=0;i<length;i++) {
if(!text.at(i).isSpace()) {
return true;
}
}
return false;
}
/**
* Returns a constrained position for the widget after applying the position
* difference.
* If no link widget exists, the position returned is the current widget
* position with the difference applied. If there's a link, the position
* to be returned is constrained using constrainTextPos method from the
* LinkWidget, if any.
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
* @return A QPointF with the constrained new position.
*/
QPointF FloatingTextWidget::constrainPosition(qreal diffX, qreal diffY)
{
qreal newX = x() + diffX;
qreal newY = y() + diffY;
if (link()) {
link()->constrainTextPos(newX, newY, width(), height(), textRole());
}
return QPointF(newX, newY);
}
/**
* Overridden from UMLWidget.
* Moves the widget to a new position using the difference between the
* current position and the new position.
* If the floating text widget is part of a sequence message, and the
* message widget is selected, it does nothing: the message widget will
* update the text position when it's moved.
* In any other case, the floating text widget constrains its move using
* constrainPosition. When the position of the floating text is constrained,
* it's kept at that position until it can be moved to another valid
* position (m_unconstrainedPositionX/Y and m_movementDirectionX/Y are
* used for that).
* Moreover, if is part of a sequence message (and the message widget
* isn't selected), it updates the position of the message widget.
* @see constrainPosition
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void FloatingTextWidget::moveWidgetBy(qreal diffX, qreal diffY)
{
if (textRole() == Uml::TextRole::Seq_Message_Self)
return;
if (textRole() == Uml::TextRole::Seq_Message
&& link() && dynamic_cast<MessageWidget*>(link())
&& dynamic_cast<MessageWidget*>(link())->isSelected()) {
return;
}
m_unconstrainedPositionX += diffX;
m_unconstrainedPositionY += diffY;
QPointF constrainedPosition = constrainPosition(diffX, diffY);
qreal newX = constrainedPosition.x();
qreal newY = constrainedPosition.y();
if (!m_movementDirectionX) {
if (m_unconstrainedPositionX != constrainedPosition.x()) {
m_movementDirectionX = (diffX > 0)? 1: -1;
}
} else if ((m_movementDirectionX < 0 && m_unconstrainedPositionX > x()) ||
(m_movementDirectionX > 0 && m_unconstrainedPositionX < x()) ) {
newX = m_unconstrainedPositionX;
m_movementDirectionX = 0;
}
if (!m_movementDirectionY) {
if (m_unconstrainedPositionY != constrainedPosition.y()) {
m_movementDirectionY = (diffY > 0)? 1: -1;
}
} else if ((m_movementDirectionY < 0 && m_unconstrainedPositionY > y()) ||
(m_movementDirectionY > 0 && m_unconstrainedPositionY < y()) ) {
newY = m_unconstrainedPositionY;
m_movementDirectionY = 0;
}
setX(newX);
setY(newY);
if (link()) {
link()->calculateNameTextSegment();
if (textRole() == Uml::TextRole::Seq_Message) {
MessageWidget* messageWidget = (MessageWidget*)link();
messageWidget->setY(newY + height());
}
}
}
/**
* Overridden from UMLWidget.
* Modifies the value of the diffX and diffY variables used to move the
* widgets.
* The values are constrained using constrainPosition.
* @see constrainPosition
*
* @param diffX The difference between current X position and new X position.
* @param diffY The difference between current Y position and new Y position.
*/
void FloatingTextWidget::constrainMovementForAllWidgets(qreal &diffX, qreal &diffY)
{
QPointF constrainedPosition = constrainPosition(diffX, diffY);
diffX = constrainedPosition.x() - x();
diffY = constrainedPosition.y() - y();
}
/**
* Override method from UMLWidget in order to additionally check widget parentage.
*
* @param p Point to be checked.
*
* @return 'this' if UMLWidget::onWidget(p) returns non 0;
* else NULL.
*/
UMLWidget* FloatingTextWidget::onWidget(const QPointF &p)
{
WidgetBase *pw = dynamic_cast<WidgetBase*>(parentItem());
if (pw == nullptr) {
return WidgetBase::onWidget(p);
}
const WidgetBase::WidgetType t = pw->baseType();
bool isWidgetChild = false;
if (t == WidgetBase::wt_Interface) {
ClassifierWidget *cw = static_cast<ClassifierWidget*>(pw);
isWidgetChild = cw->getDrawAsCircle();
} else if (t == wt_Association ||
t == WidgetBase::wt_Port || t == WidgetBase::wt_Pin) {
isWidgetChild = true;
}
if (!isWidgetChild) {
return WidgetBase::onWidget(p);
}
const qreal w = width();
const qreal h = height();
const qreal left = pw->x() + x();
const qreal right = left + w;
const qreal top = pw->y() + y();
const qreal bottom = top + h;
// uDebug() << "child_of_pw; p=(" << p.x() << "," << p.y() << "), "
// << "x=" << left << ", y=" << top << ", w=" << w << ", h=" << h
// << "; right=" << right << ", bottom=" << bottom;
if (p.x() >= left && p.x() <= right &&
p.y() >= top && p.y() <= bottom) { // Qt coord.sys. origin in top left corner
// uDebug() << "floatingtext: " << m_Text;
return this;
}
return nullptr;
}
/**
* Overrides default method
*/
void FloatingTextWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
int w = width();
int h = height();
painter->setFont(UMLWidget::font());
painter->setPen(textColor());
painter->drawText(0, 0, w, h, Qt::AlignCenter, displayText());
UMLWidget::paint(painter, option, widget);
}
/**
* Loads the "floatingtext" XMI element.
*/
bool FloatingTextWidget::loadFromXMI(QDomElement & qElement)
{
if(!UMLWidget::loadFromXMI(qElement))
return false;
m_unconstrainedPositionX = x();
m_unconstrainedPositionY = y();
QString role = qElement.attribute(QStringLiteral("role"));
if(!role.isEmpty())
m_textRole = Uml::TextRole::fromInt(role.toInt());
m_preText = qElement.attribute(QStringLiteral("pretext"));
m_postText = qElement.attribute(QStringLiteral("posttext"));
setText(qElement.attribute(QStringLiteral("text"))); // use setText for geometry update
// If all texts are empty then this is a useless widget.
// In that case we return false.
// CAVEAT: The caller should not interpret the false return value
// as an indication of failure since previous umbrello versions
// saved lots of these empty FloatingTexts.
bool usefulWidget = !isEmpty();
return usefulWidget;
}
/**
* Reimplemented from UMLWidget::saveToXMI to save the widget
* data into XMI 'floatingtext' element.
*/
void FloatingTextWidget::saveToXMI(QXmlStreamWriter& writer)
{
if (isEmpty())
return;
writer.writeStartElement(QStringLiteral("floatingtext"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("text"), m_Text);
writer.writeAttribute(QStringLiteral("pretext"), m_preText);
writer.writeAttribute(QStringLiteral("posttext"), m_postText);
/* No need to save these - the messagewidget already did it.
m_Operation = qElement.attribute("operation");
m_SeqNum = qElement.attribute("seqnum");
*/
writer.writeAttribute(QStringLiteral("role"), QString::number(m_textRole));
writer.writeEndElement();
}
/**
* Called when a menu selection has been made.
*
* @param action The action that has been selected.
*/
void FloatingTextWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
case ListPopupMenu::mt_Delete:
hide(); // This is only a workaround; if set then m_linkWidget should
// really delete this FloatingTextWidget.
update();
m_scene->removeWidget(this);
break;
case ListPopupMenu::mt_New_Operation: // needed by AssociationWidget
case ListPopupMenu::mt_Operation:
{
if (m_linkWidget == nullptr) {
logDebug0("FloatingTextWidget::slotMenuSelection(mt_Operation): m_linkWidget is NULL");
return;
}
UMLClassifier* c = m_linkWidget->operationOwner();
if (c == nullptr) {
QString opText = text();
bool ok = Dialog_Utils::askName(i18nc("operation name", "Name"),
i18n("Enter operation name:"),
opText);
if (ok)
m_linkWidget->setCustomOpText(opText);
return;
}
UMLClassifierListItem* umlObj = Object_Factory::createChildObject(c, UMLObject::ot_Operation);
if (umlObj) {
UMLOperation* newOperation = umlObj->asUMLOperation();
m_linkWidget->setOperation(newOperation);
}
}
break;
case ListPopupMenu::mt_Select_Operation:
showOperationDialog(false);
break;
case ListPopupMenu::mt_Rename:
handleRename();
break;
case ListPopupMenu::mt_Change_Font:
{
bool ok = false;
QFont fnt = QFontDialog::getFont(&ok, font(), m_scene->activeView());
if (ok) {
if(m_textRole == Uml::TextRole::Floating || m_textRole == Uml::TextRole::Seq_Message) {
setFont(fnt);
} else if (m_linkWidget) {
m_linkWidget->lwSetFont(fnt);
}
}
}
break;
case ListPopupMenu::mt_Reset_Label_Positions:
if (m_linkWidget)
m_linkWidget->resetTextPositions();
break;
default:
UMLWidget::slotMenuSelection(action);
break;
}//end switch
}
/**
* Sets the text for this label if it is acting as a sequence diagram
* message or a collaboration diagram message.
*/
void FloatingTextWidget::setMessageText()
{
if (m_linkWidget) {
m_linkWidget->setMessageText(this);
QSizeF s = minimumSize();
setSize(s.width(), s.height());
}
setVisible(!text().isEmpty());
}
| 23,556
|
C++
|
.cpp
| 707
| 27.951909
| 165
| 0.6525
|
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,401
|
packagewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/packagewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "packagewidget.h"
// app includes
#include "debug_utils.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
#include "umlscene.h"
#include "umlview.h"
// qt includes
#include <QPainter>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(PackageWidget)
/**
* Constructs a PackageWidget.
*
* @param scene The parent of this PackageWidget.
* @param o The UMLObject this will be representing.
*/
PackageWidget::PackageWidget(UMLScene * scene, UMLPackage *o)
: UMLWidget(scene, WidgetBase::wt_Package, o)
{
setSize(100, 30);
setZValue(1); // above box but below UMLWidget because may embed widgets
//set defaults from m_scene
if (m_scene) {
//check to see if correct
const Settings::OptionState& ops = m_scene->optionState();
m_showStereotype = ops.classState.showStereoType;
}
}
/**
* Destructor.
*/
PackageWidget::~PackageWidget()
{
}
/**
* Overrides standard method.
*/
void PackageWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
if (UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
else
painter->setBrush(m_scene->backgroundColor());
int w = width();
int h = height();
QFont font = UMLWidget::font();
font.setBold(true);
//FIXME italic is true when a package is first created until you click elsewhere, not sure why
font.setItalic(false);
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
painter->drawRect(0, 0, 50, fontHeight);
if (m_umlObject != nullptr
&& m_umlObject->stereotype() == QStringLiteral("subsystem")) {
const int fHalf = fontHeight / 2;
const int symY = fHalf;
const int symX = 38;
painter->drawLine(symX, symY, symX, symY + fHalf - 2); // left leg
painter->drawLine(symX + 8, symY, symX + 8, symY + fHalf - 2); // right leg
painter->drawLine(symX, symY, symX + 8, symY); // waist
painter->drawLine(symX + 4, symY, symX + 4, symY - fHalf + 2); // head
}
painter->drawRect(0, fontHeight - 1, w, h - fontHeight);
painter->setPen(textColor());
painter->setFont(font);
int lines = 1;
if (m_umlObject != nullptr) {
QString stereotype = m_umlObject->stereotype();
if (!stereotype.isEmpty()) {
painter->drawText(0, fontHeight + PACKAGE_MARGIN,
w, fontHeight, Qt::AlignCenter, m_umlObject->stereotype(true));
lines = 2;
}
}
painter->drawText(0, (fontHeight*lines) + PACKAGE_MARGIN,
w, fontHeight, Qt::AlignCenter, name());
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget
*/
QSizeF PackageWidget::minimumSize() const
{
if (!m_umlObject) {
return UMLWidget::minimumSize();
}
const QFontMetrics &fm = getFontMetrics(FT_BOLD_ITALIC);
const int fontHeight = fm.lineSpacing();
int lines = 1;
int width = fm.horizontalAdvance(m_umlObject->name());
int tempWidth = 0;
if (!m_umlObject->stereotype().isEmpty()) {
tempWidth = fm.horizontalAdvance(m_umlObject->stereotype(true));
lines = 2;
}
if (tempWidth > width)
width = tempWidth;
width += PACKAGE_MARGIN * 2;
if (width < 70)
width = 70; // minumin width of 70
int height = (lines*fontHeight) + fontHeight + (PACKAGE_MARGIN * 2);
return QSizeF(width, height);
}
/**
* Saves to the "packagewidget" XMI element.
*/
void PackageWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("packagewidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
| 4,038
|
C++
|
.cpp
| 123
| 28.081301
| 101
| 0.659815
|
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,402
|
statewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/statewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "statewidget.h"
// app includes
#include "cmds/cmdcreatediagram.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "listpopupmenu.h"
#include "statedialog.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QtGlobal>
#include <QPointer>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(StateWidget)
/**
* Creates a State widget.
*
* @param scene The parent of the widget.
* @param stateType The type of state.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
StateWidget::StateWidget(UMLScene * scene, StateType stateType, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_State, id)
{
setStateType(stateType);
m_drawVertical = true;
// Set non zero size to avoid crash on painting.
// We cannot call the reimplemented method minimumSize() in the constructor
// because the vtable is not yet finalized (i.e. dynamic dispatch does not work).
setSize(15, 15);
}
/**
* Destructor.
*/
StateWidget::~StateWidget()
{
}
/**
* Overrides the standard paint event.
*/
void StateWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
const qreal w = width();
const qreal h = height();
if (w == 0 || h == 0)
return;
setPenFromSettings(painter);
switch (m_stateType) {
case StateWidget::Normal:
{
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textStartY = (h / 2) - (fontHeight / 2);
const int count = m_Activities.count();
if (count == 0) {
painter->drawRoundedRect(0, 0, w, h, (h*40)/w, (w*40)/h);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(false);
painter->setFont(font);
painter->drawText(STATE_MARGIN, textStartY,
w - STATE_MARGIN * 2, fontHeight,
Qt::AlignCenter, name());
setPenFromSettings(painter);
} else {
painter->drawRoundedRect(0, 0, w, h, (h*40)/w, (w*40)/h);
textStartY = STATE_MARGIN;
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(true);
painter->setFont(font);
painter->drawText(STATE_MARGIN, textStartY, w - STATE_MARGIN * 2,
fontHeight, Qt::AlignCenter, name());
font.setBold(false);
painter->setFont(font);
setPenFromSettings(painter);
int linePosY = textStartY + fontHeight;
QStringList::Iterator end(m_Activities.end());
for(QStringList::Iterator it(m_Activities.begin()); it != end; ++it) {
textStartY += fontHeight;
painter->drawLine(0, linePosY, w, linePosY);
painter->setPen(textColor());
painter->drawText(STATE_MARGIN, textStartY, w - STATE_MARGIN * 2,
fontHeight, Qt::AlignCenter, *it);
setPenFromSettings(painter);
linePosY += fontHeight;
}//end for
}//end else
}
break;
case StateWidget::Initial :
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(0, 0, w, h);
break;
case StateWidget::End :
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(0, 0, w, h);
painter->setBrush(Qt::white);
painter->drawEllipse(1, 1, w - 2, h - 2);
painter->setBrush(WidgetBase::lineColor());
painter->drawEllipse(3, 3, w - 6, h - 6);
break;
case StateWidget::Fork:
case StateWidget::Join:
{
painter->setPen(Qt::black);
painter->setBrush(Qt::black);
painter->drawRect(rect());
}
break;
case StateWidget::Junction:
{
painter->setPen(Qt::black);
painter->setBrush(Qt::black);
painter->drawEllipse(rect());
}
break;
case StateWidget::DeepHistory:
{
painter->setBrush(Qt::white);
painter->drawEllipse(rect());
painter->setPen(Qt::black);
painter->setFont(UMLWidget::font());
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing() / 2;
const int xStar = fm.boundingRect(QStringLiteral("H")).width();
const int yStar = fontHeight / 4;
painter->drawText((w / 6),
(h / 4) + fontHeight, QStringLiteral("H"));
painter->drawText((w / 6) + xStar,
(h / 4) + fontHeight - yStar, QStringLiteral("*"));
}
break;
case StateWidget::ShallowHistory:
{
painter->setBrush(Qt::white);
painter->drawEllipse(rect());
painter->setPen(Qt::black);
painter->setFont(UMLWidget::font());
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing() / 2;
painter->drawText((w / 6),
(h / 4) + fontHeight, QStringLiteral("H"));
}
break;
case StateWidget::Choice:
{
const qreal x = w / 2;
const qreal y = h / 2;
QPolygonF polygon;
polygon << QPointF(x, 0) << QPointF(w, y)
<< QPointF(x, h) << QPointF(0, y);
painter->setBrush(UMLWidget::fillColor());
painter->drawPolygon(polygon);
}
break;
case StateWidget::Combined:
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
setPenFromSettings(painter);
QPainterPath path;
path.addRoundedRect(rect(), STATE_MARGIN, STATE_MARGIN);
if (useFillColor())
painter->fillPath(path, UMLWidget::fillColor());
painter->drawPath(path);
painter->drawLine(QPointF(0, fontHeight), QPointF(w, fontHeight));
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(false);
painter->setFont(font);
painter->drawText(STATE_MARGIN, 0, w - STATE_MARGIN * 2, fontHeight,
Qt::AlignCenter, name());
if (!linkedDiagram()) {
m_size = QSizeF(fm.horizontalAdvance(name()) + STATE_MARGIN * 2, fm.lineSpacing() + STATE_MARGIN);
} else {
DiagramProxyWidget::setClientRect(rect().adjusted(STATE_MARGIN, fontHeight + STATE_MARGIN, - STATE_MARGIN, -STATE_MARGIN));
DiagramProxyWidget::paint(painter, option, widget);
QSizeF size = DiagramProxyWidget::sceneRect().size();
m_size = QSizeF(qMax<qreal>(fm.horizontalAdvance(linkedDiagram()->name()), size.width()) + STATE_MARGIN * 2, fm.lineSpacing() + STATE_MARGIN + size.height());
setSize(m_size);
}
setPenFromSettings(painter);
}
break;
default:
logWarn1("StateWidget::paint: Unknown state type %1", stateTypeStr());
break;
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget
*/
QSizeF StateWidget::minimumSize() const
{
int width = 15, height = 15;
switch (m_stateType) {
case StateWidget::Normal:
{
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
int textWidth = fm.horizontalAdvance(name());
const int count = m_Activities.count();
height = fontHeight;
if(count > 0) {
height = fontHeight * (count + 1);
QStringList::ConstIterator end(m_Activities.end());
for(QStringList::ConstIterator it(m_Activities.begin()); it != end; ++it) {
int w = fm.horizontalAdvance(*it);
if(w > textWidth)
textWidth = w;
}//end for
}//end if
width = textWidth > STATE_WIDTH?textWidth:STATE_WIDTH;
height = height > STATE_HEIGHT?height:STATE_HEIGHT;
width += STATE_MARGIN * 2;
height += STATE_MARGIN * 2;
break;
}
case StateWidget::Fork:
case StateWidget::Join:
if (m_drawVertical) {
width = 8;
height = 60;
} else {
width = 60;
height = 8;
}
break;
case StateWidget::Junction:
width = 18;
height = 18;
break;
case StateWidget::DeepHistory:
case StateWidget::ShallowHistory:
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
width = height = fm.lineSpacing();
}
break;
case StateWidget::Choice:
width = 25;
height = 25;
break;
case StateWidget::Combined:
return m_size;
default:
break;
}
return QSizeF(width, height);
}
/**
* Overrides method from UMLWidget
*/
QSizeF StateWidget::maximumSize()
{
switch (m_stateType) {
case StateWidget::Initial:
case StateWidget::End:
case StateWidget::Junction:
case StateWidget::Choice:
return QSizeF(35, 35);
break;
case StateWidget::DeepHistory:
case StateWidget::ShallowHistory:
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
return QSizeF(fontHeight + 10, fontHeight + 10);
}
break;
case StateWidget::Combined:
return m_size;
default:
break;
}
return UMLWidget::maximumSize();
}
/**
* Set the aspect ratio mode.
* Some state types have a fixed aspect ratio
*/
void StateWidget::setAspectRatioMode()
{
switch (m_stateType) {
case StateWidget::Initial:
case StateWidget::End:
case StateWidget::Choice:
case StateWidget::DeepHistory:
case StateWidget::ShallowHistory:
case StateWidget::Fork:
case StateWidget::Join:
case StateWidget::Junction:
setFixedAspectRatio(true);
break;
default:
setFixedAspectRatio(false);
break;
}
}
void StateWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
{
#ifdef ENABLE_COMBINED_STATE_DIRECT_EDIT
if (m_stateType == Combined)
DiagramProxyWidget::contextMenuEvent(event);
if (event->isAccepted())
#endif
UMLWidget::contextMenuEvent(event);
}
void StateWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
#ifdef ENABLE_COMBINED_STATE_DIRECT_EDIT
if (m_stateType == Combined)
DiagramProxyWidget::mouseDoubleClickEvent(event);
if (event->isAccepted())
#endif
UMLWidget::mouseDoubleClickEvent(event);
}
void StateWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
#ifdef ENABLE_COMBINED_STATE_DIRECT_EDIT
if (m_stateType == Combined)
DiagramProxyWidget::mousePressEvent(event);
if (event->isAccepted())
#endif
UMLWidget::mousePressEvent(event);
}
void StateWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
#ifdef ENABLE_COMBINED_STATE_DIRECT_EDIT
if (m_stateType == Combined)
DiagramProxyWidget::mouseMoveEvent(event);
if (event->isAccepted())
#endif
UMLWidget::mouseMoveEvent(event);
}
void StateWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
#ifdef ENABLE_COMBINED_STATE_DIRECT_EDIT
if (m_stateType == Combined)
DiagramProxyWidget::mouseReleaseEvent(event);
if (event->isAccepted())
#endif
UMLWidget::mouseReleaseEvent(event);
}
/**
* Returns the type of state.
* @return StateType
*/
StateWidget::StateType StateWidget::stateType() const
{
return m_stateType;
}
/**
* Returns the type string of state.
*/
QString StateWidget::stateTypeStr() const
{
return QLatin1String(ENUM_NAME(StateWidget, StateType, m_stateType));
}
/**
* Sets the type of state.
*/
void StateWidget::setStateType(StateType stateType)
{
m_stateType = stateType;
setAspectRatioMode();
if (stateType == Combined) {
setAutoResize(false);
setResizable(false);
}
}
/**
* Adds an activity to this widget.
* @return true on success
*/
bool StateWidget::addActivity(const QString &activity)
{
m_Activities.append(activity);
updateGeometry();
return true;
}
/**
* Removes the given activity from the state.
*/
bool StateWidget::removeActivity(const QString &activity)
{
if(m_Activities.removeAll(activity) == 0)
return false;
updateGeometry();
return true;
}
/**
* Renames the given activity.
*/
bool StateWidget::renameActivity(const QString &activity, const QString &newName)
{
int index = - 1;
if((index = m_Activities.indexOf(activity)) == -1)
return false;
m_Activities[ index ] = newName;
return true;
}
/**
* Sets the states activities to the ones given.
*/
void StateWidget::setActivities(const QStringList &list)
{
m_Activities = list;
updateGeometry();
}
/**
* Returns the list of activities.
*/
QStringList StateWidget::activities() const
{
return m_Activities;
}
/**
* Get whether to draw a fork or join vertically.
*/
bool StateWidget::drawVertical() const
{
return m_drawVertical;
}
/**
* Set whether to draw a fork or join vertically.
*/
void StateWidget::setDrawVertical(bool to)
{
m_drawVertical = to;
setSize(height(), width());
updateGeometry();
UMLWidget::adjustAssocs(x(), y());
}
/**
* Show a properties dialog for a StateWidget.
*/
bool StateWidget::showPropertiesDialog()
{
bool result = false;
UMLApp::app()->docWindow()->updateDocumentation(false);
QPointer<StateDialog> dialog = new StateDialog(m_scene->activeView(), this);
if (dialog->exec() && dialog->getChangesMade()) {
UMLApp::app()->docWindow()->showDocumentation(this, true);
UMLApp::app()->document()->setModified(true);
result = true;
}
delete dialog;
return result;
}
/**
* Creates the "statewidget" XMI element.
*/
void StateWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("statewidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("statename"), m_Text);
writer.writeAttribute(QStringLiteral("documentation"), m_Doc);
writer.writeAttribute(QStringLiteral("statetype"), QString::number(m_stateType));
if (m_stateType == Fork || m_stateType == Join)
writer.writeAttribute(QStringLiteral("drawvertical"), QString::number(m_drawVertical));
//save states activities
writer.writeStartElement(QStringLiteral("Activities"));
QStringList::Iterator end(m_Activities.end());
for (QStringList::Iterator it(m_Activities.begin()); it != end; ++it) {
writer.writeStartElement(QStringLiteral("Activity"));
writer.writeAttribute(QStringLiteral("name"), *it);
writer.writeEndElement();
}
writer.writeEndElement(); // Activities
writer.writeEndElement(); // statewidget
}
/**
* Loads a "statewidget" XMI element.
*/
bool StateWidget::loadFromXMI(QDomElement & qElement)
{
if(!UMLWidget::loadFromXMI(qElement))
return false;
m_Text = qElement.attribute(QStringLiteral("statename"));
m_Doc = qElement.attribute(QStringLiteral("documentation"));
QString type = qElement.attribute(QStringLiteral("statetype"), QStringLiteral("1"));
setStateType((StateType)type.toInt());
setAspectRatioMode();
QString drawVertical = qElement.attribute(QStringLiteral("drawvertical"), QStringLiteral("1"));
m_drawVertical = (bool)drawVertical.toInt();
//load states activities
QDomNode node = qElement.firstChild();
QDomElement tempElement = node.toElement();
if(!tempElement.isNull() && tempElement.tagName() == QStringLiteral("Activities")) {
QDomNode node = tempElement.firstChild();
QDomElement activityElement = node.toElement();
while(!activityElement.isNull()) {
if(activityElement.tagName() == QStringLiteral("Activity")) {
QString name = activityElement.attribute(QStringLiteral("name"));
if(!name.isEmpty())
m_Activities.append(name);
}//end if
node = node.nextSibling();
activityElement = node.toElement();
}//end while
}//end if
return true;
}
/**
* Captures any popup menu signals for menus it created.
*/
void StateWidget::slotMenuSelection(QAction* action)
{
bool ok = false;
QString nameNew = name();
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
nameNew = name();
ok = Dialog_Utils::askNewName(WidgetBase::WidgetType::wt_State, nameNew);
if (ok && nameNew.length() > 0) {
setName(nameNew);
}
break;
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
case ListPopupMenu::mt_New_Activity:
nameNew = i18n("new activity");
ok = Dialog_Utils::askName(i18n("Enter Activity"),
i18n("Enter the name of the new activity:"),
nameNew);
if (ok && nameNew.length() > 0) {
addActivity(nameNew);
}
break;
case ListPopupMenu::mt_FlipHorizontal:
setDrawVertical(false);
break;
case ListPopupMenu::mt_FlipVertical:
setDrawVertical(true);
break;
default:
DiagramProxyWidget::slotMenuSelection(action);
break;
}
}
| 18,717
|
C++
|
.cpp
| 562
| 25.539146
| 174
| 0.60847
|
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,403
|
widgetlist_utils.cpp
|
KDE_umbrello/umbrello/umlwidgets/widgetlist_utils.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2009-2014 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "widgetlist_utils.h"
// app includes
#include "debug_utils.h"
#include "umlwidget.h"
// qt/kde includes
#include <QVector>
namespace WidgetList_Utils
{
/**
* Looks for the smallest x-value of the given UMLWidgets.
* @param widgetList A list with UMLWidgets.
* @return The smallest X position.
*/
qreal getSmallestX(const UMLWidgetList &widgetList)
{
qreal smallestX = 0;
int i = 1;
for(UMLWidget *widget : widgetList) {
if (i == 1) {
smallestX = widget->x();
} else {
if (smallestX > widget->x())
smallestX = widget->x();
}
i++;
}
return smallestX;
}
/**
* Looks for the smallest y-value of the given UMLWidgets.
* @param widgetList A list with UMLWidgets.
* @return The smallest Y position.
*/
qreal getSmallestY(const UMLWidgetList &widgetList)
{
if (widgetList.isEmpty())
return -1;
qreal smallestY = 0;
int i = 1;
for(UMLWidget *widget : widgetList) {
if (i == 1) {
smallestY = widget->y();
} else {
if (smallestY > widget->y())
smallestY = widget->y();
}
i++;
}
return smallestY;
}
/**
* Looks for the biggest x-value of the given UMLWidgets.
* @param widgetList A list with UMLWidgets.
* @return The biggest X position.
*/
qreal getBiggestX(const UMLWidgetList &widgetList)
{
if (widgetList.isEmpty())
return -1;
qreal biggestX = 0;
int i = 1;
for(UMLWidget *widget : widgetList) {
if (i == 1) {
biggestX = widget->x();
biggestX += widget->width();
} else {
if (biggestX < widget->x() + widget->width())
biggestX = widget->x() + widget->width();
}
i++;
}
return biggestX;
}
/**
* Looks for the biggest y-value of the given UMLWidgets.
* @param widgetList A list with UMLWidgets.
* @return The biggest Y position.
*/
qreal getBiggestY(const UMLWidgetList &widgetList)
{
if (widgetList.isEmpty())
return -1;
qreal biggestY = 0;
int i = 1;
for(UMLWidget *widget : widgetList) {
if (i == 1) {
biggestY = widget->y();
biggestY += widget->height();
} else {
if (biggestY < widget->y() + widget->height())
biggestY = widget->y() + widget->height();
}
i++;
}
return biggestY;
}
/**
* Returns the sum of the heights of the given UMLWidgets
* @param widgetList A list with UMLWidgets.
*/
qreal getHeightsSum(const UMLWidgetList &widgetList)
{
qreal heightsSum = 0;
for(UMLWidget *widget : widgetList) {
heightsSum += widget->height();
}
return heightsSum;
}
/**
* Returns the sum of the widths of the given UMLWidgets.
* @param widgetList A list with UMLWidgets.
*/
qreal getWidthsSum(const UMLWidgetList &widgetList)
{
qreal widthsSum = 0;
for(UMLWidget *widget : widgetList) {
widthsSum += widget->width();
}
return widthsSum;
}
} // namespace WidgetList_Utils
| 3,252
|
C++
|
.cpp
| 126
| 20.587302
| 92
| 0.613871
|
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,404
|
interfacewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/interfacewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2019-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "interfacewidget.h"
#include "classifier.h"
#include "debug_utils.h"
DEBUG_REGISTER_DISABLED(InterfaceWidget)
InterfaceWidget::InterfaceWidget(UMLScene *scene, UMLClassifier *c)
: ClassifierWidget(scene, c)
{
}
InterfaceWidget::InterfaceWidget(UMLScene *scene, UMLPackage *p)
: ClassifierWidget(scene, p)
{
}
| 475
|
C++
|
.cpp
| 16
| 27.4375
| 92
| 0.791574
|
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,405
|
layoutgrid.cpp
|
KDE_umbrello/umbrello/umlwidgets/layoutgrid.cpp
|
/*
SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-FileCopyrightText: 2012 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "layoutgrid.h"
#define DBG_SRC QStringLiteral("LayoutGrid")
#include "debug_utils.h"
#include "umlscene.h"
#include "uml.h"
#include <QPainter>
#include <QVarLengthArray>
DEBUG_REGISTER_DISABLED(LayoutGrid)
/**
* Constructor.
*/
LayoutGrid::LayoutGrid(UMLScene *scene)
: m_scene(scene),
m_gridSpacingX(25),
m_gridSpacingY(25),
m_gridDotColor(Qt::gray),
m_isVisible(false)
{
}
/**
* Destructor.
*/
LayoutGrid::~LayoutGrid()
{
}
void LayoutGrid::paint(QPainter *painter, const QRectF &rect)
{
if (!isVisible())
return;
int gridSizeX = gridSpacingX();
int gridSizeY = gridSpacingY();
qreal left = int(rect.left()) - (int(rect.left()) % gridSizeX);
qreal top = int(rect.top()) - (int(rect.top()) % gridSizeY);
QVarLengthArray<QLineF, 200> lines;
for (qreal x = left; x < rect.right(); x += gridSizeX)
lines.append(QLineF(x, rect.top(), x, rect.bottom()));
for (qreal y = top; y < rect.bottom(); y += gridSizeY)
lines.append(QLineF(rect.left(), y, rect.right(), y));
painter->setPen(m_gridDotColor);
painter->drawLines(lines.data(), lines.size());
}
int LayoutGrid::gridSpacingX() const
{
return m_gridSpacingX;
}
int LayoutGrid::gridSpacingY() const
{
return m_gridSpacingY;
}
void LayoutGrid::setGridSpacing(int sizeX, int sizeY)
{
logDebug2("LayoutGrid::setGridSpacing: x = %1 / y = %2", sizeX, sizeY);
m_gridSpacingX= sizeX;
m_gridSpacingY= sizeY;
}
const QColor& LayoutGrid::gridDotColor() const
{
return m_gridDotColor;
}
void LayoutGrid::setGridDotColor(const QColor& color)
{
logDebug1("LayoutGrid::setGridColor: color = %1", color.name());
m_gridDotColor = color;
}
bool LayoutGrid::isVisible() const
{
return m_isVisible;
}
void LayoutGrid::setVisible(bool visible)
{
if (m_isVisible != visible) {
logDebug1("LayoutGrid::setVisible: visible = %1", visible);
m_isVisible = visible;
m_scene->update();
}
}
| 2,190
|
C++
|
.cpp
| 81
| 23.740741
| 75
| 0.690761
|
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,406
|
childwidgetplacementport.cpp
|
KDE_umbrello/umbrello/umlwidgets/childwidgetplacementport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlwidgets/childwidgetplacementport.h"
#include "umlwidgets/umlwidget.h"
#include "pinportbase.h"
ChildWidgetPlacementPort::ChildWidgetPlacementPort(PinPortBase* widget)
: ChildWidgetPlacement(widget)
{
}
ChildWidgetPlacementPort::~ChildWidgetPlacementPort()
{
}
void ChildWidgetPlacementPort::setInitialPosition(const QPointF &scenePos)
{
#if 0
QPointF p = ownerWidget()->mapFromScene(scenePos);
p -= QPointF(width()/2, height()/2);
setPos(p);
#else
if (ownerWidget()) {
QPointF p = ownerWidget()->mapFromScene(scenePos);
p -= QPointF(width()/2, height()/2);
setPos(p);
detectConnectedSide();
setNewPositionWhenMoved(0.0, 0.0);
//setNewPositionOnParentResize();
} else {
m_connectedSide = TopLeft;
setPos(minX(), minY());
}
#endif
}
void ChildWidgetPlacementPort::setNewPositionWhenMoved(qreal diffX, qreal diffY)
{
bool setXToMin = false, setXToMax = false;
qreal newX = trimToRange(x() + diffX, minX(), maxX(), setXToMin, setXToMax);
bool setYToMin = false, setYToMax = false;
qreal newY = trimToRange(y() + diffY, minY(), maxY(), setYToMin, setYToMax);
switch (m_connectedSide)
{
case Top:
{
if (setXToMin) {
m_connectedSide = TopLeft;
}
else if (setXToMax) {
m_connectedSide = TopRight;
}
else {
newY = minY();
}
}
break;
case Bottom:
{
if (setXToMin) {
m_connectedSide = BottomLeft;
}
else if (setXToMax) {
m_connectedSide = BottomRight;
}
else {
newY = maxY();
}
}
break;
case Left:
{
if (setYToMin) {
m_connectedSide = TopLeft;
}
else if (setYToMax) {
m_connectedSide = BottomLeft;
}
else {
newX = minX();
}
}
break;
case Right:
{
if (setYToMin) {
m_connectedSide = TopRight;
}
else if (setYToMax) {
m_connectedSide = BottomRight;
}
else {
newX = maxX();
}
}
break;
case TopLeft:
{
if (newX > minX()) {
m_connectedSide = Top;
newY = minY();
}
else if (newY > minY()) {
m_connectedSide = Left;
newX = minX();
}
}
break;
case TopRight:
{
if (newX < maxX()) {
m_connectedSide = Top;
newY = minY();
}
else if (newY > minY()) {
m_connectedSide = Right;
newX = maxX();
}
}
break;
case BottomRight:
{
if (newX < maxX()) {
m_connectedSide = Bottom;
newY = maxY();
}
else if (newY < maxY()) {
m_connectedSide = Right;
newX = maxX();
}
}
break;
case BottomLeft:
{
if (newX > minX()) {
m_connectedSide = Bottom;
newY = maxY();
}
else if (newY < maxY()) {
m_connectedSide = Left;
newX = minX();
}
}
break;
default:
break;
}
setPos(newX, newY);
}
void ChildWidgetPlacementPort::detectConnectedSide()
{
if (m_widget->x() < 0) {
if (m_widget->y() < 0)
m_connectedSide = TopLeft;
else if (m_widget->y() < maxY())
m_connectedSide = Left;
else
m_connectedSide = BottomLeft;
} else if (m_widget->x() < maxX()) {
if (m_widget->y() < 0)
m_connectedSide = Top;
else if (m_widget->y() < maxY())
m_connectedSide = Undefined;
else
m_connectedSide = Bottom;
} else if (m_widget->x() >= maxX()) {
if (m_widget->y() < 0)
m_connectedSide = TopRight;
else if (m_widget->y() < maxY())
m_connectedSide = Right;
else
m_connectedSide = BottomRight;
} else {
m_connectedSide = TopLeft;
}
}
void ChildWidgetPlacementPort::setNewPositionOnParentResize()
{
switch (m_connectedSide)
{
case Right:
{
setPos(maxX(), qMin(y(), maxY()));
}
break;
case Bottom:
{
setPos(qMin(x(), maxX()), maxY());
}
break;
case TopRight:
{
setPos(maxX(), minY());
}
break;
case BottomRight:
{
setPos(maxX(), maxY());
}
break;
case BottomLeft:
{
setPos(minX(), maxY());
}
break;
default:
; // nothing to do
}
}
/**
* Returns value bound between min and max, and flags whether value has been set.
*/
qreal ChildWidgetPlacementPort::trimToRange(qreal value, qreal min, qreal max, bool& setToMin, bool& setToMax) const
{
if (value < min) {
setToMin = true;
return min;
}
else if (value > max) {
setToMax = true;
return max;
}
return value;
}
/**
* Returns minimum allowed x value.
*/
qreal ChildWidgetPlacementPort::minX() const
{
return - width() / 2;
}
/**
* Returns maximum allowed x value.
*/
qreal ChildWidgetPlacementPort::maxX() const
{
UMLWidget* owner = ownerWidget();
return owner->width() - width() / 2;
}
/**
* Returns minimum allowed y value.
*/
qreal ChildWidgetPlacementPort::minY() const
{
return - height() / 2;
}
/**
* Returns maximum allowed y value.
*/
qreal ChildWidgetPlacementPort::maxY() const
{
UMLWidget* owner = ownerWidget();
return owner->height() - height() / 2;
}
| 6,291
|
C++
|
.cpp
| 252
| 16.404762
| 116
| 0.500749
|
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,407
|
widget_utils.cpp
|
KDE_umbrello/umbrello/umlwidgets/widget_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 "widget_utils.h"
// app includes
#define DBG_SRC QStringLiteral("Widget_Utils")
#include "debug_utils.h"
#include "objectwidget.h"
#include "messagewidget.h"
#include "umlwidget.h"
#include "uml.h" // only needed for log{Warn,Error}
#include <KLocalizedString>
// qt includes
#include <QBuffer>
#include <QImageReader>
#include <QGraphicsItem>
#include <QGraphicsRectItem>
#include <QPolygonF>
#include <QXmlStreamWriter>
// c++ include
#include <cmath>
DEBUG_REGISTER(Widget_Utils)
namespace Widget_Utils
{
/**
* Find the widget identified by the given ID in the given widget
* or message list.
*
* @param id The unique ID to find.
* @param widgets The UMLWidgetList to search in.
* @param messages Optional pointer to a MessageWidgetList to search in.
*/
UMLWidget* findWidget(Uml::ID::Type id,
const UMLWidgetList& widgets,
const MessageWidgetList *messages /* = nullptr */)
{
for(UMLWidget *obj : widgets) {
if (obj->isObjectWidget()) {
if (obj->localID() == id)
return obj;
} else if (obj->id() == id) {
return obj;
}
}
if (messages) {
for(UMLWidget *obj : *messages) {
if (obj->id() == id)
return obj;
}
}
return nullptr;
}
/**
* Creates the decoration point.
* @param p base point to decorate
* @param parent parent item
* @return decoration point
*/
QGraphicsRectItem* decoratePoint(const QPointF &p, QGraphicsItem* parent)
{
const qreal SIZE = 4.0;
const qreal SIZE_HALF = SIZE / 2.0;
QGraphicsRectItem *rect = new QGraphicsRectItem(p.x() - SIZE_HALF,
p.y() - SIZE_HALF,
SIZE, SIZE,
parent);
rect->setBrush(QBrush(Qt::blue));
rect->setPen(QPen(Qt::blue));
return rect;
}
/**
* Calculates and draws a cross inside an ellipse
* @param p Pointer to a QPainter object.
* @param r The rectangle describing the ellipse.
*/
void drawCrossInEllipse(QPainter *p, const QRectF& r)
{
QRectF ellipse = r;
ellipse.moveCenter(QPointF(0, 0));
qreal a = ellipse.width() * 0.5;
qreal b = ellipse.height() * .5;
qreal xc = ellipse.center().x();
qreal yc = ellipse.center().y();
// The first point's x value is chosen to be center.x() + 70% of x radius.
qreal x1 = ellipse.center().x() + .7 * .5 * ellipse.width();
// Calculate y1 corresponding to x1 using formula.
qreal y1_sqr = b*b*(1 - (x1 * x1) / (a*a));
qreal y1 = std::sqrt(y1_sqr);
// Mirror x1, y1 along both the axes to get 4 points for the cross.
QPointF p1(xc + x1, yc + y1);
QPointF p2(xc - x1, yc + y1);
QPointF p3(xc + x1, yc - y1);
QPointF p4(xc - x1, yc - y1);
// Translate as we calculate for ellipse with (0, 0) as center.
p->translate(r.center().x(), r.center().y());
// Draw the cross now
p->drawLine(QLineF(p1, p4));
p->drawLine(QLineF(p2, p3));
// Restore the translate on painter.
p->translate(-r.center().x(), -r.center().y());
}
/**
* Draws a polygon which is almost rectangular except for the top
* right corner. A triangle is drawn in top right corner of the
* rectangle.
*
* @param painter The painter with which this shape is to be drawn.
* @param rect The rectangle dimensions.
* @param triSize The size of the triangle in the top-right corner.
*/
void drawTriangledRect(QPainter *painter,
const QRectF &rect, const QSizeF &triSize)
{
// Draw outer boundary defined by polygon "poly".
QPolygonF poly(5);
poly[0] = rect.topLeft();
poly[1] = rect.topRight() - QPointF(triSize.width(), 0);
poly[2] = rect.topRight() + QPointF(0, triSize.height());
poly[3] = rect.bottomRight();
poly[4] = rect.bottomLeft();
painter->drawPolygon(poly);
// Now draw the triangle base and height edges.
QLineF heightEdge(poly[1], poly[1] + QPointF(0, triSize.height()));
painter->drawLine(heightEdge);
QLineF baseEdge(heightEdge.p2(), poly[2]);
painter->drawLine(baseEdge);
}
// /**
// * Draws an arrow head with the given painter, with the arrow
// * sharp point at \a headPos.
// *
// * param painter The painter with which this arrow should be drawn.
// * param headPos The position where the head of the arrow should lie.
// * param arrowSize This indicates the size of the arrow head.
// * param arrowType This indicates direction of arrow as in LeftArrow, RightArrow..
// * param solid If true, a solid head is drawn. Otherwise 2 lines are drawn.
// */
// void drawArrowHead(QPainter *painter, const QPointF &arrowPos,
// const QSizeF& arrowSize, Qt::ArrowType arrowType,
// bool solid)
// {
// QPolygonF poly;
// if (arrowType == Qt::LeftArrow) {
// poly << QPointF(arrowPos.x() + arrowSize.width(), arrowPos.y() - .5 * arrowSize.height())
// << arrowPos
// << QPointF(arrowPos.x() + arrowSize.width(), arrowPos.y() + .5 * arrowSize.height());
// }
// else if (arrowType == Qt::RightArrow) {
// poly << QPointF(arrowPos.x() - arrowSize.width(), arrowPos.y() - .5 * arrowSize.height())
// << arrowPos
// << QPointF(arrowPos.x() - arrowSize.width(), arrowPos.y() + .5 * arrowSize.height());
// }
// if (solid) {
// painter->drawPolygon(poly);
// }
// else {
// painter->drawPolyline(poly);
// }
// }
// /**
// * Draws a rounded rect rounded at specified corners.
// *
// * param painter The painter with which this round rect should be drawn.
// * param rect The rectangle to be drawn.
// * param xRadius The x radius of rounded corner.
// * param yRadius The y radius of rounded corner.
// * param corners The corners to be rounded.
// */
// void drawRoundedRect(QPainter *painter, const QRectF& rect, qreal xRadius,
// qreal yRadius, Uml::Corners corners)
// {
// if (xRadius < 0 || yRadius < 0) {
// painter->drawRect(rect);
// return;
// }
// QRectF arcRect(0, 0, 2 * xRadius, 2 * yRadius);
// QPainterPath path;
// path.moveTo(rect.left(), rect.top() + yRadius);
// if (corners.testFlag(Uml::Corner::TopLeft)) {
// arcRect.moveTopLeft(rect.topLeft());
// path.arcTo(arcRect, 180, -90);
// } else {
// path.lineTo(rect.topLeft());
// }
// path.lineTo(rect.right() - xRadius, rect.top());
// if (corners.testFlag(Uml::Corner::TopRight)) {
// arcRect.moveTopRight(rect.topRight());
// path.arcTo(arcRect, 90, -90);
// } else {
// path.lineTo(rect.topRight());
// }
// path.lineTo(rect.right(), rect.bottom() - yRadius);
// if (corners.testFlag(Uml::Corner::BottomRight)) {
// arcRect.moveBottomRight(rect.bottomRight());
// path.arcTo(arcRect, 0, -90);
// } else {
// path.lineTo(rect.bottomRight());
// }
// path.lineTo(rect.left() + xRadius, rect.bottom());
// if (corners.testFlag(Uml::Corner::BottomLeft)) {
// arcRect.moveBottomLeft(rect.bottomLeft());
// path.arcTo(arcRect, 270, 90);
// } else {
// path.lineTo(rect.bottomLeft());
// }
// path.closeSubpath();
// painter->drawPath(path);
// }
/**
* Converts a point to a comma separated string i.e "x,y"
* @param point The QPointF to convert.
*/
QString pointToString(const QPointF& point)
{
return QString::fromLatin1("%1,%2").arg(point.x()).arg(point.y());
}
/**
* Converts a comma separated string to point.
*/
QPointF stringToPoint(const QString& str)
{
QPointF retVal;
QStringList list = str.split(QLatin1Char(','));
if(list.size() == 2) {
retVal.setX(list.first().toDouble());
retVal.setY(list.last().toDouble());
}
return retVal;
}
/**
* Loads pixmap from xmi.
*
* @param pixEle The dom element from which pixmap should be loaded.
*
* @param pixmap The pixmap into which the image should be loaded.
*
* @return True or false based on success or failure of this method.
*/
bool loadPixmapFromXMI(QDomElement &pixEle, QPixmap &pixmap)
{
if (pixEle.isNull()) {
return false;
}
QDomElement xpmElement = pixEle.firstChildElement(QStringLiteral("xpm"));
QByteArray xpmData = xpmElement.text().toLatin1();
QBuffer buffer(&xpmData);
buffer.open(QIODevice::ReadOnly);
QImageReader reader(&buffer, "xpm");
QImage image;
if (!reader.read(&image)) {
return false;
}
pixmap = QPixmap::fromImage(image);
return true;
}
/**
* Saves pixmap information to XMI.
*
* @param stream The QXmlStreamWriter object to write to.
* @param pixmap The pixmap to be saved.
*/
void savePixmapToXMI(QXmlStreamWriter& stream, const QPixmap& pixmap)
{
stream.writeStartElement(QStringLiteral("pixmap"));
stream.writeStartElement(QStringLiteral("xpm"));
stream.writeEndElement();
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
pixmap.save(&buffer, "xpm");
buffer.close();
stream.writeTextElement(QString(), QString::fromLatin1(buffer.data()));
stream.writeEndElement();
}
/**
* Loads gradient from xmi. The gradient pointer should be null
* and the new gradient object will be created inside this method.
* The gradient should later be deleted externally.
*
* @param gradientElement The DOM element from which gradient should be
* loaded.
*
* @param gradient The pointer to gradient into which the gradient
* should be loaded. (Allocated inside this
* method)
*
* @return True or false based on success or failure of this method.
*/
bool loadGradientFromXMI(QDomElement &gradientElement, QGradient *&gradient)
{
if(gradientElement.isNull()) {
return false;
}
int type_as_int;
QGradient::Type type;
QGradientStops stops;
QGradient::CoordinateMode cmode = QGradient::LogicalMode;
QGradient::Spread spread = QGradient::PadSpread;
type_as_int = gradientElement.attribute(QStringLiteral("type")).toInt();
type = QGradient::Type(type_as_int);
type_as_int = gradientElement.attribute(QStringLiteral("spread")).toInt();
spread = QGradient::Spread(type_as_int);
type_as_int = gradientElement.attribute(QStringLiteral("coordinatemode")).toInt();
cmode = QGradient::CoordinateMode(type_as_int);
QDomElement stopElement = gradientElement.firstChildElement(QStringLiteral("stops"));
if(stopElement.isNull()) {
return false;
}
for(QDomNode node = stopElement.firstChild(); !node.isNull(); node = node.nextSibling()) {
QDomElement ele = node.toElement();
if(ele.tagName() != QStringLiteral("stop")) {
continue;
}
qreal posn = ele.attribute(QStringLiteral("position")).toDouble();
QColor color = QColor(ele.attribute(QStringLiteral("color")));
stops << QGradientStop(posn, color);
}
if (type == QGradient::LinearGradient) {
QPointF p1 = stringToPoint(gradientElement.attribute(QStringLiteral("start")));
QPointF p2 = stringToPoint(gradientElement.attribute(QStringLiteral("finalstop")));
gradient = new QLinearGradient(p1, p2);
}
else if (type == QGradient::RadialGradient) {
QPointF center = stringToPoint(gradientElement.attribute(QStringLiteral("center")));
QPointF focal = stringToPoint(gradientElement.attribute(QStringLiteral("focalpoint")));
double radius = gradientElement.attribute(QStringLiteral("radius")).toDouble();
gradient = new QRadialGradient(center, radius, focal);
}
else { // type == QGradient::ConicalGradient
QPointF center = stringToPoint(gradientElement.attribute(QStringLiteral("center")));
double angle = gradientElement.attribute(QStringLiteral("angle")).toDouble();
gradient = new QConicalGradient(center, angle);
}
if(gradient) {
gradient->setStops(stops);
gradient->setSpread(spread);
gradient->setCoordinateMode(cmode);
return true;
}
return false;
}
/**
* Saves gradient information to XMI.
*
* @param stream The QXmlStreamWriter object to write to.
* @param gradient The gradient to be saved.
*/
void saveGradientToXMI(QXmlStreamWriter& stream, const QGradient *gradient)
{
stream.writeStartElement(QStringLiteral("gradient"));
stream.writeAttribute(QStringLiteral("type"), QString::number(gradient->type()));
stream.writeAttribute(QStringLiteral("spread"), QString::number(gradient->spread()));
stream.writeAttribute(QStringLiteral("coordinatemode"), QString::number(gradient->coordinateMode()));
QGradient::Type type = gradient->type();
if(type == QGradient::LinearGradient) {
const QLinearGradient *lg = static_cast<const QLinearGradient*>(gradient);
stream.writeAttribute(QStringLiteral("start"), pointToString(lg->start()));
stream.writeAttribute(QStringLiteral("finalstop"), pointToString(lg->finalStop()));
}
else if(type == QGradient::RadialGradient) {
const QRadialGradient *rg = static_cast<const QRadialGradient*>(gradient);
stream.writeAttribute(QStringLiteral("center"), pointToString(rg->center()));
stream.writeAttribute(QStringLiteral("focalpoint"), pointToString(rg->focalPoint()));
stream.writeAttribute(QStringLiteral("radius"), QString::number(rg->radius()));
}
else { //type == QGradient::ConicalGradient
const QConicalGradient *cg = static_cast<const QConicalGradient*>(gradient);
stream.writeAttribute(QStringLiteral("center"), pointToString(cg->center()));
stream.writeAttribute(QStringLiteral("angle"), QString::number(cg->angle()));
}
stream.writeStartElement(QStringLiteral("stops"));
for(const QGradientStop& stop : gradient->stops()) {
stream.writeStartElement(QStringLiteral("stop"));
stream.writeAttribute(QStringLiteral("position"), QString::number(stop.first));
stream.writeAttribute(QStringLiteral("color"), stop.second.name());
stream.writeEndElement();
}
stream.writeEndElement(); // stops
stream.writeEndElement(); // gradient
}
/**
* Extracts the QBrush properties into brush from the XMI xml
* element qElement.
*
* @param qElement The DOM element from which the xmi info should
* be extracted.
*
* @param brush The QBrush object into which brush details should
* be read into.
*/
bool loadBrushFromXMI(QDomElement &qElement, QBrush &brush)
{
if(qElement.isNull()) {
return false;
}
quint8 style = qElement.attribute(QStringLiteral("style")).toShort();
const QString colorString = qElement.attribute(QStringLiteral("color"));
QColor color;
color.setNamedColor(colorString);
if(style == Qt::TexturePattern) {
QPixmap pixmap;
QDomElement pixElement = qElement.firstChildElement(QStringLiteral("pixmap"));
if(!loadPixmapFromXMI(pixElement, pixmap)) {
return false;
}
brush = QBrush(color, pixmap);
}
else if(style == Qt::LinearGradientPattern
|| style == Qt::RadialGradientPattern
|| style == Qt::ConicalGradientPattern) {
QGradient *gradient = nullptr;
QDomElement gradElement = qElement.firstChildElement(QStringLiteral("gradient"));
if(!loadGradientFromXMI(gradElement, gradient) || !gradient) {
delete gradient;
return false;
}
brush = QBrush(*gradient);
delete gradient;
}
else {
brush = QBrush(color, (Qt::BrushStyle)style);
}
//TODO: Checks if transform needs to be loaded.
return true;
}
/**
* Saves the brush info as XMI.
*
* @param stream The QXmlStreamWriter object to write to.
* @param brush The QBrush whose details should be saved.
*/
void saveBrushToXMI(QXmlStreamWriter& stream, const QBrush& brush)
{
stream.writeStartElement(QStringLiteral("brush"));
stream.writeAttribute(QStringLiteral("style"), QString::number(brush.style()));
stream.writeAttribute(QStringLiteral("color"), brush.color().name());
if(brush.style() == Qt::TexturePattern) {
savePixmapToXMI(stream, brush.texture());
}
else if(brush.style() == Qt::LinearGradientPattern
|| brush.style() == Qt::RadialGradientPattern
|| brush.style() == Qt::ConicalGradientPattern) {
saveGradientToXMI(stream, brush.gradient());
}
//TODO: Check if transform of this brush needs to be saved.
stream.writeEndElement();
}
/**
* Returns true if the first widget's X is smaller than second's.
* Used for sorting the UMLWidgetList.
* @param widget1 The widget to compare.
* @param widget2 The widget to compare with.
*/
bool hasSmallerX(const UMLWidget* widget1, const UMLWidget* widget2)
{
return widget1->x() < widget2->x();
}
/**
* Returns true if the first widget's Y is smaller than second's.
* Used for sorting the UMLWidgetList.
* @param widget1 The widget to compare.
* @param widget2 The widget to compare with.
*/
bool hasSmallerY(const UMLWidget* widget1, const UMLWidget* widget2)
{
return widget1->y() < widget2->y();
}
/**
* Find the region in which the rectangle \a other lies with respect to
* the rectangle \a self.
* Beware that the Qt coordinate system has its origin point (0,0) in
* the upper left corner with Y values growing downwards, thus the Y
* related comparisons might look inverted if your are used to the
* natural coordinate system with (0,0) in the lower left corner.
*/
Uml::Region::Enum findRegion(const QRectF& self, const QRectF &other)
{
const qreal ownX = self.x();
const qreal ownY = self.y();
const qreal ownWidth = self.width();
const qreal ownHeight = self.height();
const qreal otherX = other.x();
const qreal otherY = other.y();
const qreal otherWidth = other.width();
const qreal otherHeight = other.height();
Uml::Region::Enum region = Uml::Region::Center;
if (otherX + otherWidth < ownX) {
if (otherY + otherHeight < ownY)
region = Uml::Region::NorthWest;
else if (otherY > ownY + ownHeight)
region = Uml::Region::SouthWest;
else
region = Uml::Region::West;
} else if (otherX > ownX + ownWidth) {
if (otherY + otherHeight < ownY)
region = Uml::Region::NorthEast;
else if (otherY > ownY + ownHeight)
region = Uml::Region::SouthEast;
else
region = Uml::Region::East;
} else {
if (otherY + otherHeight < ownY)
region = Uml::Region::North;
else if (otherY > ownY + ownHeight)
region = Uml::Region::South;
else
region = Uml::Region::Center;
}
return region;
}
/**
* Return the point in \a poly which precedes the point at index \a index.
* If \a index is 0 then return the last (or, if \a poly.isClosed() is
* true, the second to last) point.
*/
QPointF prevPoint(int index, const QPolygonF& poly) {
if (poly.size() < 3 || index >= poly.size())
return QPoint();
if (index == 0)
return poly.at(poly.size() - 1 - (int)poly.isClosed());
return poly.at(index - 1);
}
/**
* Return the point in \a poly which follows the point at index \a index.
* If \a index is the last index then return the first (or, if
* \a poly.isClosed() is true, the second) point.
*/
QPointF nextPoint(int index, const QPolygonF& poly) {
if (poly.size() < 3 || index >= poly.size())
return QPoint();
if (index == poly.size() - 1)
return poly.at((int)poly.isClosed());
return poly.at(index + 1);
}
/**
* Return the middle value between \a a and \a b.
*/
qreal middle(qreal a, qreal b)
{
return (a + b) / 2.0;
}
/**
* Auxiliary type for function findLine()
*/
enum Axis_Type { X , Y };
/**
* Auxiliary type for function findLine()
*/
enum Comparison_Type { Smallest, Largest };
/**
* Find the line of \a poly with the smallest or largest value (controlled by \a seek)
* along the axis controlled by \a axis.
* In case \a axis is X, do not consider lines whose Y values lie outside the Y values
* defined by \a boundingRect.
* In case \a axis is Y, do not consider lines whose X values lie outside the X values
* defined by \a boundingRect.
*/
QLineF findLine(const QPolygonF& poly, Axis_Type axis, Comparison_Type seek, const QRectF& boundingRect)
{
const int lastIndex = poly.size() - 1 - (int)poly.isClosed();
QPointF prev = poly.at(lastIndex), curr;
QPointF p1(seek == Smallest ? QPointF(1.0e6, 1.0e6) : QPointF(-1.0e6, -1.0e6));
QPointF p2;
for (int i = 0; i <= lastIndex; i++) {
curr = poly.at(i);
// uDebug() << " poly[" << i << "] = " << curr;
if (axis == X) {
if (fmin(prev.y(), curr.y()) > boundingRect.y() + boundingRect.height() ||
fmax(prev.y(), curr.y()) < boundingRect.y()) {
// line is outside Y-axis range defined by boundingRect
} else if ((seek == Smallest && curr.x() <= p1.x()) ||
(seek == Largest && curr.x() >= p1.x())) {
p1 = curr;
p2 = prev;
}
} else {
if (fmin(prev.x(), curr.x()) > boundingRect.x() + boundingRect.width() ||
fmax(prev.x(), curr.x()) < boundingRect.x()) {
// line is outside X-axis range defined by boundingRect
} else if ((seek == Smallest && curr.y() <= p1.y()) ||
(seek == Largest && curr.y() >= p1.y())) {
p1 = curr;
p2 = prev;
}
}
prev = curr;
}
return QLineF(p1, p2);
}
/**
* Determine the approximate closest points of two polygons.
* @param self First QPolygonF.
* @param other Second QPolygonF.
* @return QLineF::p1() returns point of \a self;
* QLineF::p2() returns point of \a other.
*/
QLineF closestPoints(const QPolygonF& self, const QPolygonF& other)
{
const QRectF& selfRect = self.boundingRect();
const QRectF& otherRect = other.boundingRect();
Uml::Region::Enum region = findRegion(selfRect, otherRect);
if (region == Uml::Region::Center)
return QLineF();
if (self.size() < 3 || other.size() < 3)
return QLineF();
QLineF result;
const int selfLastIndex = self.size() - 1 - (int)self.isClosed();
const int otherLastIndex = other.size() - 1 - (int)other.isClosed();
QPointF selfPoint(self.at(selfLastIndex));
QPointF otherPoint(other.at(otherLastIndex));
QLineF selfLine, otherLine;
int i;
switch (region) {
case Uml::Region::North:
// Find other's line with largest Y values
otherLine = findLine(other, Y, Largest, selfRect);
// Find own line with smallest Y values
selfLine = findLine(self, Y, Smallest, otherRect);
// Use the middle value of the X values
result.setLine(middle(selfLine.p2().x(), selfLine.p1().x()), selfLine.p1().y(),
middle(otherLine.p2().x(), otherLine.p1().x()), otherLine.p1().y());
break;
case Uml::Region::South:
// Find other's line with smallest Y values
otherLine = findLine(other, Y, Smallest, selfRect);
// Find own line with largest Y values
selfLine = findLine(self, Y, Largest, otherRect);
// Use the middle value of the X values
result.setLine(middle(selfLine.p2().x(), selfLine.p1().x()), selfLine.p1().y(),
middle(otherLine.p2().x(), otherLine.p1().x()), otherLine.p1().y());
break;
case Uml::Region::West:
// Find other's line with largest X values
otherLine = findLine(other, X, Largest, selfRect);
// Find own line with smallest X values
selfLine = findLine(self, X, Smallest, otherRect);
// Use the middle value of the Y values
result.setLine(selfLine.p1().x(), middle(selfLine.p2().y(), selfLine.p1().y()),
otherLine.p1().x(), middle(otherLine.p2().y(), otherLine.p1().y()));
break;
case Uml::Region::East:
// Find other's line with smallest X values
otherLine = findLine(other, X, Smallest, selfRect);
// Find own line with largest X values
selfLine = findLine(self, X, Largest, otherRect);
// Use the middle value of the Y values
result.setLine(selfLine.p1().x(), middle(selfLine.p2().y(), selfLine.p1().y()),
otherLine.p1().x(), middle(otherLine.p2().y(), otherLine.p1().y()));
break;
case Uml::Region::NorthWest:
// Find other's point with largest X and largest Y value
for (i = 0; i < otherLastIndex; ++i) {
QPointF current(other.at(i));
if (current.x() + current.y() >= otherPoint.x() + otherPoint.y()) {
otherPoint = current;
}
}
// Find own point with smallest X and smallest Y value
for (i = 0; i < selfLastIndex; ++i) {
QPointF current(self.at(i));
if (current.x() + current.y() <= selfPoint.x() + selfPoint.y()) {
selfPoint = current;
}
}
result.setPoints(selfPoint, otherPoint);
break;
case Uml::Region::SouthWest:
// Find other's point with largest X and smallest Y value
for (i = 0; i < otherLastIndex; ++i) {
QPointF current(other.at(i));
if (current.x() >= otherPoint.x() && current.y() <= otherPoint.y()) {
otherPoint = current;
}
}
// Find own point with smallest X and largest Y value
for (i = 0; i < selfLastIndex; ++i) {
QPointF current(self.at(i));
if (current.x() <= selfPoint.x() && current.y() >= selfPoint.y()) {
selfPoint = current;
}
}
result.setPoints(selfPoint, otherPoint);
break;
case Uml::Region::NorthEast:
// Find other's point with smallest X and largest Y value
for (i = 0; i < otherLastIndex; ++i) {
QPointF current(other.at(i));
if (current.x() <= otherPoint.x() && current.y() >= otherPoint.y()) {
otherPoint = current;
}
}
// Find own point with largest X and smallest Y value
for (i = 0; i < selfLastIndex; ++i) {
QPointF current(self.at(i));
if (current.x() >= selfPoint.x() && current.y() <= selfPoint.y()) {
selfPoint = current;
}
}
result.setPoints(selfPoint, otherPoint);
break;
case Uml::Region::SouthEast:
// Find other's point with smallest X and smallest Y value
for (i = 0; i < otherLastIndex; ++i) {
QPointF current(other.at(i));
if (current.x() + current.y() <= otherPoint.x() + otherPoint.y()) {
otherPoint = current;
}
}
// Find own point with largest X and largest Y value
for (i = 0; i < selfLastIndex; ++i) {
QPointF current(self.at(i));
if (current.x() + current.y() >= selfPoint.x() + selfPoint.y()) {
selfPoint = current;
}
}
result.setPoints(selfPoint, otherPoint);
break;
default:
// Error
break;
}
return result;
}
/**
* Returns a default name for the new widget
* @param type the widget type
* @return the default name
*/
QString defaultWidgetName(WidgetBase::WidgetType type)
{
switch(type) {
case WidgetBase::wt_Activity: return i18n("new activity");
case WidgetBase::wt_Actor: return i18n("new actor");
case WidgetBase::wt_Artifact: return i18n("new artifact");
case WidgetBase::wt_Association: return i18n("new association");
case WidgetBase::wt_Box: return i18n("new box");
case WidgetBase::wt_Category: return i18n("new category");
case WidgetBase::wt_Class: return i18n("new class");
case WidgetBase::wt_CombinedFragment: return i18n("new combined fragment");
case WidgetBase::wt_Component: return i18n("new component");
case WidgetBase::wt_Datatype: return i18n("new datatype");
case WidgetBase::wt_Entity: return i18n("new entity");
case WidgetBase::wt_Enum: return i18n("new enum");
case WidgetBase::wt_FloatingDashLine: return i18n("new floating dash line");
case WidgetBase::wt_ForkJoin: return i18n("new fork/join");
case WidgetBase::wt_Instance: return i18n("new instance");
case WidgetBase::wt_Interface: return i18n("new interface");
case WidgetBase::wt_Message: return i18n("new message");
case WidgetBase::wt_Node: return i18n("new node");
case WidgetBase::wt_Note: return i18n("new note");
case WidgetBase::wt_Object: return i18n("new object");
case WidgetBase::wt_ObjectNode: return i18n("new object node");
case WidgetBase::wt_Package: return i18n("new package");
case WidgetBase::wt_Pin: return i18n("new pin");
case WidgetBase::wt_Port: return i18n("new port");
case WidgetBase::wt_Precondition: return i18n("new precondition");
case WidgetBase::wt_Region: return i18n("new region");
case WidgetBase::wt_Signal: return i18n("new signal");
case WidgetBase::wt_State: return i18n("new state");
case WidgetBase::wt_Text: return i18n("new text");
case WidgetBase::wt_UMLWidget: return i18n("new UML widget");
case WidgetBase::wt_UseCase: return i18n("new use case");
default:
logWarn1("Widget_Utils::defaultWidgetName unknown widget type: %1",
WidgetBase::toString(type));
return i18n("new widget");
break;
}
}
/**
* Returns translated title string used by widget related dialogs
* @param type widget type
* @return translated title string
*/
QString newTitle(WidgetBase::WidgetType type)
{
switch(type) {
case WidgetBase::wt_Activity: return i18n("New activity");
case WidgetBase::wt_Actor: return i18n("New actor");
case WidgetBase::wt_Artifact: return i18n("New artifact");
case WidgetBase::wt_Association: return i18n("New association");
case WidgetBase::wt_Box: return i18n("New box");
case WidgetBase::wt_Category: return i18n("New category");
case WidgetBase::wt_Class: return i18n("New class");
case WidgetBase::wt_CombinedFragment: return i18n("New combined fragment");
case WidgetBase::wt_Component: return i18n("New component");
case WidgetBase::wt_Datatype: return i18n("New datatype");
case WidgetBase::wt_Entity: return i18n("New entity");
case WidgetBase::wt_Enum: return i18n("New enum");
case WidgetBase::wt_FloatingDashLine: return i18n("New floating dash line");
case WidgetBase::wt_ForkJoin: return i18n("New fork/join");
case WidgetBase::wt_Instance: return i18n("New instance");
case WidgetBase::wt_Interface: return i18n("New interface");
case WidgetBase::wt_Message: return i18n("New message");
case WidgetBase::wt_Node: return i18n("New node");
case WidgetBase::wt_Note: return i18n("New note");
case WidgetBase::wt_Object: return i18n("New object");
case WidgetBase::wt_ObjectNode: return i18n("New object node");
case WidgetBase::wt_Package: return i18n("New package");
case WidgetBase::wt_Pin: return i18n("New pin");
case WidgetBase::wt_Port: return i18n("New port");
case WidgetBase::wt_Precondition: return i18n("New precondition");
case WidgetBase::wt_Region: return i18n("New region");
case WidgetBase::wt_Signal: return i18n("New signal");
case WidgetBase::wt_State: return i18n("New state");
case WidgetBase::wt_Text: return i18n("New text");
case WidgetBase::wt_UMLWidget: return i18n("New UML widget");
case WidgetBase::wt_UseCase: return i18n("New use case");
default:
logWarn1("Widget_Utils::newTitle unknown widget type: %1",
WidgetBase::toString(type));
return i18n("New widget");
}
}
/**
* Returns translated text string used by widget related dialogs
* @param type widget type
* @return translated text string
*/
QString newText(WidgetBase::WidgetType type)
{
switch(type) {
case WidgetBase::wt_Activity: return i18n("Enter the name of the new activity:");
case WidgetBase::wt_Actor: return i18n("Enter the name of the new actor:");
case WidgetBase::wt_Artifact: return i18n("Enter the name of the new artifact:");
case WidgetBase::wt_Association: return i18n("Enter the name of the new association:");
case WidgetBase::wt_Box: return i18n("Enter the name of the new box:");
case WidgetBase::wt_Category: return i18n("Enter the name of the new category:");
case WidgetBase::wt_Class: return i18n("Enter the name of the new class:");
case WidgetBase::wt_CombinedFragment: return i18n("Enter the name of the new combined fragment:");
case WidgetBase::wt_Component: return i18n("Enter the name of the new component:");
case WidgetBase::wt_Datatype: return i18n("Enter the name of the new datatype:");
case WidgetBase::wt_Entity: return i18n("Enter the name of the new entity:");
case WidgetBase::wt_Enum: return i18n("Enter the name of the new enum:");
case WidgetBase::wt_FloatingDashLine: return i18n("Enter the name of the new floating dash line:");
case WidgetBase::wt_ForkJoin: return i18n("Enter the name of the new fork/join:");
case WidgetBase::wt_Instance: return i18n("Enter the name of the new instance:");
case WidgetBase::wt_Interface: return i18n("Enter the name of the new interface:");
case WidgetBase::wt_Message: return i18n("Enter the name of the new message:");
case WidgetBase::wt_Node: return i18n("Enter the name of the new node:");
case WidgetBase::wt_Note: return i18n("Enter the name of the new note:");
case WidgetBase::wt_Object: return i18n("Enter the name of the new object:");
case WidgetBase::wt_ObjectNode: return i18n("Enter the name of the new object node:");
case WidgetBase::wt_Package: return i18n("Enter the name of the new package:");
case WidgetBase::wt_Pin: return i18n("Enter the name of the new pin:");
case WidgetBase::wt_Port: return i18n("Enter the name of the new port:");
case WidgetBase::wt_Precondition: return i18n("Enter the name of the new precondition:");
case WidgetBase::wt_Region: return i18n("Enter the name of the new region:");
case WidgetBase::wt_Signal: return i18n("Enter the name of the new signal:");
case WidgetBase::wt_State: return i18n("Enter the name of the new state:");
case WidgetBase::wt_Text: return i18n("Enter the name of the new text:");
case WidgetBase::wt_UMLWidget: return i18n("Enter the name of the new uml widget:");
case WidgetBase::wt_UseCase: return i18n("Enter the name of the new use case:");
default:
logWarn1("Widget_Utils::newText unknown widget type: %1", WidgetBase::toString(type));
return i18n("Enter the name of the new widget:");
}
}
/**
* Returns translated title string used by widget related dialogs
* @param type widget type
* @return translated title string
*/
QString renameTitle(WidgetBase::WidgetType type)
{
switch(type) {
case WidgetBase::wt_Activity: return i18n("Rename activity");
case WidgetBase::wt_Actor: return i18n("Rename actor");
case WidgetBase::wt_Artifact: return i18n("Rename artifact");
case WidgetBase::wt_Association: return i18n("Rename association");
case WidgetBase::wt_Box: return i18n("Rename box");
case WidgetBase::wt_Category: return i18n("Rename category");
case WidgetBase::wt_Class: return i18n("Rename class");
case WidgetBase::wt_CombinedFragment: return i18n("Rename combined fragment");
case WidgetBase::wt_Component: return i18n("Rename component");
case WidgetBase::wt_Datatype: return i18n("Rename datatype");
case WidgetBase::wt_Entity: return i18n("Rename entity");
case WidgetBase::wt_Enum: return i18n("Rename enum");
case WidgetBase::wt_FloatingDashLine: return i18n("Rename floating dash line");
case WidgetBase::wt_ForkJoin: return i18n("Rename fork/join");
case WidgetBase::wt_Instance: return i18n("Rename instance");
case WidgetBase::wt_Interface: return i18n("Rename interface");
case WidgetBase::wt_Message: return i18n("Rename message");
case WidgetBase::wt_Node: return i18n("Rename node");
case WidgetBase::wt_Note: return i18n("Rename note");
case WidgetBase::wt_Object: return i18n("Rename object");
case WidgetBase::wt_ObjectNode: return i18n("Rename object node");
case WidgetBase::wt_Package: return i18n("Rename package");
case WidgetBase::wt_Pin: return i18n("Rename pin");
case WidgetBase::wt_Port: return i18n("Rename port");
case WidgetBase::wt_Precondition: return i18n("Rename precondition");
case WidgetBase::wt_Region: return i18n("Rename region");
case WidgetBase::wt_Signal: return i18n("Rename signal");
case WidgetBase::wt_State: return i18n("Rename state");
case WidgetBase::wt_Text: return i18n("Rename text");
case WidgetBase::wt_UMLWidget: return i18n("Rename UML widget");
case WidgetBase::wt_UseCase: return i18n("Rename use case");
default:
logWarn1("Widget_Utils::renameTitle unknown widget type: %1",
WidgetBase::toString(type));
return i18n("Rename widget");
}
}
/**
* Returns translated text string used by widget related dialogs
* @param type widget type
* @return translated text string
*/
QString renameText(WidgetBase::WidgetType type)
{
switch(type) {
case WidgetBase::wt_Activity: return i18n("Enter the new name of the activity:");
case WidgetBase::wt_Actor: return i18n("Enter the new name of the actor:");
case WidgetBase::wt_Artifact: return i18n("Enter the new name of the artifact:");
case WidgetBase::wt_Association: return i18n("Enter the new name of the association:");
case WidgetBase::wt_Box: return i18n("Enter the new name of the box:");
case WidgetBase::wt_Category: return i18n("Enter the new name of the category:");
case WidgetBase::wt_Class: return i18n("Enter the new name of the class:");
case WidgetBase::wt_CombinedFragment: return i18n("Enter the new name of the combined fragment:");
case WidgetBase::wt_Component: return i18n("Enter the new name of the component:");
case WidgetBase::wt_Datatype: return i18n("Enter the new name of the datatype:");
case WidgetBase::wt_Entity: return i18n("Enter the new name of the entity:");
case WidgetBase::wt_Enum: return i18n("Enter the new name of the enum:");
case WidgetBase::wt_FloatingDashLine: return i18n("Enter the new name of the floating dash line:");
case WidgetBase::wt_ForkJoin: return i18n("Enter the new name of the fork/join widget:");
case WidgetBase::wt_Instance: return i18n("Enter the new name of the instance:");
case WidgetBase::wt_Interface: return i18n("Enter the new name of the interface:");
case WidgetBase::wt_Message: return i18n("Enter the new name of the message:");
case WidgetBase::wt_Node: return i18n("Enter the new name of the node:");
case WidgetBase::wt_Note: return i18n("Enter the new name of the note:");
case WidgetBase::wt_Object: return i18n("Enter the new name of the object:");
case WidgetBase::wt_ObjectNode: return i18n("Enter the new name of the object node:");
case WidgetBase::wt_Package: return i18n("Enter the new name of the package:");
case WidgetBase::wt_Pin: return i18n("Enter the new name of the pin:");
case WidgetBase::wt_Port: return i18n("Enter the new name of the port:");
case WidgetBase::wt_Precondition: return i18n("Enter the new name of the precondition:");
case WidgetBase::wt_Region: return i18n("Enter the new name of the region:");
case WidgetBase::wt_Signal: return i18n("Enter the new name of the signal:");
case WidgetBase::wt_State: return i18n("Enter the new name of the state:");
case WidgetBase::wt_Text: return i18n("Enter the new name of the text:");
case WidgetBase::wt_UMLWidget: return i18n("Enter the new name of the uml widget:");
case WidgetBase::wt_UseCase: return i18n("Enter the new name of the use case:");
default:
logWarn1("Widget_Utils::renameText unknown widget type: %1", WidgetBase::toString(type));
return i18n("Enter the new name of the widget:");
}
}
/**
* Prevent nested widget(s) located inside the area of a larger widget from disappearing.
*
* @param self The widget against which to test the other widgets of the diagram
* @param widgetList The widgets of the diagram
*/
void ensureNestedVisible(UMLWidget *self, UMLWidgetList widgetList)
{
for(UMLWidget *other : widgetList) {
if (other == self)
continue;
if (other->isLocatedIn(self)) {
if (other->zValue() <= self->zValue())
other->setZValue(other->zValue() + 1.0);
} else if (self->isLocatedIn(other)) {
if (self->zValue() <= other->zValue())
self->setZValue(self->zValue() + 1.0);
}
}
}
/**
* Adorn stereotype name with guillemets.
*/
QString adornStereo(QString name, bool appendSpace /* = true */)
{
QString s = QString::fromUtf8("«") + name + QString::fromUtf8("»");
if (appendSpace)
s.append(QLatin1Char(' '));
return s;
}
}
| 46,987
|
C++
|
.cpp
| 979
| 38.974464
| 109
| 0.582653
|
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,408
|
categorywidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/categorywidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header file
#include "categorywidget.h"
// local includes
#include "category.h"
#include "debug_utils.h"
#include "listpopupmenu.h"
#include "umlview.h"
#include "uml.h" // only needed for log{Warn,Error}
// qt includes
#include <QPainter>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(CategoryWidget)
/**
* Creates a Category widget.
*
* @param scene The parent of the widget.
* @param o The UMLCategory to represent.
*/
CategoryWidget::CategoryWidget(UMLScene * scene, UMLCategory *o)
: UMLWidget(scene, WidgetBase::wt_Category, o)
{
m_fixedAspectRatio = true;
}
/**
* Destructor.
*/
CategoryWidget::~CategoryWidget()
{
}
/**
* Overrides the standard paint event.
*/
void CategoryWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
UMLWidget::setPenFromSettings(painter);
if (UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
QFont font = UMLWidget::font();
font.setUnderline(false);
font.setBold(false);
font.setItalic(m_umlObject->isAbstract());
painter->setFont(font);
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
// the height is our radius
const int h = height();
const int w = width();
const int r = h > w ? h : w;
//int middleX = w / 2;
const int textStartY = (r / 2) - (fontHeight / 2);
// draw a circle
painter->drawEllipse(0, 0, r, r);
painter->setPen(textColor());
QString letterType(QLatin1Char('D'));
switch(m_umlObject->asUMLCategory()->getType()) {
case UMLCategory::ct_Disjoint_Specialisation:
letterType = QLatin1Char('D');
break;
case UMLCategory::ct_Overlapping_Specialisation:
letterType = QLatin1Char('O');
break;
case UMLCategory::ct_Union:
letterType = QLatin1Char('U');
break;
default:
break;
}
painter->drawText(UC_MARGIN, textStartY, r - UC_MARGIN * 2, fontHeight, Qt::AlignCenter, letterType);
UMLWidget::setPenFromSettings(painter);
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget.
*/
QSizeF CategoryWidget::minimumSize() const
{
const UMLWidget::FontType ft = (m_umlObject->isAbstract() ? FT_BOLD_ITALIC : FT_BOLD);
const QFontMetrics &fm = UMLWidget::getFontMetrics(ft);
const int fontHeight = fm.lineSpacing();
int radius = UC_RADIUS + fontHeight + UC_MARGIN;
return QSizeF(radius, radius);
}
/**
* Saves this Category to file.
*/
void CategoryWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("categorywidget"));
UMLWidget::saveToXMI(writer);
writer.writeEndElement();
}
/**
* Will be called when a menu selection has been made from the
* popup menu.
*
* @param action The action that has been selected.
*/
void CategoryWidget::slotMenuSelection(QAction* action)
{
UMLCategory* catObj = umlObject()->asUMLCategory();
if (!catObj) {
logWarn1("CategoryWidget::slotMenuSelection(%1): No UMLCategory for this widget",
umlObject()->name());
return;
}
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_DisjointSpecialisation:
catObj->setType(UMLCategory::ct_Disjoint_Specialisation);
break;
case ListPopupMenu::mt_OverlappingSpecialisation:
catObj->setType(UMLCategory::ct_Overlapping_Specialisation);
break;
case ListPopupMenu::mt_Union:
catObj->setType(UMLCategory::ct_Union);
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
| 3,958
|
C++
|
.cpp
| 126
| 26.809524
| 105
| 0.686352
|
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,409
|
signalwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/signalwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "signalwidget.h"
// app includes
#include "basictypes.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "floatingtextwidget.h"
#include "linkwidget.h"
#include "listpopupmenu.h"
#include "uml.h"
#include "umldoc.h"
#include "uniqueid.h"
#include "umlview.h"
#include "umlwidget.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QEvent>
#include <QPolygon>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(SignalWidget)
/**
* Creates a Signal widget.
*
* @param scene The parent of the widget.
* @param signalType The type of Signal.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
SignalWidget::SignalWidget(UMLScene *scene, SignalType signalType, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Signal, id),
m_oldX(0),
m_oldY(0)
{
m_signalType = signalType;
m_pName = nullptr;
if (signalType == SignalWidget::Time) {
m_pName = new FloatingTextWidget(scene, Uml::TextRole::Floating, QString());
scene->setupNewWidget(m_pName);
m_pName->setX(0);
m_pName->setY(0);
connect(m_pName, SIGNAL(destroyed()), this, SLOT(slotTextDestroyed()));
}
}
/**
* Destructor.
*/
SignalWidget::~SignalWidget()
{
}
/**
* Overrides the standard paint event.
*/
void SignalWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setPenFromSettings(painter);
const int w = width();
const int h = height();
QPolygon a;
switch (m_signalType)
{
case Send :
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
{
a.setPoints(5, 0, 0,
(w*2)/3, 0,
w, h/2,
(w*2)/3, h,
0, h);
painter->drawPolygon(a);
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textStartY = (h / 2) - (fontHeight / 2);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(false);
painter->setFont(font);
painter->drawText(SIGNAL_MARGIN, textStartY,
w - SIGNAL_MARGIN * 2, fontHeight,
Qt::AlignCenter, name());
setPenFromSettings(painter);
}
break;
case Accept :
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
{
a.setPoints(5, 0, 0,
w/3, h/2,
0, h,
w, h,
w, 0);
painter->drawPolygon(a);
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
int textStartY = (h / 2) - (fontHeight / 2);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(false);
painter->setFont(font);
painter->drawText(SIGNAL_MARGIN, textStartY,
w - SIGNAL_MARGIN * 2 + (w/3), fontHeight,
Qt::AlignCenter, name());
setPenFromSettings(painter);
}
break;
case Time :
if(UMLWidget::useFillColor())
painter->setBrush(UMLWidget::fillColor());
{
a.setPoints(4, 0, 0,
w, h,
0, h,
w, 0);
painter->drawPolygon(a);
//const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
//const int fontHeight = fm.lineSpacing();
//int textStartY = (h / 2) - (fontHeight / 2);
painter->setPen(textColor());
QFont font = UMLWidget::font();
font.setBold(false);
painter->setFont(font);
setPenFromSettings(painter);
}
if (m_pName) {
if (m_pName->x() == 0 && m_pName->y() == 0) {
//the floating text has not been linked with the signal
m_pName->setX(w/2 - m_pName->width()/2);
m_pName->setY(h);
}
m_pName->setVisible((m_pName->text().length() > 0));
m_pName->updateGeometry();
}
break;
default:
logWarn1("SignalWidget::paint: Unknown signal type %1", m_signalType);
break;
}
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides the UMLWidget method.
*/
void SignalWidget::setX(qreal newX)
{
m_oldX = x();
UMLWidget::setX(newX);
}
/**
* Overrides the UMLWidget method.
*/
void SignalWidget::setY(qreal newY)
{
m_oldY = y();
UMLWidget::setY(newY);
}
/**
* Sets the name of the signal.
*/
void SignalWidget::setName(const QString &strName)
{
UMLWidget::setName(strName);
updateGeometry();
if (signalType() == SignalWidget::Time) {
if (!m_pName) {
m_pName = new FloatingTextWidget(umlScene(), Uml::TextRole::Floating, m_Text);
umlScene()->setupNewWidget(m_pName);
m_pName->setX(0);
m_pName->setY(0);
connect(m_pName, SIGNAL(destroyed()), this, SLOT(slotTextDestroyed()));
}
else
m_pName->setText(m_Text);
}
}
/**
* Returns the type of Signal.
*/
SignalWidget::SignalType SignalWidget::signalType() const
{
return m_signalType;
}
/**
* Returns the type string of Signal.
*/
QString SignalWidget::signalTypeStr() const
{
return QLatin1String(ENUM_NAME(SignalWidget, SignalType, m_signalType));
}
/**
* Sets the type of Signal.
*/
void SignalWidget::setSignalType(SignalType signalType)
{
m_signalType = signalType;
}
/**
* Show a properties dialog for a UMLWidget.
*/
bool SignalWidget::showPropertiesDialog()
{
return false;
}
/**
* Overrides mouseMoveEvent.
*/
void SignalWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* me)
{
UMLWidget::mouseMoveEvent(me);
int diffX = m_oldX - x();
int diffY = m_oldY - y();
if (m_pName!=nullptr) {
m_pName->setX(m_pName->x() - diffX);
m_pName->setY(m_pName->y() - diffY);
}
}
/**
* Loads a "signalwidget" XMI element.
*/
bool SignalWidget::loadFromXMI(QDomElement & qElement)
{
if(!UMLWidget::loadFromXMI(qElement))
return false;
m_Text = qElement.attribute(QStringLiteral("signalname"));
m_Doc = qElement.attribute(QStringLiteral("documentation"));
QString type = qElement.attribute(QStringLiteral("signaltype"));
QString textid = qElement.attribute(QStringLiteral("textid"), QStringLiteral("-1"));
Uml::ID::Type textId = Uml::ID::fromString(textid);
setSignalType((SignalType)type.toInt());
if (signalType() == Time) {
if (textId != Uml::ID::None) {
UMLWidget *flotext = m_scene -> findWidget(textId);
if (flotext != nullptr) {
// This only happens when loading files produced by
// umbrello-1.3-beta2.
m_pName = static_cast<FloatingTextWidget*>(flotext);
return true;
}
} else {
// no textid stored -> get unique new one
textId = UniqueID::gen();
}
}
//now load child elements
QDomNode node = qElement.firstChild();
QDomElement element = node.toElement();
if (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("floatingtext") || tag == QStringLiteral("UML::FloatingTextWidget")) {
m_pName = new FloatingTextWidget(m_scene, Uml::TextRole::Floating, m_Text, textId);
if(! m_pName->loadFromXMI(element)) {
// Most likely cause: The FloatingTextWidget is empty.
delete m_pName;
m_pName = nullptr;
}
else
connect(m_pName, SIGNAL(destroyed()), this, SLOT(slotTextDestroyed()));
} else {
logError1("SignalWidget::loadFromXMI: unknown tag %1", tag);
}
}
return true;
}
/**
* Creates the "signalwidget" XMI element.
*/
void SignalWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("signalwidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("signalname"), m_Text);
writer.writeAttribute(QStringLiteral("documentation"), m_Doc);
writer.writeAttribute(QStringLiteral("signaltype"), QString::number(m_signalType));
if (m_pName && !m_pName->text().isEmpty()) {
writer.writeAttribute(QStringLiteral("textid"), Uml::ID::toString(m_pName->id()));
m_pName -> saveToXMI(writer);
}
writer.writeEndElement();
}
/**
* Show a properties dialog for a SignalWidget.
*
*/
void SignalWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
{
QString name = m_Text;
bool ok = Dialog_Utils::askName(i18n("Enter signal name"),
i18n("Enter the signal name :"),
name);
if (ok && name.length() > 0) {
setName(name);
}
}
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Overrides method from UMLWidget
*/
QSizeF SignalWidget::minimumSize() const
{
int width = SIGNAL_WIDTH, height = SIGNAL_HEIGHT;
const QFontMetrics &fm = getFontMetrics(FT_BOLD);
const int fontHeight = fm.lineSpacing();
int textWidth = fm.horizontalAdvance(name());
if (m_signalType == Accept)
textWidth = int((float)textWidth * 1.3f);
height = fontHeight;
if (m_signalType != Time)
{
width = textWidth > SIGNAL_WIDTH?textWidth:SIGNAL_WIDTH;
height = height > SIGNAL_HEIGHT?height:SIGNAL_HEIGHT;
}
width += SIGNAL_MARGIN * 2;
height += SIGNAL_MARGIN * 2;
return QSizeF(width, height);
}
/**
* Called if user deletes text widget
*/
void SignalWidget::slotTextDestroyed()
{
m_pName = nullptr;
}
| 10,510
|
C++
|
.cpp
| 336
| 23.919643
| 104
| 0.588125
|
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,410
|
notewidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/notewidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "notewidget.h"
// app includes
#include "debug_utils.h"
#include "dialog_utils.h"
#include "docwindow.h"
#include "listpopupmenu.h"
#include "notedialog.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "widget_utils.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPainter>
#include <QColorDialog>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(NoteWidget)
QPointer<NoteWidget> NoteWidget::s_pCurrentNote;
/**
* Constructs a NoteWidget.
*
* @param scene The parent to this widget.
* @param noteType The NoteWidget::NoteType of this NoteWidget
* @param id The unique id of the widget.
* The default (-1) will prompt a new ID.
*/
NoteWidget::NoteWidget(UMLScene * scene, NoteType noteType , Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_Note, id),
m_diagramLink(Uml::ID::None),
m_noteType(noteType)
{
setZValue(20); //make sure always on top.
}
/**
* Destructor.
*/
NoteWidget::~NoteWidget()
{
}
/**
* Override default method.
*/
void NoteWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
int w = width();
int h = height();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
QPolygon poly(6);
poly.setPoint(0, 0, 0);
poly.setPoint(1, 0, h);
poly.setPoint(2, w, h);
poly.setPoint(3, w, defaultMargin );
poly.setPoint(4, w - defaultMargin , 0);
poly.setPoint(5, 0, 0);
setPenFromSettings(painter);
if (UMLWidget::useFillColor()) {
QBrush brush(UMLWidget::fillColor());
painter->setBrush(brush);
painter->drawPolygon(poly);
} else
painter->drawPolyline(poly);
painter->drawLine(w - defaultMargin , 0, w - defaultMargin , defaultMargin );
painter->drawLine(w - defaultMargin , defaultMargin , w, defaultMargin );
painter->setPen(textColor());
switch(m_noteType) {
case NoteWidget::PreCondition :
painter->drawText(0, defaultMargin , w, fontHeight, Qt::AlignCenter,
Widget_Utils::adornStereo(QStringLiteral("precondition")));
break;
case NoteWidget::PostCondition :
painter->drawText(0, defaultMargin , w, fontHeight, Qt::AlignCenter,
Widget_Utils::adornStereo(QStringLiteral("postcondition")));
break;
case NoteWidget::Transformation :
painter->drawText(0, defaultMargin , w, fontHeight, Qt::AlignCenter,
Widget_Utils::adornStereo(QStringLiteral("transformation")));
break;
case NoteWidget::Normal :
default :
break;
}
UMLWidget::paint(painter, option, widget);
// paintText(&p, 0, 0);
paintTextWordWrap(painter);
}
/**
* Returns the type of note.
*/
NoteWidget::NoteType NoteWidget::noteType() const
{
return m_noteType;
}
/**
* Converts a string to NoteWidget::NoteType.
*/
NoteWidget::NoteType NoteWidget::stringToNoteType(const QString& noteType)
{
if (noteType == QStringLiteral("Precondition"))
return NoteWidget::PreCondition;
else if (noteType == QStringLiteral("Postcondition"))
return NoteWidget::PostCondition;
else if (noteType == QStringLiteral("Transformation"))
return NoteWidget::Transformation;
else
return NoteWidget::Normal;
}
/**
* Sets the type of note.
*/
void NoteWidget::setNoteType(NoteType noteType)
{
m_noteType = noteType;
}
/**
* Sets the type of note.
*/
void NoteWidget::setNoteType(const QString& noteType)
{
setNoteType(stringToNoteType(noteType));
}
/**
* Return the ID of the diagram hyperlinked to this note.
*
* @return ID of a UMLView, or Uml::ID::None if no
* hyperlink is set.
*/
Uml::ID::Type NoteWidget::diagramLink() const
{
return m_diagramLink;
}
/**
* Set the ID of the diagram hyperlinked to this note.
* To switch off the hyperlink, set this to Uml::id_None.
*
* @param viewID ID of a UMLScene.
*/
void NoteWidget::setDiagramLink(Uml::ID::Type viewID)
{
UMLDoc *umldoc = UMLApp::app()->document();
UMLView *view = umldoc->findView(viewID);
if (view == nullptr) {
logError1("NoteWidget::setDiagramLink: no view found for viewID %1",
Uml::ID::toString(viewID));
return;
}
QString linkText(QStringLiteral("Diagram: ") + view->umlScene()->name());
setDocumentation(linkText);
m_diagramLink = viewID;
update();
}
/**
* Set the given diagram as hyperlinked to this note.
* If the diagram name is empty or the related view
* could not be found, the link will be removed.
*
* @param diagramName name of diagram to link to
* @return true if link could be added
* @return false if link could not be added
*/
bool NoteWidget::setDiagramLink(const QString &diagramName)
{
if (diagramName.isEmpty()) {
m_diagramLink = Uml::ID::None;
return true;
}
UMLDoc *umldoc = UMLApp::app()->document();
UMLView *view = nullptr;
for (int i = 1; i < Uml::DiagramType::N_DIAGRAMTYPES; ++i) {
Uml::DiagramType::Enum dt = Uml::DiagramType::fromInt(i);
view = umldoc->findView(dt, diagramName, true);
if (view)
break;
}
if (view == nullptr || view->umlScene() == nullptr) {
m_diagramLink = Uml::ID::None;
return false;
}
m_diagramLink = view->umlScene()->ID();
update();
return true;
}
/**
* Display a dialog box to allow the user to choose the note's type.
*/
void NoteWidget::askForNoteType(UMLWidget* &targetWidget)
{
static const QStringList list = QStringList() << i18n("Precondition")
<< i18n("Postcondition")
<< i18n("Transformation");
bool pressedOK = false;
QString type = QInputDialog::getItem (UMLApp::app(),
i18n("Note Type"), i18n("Select the Note Type"), list,
0, false, &pressedOK);
if (pressedOK) {
targetWidget->asNoteWidget()->setNoteType(type);
} else {
targetWidget->cleanup();
delete targetWidget;
targetWidget = nullptr;
}
}
/**
* Loads a "notewidget" XMI element.
*/
bool NoteWidget::loadFromXMI(QDomElement & qElement)
{
if (!UMLWidget::loadFromXMI(qElement))
return false;
setZValue(20); //make sure always on top.
setDocumentation(qElement.attribute(QStringLiteral("text")));
QString diagramlink = qElement.attribute(QStringLiteral("diagramlink"));
if (!diagramlink.isEmpty())
m_diagramLink = Uml::ID::fromString(diagramlink);
QString type = qElement.attribute(QStringLiteral("noteType"));
setNoteType((NoteType)type.toInt());
return true;
}
/**
* Saves to the "notewidget" XMI element.
*/
void NoteWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("notewidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("text"), documentation());
if (m_diagramLink != Uml::ID::None)
writer.writeAttribute(QStringLiteral("diagramlink"), Uml::ID::toString(m_diagramLink));
writer.writeAttribute(QStringLiteral("noteType"), QString::number(m_noteType));
writer.writeEndElement();
}
/**
* Show a properties dialog for a NoteWidget.
*/
bool NoteWidget::showPropertiesDialog()
{
bool result = false;
NoteDialog *dlg = nullptr;
UMLApp::app()->docWindow()->updateDocumentation(false);
dlg = new NoteDialog(umlScene()->activeView(), this);
if (dlg->exec()) {
UMLApp::app()->docWindow()->showDocumentation(this, true);
UMLApp::app()->document()->setModified(true);
update();
result = true;
}
delete dlg;
return result;
}
/**
* Will be called when a menu selection has been made from the popup
* menu.
*
* @param action The action that has been selected.
*/
void NoteWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch(sel) {
case ListPopupMenu::mt_Rename:
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
default:
UMLWidget::slotMenuSelection(action);
break;
}
}
/**
* Overrides method from UMLWidget.
*/
QSizeF NoteWidget::minimumSize() const
{
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
return QSizeF(fm.averageCharWidth()*20, fm.height() * 2);
}
/**
* Calculate content related size of widget.
* Overrides method from UMLWidget.
*/
QSizeF NoteWidget::calculateSize(bool withExtensions /* = true */) const
{
Q_UNUSED(withExtensions)
int width = 0;
int height = this->height();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
QSize size = fm.size(Qt::TextExpandTabs, documentation());
const int textWidth = size.width();
const int textHeight = size.height();
if (m_noteType == PreCondition) {
const int widthtemp = fm.horizontalAdvance(Widget_Utils::adornStereo(QStringLiteral("precondition")));
width = textWidth > widthtemp ? textWidth : widthtemp;
}
else if (m_noteType == PostCondition) {
const int widthtemp = fm.horizontalAdvance(Widget_Utils::adornStereo(QStringLiteral("postcondition")));
width = textWidth > widthtemp ? textWidth : widthtemp;
}
else if (m_noteType == Transformation) {
const int widthtemp = fm.horizontalAdvance(Widget_Utils::adornStereo(QStringLiteral("transformation")));
width = textWidth > widthtemp ? textWidth : widthtemp;
}
if (textWidth > width)
width = textWidth;
if (textHeight > height)
height = textHeight;
width += 2 * defaultMargin;
return QSizeF(width, height);
}
/**
* Paints the text. Auxiliary to paint().
* Implemented without word wrap.
*/
void NoteWidget::paintText(QPainter *painter)
{
if (painter == nullptr) {
return;
}
QString text = documentation();
if (text.length() == 0) {
return;
}
painter->setPen(Qt::black);
QFont font = UMLWidget::font();
painter->setFont(font);
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const QSize textSize = fm.size(Qt::TextExpandTabs, text);
const int width = this->width() - defaultMargin * 2;
const int height = this->height() - fontHeight;
int textY = fontHeight / 2;
int textX = defaultMargin;
if ((textSize.width() < width) && (textSize.height() < height)) {
// the entire text is small enough - draw it
painter->drawText(textX, textY,
textSize.width(), textSize.height(),
Qt::AlignLeft, text);
}
else {
// not all text can be drawn
QStringList lines = text.split(QLatin1Char('\n'));
for(const QString& line : lines) {
int lineWidth = fm.horizontalAdvance(line);
if (lineWidth < width) {
// line is small enough - draw it
painter->drawText(textX, textY,
textSize.width(), fontHeight,
Qt::AlignLeft, line);
}
else {
// draw a smaller line
for(int len = line.length(); len > 0; --len) {
QString smallerLine = line.left(len);
int smallerLineWidth = fm.horizontalAdvance(smallerLine);
if (smallerLineWidth < width) {
// line is small enough - draw it
painter->drawText(textX, textY,
width, fontHeight,
Qt::AlignLeft, smallerLine);
}
}
}
textY += fontHeight;
if (textY > height) {
// skip the next lines - size is not enough
break;
}
}
}
}
/**
* Paints the text. Auxiliary to paint().
* Implemented with word wrap.
*/
void NoteWidget::paintTextWordWrap(QPainter *painter)
{
if (painter == nullptr) {
return;
}
QString text = documentation();
if (text.length() == 0) {
return;
}
// Implement word wrap for text as follows:
// wrap at width on whole words.
// if word is wider than width then clip word
// if reach height exit and don't print anymore
// start new line on \n character
painter->setPen(Qt::black);
QFont font = UMLWidget::font();
painter->setFont(font);
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
QString word;
QString fullLine;
QString testCombineLine;
int textY = fontHeight / 2;
int textX = defaultMargin;
const int width = this -> width() - defaultMargin * 2;
const int height = this -> height() - fontHeight;
QChar returnChar = QChar::fromLatin1('\n');
QChar c;
for (int i = 0; i <= text.length(); ++i) {
if (i < text.length()) {
c = text[i];
} else {
// all chars of text have been handled already ->
// perform this last run to spool current content of "word"
c = returnChar;
}
if (c == returnChar || c.isSpace()) {
// new word delimiter found -> it is time to decide on word wrap
testCombineLine = fullLine + QLatin1Char(' ') + word;
int textWidth = fm.horizontalAdvance(testCombineLine);
if (textX + textWidth > width) {
// combination of "fullLine" and "word" doesn't fit into one line ->
// print "fullLine" in current line, update write position to next line
// and decide then on following actions
painter->drawText(textX, textY,
textWidth, fontHeight, Qt::AlignLeft, fullLine);
fullLine = word;
word = QString();
// update write position
textX = defaultMargin;
textY += fontHeight;
if (textY > height)
return;
// in case of c==newline ->
// print "word" and set write position one additional line lower
if (c == returnChar) {
// print "word" - which is now "fullLine" and set to next line
painter->drawText(textX, textY,
textWidth, fontHeight, Qt::AlignLeft, fullLine);
fullLine = QString();
textX = defaultMargin;
textY += fontHeight;
if(textY > height) return;
}
}
else if (c == returnChar) {
// newline found and combination of "fullLine" and "word" fits
// in one line
painter->drawText(textX, textY,
textWidth, fontHeight, Qt::AlignLeft, testCombineLine);
fullLine = word = QString();
textX = defaultMargin;
textY += fontHeight;
if (textY > height)
return;
} else {
// word delimiter found, and combination of "fullLine", space and "word" fits into one line
fullLine = testCombineLine;
word = QString();
}
} else {
// no word delimiter found --> add current char to "word"
if (c != QLatin1Char('\0'))
word += c;
}
}//end for
}
/**
* Event handler for moude double click events.
*
* @param event The QGraphicsSceneMouseEvent event.
*/
void NoteWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && m_diagramLink != Uml::ID::None) {
UMLDoc *umldoc = UMLApp::app()->document();
umldoc->changeCurrentView(m_diagramLink);
event->accept();
} else
showPropertiesDialog();
}
| 16,422
|
C++
|
.cpp
| 483
| 27
| 112
| 0.616193
|
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,411
|
combinedfragmentwidget.cpp
|
KDE_umbrello/umbrello/umlwidgets/combinedfragmentwidget.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "combinedfragmentwidget.h"
// app includes
#include "debug_utils.h"
#include "dialog_utils.h"
#include "listpopupmenu.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QPainter>
#include <QString>
#include <QXmlStreamWriter>
DEBUG_REGISTER_DISABLED(CombinedFragmentWidget)
static const int defaultWidth = 100;
static const int defaultHeight = 50;
static const int initialLabelWidth = 45;
static const int labelHeight = 20;
static const int labelBorderMargin = 10;
/**
* Creates a Combined Fragment widget.
*
* @param scene The parent of the widget.
* @param combinedfragmentType The type of combined fragment.
* @param id The ID to assign (-1 will prompt a new ID.)
*/
CombinedFragmentWidget::CombinedFragmentWidget(UMLScene * scene, CombinedFragmentType combinedfragmentType, Uml::ID::Type id)
: UMLWidget(scene, WidgetBase::wt_CombinedFragment, id),
m_labelWidth(initialLabelWidth)
{
setZValue(-10);
setCombinedFragmentType(combinedfragmentType);
}
/**
* Destructor.
*/
CombinedFragmentWidget::~CombinedFragmentWidget()
{
for (QList<FloatingDashLineWidget*>::iterator it=m_dashLines.begin() ; it!=m_dashLines.end() ; ++it) {
delete(*it);
}
}
/**
* Overrides the standard paint event.
*/
void CombinedFragmentWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
int w = width();
int h = height();
int line_width = initialLabelWidth;
qreal old_Y;
setPenFromSettings(painter);
if (m_CombinedFragment == Ref) {
if (UMLWidget::useFillColor()) {
painter->setBrush(UMLWidget::fillColor());
}
}
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const QString combined_fragment_value = name();
int textStartY = (h / 2) - (fontHeight / 2);
painter->drawRect(0, 0, w, h);
painter->setPen(textColor());
painter->setFont(UMLWidget::font());
QString temp = QStringLiteral("loop");
switch (m_CombinedFragment)
{
case Ref :
painter->drawText(defaultMargin, textStartY, w - defaultMargin * 2, fontHeight, Qt::AlignCenter, combined_fragment_value);
painter->drawText(defaultMargin, 0, w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("ref"));
break;
case Opt :
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("opt"));
break;
case Break :
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("break"));
break;
case Loop :
if (combined_fragment_value != QStringLiteral("-"))
{
temp += QStringLiteral(" [") + combined_fragment_value + QLatin1Char(']');
line_width += (combined_fragment_value.size() + 2) * 8;
}
painter->drawText(defaultMargin, 0, w - defaultMargin * 2, fontHeight, Qt::AlignLeft, temp);
break;
case Neg :
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("neg"));
break;
case Crit :
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("critical"));
break;
case Ass :
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("assert"));
break;
case Alt :
if (combined_fragment_value != QStringLiteral("-"))
{
temp = QLatin1Char('[') + combined_fragment_value + QLatin1Char(']');
painter->drawText(defaultMargin, labelHeight,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, temp);
if (m_dashLines.size() == 1 && m_dashLines.first()->y() < y() + labelHeight + fontHeight)
m_dashLines.first()->setY(y() + h/2);
}
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("alt"));
// dash lines
//m_dashLines.first()->paint(painter);
// TODO: move to UMLWidget::calculateSize api
for (QList<FloatingDashLineWidget*>::iterator it=m_dashLines.begin() ; it!=m_dashLines.end() ; ++it) {
(*it)->setX(x());
old_Y = (*it)->getYMin();
(*it)->setYMin(y());
(*it)->setYMax(y() + height());
(*it)->setY(y() + (*it)->y() - old_Y);
(*it)->setSize(w, (*it)->height());
(*it)->setLineColor(lineColor());
(*it)->setLineWidth(lineWidth());
}
break;
case Par :
painter->drawText(defaultMargin, 0,
w - defaultMargin * 2, fontHeight, Qt::AlignLeft, QStringLiteral("parallel"));
// dash lines
if (m_dashLines.size() != 0) {
//m_dashLines.first()->paint(painter);
// TODO: move to UMLWidget::calculateSize api
for (QList<FloatingDashLineWidget*>::iterator it=m_dashLines.begin() ; it!=m_dashLines.end() ; ++it) {
(*it)->setX(x());
old_Y = (*it)->getYMin();
(*it)->setYMin(y());
(*it)->setYMax(y() + height());
(*it)->setY(y() + (*it)->y() - old_Y);
(*it)->setSize(w, (*it)->height());
(*it)->setLineColor(lineColor());
(*it)->setLineWidth(lineWidth());
}
}
break;
default : break;
}
setPenFromSettings(painter);
painter->drawLine(0, labelHeight, line_width, labelHeight);
painter->drawLine(line_width, labelHeight, line_width + labelBorderMargin, labelHeight-labelBorderMargin);
painter->drawLine(line_width + labelBorderMargin, labelHeight-labelBorderMargin, line_width + labelBorderMargin, 0);
m_labelWidth = line_width;
UMLWidget::paint(painter, option, widget);
}
/**
* Overrides method from UMLWidget.
*/
QSizeF CombinedFragmentWidget::minimumSize() const
{
int width = 10, height = 10;
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const int textWidth = fm.horizontalAdvance(name());
height = fontHeight;
width = textWidth + 60 > defaultWidth ? textWidth + 60: defaultWidth;
if (m_CombinedFragment == Loop)
width += int((float)textWidth * 0.4f);
if (m_CombinedFragment == Alt)
height += fontHeight + 40;
height = height > defaultHeight ? height : defaultHeight;
width += defaultMargin * 2;
height += defaultMargin * 2;
return QSizeF(width, height);
}
/**
* Returns the type of combined fragment.
*/
CombinedFragmentWidget::CombinedFragmentType CombinedFragmentWidget::combinedFragmentType() const
{
return m_CombinedFragment;
}
/**
* Sets the type of combined fragment.
*/
void CombinedFragmentWidget::setCombinedFragmentType(CombinedFragmentType combinedfragmentType)
{
m_CombinedFragment = combinedfragmentType;
UMLWidget::m_resizable = true ; //(m_CombinedFragment == Normal);
bool isLoading = UMLApp::app()->document()->loading();
// creates a dash line if the combined fragment type is alternative or parallel
if (!isLoading && m_CombinedFragment == Alt && m_dashLines.isEmpty())
{
m_dashLines.push_back(new FloatingDashLineWidget(m_scene, Uml::ID::None, this));
m_scene->addWidgetCmd(m_dashLines.back());
}
}
/**
* Returns the type of combined fragment.
*/
CombinedFragmentWidget::CombinedFragmentType CombinedFragmentWidget::combinedFragmentType(const QString& type) const
{
if (type == QStringLiteral("Reference"))
return (CombinedFragmentWidget::Ref);
if (type == QStringLiteral("Option"))
return (CombinedFragmentWidget::Opt);
if (type == QStringLiteral("Break"))
return (CombinedFragmentWidget::Break);
if (type == QStringLiteral("Loop"))
return (CombinedFragmentWidget::Loop);
if (type == QStringLiteral("Negative"))
return (CombinedFragmentWidget::Neg);
if (type == QStringLiteral("Critical"))
return (CombinedFragmentWidget::Crit);
if (type == QStringLiteral("Assertion"))
return (CombinedFragmentWidget::Ass);
if (type == QStringLiteral("Alternative"))
return (CombinedFragmentWidget::Alt);
if (type == QStringLiteral("Parallel"))
return (CombinedFragmentWidget::Par);
// Shouldn't happen
Q_ASSERT(0);
return (CombinedFragmentWidget::Ref);
}
/**
* Sets the type of combined fragment.
*/
void CombinedFragmentWidget::setCombinedFragmentType(const QString& combinedfragmentType)
{
setCombinedFragmentType(combinedFragmentType(combinedfragmentType));
}
/**
* ...
*/
void CombinedFragmentWidget::askNameForWidgetType(UMLWidget* &targetWidget, const QString& dialogTitle,
const QString& dialogPrompt, const QString& defaultName)
{
Q_UNUSED(defaultName);
bool pressedOK = false;
const QStringList list = QStringList()
<< QStringLiteral("Reference")
<< QStringLiteral("Option")
<< QStringLiteral("Break")
<< QStringLiteral("Loop")
<< QStringLiteral("Negative")
<< QStringLiteral("Critical")
<< QStringLiteral("Assertion")
<< QStringLiteral("Alternative")
<< QStringLiteral("Parallel") ;
QPointer<QInputDialog> inputDlg = new QInputDialog();
inputDlg->setComboBoxItems(list);
inputDlg->setOptions(QInputDialog::UseListViewForComboBoxItems);
inputDlg->setWindowTitle(dialogTitle);
inputDlg->setLabelText(dialogPrompt);
pressedOK = inputDlg->exec();
QStringList result;
result.append(inputDlg->textValue());
delete inputDlg;
if (pressedOK) {
QString type = result.join(QString());
targetWidget->asCombinedFragmentWidget()->setCombinedFragmentType(type);
if (type == QStringLiteral("Reference"))
Dialog_Utils::askNameForWidget(targetWidget, i18n("Enter the name of the diagram referenced"), i18n("Enter the name of the diagram referenced"), i18n("Diagram name"));
else if (type == QStringLiteral("Loop"))
Dialog_Utils::askNameForWidget(targetWidget, i18n("Enter the guard of the loop"), i18n("Enter the guard of the loop"), i18n("-"));
else if (type == QStringLiteral("Alternative"))
Dialog_Utils::askNameForWidget(targetWidget, i18n("Enter the first alternative name"), i18n("Enter the first alternative name"), i18n("-"));
} else {
targetWidget->cleanup();
delete targetWidget;
targetWidget = nullptr;
}
}
/**
* Saves the widget to the "combinedFragmentwidget" XMI element.
*/
void CombinedFragmentWidget::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("combinedFragmentwidget"));
UMLWidget::saveToXMI(writer);
writer.writeAttribute(QStringLiteral("combinedFragmentname"), m_Text);
writer.writeAttribute(QStringLiteral("documentation"), m_Doc);
writer.writeAttribute(QStringLiteral("CombinedFragmenttype"), QString::number(m_CombinedFragment));
// save the corresponding floating dash lines
for (QList<FloatingDashLineWidget*>::iterator it = m_dashLines.begin() ; it != m_dashLines.end() ; ++it) {
(*it)-> saveToXMI(writer);
}
writer.writeEndElement();
}
/**
* Loads the widget from the "CombinedFragmentwidget" XMI element.
*/
bool CombinedFragmentWidget::loadFromXMI(QDomElement & qElement)
{
if (!UMLWidget::loadFromXMI(qElement))
return false;
m_Text = qElement.attribute(QStringLiteral("combinedFragmentname"));
m_Doc = qElement.attribute(QStringLiteral("documentation"));
QString type = qElement.attribute(QStringLiteral("CombinedFragmenttype"));
//now load child elements
QDomNode node = qElement.firstChild();
QDomElement element = node.toElement();
while (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("floatingdashlinewidget")) {
FloatingDashLineWidget * fdlwidget = new FloatingDashLineWidget(m_scene, Uml::ID::None, this);
m_dashLines.push_back(fdlwidget);
if (!fdlwidget->loadFromXMI(element)) {
// Most likely cause: The FloatingTextWidget is empty.
delete m_dashLines.back();
return false;
}
else {
m_scene->addWidgetCmd(fdlwidget);
fdlwidget->clipSize();
}
} else {
logError1("CombinedFragmentWidget::loadFromXMI: unknown tag %1", tag);
}
node = node.nextSibling();
element = node.toElement();
}
// m_dashLines = listline;
setCombinedFragmentType((CombinedFragmentType)type.toInt());
return true;
}
void CombinedFragmentWidget::removeDashLine(FloatingDashLineWidget *line)
{
if (m_dashLines.contains(line))
m_dashLines.removeOne(line);
}
/**
* Overrides the function from UMLWidget. Deletes all FloatingDashLineWidgets
* that are associated with this instance.
*/
void CombinedFragmentWidget::cleanup()
{
for(FloatingDashLineWidget* w : m_dashLines)
{
if (!w->isSelected()) {
// no need to make this undoable, since the dashlines will be
// reconstructed when deleting the combined fragment is undone.
umlScene()->removeWidgetCmd(w);
}
}
}
/**
* Overrides the function from UMLWidget.
*
* @param action The command to be executed.
*/
void CombinedFragmentWidget::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch (sel) {
// for alternative or parallel combined fragments
case ListPopupMenu::mt_AddInteractionOperand:
m_dashLines.push_back(new FloatingDashLineWidget(m_scene, Uml::ID::None, this));
if (m_CombinedFragment == Alt)
{
m_dashLines.back()->setText(QStringLiteral("else"));
}
// TODO: move to UMLWidget::calculateSize api
m_dashLines.back()->setX(x());
m_dashLines.back()->setYMin(y());
m_dashLines.back()->setYMax(y() + height());
m_dashLines.back()->setY(y() + height() / 2);
m_dashLines.back()->setSize(width(), m_dashLines.back()->height());
m_scene->setupNewWidget(m_dashLines.back());
break;
case ListPopupMenu::mt_Rename:
{
bool ok = false;
QString name = m_Text;
if (m_CombinedFragment == Alt) {
ok = Dialog_Utils::askName(i18n("Enter first alternative"),
i18n("Enter first alternative :"),
name);
}
else if (m_CombinedFragment == Ref) {
ok = Dialog_Utils::askName(i18n("Enter referenced diagram name"),
i18n("Enter referenced diagram name :"),
name);
}
else if (m_CombinedFragment == Loop) {
ok = Dialog_Utils::askName(i18n("Enter the guard of the loop"),
i18n("Enter the guard of the loop:"),
name);
}
if (ok && name.length() > 0)
m_Text = name;
}
break;
case ListPopupMenu::mt_Properties:
showPropertiesDialog();
break;
default:
UMLWidget::slotMenuSelection(action);
}
}
/**
* Overrides UMLWidget method to optionally set-up a dashed line
*/
bool CombinedFragmentWidget::activate(IDChangeLog *ChangeLog)
{
if(UMLWidget::activate(ChangeLog))
{
if (!UMLApp::app()->document()->loading())
setDashLineGeometryAndPosition();
return true;
}
return false;
}
/**
* Sets the geometry and positions of the last dash line
*/
void CombinedFragmentWidget::setDashLineGeometryAndPosition() const
{
if (m_CombinedFragment == Alt && !m_dashLines.isEmpty())
{
m_dashLines.back()->setText(QStringLiteral("else"));
m_dashLines.back()->setX(x());
m_dashLines.back()->setYMin(y());
m_dashLines.back()->setYMax(y() + height());
m_dashLines.back()->setY(y() + height() / 2);
m_dashLines.back()->setSize(width(), m_dashLines.back()->height());
}
}
void CombinedFragmentWidget::toForeground()
{
}
QRectF CombinedFragmentWidget::boundingRect() const
{
const qreal r = defaultMargin / 2.0;
return rect().adjusted(-r, -r, r, r);
}
QPainterPath CombinedFragmentWidget::shape() const
{
const qreal w = width();
const qreal h = height();
const QFontMetrics &fm = getFontMetrics(FT_NORMAL);
const int fontHeight = fm.lineSpacing();
const qreal s = selectionMarkerSize * resizeMarkerLineCount + 4;
const qreal r = defaultMargin / 2.0;
qreal lw = m_labelWidth + r;
qreal lh = labelHeight + r;
if (m_CombinedFragment == Alt) {
const int textWidth = fm.horizontalAdvance(name() + QStringLiteral("[]"));
lh += fontHeight;
if (lw < textWidth)
lw = textWidth + r;
}
QPainterPath outerPath;
outerPath.setFillRule(Qt::WindingFill);
outerPath.addRect(boundingRect());
QPolygonF inner;
inner.append(QPointF(r, lh));
inner.append(QPointF(lw, lh));
inner.append(QPointF(lw + labelBorderMargin, lh - labelBorderMargin));
inner.append(QPointF(lw + labelBorderMargin, r));
inner.append(QPointF(w - selectionMarkerSize - r, r));
inner.append(QPointF(w - r, selectionMarkerSize + r));
inner.append(QPointF(w - r, h - s));
inner.append(QPointF(w - s, h - r));
inner.append(QPointF(selectionMarkerSize + r, h - r));
inner.append(QPointF(r, h - selectionMarkerSize - r));
inner.append(QPointF(r, lh));
QPainterPath innerPath;
innerPath.addPolygon(inner);
QPainterPath result = outerPath.subtracted(innerPath);
return result.simplified();
}
| 19,009
|
C++
|
.cpp
| 478
| 31.857741
| 179
| 0.627571
|
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,412
|
statusbartoolbutton.cpp
|
KDE_umbrello/umbrello/umlwidgets/statusbartoolbutton.cpp
|
// vim: set tabstop=4 shiftwidth=4 noexpandtab:
/*
Widget taken from Gwenview
SPDX-FileCopyrightText: 2007 Aurélien Gâteau <agateau@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
// Self
#include "statusbartoolbutton.h"
// Qt
#include <QAction>
#include <QStyleOptionToolButton>
#include <QStylePainter>
#include <QToolButton>
// KDE
#include <KLocalizedString>
StatusBarToolButton::StatusBarToolButton(QWidget* parent)
: QToolButton(parent),
mGroupPosition(NotGrouped)
{
setToolButtonStyle(Qt::ToolButtonTextOnly);
setFocusPolicy(Qt::NoFocus);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
}
QSize StatusBarToolButton::minimumSizeHint() const
{
return sizeHint();
}
QSize StatusBarToolButton::sizeHint() const
{
QSize sh = QToolButton::sizeHint();
sh.setHeight(fontMetrics().height());
return sh;
}
void StatusBarToolButton::setGroupPosition(StatusBarToolButton::GroupPosition groupPosition)
{
mGroupPosition = groupPosition;
}
void StatusBarToolButton::paintEvent(QPaintEvent* event)
{
if (mGroupPosition == NotGrouped) {
QToolButton::paintEvent(event);
return;
}
QStylePainter painter(this);
QStyleOptionToolButton opt;
initStyleOption(&opt);
QStyleOptionToolButton panelOpt = opt;
// Panel
QRect& panelRect = panelOpt.rect;
switch (mGroupPosition) {
case GroupLeft:
panelRect.setWidth(panelRect.width() * 2);
break;
case GroupCenter:
panelRect.setLeft(panelRect.left() - panelRect.width());
panelRect.setWidth(panelRect.width() * 3);
break;
case GroupRight:
panelRect.setLeft(panelRect.left() - panelRect.width());
break;
case NotGrouped:
Q_ASSERT(0);
}
painter.drawPrimitive(QStyle::PE_PanelButtonTool, panelOpt);
// Separator
const int y1 = opt.rect.top() + 6;
const int y2 = opt.rect.bottom() - 6;
if (mGroupPosition & GroupRight) {
const int x = opt.rect.left();
painter.setPen(opt.palette.color(QPalette::Light));
painter.drawLine(x, y1, x, y2);
}
if (mGroupPosition & GroupLeft) {
const int x = opt.rect.right();
painter.setPen(opt.palette.color(QPalette::Mid));
painter.drawLine(x, y1, x, y2);
}
// Text
painter.drawControl(QStyle::CE_ToolButtonLabel, opt);
// Filtering message on tooltip text for CJK to remove accelerators.
// Quoting ktoolbar.cpp:
// """
// CJK languages use more verbose accelerator marker: they add a Latin
// letter in parenthesis, and put accelerator on that. Hence, the default
// removal of ampersand only may not be enough there, instead the whole
// parenthesis construct should be removed. Provide these filtering i18n
// messages so that translators can use Transcript for custom removal.
// """
if (!actions().isEmpty()) {
QAction* action = actions().first();
setToolTip(i18nc("@info:tooltip of custom toolbar button", "%1", action->toolTip()));
}
}
| 3,054
|
C++
|
.cpp
| 93
| 28.172043
| 93
| 0.703263
|
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,413
|
docbook2xhtmlgeneratorjob.cpp
|
KDE_umbrello/umbrello/docgenerators/docbook2xhtmlgeneratorjob.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "docbook2xhtmlgeneratorjob.h"
#include "debug_utils.h"
#include "file_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "xhtmlgenerator.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 <QStandardPaths>
#include <QTemporaryFile>
#include <QTextStream>
#include <QUrl>
DEBUG_REGISTER(Docbook2XhtmlGeneratorJob)
extern int xmlLoadExtDtdDefaultValue;
/**
* Constructor
* @param docBookUrl The Url of the Docbook that is to be converted to XHtml
* @param parent Parent object for QThread constructor
*/
Docbook2XhtmlGeneratorJob::Docbook2XhtmlGeneratorJob(QUrl& docBookUrl, QObject* parent)
:QThread(parent), m_docbookUrl(docBookUrl)
{
}
void Docbook2XhtmlGeneratorJob::run()
{
UMLDoc* umlDoc = UMLApp::app()->document();
xsltStylesheetPtr cur = nullptr;
xmlDocPtr doc, res;
const char *params[16 + 1];
int nbparams = 0;
params[nbparams] = nullptr;
umlDoc->writeToStatusBar(i18n("Exporting to XHTML..."));
QString xsltFileName = XhtmlGenerator::customXslFile();
// use public xml catalogs
xmlLoadCatalogs(File_Utils::xmlCatalogFilePath().toLocal8Bit().constData());
xmlSubstituteEntitiesDefault(1);
xmlLoadExtDtdDefaultValue = 1;
logDebug1("Docbook2XhtmlGeneratorJob::run: Parsing stylesheet %1", xsltFileName);
cur = xsltParseStylesheetFile((const xmlChar *)xsltFileName.toLatin1().constData());
logDebug1("Docbook2XhtmlGeneratorJob::run: Parsing file %1", m_docbookUrl.path());
doc = xmlParseFile((const char*)(m_docbookUrl.path().toUtf8().constData()));
logDebug0("Docbook2XhtmlGeneratorJob::run: Applying stylesheet");
res = xsltApplyStylesheet(cur, doc, params);
QTemporaryFile tmpXhtml;
tmpXhtml.setAutoRemove(false);
tmpXhtml.open();
logDebug1("Docbook2XhtmlGeneratorJob::run: Writing HTML result to temp file: %1",
tmpXhtml.fileName());
xsltSaveResultToFd(tmpXhtml.handle(), res, cur);
tmpXhtml.close();
xsltFreeStylesheet(cur);
xmlFreeDoc(res);
xmlFreeDoc(doc);
xsltCleanupGlobals();
xmlCleanupParser();
Q_EMIT xhtmlGenerated(tmpXhtml.fileName());
}
| 2,535
|
C++
|
.cpp
| 72
| 32.680556
| 92
| 0.772634
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.