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,211
|
errors.cpp
|
KDE_umbrello/lib/cppparser/errors.cpp
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2002, 2003 Roberto Raggi <roberto@kdevelop.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "errors.h"
#include <KLocalizedString>
Error& Errors::_InternalError()
{
static Error *error = nullptr;
if (error == nullptr)
error = new Error(1, -1, i18n("Internal Error"));
return *error;
}
Error &Errors::_SyntaxError()
{
static Error *error = nullptr;
if (error == nullptr)
error = new Error(2, -1, i18n("Syntax Error before '%1'"));
return *error;
}
Error &Errors::_ParseError()
{
static Error *error = nullptr;
if (error == nullptr)
error = new Error(3, -1, i18n("Parse Error before '%1'"));
return *error;
}
| 751
|
C++
|
.cpp
| 27
| 24.111111
| 75
| 0.653686
|
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,212
|
cachemanager.cpp
|
KDE_umbrello/lib/cppparser/cachemanager.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006 David Nolden <david.nolden.kdevelop@art-master.de>
*/
#include "cachemanager.h"
#define DBG_SRC QLatin1String("CacheManager")
#include "debug_utils.h"
DEBUG_REGISTER_DISABLED(CacheManager)
void CacheNode::access() const
{
m_manager->access(this);
}
void CacheManager::remove(const CacheNode* node)
{
m_set.erase(node);
}
void CacheManager::add(const CacheNode* node)
{
m_set.insert(node);
}
CacheNode::CacheNode(Manager* manager) : m_manager(manager), m_value(manager->currentMax()) //initialize m_value with the current maximum, so the new node has a chance even in a cache full of high-rated nodes
{
m_manager->add(this);
}
CacheNode::~CacheNode()
{
m_manager->remove(this);
};
void CacheManager::restart(unsigned int normalizeby)
{
m_currentFrame = 1;
m_currentMax = 1;
SetType oldSet = m_set;
m_set = SetType();
for (SetType::iterator it = oldSet.begin(); it != oldSet.end(); ++it) {
unsigned int newValue = (*it)->value() / (normalizeby / 1000);
if (newValue > m_currentMax) m_currentMax = newValue;
(*it)->setValue(newValue); ///This way not all information is discarded
m_set.insert(*it);
}
}
void CacheManager::access(const CacheNode* node)
{
static const unsigned int limit = (std::numeric_limits<unsigned int>::max() / 3)*2;
m_set.erase(node);
node->setValue(m_currentMax+1);
m_set.insert(node);
if (node->value() > m_currentMax)
m_currentMax = node->value();
if (node->value() > limit)
restart(node->value());
}
void CacheManager::setMaxNodes (int maxNodes)
{
m_maxNodes = maxNodes;
increaseFrame();
}
void CacheManager::increaseFrame()
{
m_currentFrame ++;
if (m_set.size() > m_maxNodes) {
DEBUG() << "Have " << m_set.size() << " nodes, maximum is " << m_maxNodes << ", erasing." ;
int mustErase = m_set.size() - m_maxNodes;
while (!m_set.empty() && mustErase != 0) {
--mustErase;
SetType::iterator it = m_set.begin();
erase(*it);
}
DEBUG() << "Have " << m_set.size() << " nodes after erasing." ;
}
}
void CacheManager::removeLowerHalf()
{
int maxNodes = m_maxNodes;
setMaxNodes(m_set.size() / 2);
setMaxNodes(maxNodes);
}
void CacheManager::saveMemory()
{
removeLowerHalf();
}
| 2,416
|
C++
|
.cpp
| 81
| 25.740741
| 210
| 0.652305
|
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,213
|
codemodel_treeparser.cpp
|
KDE_umbrello/lib/interfaces/codemodel_treeparser.cpp
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2003 Roberto Raggi <roberto@kdevelop.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "codemodel_treeparser.h"
#include "codemodel.h"
CodeModelTreeParser::CodeModelTreeParser()
{
}
CodeModelTreeParser::~CodeModelTreeParser()
{
}
void CodeModelTreeParser::parseCode(const CodeModel * model)
{
const FileList fileList = model->fileList();
for (FileList::ConstIterator it=fileList.begin(); it!=fileList.end(); ++it)
parseFile(*it);
}
void CodeModelTreeParser::parseFile(const FileModel * file)
{
const NamespaceList namespaceList = file->namespaceList();
const ClassList classList = file->classList();
const FunctionList functionList = file->functionList();
const FunctionDefinitionList functionDefinitionList = file->functionDefinitionList();
const VariableList variableList = file->variableList();
for (NamespaceList::ConstIterator it=namespaceList.begin(); it!=namespaceList.end(); ++it)
parseNamespace(*it);
for (ClassList::ConstIterator it=classList.begin(); it!=classList.end(); ++it)
parseClass(*it);
for (FunctionList::ConstIterator it=functionList.begin(); it!=functionList.end(); ++it)
parseFunction(*it);
for (FunctionDefinitionList::ConstIterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
parseFunctionDefinition(*it);
for (VariableList::ConstIterator it=variableList.begin(); it!=variableList.end(); ++it)
parseVariable(*it);
}
void CodeModelTreeParser::parseNamespace(const NamespaceModel * ns)
{
const NamespaceList namespaceList = ns->namespaceList();
const ClassList classList = ns->classList();
const FunctionList functionList = ns->functionList();
const FunctionDefinitionList functionDefinitionList = ns->functionDefinitionList();
const VariableList variableList = ns->variableList();
for (NamespaceList::ConstIterator it=namespaceList.begin(); it!=namespaceList.end(); ++it)
parseNamespace(*it);
for (ClassList::ConstIterator it=classList.begin(); it!=classList.end(); ++it)
parseClass(*it);
for (FunctionList::ConstIterator it=functionList.begin(); it!=functionList.end(); ++it)
parseFunction(*it);
for (FunctionDefinitionList::ConstIterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
parseFunctionDefinition(*it);
for (VariableList::ConstIterator it=variableList.begin(); it!=variableList.end(); ++it)
parseVariable(*it);
}
void CodeModelTreeParser::parseClass(const ClassModel * klass)
{
const ClassList classList = klass->classList();
const FunctionList functionList = klass->functionList();
const FunctionDefinitionList functionDefinitionList = klass->functionDefinitionList();
const VariableList variableList = klass->variableList();
for (ClassList::ConstIterator it=classList.begin(); it!=classList.end(); ++it)
parseClass(*it);
for (FunctionList::ConstIterator it=functionList.begin(); it!=functionList.end(); ++it)
parseFunction(*it);
for (FunctionDefinitionList::ConstIterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
parseFunctionDefinition(*it);
for (VariableList::ConstIterator it=variableList.begin(); it!=variableList.end(); ++it)
parseVariable(*it);
}
void CodeModelTreeParser::parseFunction(const FunctionModel * /*fun*/)
{
}
void CodeModelTreeParser::parseFunctionDefinition(const FunctionDefinitionModel * /*fun*/)
{
}
void CodeModelTreeParser::parseVariable(const VariableModel * /*var*/)
{
}
| 3,663
|
C++
|
.cpp
| 78
| 42.564103
| 121
| 0.743834
|
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,214
|
hashedstring.cpp
|
KDE_umbrello/lib/interfaces/hashedstring.cpp
|
/*
SPDX-FileCopyrightText: 2006 David Nolden <david.nolden.kdevelop@art-master.de>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "hashedstring.h"
#include <kdatastream.h>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <set>
//It needs to be measured whether this flag should be turned on or off. It seems just to move the complexity from one position to the other, without any variant being really better.
#define USE_HASHMAP
size_t fastHashString(const QString& str);
size_t hashStringSafe(const QString& str)
{
size_t hash = 0;
int len = str.length();
for (int a = 0; a < len; a++) {
hash = str[a].unicode() + (hash * 17);
}
return hash;
}
size_t HashedString::hashString(const QString& str)
{
return fastHashString(str);
}
size_t fastHashString(const QString& str)
{
size_t hash = 0;
if (!str.isEmpty()) {
const QChar* curr = str.unicode();
const QChar* end = curr + str.length();
QChar c;
for (; curr < end ;) {
c = *curr;
hash = c.unicode() + (hash * 17);
++curr;
}
}
return hash;
}
void HashedString::initHash()
{
m_hash = hashString(m_str);
}
class HashedStringSetData : public QSharedData
{
public:
#ifdef USE_HASHMAP
typedef QSet<HashedString> StringSet;
#else
typedef QSet<HashedString> StringSet; //must be a set, so the set-algorithms work
#endif
StringSet m_files;
mutable bool m_hashValid;
mutable size_t m_hash;
HashedStringSetData()
: m_hashValid(false),
m_hash(0)
{
}
inline void invalidateHash()
{
m_hashValid = false;
}
void computeHash() const;
};
void HashedStringSetData::computeHash() const
{
int num = 1;
m_hash = 0;
for (StringSet::const_iterator it = m_files.begin(); it != m_files.end(); ++it) {
num *= 7;
m_hash += num * (*it).hash();
}
m_hashValid = true;
}
HashedStringSet::HashedStringSet() {}
HashedStringSet::~HashedStringSet() {}
HashedStringSet::HashedStringSet(const HashedString& file)
{
insert(file);
}
HashedStringSet::HashedStringSet(const HashedStringSet& rhs) : m_data(rhs.m_data) {}
HashedStringSet operator + (const HashedStringSet& lhs, const HashedStringSet& rhs)
{
HashedStringSet ret = lhs;
ret += rhs;
return ret;
}
int HashedStringSet::size() const
{
if (!m_data) return 0;
return m_data->m_files.size();
}
HashedStringSet& HashedStringSet::operator = (const HashedStringSet& rhs)
{
m_data = rhs.m_data;
return *this;
}
HashedStringSet& HashedStringSet::operator +=(const HashedStringSet& rhs)
{
if (!rhs.m_data)
return * this;
#ifndef USE_HASHMAP
QExplicitlySharedDataPointer<HashedStringSetData> oldData = m_data;
if (!oldData) oldData = new HashedStringSetData();
m_data = new HashedStringSetData();
std::set_union(oldData->m_files.begin(), oldData->m_files.end(), rhs.m_data->m_files.begin(), rhs.m_data->m_files.end(), std::insert_iterator<HashedStringSetData::StringSet>(m_data->m_files, m_data->m_files.end()));
#else
makeDataPrivate();
for (HashedStringSetData::StringSet::const_iterator it = rhs.m_data->m_files.begin(); it != rhs.m_data->m_files.end(); ++it) {
m_data->m_files.insert(*it);
}
/*HashedStringSetData::StringSet::const_iterator end = rhs.m_data->m_files.end();
HashedStringSetData::StringSet& mySet(m_data->m_files);
for(HashedStringSetData::StringSet::const_iterator it = rhs.m_data->m_files.begin(); it != end; ++it) {
mySet.insert(*it);
}*/
#endif
return *this;
}
HashedStringSet& HashedStringSet::operator -=(const HashedStringSet& rhs)
{
if (!m_data) return *this;
if (!rhs.m_data) return *this;
#ifndef USE_HASHMAP
QExplicitlySharedDataPointer<HashedStringSetData> oldData = m_data;
m_data = new HashedStringSetData();
std::set_difference(oldData->m_files.begin(), oldData->m_files.end(), rhs.m_data->m_files.begin(), rhs.m_data->m_files.end(), std::insert_iterator<HashedStringSetData::StringSet>(m_data->m_files, m_data->m_files.end()));
#else
makeDataPrivate();
HashedStringSetData::StringSet::const_iterator end = rhs.m_data->m_files.end();
HashedStringSetData::StringSet& mySet(m_data->m_files);
for (HashedStringSetData::StringSet::const_iterator it = rhs.m_data->m_files.begin(); it != end; ++it) {
mySet.remove(*it);
}
#endif
return *this;
}
void HashedStringSet::makeDataPrivate()
{
if (!m_data) {
m_data = new HashedStringSetData();
return ;
}
m_data.detach();
}
bool HashedStringSet::operator[] (const HashedString& rhs) const
{
//if (rhs.str() == "*")
//return true; /// * stands for "any file"
if (!m_data)
return false;
return m_data->m_files.find(rhs) != m_data->m_files.end();
}
void HashedStringSet::insert(const HashedString& str)
{
if (str.str().isEmpty()) return;
makeDataPrivate();
m_data->m_files.insert(str);
m_data->invalidateHash();
}
bool HashedStringSet::operator <= (const HashedStringSet& rhs) const
{
if (!m_data)
return true;
if (m_data->m_files.empty())
return true;
if (!rhs.m_data)
return false;
#ifndef USE_HASHMAP
return std::includes(rhs.m_data->m_files.begin(), rhs.m_data->m_files.end(), m_data->m_files.begin(), m_data->m_files.end());
#else
const HashedStringSetData::StringSet& otherSet(rhs.m_data->m_files);
HashedStringSetData::StringSet::const_iterator end = rhs.m_data->m_files.end();
HashedStringSetData::StringSet::const_iterator myEnd = m_data->m_files.end();
for (HashedStringSetData::StringSet::const_iterator it = m_data->m_files.begin(); it != myEnd; ++it) {
HashedStringSetData::StringSet::const_iterator i = otherSet.find(*it);
if (i == end) return false;
}
return true;
#endif
}
bool HashedStringSet::operator == (const HashedStringSet& rhs) const
{
if (hash() != rhs.hash()) return false;
bool empty1 = false;
if (!m_data)
empty1 = true;
else if (m_data->m_files.empty())
empty1 = true;
bool empty2 = false;
if (!rhs.m_data)
empty2 = true;
else if (rhs.m_data->m_files.empty())
empty2 = true;
if (empty1 && empty2)
return true;
if (empty1 || empty2)
return false;
return m_data->m_files == rhs.m_data->m_files;
}
size_t HashedStringSet::hash() const
{
if (!m_data) return 0;
if (!m_data->m_hashValid) m_data->computeHash();
return m_data->m_hash;
}
void HashedStringSet::read(QDataStream& stream)
{
bool b;
stream >> b;
if (b) {
m_data = new HashedStringSetData();
int cnt;
stream >> cnt;
HashedString s;
for (int a = 0; a < cnt; a++) {
stream >> s;
m_data->m_files.insert(s);
}
} else {
m_data = nullptr;
}
}
void HashedStringSet::write(QDataStream& stream) const
{
bool b = m_data;
stream << b;
if (b) {
int cnt = m_data->m_files.size();
stream << cnt;
for (HashedStringSetData::StringSet::const_iterator it = m_data->m_files.begin(); it != m_data->m_files.end(); ++it) {
stream << *it;
}
}
}
std::string HashedStringSet::print() const
{
std::ostringstream s;
if (m_data) {
for (HashedStringSetData::StringSet::const_iterator it = m_data->m_files.begin(); it != m_data->m_files.end(); ++it) {
s << (*it).str().toLatin1().data() << "\n";
}
}
return s.str();
}
QDataStream& operator << (QDataStream& stream, const HashedString& str)
{
stream << str.m_str;
stream << str.m_hash;
return stream;
}
QDataStream& operator >> (QDataStream& stream, HashedString& str)
{
stream >> str.m_str;
stream >> str.m_hash;
return stream;
}
void HashedStringSetGroup::addSet(size_t id, const HashedStringSet& set)
{
if (set.m_data && !set.m_data->m_files.empty()) {
m_sizeMap[ id ] = set.size();
for (HashedStringSetData::StringSet::const_iterator it = set.m_data->m_files.begin(); it != set.m_data->m_files.end(); ++it) {
GroupMap::iterator itr = m_map.find(*it);
if (itr == m_map.end()) {
itr = m_map.insert(*it, ItemSet());
}
itr->insert(id);
}
} else {
m_global.insert(id);
}
}
void HashedStringSetGroup::disableSet(size_t id)
{
m_disabled.insert(id);
}
void HashedStringSetGroup::enableSet(size_t id)
{
m_disabled.erase(id);
}
bool HashedStringSetGroup::isDisabled(size_t id) const
{
return m_disabled.find(id) != m_disabled.end();
}
void HashedStringSetGroup::removeSet(size_t id)
{
m_disabled.erase(id);
m_global.erase(id);
m_sizeMap.remove(id);
for (GroupMap::iterator it = m_map.begin(); it != m_map.end(); ++it) {
it->erase(id);
}
}
void HashedStringSetGroup::findGroups(HashedStringSet strings, ItemSet& target) const
{
target.clear();
if (!strings.m_data) {
std::set_difference(m_global.begin(), m_global.end(), m_disabled.begin(), m_disabled.end(), std::insert_iterator<ItemSet>(target, target.end()));
return;
}
//This might yet be optimized by sorting the sets according to their size, and starting the intersectioning with the smallest ones.
QHash<size_t, uint> hitCounts;
for (HashedStringSetData::StringSet::const_iterator it = strings.m_data->m_files.begin(); it != strings.m_data->m_files.end(); ++it) {
GroupMap::const_iterator itr = m_map.find(*it);
if (itr == m_map.end()) {
//There are no string-sets that include the currently searched for string
continue;
}
for (ItemSet::const_iterator it2 = itr->begin(); it2 != itr->end(); ++it2) {
QHash<size_t, uint>::iterator v = hitCounts.find(*it2);
if (v != hitCounts.end()) {
++(*v);
} else {
hitCounts[*it2] = 1;
}
}
}
//Now count together all groups that are completely within the given string-set(their hitCount equals their size)
ItemSet found;
for (QHash<size_t, uint>::const_iterator it = hitCounts.constBegin(); it != hitCounts.constEnd(); ++it) {
if (it.value() == (*m_sizeMap.find(it.key())))
found.insert(it.key());
}
std::set_union(found.begin(), found.end(), m_global.begin(), m_global.end(), std::insert_iterator<ItemSet>(target, target.end()));
target.swap(found);
target.clear();
std::set_difference(found.begin(), found.end(), m_disabled.begin(), m_disabled.end(), std::insert_iterator<ItemSet>(target, target.end()));
}
uint qHash(const HashedString &key)
{
return key.hash();
}
| 10,834
|
C++
|
.cpp
| 335
| 27.397015
| 224
| 0.639001
|
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,215
|
codemodel_utils.cpp
|
KDE_umbrello/lib/interfaces/codemodel_utils.cpp
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2003 Roberto Raggi <roberto@kdevelop.org>
SPDX-FileCopyrightText: 2003 Alexander Dymo <adymo@kdevelop.org>
SPDX-FileCopyrightText: 2004 Jonas Jacobi <j.jacobi@gmx.de>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "codemodel_utils.h"
namespace CodeModelUtils
{
namespace Functions
{
void processClasses(FunctionList &list, const ClassDom dom)
{
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
}
}
void processNamespaces(FunctionList &list, const NamespaceDom dom)
{
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list, *it);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
}
}
void processNamespaces(FunctionList & list, const NamespaceDom dom, QMap< FunctionDom, Scope > & relations)
{
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list, *it, relations);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it, relations, dom);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
relations[*it].ns = dom;
}
}
void processClasses(FunctionList & list, const ClassDom dom, QMap< FunctionDom, Scope > & relations)
{
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it, relations);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
relations[*it].klass = dom;
}
}
void processClasses(FunctionList & list, const ClassDom dom, QMap< FunctionDom, Scope > & relations, const NamespaceDom & nsdom)
{
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it, relations, nsdom);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
relations[*it].klass = dom;
relations[*it].ns = nsdom;
}
}
} // end of Functions namespace
namespace FunctionDefinitions
{
void processClasses(FunctionDefinitionList &list, const ClassDom dom)
{
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it);
}
const FunctionDefinitionList fnlist = dom->functionDefinitionList();
for (FunctionDefinitionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
}
}
void processNamespaces(FunctionDefinitionList &list, const NamespaceDom dom)
{
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list, *it);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it);
}
const FunctionDefinitionList fnlist = dom->functionDefinitionList();
for (FunctionDefinitionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
}
}
void processNamespaces(FunctionDefinitionList & list, const NamespaceDom dom, QMap< FunctionDefinitionDom, Scope > & relations)
{
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list, *it, relations);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it, relations, dom);
}
const FunctionDefinitionList fnlist = dom->functionDefinitionList();
for (FunctionDefinitionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
relations[*it].ns = dom;
}
}
void processClasses(FunctionDefinitionList & list, const ClassDom dom, QMap< FunctionDefinitionDom, Scope > & relations)
{
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it, relations);
}
const FunctionDefinitionList fnlist = dom->functionDefinitionList();
for (FunctionDefinitionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
relations[*it].klass = dom;
}
}
void processClasses(FunctionDefinitionList & list, const ClassDom dom, QMap< FunctionDefinitionDom, Scope > & relations, const NamespaceDom & nsdom)
{
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it, relations, nsdom);
}
const FunctionDefinitionList fnlist = dom->functionDefinitionList();
for (FunctionDefinitionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
relations[*it].klass = dom;
relations[*it].ns = nsdom;
}
}
} // end of FunctionDefinitions namespace
FunctionList allFunctions(const FileDom &dom)
{
using namespace Functions;
FunctionList list;
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list, *it);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list, *it);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.append(*it);
}
return list;
}
AllFunctions allFunctionsDetailed(const FileDom & dom)
{
using namespace Functions;
AllFunctions list;
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list.functionList, *it, list.relations);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list.functionList, *it, list.relations);
}
const FunctionList fnlist = dom->functionList();
for (FunctionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.functionList.append(*it);
}
return list;
}
AllFunctionDefinitions allFunctionDefinitionsDetailed(const FileDom & dom)
{
using namespace FunctionDefinitions;
AllFunctionDefinitions list;
const NamespaceList nslist = dom->namespaceList();
for (NamespaceList::ConstIterator it = nslist.begin(); it != nslist.end(); ++it) {
processNamespaces(list.functionList, *it, list.relations);
}
const ClassList cllist = dom->classList();
for (ClassList::ConstIterator it = cllist.begin(); it != cllist.end(); ++it) {
processClasses(list.functionList, *it, list.relations);
}
const FunctionDefinitionList fnlist = dom->functionDefinitionList();
for (FunctionDefinitionList::ConstIterator it = fnlist.begin(); it != fnlist.end(); ++it) {
list.functionList.append(*it);
}
return list;
}
bool resultTypesFit(const FunctionDom & dec, const FunctionDefinitionDom & def)
{
if (!def->resultType().contains("::")) return dec->resultType() == def->resultType();
QStringList l1 = dec->scope() + QStringList::split("::", dec->resultType());
QStringList l2 = QStringList::split("::", def->resultType());
if (l1.isEmpty() || l2.isEmpty() || l1.back() != l2.back()) return false;
while (!l1.isEmpty() && !l2.isEmpty()) {
if (l1.back() == l2.back()) {
l1.pop_back();
l2.pop_back();
} else {
l1.pop_back();
}
}
if (l2.isEmpty()) return true;
return false;
}
bool compareDeclarationToDefinition(const FunctionDom & dec, const FunctionDefinitionDom & def)
{
if (dec->scope() == def->scope() && dec->name() == def->name() && resultTypesFit(dec, def) && dec->isConstant() == def->isConstant()) {
const ArgumentList defList = def->argumentList(), decList = dec->argumentList();
if (defList.size() != decList.size())
return false;
size_t n = defList.size();
for (size_t i = 0; i < n; ++i)
if (defList[i]->type() != decList[i]->type())
return false;
return true;
}
return false;
}
bool compareDeclarationToDefinition(const FunctionDom & dec, const FunctionDefinitionDom & def, const std::set<NamespaceImportModel> & nsImports)
{
if (dec->name() == def->name() && resultTypesFit(dec, def) && dec->isConstant() == def->isConstant()) {
const ArgumentList defList = def->argumentList(), decList = dec->argumentList();
if (defList.size() != decList.size())
return false;
size_t n = defList.size();
for (size_t i = 0; i < n; ++i)
if (defList[i]->type() != decList[i]->type())
return false;
const QStringList &defScope = def->scope(), &decScope = dec->scope();
if (defScope != decScope) {
if (defScope.size() >= decScope.size())
return false;
n = decScope.size();
for (size_t i1 = 0, i2 = 0; i1 < n; ++i1) {
if (i2 >= defScope.size() || decScope[i1] != defScope[i2]) {
NamespaceImportModel model;
model.setName(decScope[i1]);
model.setFileName(def->fileName());
if (nsImports.find(model) == nsImports.end())
return false;
} else {
++i2;
}
}
}
return true;
}
return false;
}
FunctionList allFunctionsExhaustive(FileDom &dom)
{
PredAmOwner<FunctionDom> ow(dom);
FunctionList ret;
findFunctionDeclarations(ow, dom->wholeGroup(), ret);
return ret;
}
FunctionDefinitionList allFunctionDefinitionsExhaustive(FileDom &dom)
{
PredAmOwner<FunctionDefinitionDom> ow(dom);
FunctionDefinitionList ret;
findFunctionDefinitions(ow, dom->wholeGroup(), ret);
return ret;
}
ClassDom findClassByPosition(NamespaceModel* nameSpace, int line, int col)
{
if (nameSpace == 0)
return 0;
NamespaceList nsList = nameSpace->namespaceList();
for (NamespaceList::iterator i = nsList.begin(); i != nsList.end(); ++i) {
ClassDom result = findClassByPosition(*i, line, col);
if (result != 0)
return result;
}
ClassList classes = nameSpace->classList();
for (ClassList::iterator i = classes.begin(); i != classes.end(); ++i) {
ClassDom result = findClassByPosition(*i, line, col);
if (result != 0)
return result;
}
return 0;
}
ClassDom findClassByPosition(ClassModel* aClass, int line, int col)
{
if (aClass == 0)
return 0;
ClassList classes = aClass->classList();
for (ClassList::iterator i = classes.begin(); i != classes.end(); ++i) {
ClassDom result = findClassByPosition(*i, line, col);
if (result != 0)
return result;
}
int startLine, startCol;
aClass->getStartPosition(&startLine, &startCol);
if (startLine <= line) {
int endLine, endCol;
aClass->getEndPosition(&endLine, &endCol);
if (endLine >= line)
return (aClass);
}
return 0;
}
int findLastMethodLine(ClassDom aClass, CodeModelItem::Access access)
{
int point = -1;
const FunctionList functionList = aClass->functionList();
for (FunctionList::ConstIterator it=functionList.begin(); it!=functionList.end(); ++it) {
int funEndLine, funEndColumn;
(*it)->getEndPosition(&funEndLine, &funEndColumn);
if ((*it)->access() == access && point < funEndLine)
point = funEndLine;
}
return point;
}
int findLastVariableLine(ClassDom aClass, CodeModelItem::Access access)
{
int point = -1;
const VariableList varList = aClass->variableList();
for (VariableList::ConstIterator it= varList.begin(); it!= varList.end(); ++it) {
int varEndLine, varEndColumn;
(*it)->getEndPosition(&varEndLine, &varEndColumn);
if ((*it)->access() == access && point < varEndLine)
point = varEndLine;
}
return point;
}
QString accessSpecifierToString(CodeModelItem::Access access)
{
switch (access) {
case CodeModelItem::Public:
return "public";
case CodeModelItem::Protected:
return "protected";
case CodeModelItem::Private:
return "private";
default:
return "unknown";
}
}
FunctionDefinitionDom CodeModelHelper::functionDefinitionAt(NamespaceDom ns, int line, int column)
{
NamespaceList namespaceList = ns->namespaceList();
NamespaceList::iterator nslEnd = namespaceList.end();
for (NamespaceList::iterator it=namespaceList.begin(); it!=nslEnd; ++it) {
if (FunctionDefinitionDom def = functionDefinitionAt(*it, line, column))
return def;
}
ClassList classList = ns->classList();
ClassList::iterator clEnd = classList.end();
for (ClassList::iterator it=classList.begin(); it!=clEnd; ++it) {
if (FunctionDefinitionDom def = functionDefinitionAt(*it, line, column))
return def;
}
FunctionDefinitionList functionDefinitionList = ns->functionDefinitionList();
FunctionDefinitionList::iterator fdlEnd = functionDefinitionList.end();
for (FunctionDefinitionList::iterator it=functionDefinitionList.begin();
it!=fdlEnd; ++it) {
if (FunctionDefinitionDom def = functionDefinitionAt(*it, line, column))
return def;
}
return FunctionDefinitionDom();
}
FunctionDefinitionDom CodeModelHelper::functionDefinitionAt(ClassDom klass, int line, int column)
{
ClassList classList = klass->classList();
ClassList::iterator clEnd = classList.end();
for (ClassList::iterator it=classList.begin(); it!=clEnd; ++it) {
if (FunctionDefinitionDom def = functionDefinitionAt(*it, line, column))
return def;
}
FunctionDefinitionList functionDefinitionList = klass->functionDefinitionList();
FunctionDefinitionList::iterator fdlEnd = functionDefinitionList.end();
for (FunctionDefinitionList::Iterator it=functionDefinitionList.begin();
it!=fdlEnd; ++it) {
if (FunctionDefinitionDom def = functionDefinitionAt(*it, line, column))
return def;
}
return FunctionDefinitionDom();
}
FunctionDefinitionDom CodeModelHelper::functionDefinitionAt(FunctionDefinitionDom fun, int line, int // column
)
{
int startLine, startColumn;
int endLine, endColumn;
fun->getStartPosition(&startLine, &startColumn);
fun->getEndPosition(&endLine, &endColumn);
if (!(line >= startLine && line <= endLine) || fun->fileName() != m_fileName)
return FunctionDefinitionDom();
/*
if (line == startLine && column < startColumn)
return FunctionDefinitionDom();
if (line == endLine && column > endColumn)
return FunctionDefinitionDom();*/
return fun;
}
FunctionDom CodeModelHelper::functionDeclarationAt(NamespaceDom ns, int line, int column)
{
NamespaceList namespaceList = ns->namespaceList();
NamespaceList::iterator nsEnd = namespaceList.end();
for (NamespaceList::iterator it=namespaceList.begin(); it!=nsEnd; ++it) {
if (FunctionDom def = functionDeclarationAt(*it, line, column))
return def;
}
ClassList classList = ns->classList();
ClassList::iterator clEnd = classList.end();
for (ClassList::iterator it=classList.begin(); it!=clEnd; ++it) {
if (FunctionDom def = functionDeclarationAt(*it, line, column))
return def;
}
FunctionList functionList = ns->functionList();
FunctionList::iterator flEnd = functionList.end();
for (FunctionList::iterator it=functionList.begin();
it!=flEnd; ++it) {
if (FunctionDom def = functionDeclarationAt(*it, line, column))
return def;
}
return FunctionDom();
}
FunctionDom CodeModelHelper::functionDeclarationAt(ClassDom klass, int line, int column)
{
ClassList classList = klass->classList();
ClassList::iterator clEnd = classList.end();
for (ClassList::iterator it=classList.begin(); it!=clEnd; ++it) {
if (FunctionDom def = functionDeclarationAt(*it, line, column))
return def;
}
FunctionList functionList = klass->functionList();
FunctionList::iterator flEnd = functionList.end();
for (FunctionList::Iterator it=functionList.begin();
it!=flEnd; ++it) {
if (FunctionDom def = functionDeclarationAt(*it, line, column))
return def;
}
return FunctionDom();
}
FunctionDom CodeModelHelper::functionDeclarationAt(FunctionDom fun, int line, int // column
)
{
int startLine, startColumn;
int endLine, endColumn;
fun->getStartPosition(&startLine, &startColumn);
fun->getEndPosition(&endLine, &endColumn);
if (!(line >= startLine && line <= endLine) || fun->fileName() != m_fileName)
return FunctionDom();
/* if (line == startLine && column < startColumn)
return FunctionDom();
if (line == endLine && column > endColumn)
return FunctionDom();*/
return fun;
}
ClassDom CodeModelHelper::classAt(NamespaceDom ns, int line, int column)
{
NamespaceList namespaceList = ns->namespaceList();
NamespaceList::iterator nsEnd = namespaceList.end();
for (NamespaceList::iterator it=namespaceList.begin(); it!=nsEnd; ++it) {
if (ClassDom def = classAt(*it, line, column))
return def;
}
ClassList classList = ns->classList();
ClassList::iterator clEnd = classList.end();
for (ClassList::iterator it=classList.begin(); it!=clEnd; ++it) {
if (ClassDom def = classAt(*it, line, column))
return def;
}
return ClassDom();
}
ClassDom CodeModelHelper::classAt(ClassDom klass, int line, int column)
{
ClassList classList = klass->classList();
ClassList::iterator clEnd = classList.end();
for (ClassList::iterator it=classList.begin(); it!=clEnd; ++it) {
if (ClassDom def = classAt(*it, line, column))
return def;
}
int startLine, startColumn;
int endLine, endColumn;
klass->getStartPosition(&startLine, &startColumn);
klass->getEndPosition(&endLine, &endColumn);
if (!(line >= startLine && line <= endLine) || klass->fileName() != m_fileName)
return ClassDom();
return klass;
}
CodeModelHelper::CodeModelHelper(CodeModel* model, FileDom file) : m_model(model)
{
if (!file) return;
m_files = file->wholeGroup();
m_fileName = file->name();
}
FunctionDom CodeModelHelper::functionAt(int line, int column, FunctionTypes types)
{
if (m_files.isEmpty()) return FunctionDom();
FunctionDom ret;
FileList::iterator it = m_files.begin();
while (it != m_files.end()) {
if (types & Declaration) {
ret = functionDeclarationAt(model_cast<NamespaceDom>(*it), line, column);
if (ret) return ret;
}
if (types & Definition) {
FunctionDefinitionDom r = functionDefinitionAt(model_cast<NamespaceDom>(*it), line, column);
if (r) {
ret = model_cast<FunctionDom>(r);
return ret;
}
}
++it;
}
return ret;
}
ClassDom CodeModelHelper::classAt(int line, int column)
{
if (m_files.isEmpty()) return ClassDom();
ClassDom ret;
FileList::iterator it = m_files.begin();
while (it != m_files.end()) {
ret = classAt(model_cast<NamespaceDom>(*it), line, column);
if (ret) return ret;
++it;
}
return ret;
}
}//end of namespace CodeModeUtils
| 21,313
|
C++
|
.cpp
| 537
| 33.392924
| 148
| 0.653546
|
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,216
|
codemodel.cpp
|
KDE_umbrello/lib/interfaces/codemodel.cpp
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2003 Roberto Raggi <roberto@kdevelop.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "codemodel.h"
#include "debug_utils.h"
#include "driver.h"
#include <kdatastream.h>
///Little helper-functions to save a lot of typing and possible errors
template<class MapContainer>
bool eachCanUpdate(const MapContainer& old, const MapContainer& newMap)
{
if (old.size() != newMap.size()) return false;
typename MapContainer::const_iterator oldIt = old.begin();
typename MapContainer::const_iterator newIt = newMap.begin();
while (oldIt != old.end()) {
typedef typename MapContainer::mapped_type ListType;
if ((*oldIt).size() != (*newIt).size()) return false;
typename ListType::const_iterator it1 = (*oldIt).begin();
typename ListType::const_iterator it2 = (*newIt).begin();
while (it1 != (*oldIt).end()) {
if (!(*it1)->canUpdate(*it2)) return false;
++it1;
++it2;
}
++oldIt;
++newIt;
}
return true;
}
template<class MapContainer>
void eachUpdate(MapContainer& old, const MapContainer& newMap)
{
if (old.size() != newMap.size()) uError() << "error in eachUpdate(...) 1" ;
typename MapContainer::iterator oldIt = old.begin();
typename MapContainer::const_iterator newIt = newMap.begin();
while (oldIt != old.end()) {
if ((*oldIt).size() != (*newIt).size()) uError() << "error in eachUpdate(...) 2" ;
typedef typename MapContainer::mapped_type ListType;
typename ListType::iterator it1 = (*oldIt).begin();
typename ListType::const_iterator it2 = (*newIt).begin();
while (it1 != (*oldIt).end()) {
(*it1)->update(*it2);
++it1;
++it2;
}
++oldIt;
++newIt;
}
}
///Versions for contains that do not contain maps again
template<class MapContainer>
bool eachCanUpdateSingle(const MapContainer& old, const MapContainer& newMap)
{
if (old.size() != newMap.size()) return false;
typename MapContainer::const_iterator oldIt = old.begin();
typename MapContainer::const_iterator newIt = newMap.begin();
while (oldIt != old.end()) {
if (!(*oldIt)->canUpdate(*newIt)) return false;
++oldIt;
++newIt;
}
return true;
}
template<class MapContainer>
void eachUpdateSingle(MapContainer& old, const MapContainer& newMap)
{
if (old.size() != newMap.size()) uError() << "error in eachUpdate(...) 1" ;
typename MapContainer::iterator oldIt = old.begin();
typename MapContainer::const_iterator newIt = newMap.begin();
while (oldIt != old.end()) {
(*oldIt)->update(*newIt);
++oldIt;
++newIt;
}
}
CodeModel::CodeModel()
{
wipeout();
m_currentGroupId = 1; ///0 stands for invalid group
}
CodeModel::~ CodeModel()
{
}
int CodeModel::newGroupId()
{
return (m_currentGroupId++) * 2;
}
inline bool isSingleGroup(const int group)
{
return (group % 2) == 0;
}
QStringList CodeModel::getGroupStrings(int gid) const
{
QStringList ret;
for (QMap<QString, FileDom>::ConstIterator it = m_files.begin(); it != m_files.end(); ++it) {
if ((*it)->groupId() == gid) ret.append((*it)-> name());
}
return ret;
}
FileList CodeModel::getGroup(int gid) const
{
FileList ret;
for (QMap<QString, FileDom>::ConstIterator it = m_files.begin(); it != m_files.end(); ++it) {
if ((*it)->groupId() == gid) ret.append(*it);
}
return ret;
}
FileList CodeModel::getGroup(const FileDom& dom) const
{
return getGroup(dom->groupId());
}
int CodeModel::mergeGroups(int g1, int g2)
{
if (!g1 || !g2) return 0;
if (g1 == g2) return g1;
int ng = isSingleGroup(g1) ? g2 : g1;
if (isSingleGroup(ng))
ng = newGroupId() + 1;
for (QMap<QString, FileDom>::iterator it = m_files.begin(); it != m_files.end(); ++it) {
if ((*it)->groupId() == g2 || (*it)->groupId() == g1) (*it)->setGroupId(ng);
}
return ng;
}
template<class Type> static void dumpMap(std::ostream& file, QMap<QString, Type>& map)
{
typename QMap<QString, Type>::Iterator it = map.begin();
for (; it != map.end(); ++it) {
typename Type::Iterator it2 = (*it).begin();
for (; it2 != (*it).end(); ++it2) {
(*it2) -> dump(file, true);
}
}
}
template<class Type> static void dumpMapDirect(std::ostream& file, QMap<QString, Type>& map)
{
typename QMap<QString, Type>::Iterator it = map.begin();
for (; it != map.end(); ++it) {
(*it) -> dump(file, true);
}
}
void CodeModelItem::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "name: " << name().ascii() << "\n";
str << "kind: " << m_kind << " ";
if (isFile()) str << "isFile ";
if (isNamespace()) str << "isNamespace ";
if (isClass()) str << "isClass ";
if (isFunction()) str << "isFunction ";
if (isFunctionDefinition()) str << "isFunctionDefinition ";
if (isVariable()) str << "isVariable ";
if (isArgument()) str << "isArgument ";
if (isEnum()) str << "isEnum ";
if (isEnumerator()) str << "isEnumerator ";
if (isTypeAlias()) str << "isTypeAlias ";
if (isCustom()) str << "isCustom ";
str << "\n";
str << "File: " << fileName().ascii() << " ";
int line, col;
getStartPosition(&line, &col);
str << "s:(" << line << ", " << col << ") ";
getEndPosition(&line, &col);
str << "e:(" << line << ", " << col << ")\n";
Info.prepend(str.str().c_str());
file << Info.ascii() << "\n";
if (recurse) {} ///just to get rid of the warning
}
void ClassModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "scope: " << m_scope.join("::").ascii() << "\n";
str << "bases: " << m_baseClassList.join(" ").ascii() << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {
dumpMap(file, m_classes);
}
}
void NamespaceAliasModel::read(QDataStream& stream)
{
QString tempFileName;
stream >> m_name >> m_aliasName >> tempFileName;
m_fileName = HashedString(tempFileName);
}
void NamespaceAliasModel::write(QDataStream& stream) const
{
stream << m_name << m_aliasName << m_fileName.str();
}
void NamespaceImportModel::read(QDataStream& stream)
{
QString tempFileName;
stream >> m_name >> tempFileName;
m_fileName = HashedString(tempFileName);
}
void NamespaceImportModel::write(QDataStream& stream) const
{
stream << m_name << m_fileName.str();
}
void NamespaceModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
Info.prepend(str.str().c_str());
ClassModel::dump(file, false, Info);
if (recurse) {
dumpMapDirect(file, m_namespaces);
}
}
void ArgumentModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "type: " << m_type.ascii() << " default: " << m_defaultValue.ascii() << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {} ///just to get rid of the warning
}
void FunctionModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "access: " << m_access;
str << " scope: " << m_scope.join("::").ascii() << "\n";
if (isAbstract()) str << "isAbstract ";
if (isConstant()) str << "isConstant ";
if (isFunction()) str << "isFunction ";
if (isInline()) str << "isInline ";
if (isSignal()) str << "isSignal ";
if (isSlot()) str << "isSlot ";
if (isStatic()) str << "isStatic ";
if (isVirtual()) str << "isVirtual ";
str << "\n";
str << "result-type: " << resultType().ascii() << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {
for (ArgumentList::iterator it = m_arguments.begin(); it != m_arguments.end(); ++it) {
(*it) -> dump(file, true);
}
}
}
void VariableModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "access: " << m_access << "type: " << m_type.ascii() << "\n";
if (isStatic()) str << "isStatic ";
str << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {} ///just to get rid of the warning
}
void CodeModel::dump(std::ostream& file, QString Info)
{
ostringstream str(ostringstream::out);
Info.prepend(str.str().c_str());
file << Info.ascii() << "\n";
QMap<QString, FileDom>::iterator it = m_files.begin();
for (; it != m_files.end(); ++it) {
(*it) -> dump(file, true);
}
}
void EnumModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "access: " << m_access << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {
dumpMapDirect(file, m_enumerators);
}
}
void EnumeratorModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "value: " << m_value.ascii() << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {} ///just to get rid of the warning
}
void TypeAliasModel::dump(std::ostream& file, bool recurse, QString Info)
{
ostringstream str(ostringstream::out);
str << "type: " << m_type.ascii() << "\n";
Info.prepend(str.str().c_str());
CodeModelItem::dump(file, false, Info);
if (recurse) {} ///just to get rid of the warning
}
void CodeModel::wipeout()
{
m_files.clear();
NamespaceDom ns = create<NamespaceModel>();
ns->setName("::");
m_globalNamespace = ns;
}
FileList CodeModel::fileList()
{
return m_files.values();
}
const FileList CodeModel::fileList() const
{
return m_files.values();
}
bool CodeModel::hasFile(const QString & name) const
{
return m_files.contains(name);
}
FileDom CodeModel::fileByName(const QString & name)
{
QMap<QString, FileDom>::const_iterator it = m_files.find(name);
if (it != m_files.end()) {
return *it;
} else {
return FileDom();
}
}
const FileDom CodeModel::fileByName(const QString & name) const
{
QMap<QString, FileDom>::const_iterator it = m_files.find(name);
if (it != m_files.end()) {
return *it;
} else {
return FileDom();
}
}
void CodeModel::addNamespace(NamespaceDom target, NamespaceDom source)
{
if (source->name().isEmpty()) {
return;
} else if (!target->hasNamespace(source->name())) {
NamespaceDom ns = this->create<NamespaceModel>();
ns->setName(source->name());
ns->setFileName(source->fileName()); /// \FIXME ROBE
ns->setScope(source->scope());
target->addNamespace(ns);
}
NamespaceDom ns = target->namespaceByName(source->name());
NamespaceList namespaceList = source->namespaceList();
ClassList classList = source->classList();
FunctionList functionList = source->functionList();
FunctionDefinitionList functionDefinitionList = source->functionDefinitionList();
VariableList variableList = source->variableList();
EnumList enumList = source->enumList();
TypeAliasList typeAliasList = source->typeAliasList();
const NamespaceModel::NamespaceAliasModelList& namespaceAliases = source->namespaceAliases();
const NamespaceModel::NamespaceImportModelList& namespaceImports = source->namespaceImports();
for (NamespaceList::Iterator it=namespaceList.begin(); it!=namespaceList.end(); ++it)
addNamespace(ns, *it);
for (ClassList::Iterator it=classList.begin(); it!=classList.end(); ++it)
ns->addClass(*it);
for (FunctionList::Iterator it=functionList.begin(); it!=functionList.end(); ++it)
ns->addFunction(*it);
for (FunctionDefinitionList::Iterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
ns->addFunctionDefinition(*it);
for (VariableList::Iterator it=variableList.begin(); it!=variableList.end(); ++it)
ns->addVariable(*it);
for (EnumList::Iterator it=enumList.begin(); it!=enumList.end(); ++it)
ns->addEnum(*it);
for (TypeAliasList::Iterator it=typeAliasList.begin(); it!=typeAliasList.end(); ++it)
ns->addTypeAlias(*it);
for (NamespaceModel::NamespaceAliasModelList::const_iterator it=namespaceAliases.begin(); it != namespaceAliases.end(); ++it)
ns->addNamespaceAlias(*it);
for (NamespaceModel::NamespaceImportModelList::const_iterator it=namespaceImports.begin(); it != namespaceImports.end(); ++it)
ns->addNamespaceImport(*it);
}
void CodeModel::removeNamespace(NamespaceDom target, NamespaceDom source)
{
if (source->name().isEmpty() || !target->hasNamespace(source->name()))
return;
NamespaceDom ns = target->namespaceByName(source->name());
NamespaceList namespaceList = source->namespaceList();
ClassList classList = source->classList();
FunctionList functionList = source->functionList();
FunctionDefinitionList functionDefinitionList = source->functionDefinitionList();
VariableList variableList = source->variableList();
EnumList enumList = source->enumList();
TypeAliasList typeAliasList = source->typeAliasList();
const NamespaceModel::NamespaceAliasModelList& namespaceAliases = source->namespaceAliases();
const NamespaceModel::NamespaceImportModelList& namespaceImports = source->namespaceImports();
for (NamespaceList::Iterator it=namespaceList.begin(); it!=namespaceList.end(); ++it)
removeNamespace(ns, *it);
for (ClassList::Iterator it=classList.begin(); it!=classList.end(); ++it)
ns->removeClass(*it);
for (FunctionList::Iterator it=functionList.begin(); it!=functionList.end(); ++it)
ns->removeFunction(*it);
for (FunctionDefinitionList::Iterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
ns->removeFunctionDefinition(*it);
for (VariableList::Iterator it=variableList.begin(); it!=variableList.end(); ++it)
ns->removeVariable(*it);
for (EnumList::Iterator it=enumList.begin(); it!=enumList.end(); ++it)
ns->removeEnum(*it);
for (TypeAliasList::Iterator it=typeAliasList.begin(); it!=typeAliasList.end(); ++it)
ns->removeTypeAlias(*it);
for (NamespaceModel::NamespaceAliasModelList::const_iterator it=namespaceAliases.begin(); it != namespaceAliases.end(); ++it)
ns->removeNamespaceAlias(*it);
for (NamespaceModel::NamespaceImportModelList::const_iterator it=namespaceImports.begin(); it != namespaceImports.end(); ++it)
ns->removeNamespaceImport(*it);
if (ns->namespaceList().isEmpty() &&
ns->classList().isEmpty() &&
ns->functionList().isEmpty() &&
ns->functionDefinitionList().isEmpty() &&
ns->variableList().isEmpty() &&
ns->enumList().isEmpty() &&
ns->typeAliasList().isEmpty() &&
ns->namespaceImports().empty() &&
ns->namespaceAliases().empty()) {
target->removeNamespace(ns);
}
}
bool CodeModel::addFile(FileDom file)
{
if (file->name().isEmpty())
return false;
if (m_files.find(file->name()) != m_files.end()) {
uDebug() << "file " << file->name() << " was added to code-model without removing it before! \n" << kdBacktrace(); //FIXME KF5
removeFile(fileByName(file->name()));
}
// update global namespace
NamespaceList namespaceList = file->namespaceList();
ClassList classList = file->classList();
FunctionList functionList = file->functionList();
FunctionDefinitionList functionDefinitionList = file->functionDefinitionList();
VariableList variableList = file->variableList();
EnumList enumList = file->enumList();
TypeAliasList typeAliasList = file->typeAliasList();
const NamespaceModel::NamespaceAliasModelList& namespaceAliases = file->namespaceAliases();
const NamespaceModel::NamespaceImportModelList& namespaceImports = file->namespaceImports();
for (NamespaceList::Iterator it=namespaceList.begin(); it!=namespaceList.end(); ++it)
addNamespace(m_globalNamespace, *it);
for (ClassList::Iterator it=classList.begin(); it!=classList.end(); ++it)
m_globalNamespace->addClass(*it);
for (FunctionList::Iterator it=functionList.begin(); it!=functionList.end(); ++it)
m_globalNamespace->addFunction(*it);
for (FunctionDefinitionList::Iterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
m_globalNamespace->addFunctionDefinition(*it);
for (VariableList::Iterator it=variableList.begin(); it!=variableList.end(); ++it)
m_globalNamespace->addVariable(*it);
for (EnumList::Iterator it=enumList.begin(); it!=enumList.end(); ++it)
m_globalNamespace->addEnum(*it);
for (TypeAliasList::Iterator it=typeAliasList.begin(); it!=typeAliasList.end(); ++it)
m_globalNamespace->addTypeAlias(*it);
for (NamespaceModel::NamespaceAliasModelList::const_iterator it=namespaceAliases.begin(); it != namespaceAliases.end(); ++it)
m_globalNamespace->addNamespaceAlias(*it);
for (NamespaceModel::NamespaceImportModelList::const_iterator it=namespaceImports.begin(); it != namespaceImports.end(); ++it)
m_globalNamespace->addNamespaceImport(*it);
m_files.insert(file->name(), file);
return true;
}
void CodeModel::removeFile(FileDom file)
{
// update global namespace
NamespaceList namespaceList = file->namespaceList();
ClassList classList = file->classList();
FunctionList functionList = file->functionList();
FunctionDefinitionList functionDefinitionList = file->functionDefinitionList();
VariableList variableList = file->variableList();
EnumList enumList = file->enumList();
TypeAliasList typeAliasList = file->typeAliasList();
const NamespaceModel::NamespaceAliasModelList& namespaceAliases = file->namespaceAliases();
const NamespaceModel::NamespaceImportModelList& namespaceImports = file->namespaceImports();
for (NamespaceList::Iterator it=namespaceList.begin(); it!=namespaceList.end(); ++it)
removeNamespace(m_globalNamespace, *it);
for (ClassList::Iterator it=classList.begin(); it!=classList.end(); ++it)
m_globalNamespace->removeClass(*it);
for (FunctionList::Iterator it=functionList.begin(); it!=functionList.end(); ++it)
m_globalNamespace->removeFunction(*it);
for (FunctionDefinitionList::Iterator it=functionDefinitionList.begin(); it!=functionDefinitionList.end(); ++it)
m_globalNamespace->removeFunctionDefinition(*it);
for (VariableList::Iterator it=variableList.begin(); it!=variableList.end(); ++it)
m_globalNamespace->removeVariable(*it);
for (EnumList::Iterator it=enumList.begin(); it!=enumList.end(); ++it)
m_globalNamespace->removeEnum(*it);
for (TypeAliasList::Iterator it=typeAliasList.begin(); it!=typeAliasList.end(); ++it)
m_globalNamespace->removeTypeAlias(*it);
for (NamespaceModel::NamespaceAliasModelList::const_iterator it=namespaceAliases.begin(); it != namespaceAliases.end(); ++it)
m_globalNamespace->removeNamespaceAlias(*it);
for (NamespaceModel::NamespaceImportModelList::const_iterator it=namespaceImports.begin(); it != namespaceImports.end(); ++it)
m_globalNamespace->removeNamespaceImport(*it);
m_files.remove(file->name());
}
// ------------------------------------------------------------------------
CodeModelItem::CodeModelItem(int kind, CodeModel* model)
: m_kind(kind), m_model(model)
{
//uDebug() << "CodeModelItem::CodeModelItem()";
m_startLine = 0;
m_startColumn = 0;
m_endLine = 0;
m_endColumn = 0;
}
CodeModelItem::~ CodeModelItem()
{
}
QString CodeModelItem::name() const
{
return m_name;
}
void CodeModelItem::setName(const QString & name)
{
m_name = name;
}
const FileDom CodeModelItem::file() const
{
return m_model->fileByName(m_fileName);
}
FileDom CodeModelItem::file()
{
return m_model->fileByName(m_fileName);
}
QString CodeModelItem::fileName() const
{
return m_fileName;
}
void CodeModelItem::setFileName(const QString& fileName)
{
m_fileName = fileName;
}
void CodeModelItem::getStartPosition(int * line, int * column) const
{
if (line) *line = m_startLine;
if (column) *column = m_startColumn;
}
void CodeModelItem::setStartPosition(int line, int column)
{
m_startLine = line;
m_startColumn = column;
}
void CodeModelItem::getEndPosition(int * line, int * column) const
{
if (line) *line = m_endLine;
if (column) *column = m_endColumn;
}
void CodeModelItem::setEndPosition(int line, int column)
{
m_endLine = line;
m_endColumn = column;
}
void CodeModelItem::update(const CodeModelItem* i)
{
m_startLine = i->m_startLine;
m_startColumn = i->m_startColumn;
m_endLine = i->m_endLine;
m_endColumn = i->m_endColumn;
}
bool CodeModelItem::canUpdate(const CodeModelItem* i) const
{
if (i->m_kind != m_kind || i->m_name != m_name)
return false;
return true;
}
// ------------------------------------------------------------------------
NamespaceModel::NamespaceModel(CodeModel* model)
: ClassModel(model)
{
setKind(Namespace);
}
NamespaceList NamespaceModel::namespaceList()
{
return m_namespaces.values();
}
const NamespaceList NamespaceModel::namespaceList() const
{
return m_namespaces.values();
}
NamespaceDom NamespaceModel::namespaceByName(const QString & name)
{
return m_namespaces.contains(name) ? m_namespaces[ name ] : NamespaceDom();
}
const NamespaceDom NamespaceModel::namespaceByName(const QString & name) const
{
return m_namespaces.contains(name) ? m_namespaces[ name ] : NamespaceDom();
}
bool NamespaceModel::hasNamespace(const QString & name) const
{
return m_namespaces.contains(name);
}
bool NamespaceModel::addNamespace(NamespaceDom ns)
{
if (ns->name().isEmpty())
return false;
m_namespaces[ ns->name() ] = ns;
return true;
}
void NamespaceModel::removeNamespace(NamespaceDom ns)
{
m_namespaces.remove(ns->name());
}
// ------------------------------------------------------------------------
FileModel::FileModel(CodeModel* model)
: NamespaceModel(model), m_groupId(model->newGroupId()), m_parseResult(0)
{
}
// ------------------------------------------------------------------------
ClassModel::ClassModel(CodeModel* model)
: CodeModelItem(Class, model)
{
}
QStringList ClassModel::baseClassList() const
{
return m_baseClassList;
}
bool ClassModel::addBaseClass(const QString & baseClass)
{
m_baseClassList.push_back(baseClass);
return true;
}
void ClassModel::removeBaseClass(const QString & baseClass)
{
m_baseClassList.remove(baseClass);
}
ClassList ClassModel::classList()
{
ClassList l;
QMap<QString, ClassList>::Iterator it = m_classes.begin();
while (it != m_classes.end()) {
l += *it;
++it;
}
return l;
}
const ClassList ClassModel::classList() const
{
ClassList l;
QMap<QString, ClassList>::ConstIterator it = m_classes.begin();
while (it != m_classes.end()) {
l += *it;
++it;
}
return l;
}
bool ClassModel::hasClass(const QString & name) const
{
return m_classes.contains(name);
}
ClassList ClassModel::classByName(const QString & name)
{
return m_classes.contains(name) ? m_classes[ name ] : ClassList();
}
const ClassList ClassModel::classByName(const QString & name) const
{
return m_classes.contains(name) ? m_classes[ name ] : ClassList();
}
bool ClassModel::addClass(ClassDom klass)
{
if (klass->name().isEmpty())
return false;
m_classes[ klass->name() ].push_back(klass);
return true;
}
void ClassModel::removeClass(ClassDom klass)
{
m_classes[ klass->name() ].remove(klass);
if (m_classes[klass->name()].isEmpty())
m_classes.remove(klass->name());
}
FunctionList ClassModel::functionList()
{
FunctionList l;
QMap<QString, FunctionList>::Iterator it = m_functions.begin();
while (it != m_functions.end()) {
l += *it;
++it;
}
return l;
}
const FunctionList ClassModel::functionList() const
{
FunctionList l;
QMap<QString, FunctionList>::ConstIterator it = m_functions.begin();
while (it != m_functions.end()) {
l += *it;
++it;
}
return l;
}
bool ClassModel::hasFunction(const QString & name) const
{
return m_functions.contains(name);
}
FunctionList ClassModel::functionByName(const QString & name)
{
return m_functions.contains(name) ? m_functions[ name ] : FunctionList();
}
const FunctionList ClassModel::functionByName(const QString & name) const
{
return m_functions.contains(name) ? m_functions[ name ] : FunctionList();
}
bool ClassModel::addFunction(FunctionDom fun)
{
if (fun->name().isEmpty())
return false;
m_functions[ fun->name() ].push_back(fun);
return true;
}
void ClassModel::removeFunction(FunctionDom fun)
{
m_functions[ fun->name() ].remove(fun);
if (m_functions[fun->name()].isEmpty())
m_functions.remove(fun->name());
}
FunctionDefinitionList ClassModel::functionDefinitionList()
{
FunctionDefinitionList l;
QMap<QString, FunctionDefinitionList>::Iterator it = m_functionDefinitions.begin();
while (it != m_functionDefinitions.end()) {
l += *it;
++it;
}
return l;
}
const FunctionDefinitionList ClassModel::functionDefinitionList() const
{
FunctionDefinitionList l;
QMap<QString, FunctionDefinitionList>::ConstIterator it = m_functionDefinitions.begin();
while (it != m_functionDefinitions.end()) {
l += *it;
++it;
}
return l;
}
bool ClassModel::hasFunctionDefinition(const QString & name) const
{
return m_functionDefinitions.contains(name);
}
FunctionDefinitionList ClassModel::functionDefinitionByName(const QString & name)
{
return m_functionDefinitions.contains(name) ? m_functionDefinitions[ name ] : FunctionDefinitionList();
}
const FunctionDefinitionList ClassModel::functionDefinitionByName(const QString & name) const
{
return m_functionDefinitions.contains(name) ? m_functionDefinitions[ name ] : FunctionDefinitionList();
}
bool ClassModel::addFunctionDefinition(FunctionDefinitionDom fun)
{
if (fun->name().isEmpty())
return false;
m_functionDefinitions[ fun->name() ].push_back(fun);
return true;
}
void ClassModel::removeFunctionDefinition(FunctionDefinitionDom fun)
{
m_functionDefinitions[ fun->name() ].remove(fun);
if (m_functionDefinitions[fun->name()].isEmpty())
m_functionDefinitions.remove(fun->name());
}
VariableList ClassModel::variableList()
{
return m_variables.values();
}
const VariableList ClassModel::variableList() const
{
return m_variables.values();
}
VariableDom ClassModel::variableByName(const QString & name)
{
return m_variables.contains(name) ? m_variables[ name ] : VariableDom();
}
const VariableDom ClassModel::variableByName(const QString & name) const
{
return m_variables.contains(name) ? m_variables[ name ] : VariableDom();
}
bool ClassModel::hasVariable(const QString & name) const
{
return m_variables.contains(name);
}
bool ClassModel::addVariable(VariableDom var)
{
if (var->name().isEmpty())
return false;
m_variables.insert(var->name(), var);
return true;
}
void ClassModel::removeVariable(VariableDom var)
{
m_variables.remove(var->name());
}
EnumList ClassModel::enumList()
{
return m_enumerators.values();
}
const EnumList ClassModel::enumList() const
{
return m_enumerators.values();
}
EnumDom ClassModel::enumByName(const QString & name)
{
return m_enumerators.contains(name) ? m_enumerators[ name ] : EnumDom();
}
const EnumDom ClassModel::enumByName(const QString & name) const
{
return m_enumerators.contains(name) ? m_enumerators[ name ] : EnumDom();
}
bool ClassModel::hasEnum(const QString & name) const
{
return m_enumerators.contains(name);
}
bool ClassModel::addEnum(EnumDom e)
{
if (e->name().isEmpty())
return false;
m_enumerators.insert(e->name(), e);
return true;
}
void ClassModel::update(const ClassModel* klass)
{
CodeModelItem::update(klass);
eachUpdate(m_classes, klass->m_classes) ;
eachUpdate(m_functions, klass->m_functions) ;
eachUpdate(m_functionDefinitions, klass->m_functionDefinitions) ;
eachUpdateSingle(m_variables, klass->m_variables) ;
eachUpdateSingle(m_enumerators, klass->m_enumerators) ;
eachUpdate(m_typeAliases, klass->m_typeAliases);
}
bool ClassModel::canUpdate(const ClassModel* klass) const
{
if (!CodeModelItem::canUpdate(klass))
return false;
return eachCanUpdate(m_classes, klass->m_classes) &&
eachCanUpdate(m_functions, klass->m_functions) &&
eachCanUpdate(m_functionDefinitions, klass->m_functionDefinitions) &&
eachCanUpdateSingle(m_variables, klass->m_variables) &&
eachCanUpdateSingle(m_enumerators, klass->m_enumerators) &&
eachCanUpdate(m_typeAliases, klass->m_typeAliases);
}
void ClassModel::removeEnum(EnumDom e)
{
m_enumerators.remove(e->name());
}
TypeAliasList ClassModel::typeAliasList()
{
TypeAliasList l;
QMap<QString, TypeAliasList>::Iterator it = m_typeAliases.begin();
while (it != m_typeAliases.end()) {
l += *it;
++it;
}
return l;
}
const TypeAliasList ClassModel::typeAliasList() const
{
TypeAliasList l;
QMap<QString, TypeAliasList>::ConstIterator it = m_typeAliases.begin();
while (it != m_typeAliases.end()) {
l += *it;
++it;
}
return l;
}
bool ClassModel::hasTypeAlias(const QString & name) const
{
return m_typeAliases.contains(name);
}
TypeAliasList ClassModel::typeAliasByName(const QString & name)
{
return m_typeAliases.contains(name) ? m_typeAliases[ name ] : TypeAliasList();
}
const TypeAliasList ClassModel::typeAliasByName(const QString & name) const
{
return m_typeAliases.contains(name) ? m_typeAliases[ name ] : TypeAliasList();
}
bool ClassModel::addTypeAlias(TypeAliasDom typeAlias)
{
if (typeAlias->name().isEmpty())
return false;
m_typeAliases[ typeAlias->name() ].push_back(typeAlias);
return true;
}
void ClassModel::removeTypeAlias(TypeAliasDom typeAlias)
{
m_typeAliases[ typeAlias->name() ].remove(typeAlias);
if (m_typeAliases[typeAlias->name()].isEmpty())
m_typeAliases.remove(typeAlias->name());
}
// ------------------------------------------------------------------------
ArgumentModel::ArgumentModel(CodeModel* model)
: CodeModelItem(Argument, model)
{
}
QString ArgumentModel::type() const
{
return m_type;
}
void ArgumentModel::setType(const QString& type)
{
m_type = type;
}
QString ArgumentModel::defaultValue() const
{
return m_defaultValue;
}
void ArgumentModel::setDefaultValue(const QString & defaultValue)
{
m_defaultValue = defaultValue;
}
// ------------------------------------------------------------------------
FunctionModel::FunctionModel(CodeModel* model)
: CodeModelItem(Function, model)
{
m_access = Public;
d.v.m_signal = false;
d.v.m_slot = false;
d.v.m_virtual = false;
d.v.m_static = false;
d.v.m_inline = false;
d.v.m_constant = false;
d.v.m_abstract = false;
}
bool FunctionModel::isVirtual() const
{
return d.v.m_virtual;
}
void FunctionModel::setVirtual(bool isVirtual)
{
d.v.m_virtual = isVirtual;
}
bool FunctionModel::isStatic() const
{
return d.v.m_static;
}
void FunctionModel::setStatic(bool isStatic)
{
d.v.m_static = isStatic;
}
bool FunctionModel::isInline() const
{
return d.v.m_inline;
}
void FunctionModel::setInline(bool isInline)
{
d.v.m_inline = isInline;
}
bool FunctionModel::isConstant() const
{
return d.v.m_constant;
}
void FunctionModel::setConstant(bool isConstant)
{
d.v.m_constant = isConstant;
}
bool FunctionModel::isAbstract() const
{
return d.v.m_abstract;
}
void FunctionModel::setAbstract(bool isAbstract)
{
d.v.m_abstract = isAbstract;
}
QString FunctionModel::resultType() const
{
return m_resultType;
}
void FunctionModel::setResultType(const QString& type)
{
m_resultType = type;
}
ArgumentList FunctionModel::argumentList()
{
return m_arguments;
}
const ArgumentList FunctionModel::argumentList() const
{
return m_arguments;
}
bool FunctionModel::addArgument(ArgumentDom arg)
{
m_arguments.push_back(arg);
return true;
}
void FunctionModel::removeArgument(ArgumentDom arg)
{
m_arguments.remove(arg);
}
void FunctionModel::update(const FunctionModel* i)
{
m_access = i->m_access;
CodeModelItem::update(i);
}
bool FunctionModel::canUpdate(const FunctionModel* i) const
{
if (!CodeModelItem::canUpdate(i))
return false;
if (m_resultType != i->m_resultType || m_arguments.count() != i->m_arguments.count() || m_scope != i->m_scope)
return false;
return true;
}
// ------------------------------------------------------------------------
VariableModel::VariableModel(CodeModel* model)
: CodeModelItem(Variable, model)
{
m_access = Public;
m_static = false;
m_isEnumeratorVariable = false;
}
bool VariableModel::isStatic() const
{
return m_static;
}
void VariableModel::setStatic(bool isStatic)
{
m_static = isStatic;
}
QString VariableModel::type() const
{
return m_type;
}
void VariableModel::setType(const QString& type)
{
m_type = type;
}
bool VariableModel::isEnumeratorVariable() const
{
return m_isEnumeratorVariable;
}
void VariableModel::setEnumeratorVariable(bool b)
{
m_isEnumeratorVariable = b;
}
int FunctionModel::access() const
{
return m_access;
}
void FunctionModel::setAccess(int access)
{
m_access = access;
}
bool FunctionModel::isSignal() const
{
return d.v.m_signal;
}
void FunctionModel::setSignal(bool isSignal)
{
d.v.m_signal = isSignal;
}
bool FunctionModel::isSlot() const
{
return d.v.m_slot;
}
void FunctionModel::setSlot(bool isSlot)
{
d.v.m_slot = isSlot;
}
FunctionDefinitionModel::FunctionDefinitionModel(CodeModel* model)
: FunctionModel(model)
{
}
int VariableModel::access() const
{
return m_access;
}
void VariableModel::setAccess(int access)
{
m_access = access;
}
const NamespaceDom CodeModel::globalNamespace() const
{
return m_globalNamespace;
}
void CodeModelItem::read(QDataStream & stream)
{
stream
>> m_kind
>> m_name
>> m_fileName
>> m_startLine
>> m_startColumn
>> m_endLine
>> m_endColumn
>> m_comment;
if (isTemplateable()) {
TemplateModelItem* t = (TemplateModelItem*)(this);
t->read(stream);
}
}
void CodeModelItem::write(QDataStream & stream) const
{
stream
<< m_kind
<< m_name
<< m_fileName
<< m_startLine
<< m_startColumn
<< m_endLine
<< m_endColumn
<< m_comment;
if (isTemplateable()) {
TemplateModelItem* t = (TemplateModelItem*)(this);
t-> write(stream);
}
}
void ClassModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
TemplateModelItem::read(stream);
stream >> m_scope >> m_baseClassList;
int n;
m_classes.clear();
stream >> n;
for (int i=0; i<n; ++i) {
ClassDom klass = codeModel()->create<ClassModel>();
klass->read(stream);
addClass(klass);
}
m_functions.clear();
stream >> n;
for (int i=0; i<n; ++i) {
FunctionDom fun = codeModel()->create<FunctionModel>();
fun->read(stream);
addFunction(fun);
}
m_functionDefinitions.clear();
stream >> n;
for (int i=0; i<n; ++i) {
FunctionDefinitionDom fun = codeModel()->create<FunctionDefinitionModel>();
fun->read(stream);
addFunctionDefinition(fun);
}
m_variables.clear();
stream >> n;
for (int i=0; i<n; ++i) {
VariableDom var = codeModel()->create<VariableModel>();
var->read(stream);
addVariable(var);
}
m_enumerators.clear();
stream >> n;
for (int i=0; i<n; ++i) {
EnumDom e = codeModel()->create<EnumModel>();
e->read(stream);
addEnum(e);
}
m_typeAliases.clear();
stream >> n;
for (int i=0; i<n; ++i) {
TypeAliasDom typeAlias = codeModel()->create<TypeAliasModel>();
typeAlias->read(stream);
addTypeAlias(typeAlias);
}
}
void ClassModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
TemplateModelItem::write(stream);
stream << m_scope << m_baseClassList;
const ClassList class_list = classList();
stream << int(class_list.size());
for (ClassList::ConstIterator it = class_list.begin(); it!=class_list.end(); ++it)
(*it)->write(stream);
const FunctionList function_list = functionList();
stream << int(function_list.size());
for (FunctionList::ConstIterator it = function_list.begin(); it!=function_list.end(); ++it)
(*it)->write(stream);
const FunctionDefinitionList function_definition_list = functionDefinitionList();
stream << int(function_definition_list.size());
for (FunctionDefinitionList::ConstIterator it = function_definition_list.begin(); it!=function_definition_list.end(); ++it)
(*it)->write(stream);
const VariableList variable_list = variableList();
stream << int(variable_list.size());
for (VariableList::ConstIterator it = variable_list.begin(); it!=variable_list.end(); ++it)
(*it)->write(stream);
const EnumList enum_list = enumList();
stream << int(enum_list.size());
for (EnumList::ConstIterator it = enum_list.begin(); it!=enum_list.end(); ++it)
(*it)->write(stream);
const TypeAliasList type_alias_list = typeAliasList();
stream << int(type_alias_list.size());
for (TypeAliasList::ConstIterator it = type_alias_list.begin(); it!=type_alias_list.end(); ++it)
(*it)->write(stream);
}
void NamespaceModel::read(QDataStream & stream)
{
ClassModel::read(stream);
int n;
m_namespaces.clear();
m_namespaceAliases.clear();
m_namespaceImports.clear();
stream >> n;
for (int i=0; i<n; ++i) {
NamespaceDom ns = codeModel()->create<NamespaceModel>();
ns->read(stream);
addNamespace(ns);
}
stream >> n;
for (int a = 0; a < n; a++) {
NamespaceAliasModel m;
m.read(stream);
m_namespaceAliases.insert(m);
}
stream >> n;
for (int a = 0; a < n; a++) {
NamespaceImportModel m;
m.read(stream);
m_namespaceImports.insert(m);
}
}
void NamespaceModel::addNamespaceImport(const NamespaceImportModel& import)
{
m_namespaceImports.insert(import);
}
void NamespaceModel::addNamespaceAlias(const NamespaceAliasModel& alias)
{
m_namespaceAliases.insert(alias);
}
void NamespaceModel::removeNamespaceImport(const NamespaceImportModel& import)
{
m_namespaceImports.erase(import);
}
void NamespaceModel::removeNamespaceAlias(const NamespaceAliasModel& alias)
{
m_namespaceAliases.erase(alias);
}
void NamespaceModel::write(QDataStream & stream) const
{
ClassModel::write(stream);
const NamespaceList namespace_list = namespaceList();
stream << int(namespace_list.size());
for (NamespaceList::ConstIterator it = namespace_list.begin(); it!=namespace_list.end(); ++it)
(*it)->write(stream);
stream << int(m_namespaceAliases.size());
for (NamespaceAliasModelList::const_iterator it = m_namespaceAliases.begin(); it != m_namespaceAliases.end(); ++it)
(*it).write(stream);
stream << int(m_namespaceImports.size());
for (NamespaceImportModelList::const_iterator it = m_namespaceImports.begin(); it != m_namespaceImports.end(); ++it)
(*it).write(stream);
}
bool NamespaceModel::canUpdate(const NamespaceModel* ns) const
{
if (!ClassModel::canUpdate(ns))
return false;
const NamespaceAliasModelList& aliases = namespaceAliases();
const NamespaceImportModelList& imports = namespaceImports();
const NamespaceAliasModelList& aliases2 = ns->namespaceAliases();
const NamespaceImportModelList& imports2 = ns->namespaceImports();
if (aliases.size() != aliases2.size()) return false;
if (imports.size() != imports2.size()) return false;
///Test if all aliases are same, if not return false
NamespaceModel::NamespaceAliasModelList::const_iterator it_al1 = aliases.begin();
NamespaceModel::NamespaceAliasModelList::const_iterator it_al2 = aliases2.begin();
while (it_al1 != aliases.end()) {
if (!(*it_al1 == *it_al2))
return false;
++it_al1;
++it_al2;
}
///Test if all imports are same, if not return false
NamespaceModel::NamespaceImportModelList::const_iterator it_ip1 = imports.begin();
NamespaceModel::NamespaceImportModelList::const_iterator it_ip2 = imports2.begin();
while (it_ip1 != imports.end()) {
if (!(*it_ip1 == *it_ip2))
return false;
++it_ip1;
++it_ip2;
}
return eachCanUpdateSingle(m_namespaces, ns->m_namespaces);
}
void NamespaceModel::update(const NamespaceModel* ns)
{
ClassModel::update(ns);
eachUpdateSingle(m_namespaces, ns->m_namespaces);
}
void FileModel::read(QDataStream & stream)
{
stream >> m_groupId;
bool b;
stream >> b;
if (b) {
int i;
stream >> i;
ParsedFileType t((ParsedFileType) i);
switch (t) {
case CppParsedFile:
m_parseResult = (AbstractParseResult*)(new ParsedFile(stream));
break;
}
}
NamespaceModel::read(stream);
}
void FileModel::write(QDataStream & stream) const
{
stream << m_groupId;
bool b = m_parseResult;
stream << b;
if (b) {
int i = m_parseResult->type();
stream << i;
m_parseResult->write(stream);
}
NamespaceModel::write(stream);
}
void ArgumentModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
stream >> m_type >> m_defaultValue;
}
void ArgumentModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
stream << m_type << m_defaultValue;
}
void FunctionModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
TemplateModelItem::read(stream);
stream >> m_scope;
stream >> d.flags;
int n;
m_arguments.clear();
stream >> n;
for (int i=0; i<n; ++i) {
ArgumentDom arg = codeModel()->create<ArgumentModel>();
arg->read(stream);
addArgument(arg);
}
stream
>> m_resultType;
}
void FunctionModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
TemplateModelItem::write(stream);
stream << m_scope;
stream << d.flags;
const ArgumentList argument_list = argumentList();
stream << int(argument_list.size());
for (ArgumentList::ConstIterator it = argument_list.begin(); it!=argument_list.end(); ++it)
(*it)->write(stream);
stream
<< m_resultType;
}
void CodeModel::read(QDataStream & stream)
{
int n;
m_files.clear();
stream >> n;
for (int i=0; i<n; ++i) {
FileDom file = this->create<FileModel>();
file->read(stream);
addFile(file);
}
}
void CodeModel::write(QDataStream & stream) const
{
const FileList file_list = fileList();
stream << int(file_list.size());
for (FileList::ConstIterator it = file_list.begin(); it!=file_list.end(); ++it)
(*it)->write(stream);
}
void VariableModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
stream >> m_access >> m_static >> m_type >> m_isEnumeratorVariable;
}
void VariableModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
stream << m_access << m_static << m_type << m_isEnumeratorVariable;
}
void VariableModel::update(const VariableModel* i)
{
m_access = i->m_access;
CodeModelItem::update(i);
}
bool VariableModel::canUpdate(const VariableModel* i) const
{
if (!CodeModelItem::canUpdate(i))
return false;
if (m_access != i->m_access || m_static != i->m_static || m_type != i->m_type || m_isEnumeratorVariable != i->m_isEnumeratorVariable)
return false;
return true;
}
// -------------------------------------------------------
EnumModel::EnumModel(CodeModel * model)
: CodeModelItem(Enum, model)
{
}
int EnumModel::access() const
{
return m_access;
}
void EnumModel::setAccess(int access)
{
m_access = access;
}
EnumeratorList EnumModel::enumeratorList()
{
return m_enumerators.values();
}
const EnumeratorList EnumModel::enumeratorList() const
{
return m_enumerators.values();
}
void EnumModel::addEnumerator(EnumeratorDom enumerator)
{
m_enumerators.insert(enumerator->name(), enumerator);
}
void EnumModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
stream >> m_access;
int n;
stream >> n;
for (int i=0; i<n; ++i) {
EnumeratorDom e = codeModel()->create<EnumeratorModel>();
e->read(stream);
addEnumerator(e);
}
}
void EnumModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
stream << m_access;
const EnumeratorList enumerator_list = enumeratorList();
stream << int(enumerator_list.size());
for (EnumeratorList::ConstIterator it = enumerator_list.begin(); it!=enumerator_list.end(); ++it)
(*it)->write(stream);
}
EnumeratorModel::EnumeratorModel(CodeModel * model)
: CodeModelItem(Enumerator, model)
{
}
QString EnumeratorModel::value() const
{
return m_value;
}
void EnumeratorModel::setValue(const QString & value)
{
m_value = value;
}
void EnumeratorModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
stream >> m_value;
}
void EnumeratorModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
stream << m_value;
}
void EnumModel::removeEnumerator(EnumeratorDom e)
{
m_enumerators.remove(e->name());
}
void EnumModel::update(const EnumModel* i)
{
m_access = i->m_access;
CodeModelItem::update(i);
}
bool EnumModel::canUpdate(const EnumModel* i) const
{
if (!CodeModelItem::canUpdate(i))
return false;
///@todo check not complete
if (m_access != i->m_access || m_enumerators.count() != i->m_enumerators.count())
return false;
return true;
}
// ---------------------------------------------------------------
TypeAliasModel::TypeAliasModel(CodeModel * model)
: CodeModelItem(TypeAlias, model)
{
}
void TypeAliasModel::read(QDataStream & stream)
{
CodeModelItem::read(stream);
stream >> m_type;
}
void TypeAliasModel::write(QDataStream & stream) const
{
CodeModelItem::write(stream);
stream << m_type;
}
QString TypeAliasModel::type() const
{
return m_type;
}
void TypeAliasModel::setType(const QString & type)
{
m_type = type;
}
void TypeAliasModel::update(const TypeAliasModel* i)
{
CodeModelItem::update(i);
}
bool TypeAliasModel::canUpdate(const TypeAliasModel* i) const
{
if (!CodeModelItem::canUpdate(i))
return false;
return m_type == i->m_type;
}
void FileModel::update(const FileModel* file)
{
m_parseResult = file->m_parseResult;
NamespaceModel::update(file);
}
FileList FileModel::wholeGroup()
{
if (isSingleGroup(m_groupId)) return (FileList() << FileDom(this));
return codeModel()->getGroup(m_groupId);
}
QStringList FileModel::wholeGroupStrings() const
{
if (isSingleGroup(m_groupId)) return (QStringList() << name());
return codeModel()->getGroupStrings(m_groupId);
}
ParseResultPointer FileModel::parseResult() const
{
return m_parseResult;
}
void FileModel::setParseResult(const ParseResultPointer& result)
{
m_parseResult = result;
}
| 48,420
|
C++
|
.cpp
| 1,508
| 27.833554
| 137
| 0.668785
|
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,217
|
cxx11-constexpr.cpp
|
KDE_umbrello/test/import/cxx/cxx11-constexpr.cpp
|
// https://en.wikipedia.org/wiki/C%2B%2B11#constexpr_.E2.80.93_Generalized_constant_expressions
// #1
constexpr int get_five() {return 5;}
int some_value[get_five() + 7]; // Create an array of 12 integers. Legal C++11
// #2
constexpr double earth_gravitational_acceleration = 9.8;
constexpr double moon_gravitational_acceleration = earth_gravitational_acceleration / 6.0;
class ConstExprConstructorDeclaration {
constexpr ConstExprConstructorDeclaration(QString ¶m);
};
class ConstExprConstructorDefinition {
constexpr ConstExprConstructorDefinition(QString ¶m) {}
};
class ExplicitConstExprConstructorDeclaration {
explicit constexpr ExplicitConstructorDeclaration(QString ¶m);
};
class ExplicitConstExprConstructorDefinition {
explicit constexpr ExplicitConstructorDefinition(QString ¶m) {}
};
| 834
|
C++
|
.cpp
| 19
| 41.736842
| 95
| 0.812114
|
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,218
|
po2xmi.cpp
|
KDE_umbrello/tools/po2xmi.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
SPDX-FileCopyrightText: 2014-2020 Ralf Habacker <ralf.habacker@freenet.de>
*/
#include "shared.h"
#include <stdlib.h>
#include <iostream>
#include <assert.h>
#include <fstream>
#include <QList>
#include <QTextStream>
#include <QXmlStreamReader>
using namespace std;
int main( int argc, char **argv )
{
if (argc != 3) {
qWarning("usage: %s english-XML translated-PO", argv[0]);
::exit(1);
}
TranslationMap translationMap;
if (!fetchPoFile(QLatin1String(argv[2]), translationMap)) {
cerr << "failed to fetch po file: '" << argv[2] << "'" << endl;
exit(2);
}
return applyTranslationToXMIFile(argv[1], XMILanguagesAttributes(), translationMap) ? 0 : 2;
}
| 851
|
C++
|
.cpp
| 27
| 28.074074
| 95
| 0.697304
|
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,219
|
xmi2pot.cpp
|
KDE_umbrello/tools/xmi2pot.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
SPDX-FileCopyrightText: 2014-2020 Ralf Habacker <ralf.habacker@freenet.de>
*/
#include <stdlib.h>
#include <iostream>
#include <qfileinfo.h>
#include <qdatetime.h>
#include <QStringList>
#include <QXmlStreamReader>
#include "shared.h"
using namespace std;
void outputMsg(const char *prefix, const QString &message);
int main( int argc, char **argv )
{
if (argc != 2) {
cerr << "usage: " << argv[0] << " english-XMI" << endl;
exit(1);
}
POMap map;
if (!extractAttributesFromXMI(argv[1], XMILanguagesAttributes(), map)) {
cerr << "failed to extract attributes from: '" << argv[1] << "'" << endl;
exit(2);
}
const QDateTime now = QDateTime::currentDateTime().toUTC();
cout << "# SOME DESCRIPTIVE TITLE.\n";
cout << "# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n";
cout << "#\n";
cout << "#, fuzzy\n";
cout << "msgid \"\"\n";
cout << "msgstr \"\"\n";
cout << "\"Project-Id-Version: PACKAGE VERSION\\n\"\n";
cout << "\"Report-Msgid-Bugs-To: https://bugs.kde.org\\n\"\n";
cout << "\"POT-Creation-Date: " << now.toString(QStringLiteral("yyyy-MM-dd hh:mm")).toUtf8().data() << "+0000\\n\"\n";
cout << "\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"\n";
cout << "\"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n\"\n";
cout << "\"Language-Team: LANGUAGE <kde-i18n-doc@kde.org>\\n\"\n";
cout << "\"MIME-Version: 1.0\\n\"\n";
cout << "\"Content-Type: text/plain; charset=UTF-8\\n\"\n";
cout << "\"Content-Transfer-Encoding: 8bit\\n\"\n";
cout << "\n";
const QString fname = QFileInfo(QLatin1String(argv[1])).fileName();
for (POMap::ConstIterator it = map.constBegin(); it != map.constEnd(); ++it)
{
cout << "#. Tag: " << (*it).tagNames.join(QStringLiteral(" ")).toUtf8().data() << '\n';
cout << "#: ";
for (QList<int>::ConstIterator it2 =
(*it).lineNumbers.constBegin(); it2 != (*it).lineNumbers.constEnd(); ++it2) {
if (it2 != (*it).lineNumbers.constBegin())
cout << " ";
cout << fname.toUtf8().data() << ":" << (*it2);
}
cout << "\n";
cout << "#, no-c-format\n";
cout << "msgid" << toGetTextString((*it).value).toUtf8().data() << '\n';
cout << "msgstr \"\"\n";
cout << "\n";
}
return 0;
}
| 2,501
|
C++
|
.cpp
| 61
| 35.163934
| 122
| 0.572547
|
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,220
|
shared.cpp
|
KDE_umbrello/tools/shared.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
SPDX-FileCopyrightText: 2014-2020 Ralf Habacker <ralf.habacker@freenet.de>
*/
#include "shared.h"
#include <iostream>
#include <QFile>
#include <QStringList>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QtDebug>
#include <QRegularExpression>
QDebug operator <<(QDebug out, const QXmlStreamAttribute &a)
{
out << "QXmlStreamAttribute("
<< "prefix:" << a.prefix().toString()
<< "namespaceuri:" << a.namespaceUri().toString()
<< "name:" << a.name().toString()
<< " value:" << a.value().toString()
<< ")";
return out;
}
using namespace std;
/**
* Return list of xmi file attributes containing language information.
*
* @return list of xmi element attributes
*/
QStringList XMILanguagesAttributes()
{
return QStringList() << QStringLiteral("comment") << QStringLiteral("documentation")
<< QStringLiteral("label") << QStringLiteral("name")
<< QStringLiteral("pretext") << QStringLiteral("posttext") << QStringLiteral("text")
<< QStringLiteral("statename") << QStringLiteral("activityname") << QStringLiteral("instancename");
}
/**
* Extract language related XML attributes from XMI file
* @param fileName file to extract attributes from
* @param attributes List with attribute names to extract
* @param result map with extracted results
* @return true successful extraction
* @return false extraction failure
*/
bool extractAttributesFromXMI(const char *fileName, const QStringList &attributes, POMap &result)
{
QFile file( QLatin1String((char*)fileName) );
QXmlStreamReader xmlReader;
if(!file.open(QIODevice::ReadOnly))
return false;
xmlReader.setDevice(&file);
while (!xmlReader.atEnd()) {
QXmlStreamReader::TokenType type = xmlReader.readNext();
if (type != QXmlStreamReader::StartElement)
continue;
for(const QString &attributeName : attributes) {
if (!xmlReader.attributes().hasAttribute(attributeName))
continue;
QString value = xmlReader.attributes().value(attributeName).toString();
if (value.isEmpty())
continue;
QString tagName = xmlReader.name().toString() + QLatin1Char(':') + attributeName;
QString key = value;
if (result.contains(key)) {
result[key].lineNumbers.append(xmlReader.lineNumber());
result[key].tagNames.append(tagName);
} else {
POEntry entry;
entry.tagNames.append(tagName);
entry.value = value;
entry.lineNumbers.append(xmlReader.lineNumber());
result[key] = entry;
}
}
}
if (xmlReader.hasError()) {
std::cerr << "Parsing failed." << std::endl;
return false;
}
return true;
}
QString fromGetTextString(QString s)
{
s.replace(QStringLiteral("\\n"), QStringLiteral("\n"));
s.replace(QStringLiteral("\\\""), QStringLiteral("\""));
return s;
}
QString toXMLCharacterEntities(QString s)
{
s.replace(QStringLiteral("\\n"), QStringLiteral("
"));
s.replace(QStringLiteral("\\\""), QStringLiteral("&qout;"));
s.replace(QLatin1Char('&'), QStringLiteral("&"));
s.replace(QLatin1Char('<'), QStringLiteral("<"));
s.replace(QLatin1Char('>'), QStringLiteral(">"));
return s;
}
QString escape(QString s)
{
s.replace(QRegularExpression(QStringLiteral("\\\\")), QStringLiteral("\\\\"));
s.replace(QRegularExpression(QStringLiteral("\"")), QStringLiteral("\\\""));
return s;
}
QString toGetTextString(const QString &message)
{
QStringList list = message.split(QLatin1Char('\n'));
QString line;
QString result;
if (list.count() == 1) {
line = list.first();
if (line.isEmpty())
result += QStringLiteral(" \"\"\n");
else
result += QStringLiteral(" \"") + escape(line) + QStringLiteral("\"\n");
} else {
result += QStringLiteral(" \"\"\n");
QStringList::ConstIterator last = list.constEnd();
if (!list.isEmpty())
--last;
for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it) {
line = *it;
if (!line.isEmpty()) {
result += QStringLiteral(" \"") + escape(line);
if (it == last)
result += QStringLiteral("\"\n");
else
result += QStringLiteral("\\n\"\n");
} else {
result += QStringLiteral(" \"");
if (it != last)
result += QStringLiteral("\\n");
result += QStringLiteral("\"\n");
}
}
}
return result;
}
/**
* Fetch Pot file.
*
* @param fileName file to parse
* @param map returned map with parsed items
* @return true parsed successfully
* @return false parse failure
*/
bool fetchPoFile(const QString &fileName, TranslationMap &map)
{
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly))
return false;
QTextStream in(&file);
in.setCodec("UTF-8");
QString key, value;
bool multiLineID = false;
bool multiLineValue = false;
while (!in.atEnd()) {
QString line = in.readLine();
// handle multilines
if (line.startsWith(QStringLiteral("msgid"))) {
key = line.mid(7,line.length()-7-1);
if (key.isEmpty())
multiLineID = true;
} else if (line.startsWith(QStringLiteral("msgstr"))) {
value = line.mid(8, line.length()-8-1);
if (multiLineID && !key.isEmpty() && value.isEmpty())
multiLineValue = true;
else
map[fromGetTextString(key)] = fromGetTextString(value);
} else if (multiLineID) {
QString s = line.trimmed();
if (s.isEmpty() || s[0] != QLatin1Char('\"'))
multiLineID = false;
else
key += s.mid(1,s.length()-1);
} else if (multiLineValue) {
QString s = line.trimmed();
if (s.isEmpty() || s[0] != QLatin1Char('\"')) {
multiLineValue = false;
multiLineID = false;
map[fromGetTextString(key)] = fromGetTextString(value);
}
else
value += s.mid(1,s.length()-1);
}
}
return true;
}
bool applyTranslationToXMIFile(const char *fileName, const QStringList &attributes, TranslationMap &translations)
{
QFile file(QLatin1String((char*)fileName));
if (!file.open(QIODevice::ReadOnly))
return false;
QXmlStreamReader reader(&file);
QFile outFile;
if (!outFile.open(stdout, QIODevice::WriteOnly))
return false;
QXmlStreamWriter writer(&outFile);
writer.setAutoFormatting (true);
writer.setAutoFormattingIndent(1);
writer.setCodec(reader.documentEncoding().toLatin1().constData());
while (!reader.atEnd())
{
QXmlStreamReader::TokenType type = reader.readNext();
switch(type)
{
case QXmlStreamReader::ProcessingInstruction:
writer.writeProcessingInstruction(reader.processingInstructionTarget().toString(), reader.processingInstructionData().toString());
break;
case QXmlStreamReader::DTD:
writer.writeDTD(reader.text().toString());
break;
case QXmlStreamReader::StartDocument:
writer.writeStartDocument(reader.documentVersion().toString());
break;
case QXmlStreamReader::StartElement:
{
writer.writeStartElement(reader.namespaceUri().toString(), reader.name().toString());
if (reader.namespaceDeclarations().size() > 0)
{
QXmlStreamNamespaceDeclaration ns = reader.namespaceDeclarations().first();
writer.writeNamespace(ns.namespaceUri().toString(), ns.prefix().toString());
}
const QXmlStreamAttributes& readerAttributes = reader.attributes();
QXmlStreamAttributes writerAttributes;
for(int index = 0; index < readerAttributes.size(); index++)
{
QXmlStreamAttribute attr = readerAttributes[index];
QString name = attr.qualifiedName().toString();
if (!attributes.contains(name)) {
writerAttributes.append(attr);
continue;
}
QString value = attr.value().toString();
if (value.isEmpty()) {
writerAttributes.append(attr);
continue;
}
if (!translations.contains(value))
{
cerr << "could not find translation for attribute '" << qPrintable(name) << "':'" << qPrintable(value) << "'" << std::endl;
continue;
}
QString newValue = translations[value];
if (newValue.isEmpty()) {
writerAttributes.append(attr);
continue;
}
//cerr << name.toUtf8().data() << ":" << value.toUtf8().data() << "->" << newValue.toUtf8().data() << endl;
QXmlStreamAttribute newAttribute(name, newValue);
writerAttributes.append(newAttribute);
//qDebug() << writerAttributes;
}
writer.writeAttributes(writerAttributes);
//QString content = xmlReader.readElementText(QXmlStreamReader::SkipChildElements);
//writer.writeCharacters(content);
break;
}
case QXmlStreamReader::Characters:
writer.writeCharacters(reader.text().toString());
break;
case QXmlStreamReader::Comment:
writer.writeComment(reader.text().toString());
break;
case QXmlStreamReader::EndElement:
writer.writeEndElement();
break;
case QXmlStreamReader::EndDocument:
writer.writeEndDocument();
break;
default:
break;
}
}
outFile.close();
return true;
}
| 10,472
|
C++
|
.cpp
| 275
| 28.716364
| 143
| 0.587269
|
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,221
|
testclassifier.cpp
|
KDE_umbrello/unittests/testclassifier.cpp
|
/*
SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testclassifier.h"
// app include
#include "uml.h"
#include "association.h"
#include "classifier.h"
#include "datatype.h"
#include "operation.h"
#include "model_utils.h"
//-----------------------------------------------------------------------------
void TEST_classifier::test_equal()
{
UMLClassifier* a = new UMLClassifier(QStringLiteral("Test A"), Uml::ID::None);
UMLClassifier* b = a;
UMLClassifier* c = new UMLClassifier(QStringLiteral("Test A"), Uml::ID::None);
UMLClassifier* d = new UMLClassifier(QStringLiteral("Test B"), Uml::ID::None);
QCOMPARE(*a == *b, true);
QCOMPARE(*a == *c, true);
QCOMPARE(*b == *c, true);
QCOMPARE(*c == *d, false);
}
void TEST_classifier::test_copyInto()
{
UMLClassifier a(QStringLiteral("Test A"), Uml::ID::None);
UMLClassifier b(QStringLiteral("Test B"), Uml::ID::None);
b.copyInto(&a);
QCOMPARE(a == b, true);
}
void TEST_classifier::test_clone()
{
UMLClassifier* a = new UMLClassifier(QStringLiteral("Test A"), Uml::ID::None);
UMLClassifier* b = a->clone()->asUMLClassifier();
QCOMPARE(*a == *b, true);
}
void TEST_classifier::test_addAttributeWithType()
{
UMLClassifier a(QStringLiteral("Test A"), Uml::ID::None);
a.addAttribute(QStringLiteral("attributeA_"), Uml::ID::None);
UMLAttribute *attrA = a.addAttribute(QStringLiteral("attributeA_"), Uml::ID::None);
/* UMLAttribute* attrB = */ a.addAttribute(QStringLiteral("attributeB_"), Uml::ID::None);
int num1 = a.getAttributeList().count();
QCOMPARE(num1, 2);
int num2 = a.removeAttribute(attrA);
QCOMPARE(num2, 1); // one deleted
int num3 = a.getAttributeList().count();
QCOMPARE(num3, num1 - 1);
}
void TEST_classifier::test_addAttributeWithObject()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_addAttributeWithAttribute()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_removeAndCountAttribute()
{
UMLClassifier* a = new UMLClassifier(QStringLiteral("Test A"), Uml::ID::None);
int num0 = a->getAttributeList().count();
QCOMPARE(num0, 0); // no attributes present yet
/*UMLAttribute* attrA = */ a->addAttribute(QStringLiteral("attributeA_"), Uml::ID::None);
UMLAttribute* attrB = a->addAttribute(QStringLiteral("attributeB_"), Uml::ID::None);
UMLAttribute* attrC = a->addAttribute(QStringLiteral("attributeC_"), Uml::ID::None);
/* UMLAttribute* attrD = */ a->addAttribute(QStringLiteral("attributeD_"), Uml::ID::None);
int num1 = a->getAttributeList().count();
QCOMPARE(num1, 4);
int num2 = a->removeAttribute(attrB);
QCOMPARE(num2, 3); // one deleted
num2 = a->removeAttribute(attrC);
QCOMPARE(num2, 2); // one deleted
int num3 = a->getAttributeList().count();
QCOMPARE(num3, 2);
}
void TEST_classifier::test_getAttributeList()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_addOperationWithPosition()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_addOperationWithLog()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_checkOperationSignature()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_removeAndCountOperation()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_getOperationList()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_addTemplateWithType()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_addTemplateWithLog()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_addTemplateWithPosition()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_removeAndCountTemplate()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_findTemplate()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_getTemplateList()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_takeItem()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_getFilteredList()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_resolveRef()
{
qDebug() << "already tested by testumlobject";
}
void TEST_classifier::test_findOperations()
{
UMLClassifier c(QStringLiteral("Test A"), Uml::ID::None);
UMLOperation o1(nullptr, QStringLiteral("testop1"));
c.addOperation(&o1);
int num1 = c.getOpList().count();
QCOMPARE(num1, 1);
UMLOperation o2(nullptr, QStringLiteral("testop2"));
c.addOperation(&o2);
int num2 = c.getOpList().count();
QCOMPARE(num2, 2);
QCOMPARE(c.findOperations(QStringLiteral("testop1")).count(), 1);
QCOMPARE(c.findOperations(QStringLiteral("testop2")).count(), 1);
QCOMPARE(c.findOperations(QStringLiteral("testOp1")).count(), 0);
QCOMPARE(c.findOperations(QStringLiteral("testOp2")).count(), 0);
// case insensitive language
Uml::ProgrammingLanguage::Enum lang = UMLApp::app()->activeLanguage();
UMLApp::app()->setActiveLanguage(Uml::ProgrammingLanguage::PostgreSQL);
QCOMPARE(c.findOperations(QStringLiteral("testOp1")).count(), 1);
QCOMPARE(c.findOperations(QStringLiteral("testOp2")).count(), 1);
UMLApp::app()->setActiveLanguage(lang);
}
void TEST_classifier::test_findChildObjectById()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_findOperation()
{
UMLClassifier c(QStringLiteral("Test A"), Uml::ID::None);
UMLOperation o1(nullptr, QStringLiteral("testop1"));
UMLAttribute a1(nullptr, QStringLiteral("aParam"));
a1.setTypeName(QStringLiteral("int"));
o1.addParm(&a1);
c.addOperation(&o1);
UMLOperation o2(nullptr, QStringLiteral("testop1"));
UMLAttribute a2(nullptr, QStringLiteral("aParam"));
a2.setTypeName(QStringLiteral("double"));
o2.addParm(&a2);
c.addOperation(&o2);
Model_Utils::NameAndType_List searchTypes;
// first function
searchTypes << Model_Utils::NameAndType(QStringLiteral("aParam"), a1.getType());
UMLOperation *o = c.findOperation(QStringLiteral("testop1"), searchTypes);
QVERIFY(o);
// second function
searchTypes.clear();
searchTypes << Model_Utils::NameAndType(QStringLiteral("aParam"), a2.getType());
o = c.findOperation(QStringLiteral("testop1"), searchTypes);
QVERIFY(o);
// unknown type
UMLDatatype d1(QStringLiteral("someType"));
searchTypes.clear();
searchTypes << Model_Utils::NameAndType(QStringLiteral("aParam"), &d1);
o = c.findOperation(QStringLiteral("testop1"), searchTypes);
QVERIFY(!o);
#if 0
// different param name
searchTypes.clear();
searchTypes << Model_Utils::NameAndType("otherParam", a1.getType());
o = c.findOperation("testop1", searchTypes);
QVERIFY(!o);
// different param name
searchTypes.clear();
searchTypes << Model_Utils::NameAndType("otherParam", a2.getType());
o = c.findOperation("testop1", searchTypes);
QVERIFY(!o);
#else
qDebug() <<"finding param names is not supported";
#endif
}
void TEST_classifier::test_findSuperClassConcepts()
{
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
UMLAssociation a1(Uml::AssociationType::Generalization, &c1, &c2);
QCOMPARE(c1.findSuperClassConcepts(UMLClassifier::ALL).size(), 0);
c1.addAssociationEnd(&a1);
QCOMPARE(c1.findSuperClassConcepts(UMLClassifier::ALL).size(), 1);
UMLAssociation a2(Uml::AssociationType::Realization, &c1, &c2);
c1.addAssociationEnd(&a2);
QCOMPARE(c1.findSuperClassConcepts(UMLClassifier::ALL).size(), 2);
}
void TEST_classifier::test_findSubClassConcepts()
{
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
UMLAssociation a1(Uml::AssociationType::Generalization, &c1, &c2);
QCOMPARE(c2.findSubClassConcepts(UMLClassifier::ALL).size(), 0);
c2.addAssociationEnd(&a1);
QCOMPARE(c2.findSubClassConcepts(UMLClassifier::ALL).size(), 1);
UMLAssociation a2(Uml::AssociationType::Realization, &c1, &c2);
c2.addAssociationEnd(&a2);
QCOMPARE(c2.findSubClassConcepts(UMLClassifier::ALL).size(), 2);
}
void TEST_classifier::test_setGetClassAssoc()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_isInterface()
{
UMLClassifier c1(QStringLiteral("Test A"));
QCOMPARE(c1.isInterface(), false);
c1.setBaseType(UMLObject::ObjectType::ot_Interface);
QCOMPARE(c1.isInterface(), true);
c1.setBaseType(UMLObject::ObjectType::ot_Class);
QCOMPARE(c1.isInterface(), false);
}
void TEST_classifier::test_setGetOriginType()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_setGetIsReference()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_hasAbstractOps()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_makeChildObject()
{
IS_NOT_IMPL();
}
void TEST_classifier::test_getUniAssociationToBeImplemented()
{
IS_NOT_IMPL();
}
typedef TestUML<UMLClassifier, const QString&> TestUMLClassifier;
void TEST_classifier::test_saveAndLoad()
{
UMLPackage parent(QStringLiteral("test package"));
TestUMLClassifier c1(QStringLiteral("Test A"));
c1.setUMLPackage(&parent);
UMLOperation o1(nullptr, QStringLiteral("testop1"));
c1.addOperation(&o1);
UMLOperation o2(nullptr, QStringLiteral("testop2"));
c1.addOperation(&o2);
QString save = c1.testSave1();
//c1.testDump("save");
TestUMLClassifier c2;
c2.setUMLPackage(&parent);
QCOMPARE(c2.testLoad1(save), true);
//c2.testDump("after load");
QCOMPARE(c2.testSave1(), save);
}
QTEST_MAIN(TEST_classifier)
| 9,404
|
C++
|
.cpp
| 282
| 29.904255
| 94
| 0.705221
|
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,222
|
testcppwriter.cpp
|
KDE_umbrello/unittests/testcppwriter.cpp
|
/*
SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testcppwriter.h"
// app include
#include "classifier.h"
#include "cppwriter.h"
const bool IS_NOT_IMPL = false;
//-----------------------------------------------------------------------------
class CppWriterTest : public CppWriter
{
public:
QString findFileName(UMLPackage* classifier, const QString &ext)
{
return CppWriter::findFileName(classifier, ext);
}
};
void TestCppWriter::test_language()
{
CppWriter* cpp = new CppWriter();
Uml::ProgrammingLanguage::Enum lang = cpp->language();
QVERIFY(lang == Uml::ProgrammingLanguage::Cpp);
}
void TestCppWriter::test_writeClass()
{
CppWriterTest* cpp = new CppWriterTest();
UMLClassifier* c = new UMLClassifier(QStringLiteral("Customer"), "12345678");
UMLAttribute* attr;
attr = c->createAttribute(QStringLiteral("name_"));
attr = c->createAttribute(QStringLiteral("address_"));
c->addAttribute(attr);
UMLOperation* op;
op = c->createOperation(QStringLiteral("getName"));
op = c->createOperation(QStringLiteral("getAddress"));
c->addOperation(op);
cpp->writeClass(c);
// does the just created file exist?
QFile fileHeader(temporaryPath() + cpp->findFileName(c, QStringLiteral(".h")));
QFile fileCPP(temporaryPath() + cpp->findFileName(c, QStringLiteral(".cpp")));
QCOMPARE(fileHeader.exists(), true);
QCOMPARE(fileCPP.exists(), true);
}
void TestCppWriter::test_reservedKeywords()
{
CppWriter* cpp = new CppWriter();
QStringList list = cpp->reservedKeywords();
QCOMPARE(list.empty(), false);
QCOMPARE(list[0], QStringLiteral("and"));
QCOMPARE(list[11], QStringLiteral("case"));
QCOMPARE(list.last(), QStringLiteral("xor_eq"));
}
void TestCppWriter::test_defaultDatatypes()
{
CppWriter* cpp = new CppWriter();
QStringList list = cpp->defaultDatatypes();
QCOMPARE(list.empty(), false);
QCOMPARE(list[1], QStringLiteral("int"));
QCOMPARE(list[10], QStringLiteral("short int"));
QCOMPARE(list[5], QStringLiteral("string"));
}
QTEST_MAIN(TestCppWriter)
| 2,226
|
C++
|
.cpp
| 62
| 32.274194
| 88
| 0.689126
|
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,223
|
testpreconditionwidget.cpp
|
KDE_umbrello/unittests/testpreconditionwidget.cpp
|
/*
SPDX-FileCopyrightText: 2019 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testpreconditionwidget.h"
#include "preconditionwidget.h"
#include "folder.h"
#include "objectwidget.h"
#include "umlscene.h"
#include <QXmlStreamWriter>
typedef TestWidget<PreconditionWidget, ObjectWidget*> TestPreconditionWidgetClass;
void TestPreconditionWidget::test_saveAndLoad()
{
UMLFolder folder(QStringLiteral("testfolder"));
UMLScene scene(&folder);
UMLObject o(nullptr);
ObjectWidget ow(&scene, &o);
scene.addWidgetCmd(&ow);
TestPreconditionWidgetClass pw1(&scene, &ow);
scene.addWidgetCmd(&pw1);
QString save = pw1.testSave1();
//pw1.testDump("save");
TestPreconditionWidgetClass pw2(&scene, nullptr);
QCOMPARE(pw2.testLoad1(save), true);
QCOMPARE(pw2.testSave1(), save);
//pw2.testDump("load");
QCOMPARE(pw2.objectWidget(), &ow);
}
QTEST_MAIN(TestPreconditionWidget)
| 1,023
|
C++
|
.cpp
| 29
| 31.793103
| 88
| 0.75355
|
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,225
|
testumlobject.cpp
|
KDE_umbrello/unittests/testumlobject.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 "testumlobject.h"
// app include
#include "attribute.h"
#include "classifier.h"
#include "folder.h"
#include "operation.h"
#include "package.h"
#include "stereotype.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QXmlStreamWriter>
//-----------------------------------------------------------------------------
void TestUMLObject::test_copyInto()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject a(QStringLiteral("Test A"));
a.setUMLPackage(&parent);
UMLObject b(QStringLiteral("Test B"));
b.setUMLPackage(&parent);
b.copyInto(&a);
QCOMPARE(a, b);
UMLClassifier c(QStringLiteral("Test Classifier"));
UMLOperation op(&c, QStringLiteral("Test Parent"));
UMLAttribute at(&op, QStringLiteral("Attribute"));
UMLAttribute at2(&op,QStringLiteral("Attribute 2"));
at2.copyInto(&at);
QCOMPARE(at, at2);
QCOMPARE(at2.umlParent(), at.umlParent());
}
void TestUMLObject::test_clone()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject a(QStringLiteral("Test A"));
a.setUMLPackage(&parent);
UMLObject &b = *a.clone();
QCOMPARE(a, b);
}
void TestUMLObject::test_doc()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject a(QStringLiteral("Test A"));
QCOMPARE(a.hasDoc(), false);
a.setDoc(QStringLiteral("new doc"));
QCOMPARE(a.hasDoc(), true);
QCOMPARE(a.doc(), QStringLiteral("new doc"));
}
void TestUMLObject::test_equal()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject a(QStringLiteral("Test A"), Uml::ID::Reserved);
a.setUMLPackage(&parent);
UMLObject b(a);
UMLObject c(QStringLiteral("Test A"), Uml::ID::Reserved);
c.setUMLPackage(&parent);
UMLObject d(QStringLiteral("Test B"), Uml::ID::None);
QCOMPARE(a, b);
QCOMPARE(a, c);
QCOMPARE(b, c);
QCOMPARE(c == d, false);
}
void TestUMLObject::test_fullyQualifiedName()
{
UMLObject* a = new UMLObject(QStringLiteral("Test A"));
cleanupOnExit(a);
QCOMPARE(a->fullyQualifiedName(), QStringLiteral("Test A"));
UMLPackage* topParent = new UMLPackage(QStringLiteral("Top Parent"));
cleanupOnExit(topParent);
UMLPackage* parent = new UMLPackage(QStringLiteral("Test Parent"));
cleanupOnExit(parent);
parent->setUMLPackage(topParent);
a->setUMLPackage(parent);
QCOMPARE(a->umlPackage()->fullyQualifiedName(), a->package());
QCOMPARE(a->fullyQualifiedName(), QStringLiteral("Top Parent::Test Parent::Test A"));
QCOMPARE(a->fullyQualifiedName(QStringLiteral("-")), QStringLiteral("Top Parent-Test Parent-Test A"));
UMLFolder *f = UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical);
parent->setUMLPackage(f);
QCOMPARE(a->fullyQualifiedName(QStringLiteral("::"), true), QStringLiteral("Logical View::Test Parent::Test A"));
}
void TestUMLObject::test_isAbstract()
{
UMLObject a(QStringLiteral("Test A"));
QCOMPARE(a.isAbstract(), false);
a.setAbstract(true);
QCOMPARE(a.isAbstract(), true);
}
void TestUMLObject::test_isStatic()
{
UMLObject a(QStringLiteral("Test A"));
QCOMPARE(a.isStatic(), false);
a.setStatic(true);
QCOMPARE(a.isStatic(), true);
}
typedef TestUML<UMLObject, const QString &> TESTUMLObject;
void TestUMLObject::test_resolveRef()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLStereotype *stereotype = UMLApp::app()->document()->createStereotype(QStringLiteral("test"));
UMLObject a(QStringLiteral("Test A"));
// no resolve
a.setUMLPackage(&parent);
QCOMPARE(a.resolveRef(), true);
// secondary
a.setSecondaryId(Uml::ID::toString(stereotype->id()));
QCOMPARE(a.resolveRef(), true);
// secondary fallback
a.setSecondaryId(QStringLiteral(""));
a.setSecondaryFallback(Uml::ID::toString(stereotype->id()));
QCOMPARE(a.resolveRef(), true);
// unknown stereotype
TESTUMLObject b(QStringLiteral("Test B"));
UMLStereotype stereotype2(QStringLiteral("test"));
b.setUMLPackage(&parent);
b.setSecondaryId(Uml::ID::toString(stereotype2.id()));
QCOMPARE(b.resolveRef(), true);
// resolveRef creates an "undef" datatype and assigns it to m_Secondary
QCOMPARE(b.secondary()->name(), QStringLiteral("undef"));
}
void TestUMLObject::test_saveAndLoad()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject a(QStringLiteral("Test A"));
a.setUMLPackage(&parent);
a.setStereotypeCmd(QStringLiteral("test"));
// save
QString xml;
QXmlStreamWriter writer(&xml);
a.save1(writer, QStringLiteral("test"));
writer.writeEndElement();
// convert XML string to QDomElement
QString error;
int line;
QDomDocument doc;
QVERIFY(doc.setContent(xml, &error, &line));
QDomElement save = doc.firstChild().toElement();
// load
UMLObject b;
b.setUMLPackage(&parent);
QCOMPARE(b.loadFromXMI(save), true);
QCOMPARE(a, b);
}
void TestUMLObject::test_setBaseType()
{
UMLObject a(QStringLiteral("Test A"));
QCOMPARE(a.baseType(), UMLObject::ot_UMLObject);
a.setBaseType(UMLObject::ot_Class);
QCOMPARE(a.baseType(), UMLObject::ot_Class);
}
void TestUMLObject::test_setStereotype()
{
UMLObject a(QStringLiteral("Test A"));
QCOMPARE(a.stereotype(), QStringLiteral(""));
a.setStereotypeCmd(QStringLiteral("test"));
QCOMPARE(a.stereotype(), QStringLiteral("test"));
}
void TestUMLObject::test_setUMLPackage()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject a(QStringLiteral("Test A"));
QCOMPARE(a.umlPackage(), (UMLPackage*)0);
a.setUMLPackage(&parent);
QCOMPARE(a.umlPackage(), &parent);
}
void TestUMLObject::test_setVisibility()
{
UMLObject a(QStringLiteral("Test A"));
QVERIFY(a.visibility() == Uml::Visibility::Public);
a.setVisibilityCmd(Uml::Visibility::Protected);
QVERIFY(a.visibility() == Uml::Visibility::Protected);
a.setVisibilityCmd(Uml::Visibility::Private);
QVERIFY(a.visibility() == Uml::Visibility::Private);
a.setVisibilityCmd(Uml::Visibility::Implementation);
QVERIFY(a.visibility() == Uml::Visibility::Implementation);
a.setVisibilityCmd(Uml::Visibility::FromParent);
QVERIFY(a.visibility() == Uml::Visibility::FromParent);
}
void TestUMLObject::test_toString()
{
QCOMPARE(UMLObject::toString(UMLObject::ot_Class), QStringLiteral("ot_Class"));
QCOMPARE(UMLObject::toI18nString(UMLObject::ot_Class), i18n("Class &name:"));
}
void TestUMLObject::test_dynamic_cast()
{
QScopedPointer<UMLObject> a1(new UMLClassifier);
const UMLClassifier *b = a1->asUMLClassifier();
QVERIFY(b);
UMLObject *a2 = nullptr;
b = a2->asUMLClassifier();
QVERIFY(!b);
}
void TestUMLObject::test_isUMLXXX()
{
UMLObject a(QStringLiteral("Test A"));
QVERIFY(a.isUMLObject());
a.setBaseType(UMLObject::ObjectType::ot_Actor);
QVERIFY(a.isUMLActor());
a.setBaseType(UMLObject::ObjectType::ot_Artifact);
QVERIFY(a.isUMLArtifact());
a.setBaseType(UMLObject::ObjectType::ot_Association);
QVERIFY(a.isUMLAssociation());
a.setBaseType(UMLObject::ObjectType::ot_Attribute);
QVERIFY(a.isUMLAttribute());
a.setBaseType(UMLObject::ObjectType::ot_Category);
QVERIFY(a.isUMLCategory());
a.setBaseType(UMLObject::ObjectType::ot_CheckConstraint);
QVERIFY(a.isUMLCheckConstraint());
a.setBaseType(UMLObject::ObjectType::ot_Class);
QVERIFY(a.isUMLClassifier());
a.setBaseType(UMLObject::ObjectType::ot_Component);
QVERIFY(a.isUMLComponent());
a.setBaseType(UMLObject::ObjectType::ot_Datatype);
QVERIFY(a.isUMLDatatype());
a.setBaseType(UMLObject::ObjectType::ot_Entity);
QVERIFY(a.isUMLEntity());
a.setBaseType(UMLObject::ObjectType::ot_EntityAttribute);
QVERIFY(a.isUMLEntityAttribute());
a.setBaseType(UMLObject::ObjectType::ot_EntityConstraint);
QVERIFY(a.isUMLEntityConstraint());
a.setBaseType(UMLObject::ObjectType::ot_Enum);
QVERIFY(a.isUMLEnum());
a.setBaseType(UMLObject::ObjectType::ot_EnumLiteral);
QVERIFY(a.isUMLEnumLiteral());
a.setBaseType(UMLObject::ObjectType::ot_Folder);
QVERIFY(a.isUMLFolder());
a.setBaseType(UMLObject::ObjectType::ot_ForeignKeyConstraint);
QVERIFY(a.isUMLForeignKeyConstraint());
a.setBaseType(UMLObject::ObjectType::ot_Instance);
QVERIFY(a.isUMLInstance());
a.setBaseType(UMLObject::ObjectType::ot_InstanceAttribute);
QVERIFY(a.isUMLInstanceAttribute());
// UMLClassifier has isInterface()
// a.setBaseType(UMLObject::ObjectType::ot_Interface);
// QVERIFY(a.isUMLInterface());
a.setBaseType(UMLObject::ObjectType::ot_Node);
QVERIFY(a.isUMLNode());
a.setBaseType(UMLObject::ObjectType::ot_Operation);
QVERIFY(a.isUMLOperation());
a.setBaseType(UMLObject::ObjectType::ot_Package);
QVERIFY(a.isUMLPackage());
a.setBaseType(UMLObject::ObjectType::ot_Port);
QVERIFY(a.isUMLPort());
a.setBaseType(UMLObject::ObjectType::ot_Role);
QVERIFY(a.isUMLRole());
a.setBaseType(UMLObject::ObjectType::ot_Stereotype);
QVERIFY(a.isUMLStereotype());
// a.setBaseType(UMLObject::ObjectType::ot_SubSystem);
// QVERIFY(a.isUMLSubSystem());
a.setBaseType(UMLObject::ObjectType::ot_Template);
QVERIFY(a.isUMLTemplate());
a.setBaseType(UMLObject::ObjectType::ot_UMLObject);
QVERIFY(a.isUMLObject());
a.setBaseType(UMLObject::ObjectType::ot_UniqueConstraint);
QVERIFY(a.isUMLUniqueConstraint());
a.setBaseType(UMLObject::ObjectType::ot_UseCase);
QVERIFY(a.isUMLUseCase());
}
QTEST_MAIN(TestUMLObject)
| 9,840
|
C++
|
.cpp
| 264
| 33.25
| 117
| 0.712115
|
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,226
|
testlistpopupmenu.cpp
|
KDE_umbrello/unittests/testlistpopupmenu.cpp
|
/*
SPDX-FileCopyrightText: 2018 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testlistpopupmenu.h"
#include "associationwidgetpopupmenu.h"
#include "dialogspopupmenu.h"
#include "widgetbasepopupmenu.h"
#include "umllistviewpopupmenu.h"
#include "umlscenepopupmenu.h"
#include "category.h"
#include "entity.h"
#include "classifier.h"
#include "instance.h"
#include "associationwidget.h"
#include "categorywidget.h"
#include "classifierwidget.h"
#include "entitywidget.h"
#include "folder.h"
#include "umllistview.h"
#include "umlscene.h"
#include "umlview.h"
void TestListPopupMenu::test_createWidgetsSingleSelect()
{
UMLFolder folder(QStringLiteral("test"));
UMLView view(&folder);
UMLScene scene(&folder, &view);
QWidget qWidget;
for(int i = WidgetBase::wt_Min+1; i < WidgetBase::wt_Max; i++) {
WidgetBase::WidgetType type = static_cast<WidgetBase::WidgetType>(i);
WidgetBase *widget = nullptr;
if (type == WidgetBase::wt_Entity) {
widget = new EntityWidget(&scene, new UMLEntity(QStringLiteral("entity")));
} else if (type == WidgetBase::wt_Category) {
widget = new CategoryWidget(&scene, new UMLCategory(QStringLiteral("category")));
} else if (type == WidgetBase::wt_Class) {
widget = new ClassifierWidget(&scene, new UMLClassifier(QStringLiteral("classifier")));
} else if (type == WidgetBase::wt_Interface) {
widget = new ClassifierWidget(&scene, new UMLClassifier(QStringLiteral("instance")));
widget->setBaseType(type);
} else
widget = new WidgetBase(&scene, type);
WidgetBasePopupMenu popup(&qWidget, widget, false);
popup.dumpActions(WidgetBase::toString(type));
}
}
void TestListPopupMenu::test_createWidgetsMultiSelect()
{
UMLFolder folder(QStringLiteral("test"));
UMLView view(&folder);
UMLScene scene(&folder, &view);
QWidget qWidget;
for(int i = WidgetBase::wt_Min+1; i < WidgetBase::wt_Max; i++) {
WidgetBase::WidgetType type = static_cast<WidgetBase::WidgetType>(i);
WidgetBase *widget = nullptr;
if (type == WidgetBase::wt_Entity) {
widget = new EntityWidget(&scene, new UMLEntity(QStringLiteral("entity")));
} else if (type == WidgetBase::wt_Category) {
widget = new CategoryWidget(&scene, new UMLCategory(QStringLiteral("category")));
} else if (type == WidgetBase::wt_Class) {
widget = new ClassifierWidget(&scene, new UMLClassifier(QStringLiteral("classifier")));
} else if (type == WidgetBase::wt_Interface) {
widget = new ClassifierWidget(&scene, new UMLClassifier(QStringLiteral("instance")));
widget->setBaseType(type);
} else
widget = new WidgetBase(&scene, type);
WidgetBasePopupMenu popupMulti(&qWidget, widget, true, type);
popupMulti.dumpActions(WidgetBase::toString(type));
}
}
void TestListPopupMenu::test_createAssociationWidget()
{
UMLFolder folder(QStringLiteral("test"));
UMLView view(&folder);
UMLScene scene(&folder, &view);
QWidget qWidget;
UMLWidget widgetA(&scene, WidgetBase::wt_UMLWidget, nullptr), widgetB(&scene, WidgetBase::wt_UMLWidget, nullptr);
for (int i = Uml::AssociationType::Generalization; i < Uml::AssociationType::Reserved; ++i) {
Uml::AssociationType::Enum type = Uml::AssociationType::fromInt(i);
AssociationWidget *widget = AssociationWidget::create(&scene, &widgetA, type, &widgetB);
AssociationWidgetPopupMenu popup(&qWidget,type, widget);
popup.dumpActions(Uml::AssociationType::toString(type));
}
}
void TestListPopupMenu::test_createUMLScene()
{
UMLFolder folder(QStringLiteral("test"));
UMLView view(&folder);
QWidget qWidget;
for(int i = Uml::DiagramType::Undefined+1; i < Uml::DiagramType::N_DIAGRAMTYPES; i++) {
Uml::DiagramType::Enum type = Uml::DiagramType::fromInt(i);
view.umlScene()->setType(type);
UMLScenePopupMenu popup(&qWidget, view.umlScene());
popup.dumpActions(Uml::DiagramType::toString(type));
}
}
void TestListPopupMenu::test_createUMLListview()
{
QWidget qWidget;
UMLObject object;
UMLCategory category;
UMLListView view;
for(int i = UMLListViewItem::ListViewType::lvt_Min+1; i < UMLListViewItem::ListViewType::lvt_Max; i++) {
UMLListViewItem::ListViewType type = static_cast<UMLListViewItem::ListViewType>(i);
UMLListViewItem item(&view, QStringLiteral("test"), type);
item.setUMLObject(type == UMLListViewItem::ListViewType::lvt_Category ? &category : &object);
UMLListViewPopupMenu popup(&qWidget, &item);
popup.dumpActions(UMLListViewItem::toString(type));
}
}
void TestListPopupMenu::test_createMiscMenu()
{
QWidget qWidget;
for(int i = DialogsPopupMenu::TriggerType::tt_Min+1; i < DialogsPopupMenu::TriggerType::tt_Max; i++) {
DialogsPopupMenu::TriggerType tt = static_cast<DialogsPopupMenu::TriggerType>(i);
DialogsPopupMenu popup(&qWidget, tt);
popup.dumpActions(DialogsPopupMenu::toString(tt));
}
}
QTEST_MAIN(TestListPopupMenu)
| 5,287
|
C++
|
.cpp
| 120
| 38.316667
| 117
| 0.697711
|
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,227
|
testoptionstate.cpp
|
KDE_umbrello/unittests/testoptionstate.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 "testoptionstate.h"
#include "optionstate.h"
void TestOptionState::test_create()
{
Settings::OptionState options;
QCOMPARE(options.classState.showAtts, false);
QCOMPARE(options.classState.showOps, false);
QCOMPARE(options.uiState.useFillColor, false);
QScopedPointer<Settings::OptionState> optionsA(new Settings::OptionState);
QCOMPARE(optionsA->classState.showAtts, false);
QCOMPARE(optionsA->classState.showOps, false);
QCOMPARE(optionsA->uiState.useFillColor, false);
}
void TestOptionState::test_saveAndLoad()
{
Settings::OptionState options;
options.classState.showAtts = true;
options.classState.showOps = true;
options.uiState.useFillColor = true;
// save
QString xml;
QXmlStreamWriter stream(&xml);
stream.writeStartElement(QStringLiteral("test"));
options.saveToXMI(stream);
stream.writeEndElement();
// convert XML string to QDomElement
QDomDocument doc;
QString error;
int line;
QVERIFY(doc.setContent(xml, &error, &line));
QDomElement element = doc.firstChild().toElement();
// load
Settings::OptionState optionsB;
QCOMPARE(optionsB.loadFromXMI(element), true);
QCOMPARE(optionsB.classState.showAtts, true);
QCOMPARE(optionsB.classState.showOps, true);
QCOMPARE(optionsB.uiState.useFillColor, true);
}
QTEST_MAIN(TestOptionState)
| 1,550
|
C++
|
.cpp
| 43
| 31.837209
| 88
| 0.753507
|
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,228
|
testllvmparser.cpp
|
KDE_umbrello/unittests/testllvmparser.cpp
|
/*
SPDX-FileCopyrightText: 2016 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include <clang/Basic/Version.h>
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/Tooling.h"
#include <QFile>
#include <QString>
using namespace clang;
class FindNamedClassVisitor : public RecursiveASTVisitor<FindNamedClassVisitor>
{
public:
explicit FindNamedClassVisitor(ASTContext *Context)
: Context(Context)
{
}
bool VisitStmt(Stmt *s)
{
s->dump();
return true;
}
bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
{
if (Declaration->getQualifiedNameAsString() == "n::m::C") {
#if CLANG_VERSION_MAJOR >= 8
FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getBeginLoc());
#else
FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getLocStart());
#endif
if (FullLocation.isValid())
llvm::outs() << "Found declaration at "
<< FullLocation.getSpellingLineNumber() << ":"
<< FullLocation.getSpellingColumnNumber() << "\n";
}
return true;
}
private:
ASTContext *Context;
};
class FindNamedClassConsumer : public clang::ASTConsumer
{
public:
explicit FindNamedClassConsumer(ASTContext *Context)
: Visitor(Context)
{
}
virtual void HandleTranslationUnit(clang::ASTContext &Context)
{
if (!Visitor.TraverseDecl(Context.getTranslationUnitDecl()))
llvm::errs() << "could not parse file";
}
private:
FindNamedClassVisitor Visitor;
};
class FindNamedClassAction : public clang::ASTFrontendAction
{
public:
virtual std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &Compiler, llvm::StringRef InFile)
{
Q_UNUSED(InFile);
return std::unique_ptr<clang::ASTConsumer>(
new FindNamedClassConsumer(&Compiler.getASTContext()));
}
};
int main(int argc, char **argv)
{
QByteArray defaultSource = "namespace n {\n namespace m {\n class C {}; \n} \n}";
if (argc > 1) {
QFile source(argv[1]);
if (!source.open(QFile::ReadOnly))
return 1;
defaultSource = source.readAll();
}
return clang::tooling::runToolOnCode(new FindNamedClassAction, defaultSource.data()) ? 0 : 2;
}
| 2,568
|
C++
|
.cpp
| 80
| 26.525
| 97
| 0.679466
|
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,229
|
testwidgetbase.cpp
|
KDE_umbrello/unittests/testwidgetbase.cpp
|
/*
SPDX-FileCopyrightText: 2020 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testwidgetbase.h"
#include "folder.h"
#include "widgetbase.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
void TestWidgetBase::test_setSelected()
{
UMLFolder folder(QStringLiteral("folder"));
UMLView view(&folder);
UMLScene scene(&folder, &view);
WidgetBase widget1(&scene, WidgetBase::wt_UMLWidget);
scene.addItem(&widget1);
// simple widget
widget1.setSelected(true);
QVERIFY(widget1.isSelected());
widget1.setSelected(false);
QVERIFY(!widget1.isSelected());
widget1.setSelected(true);
scene.clearSelected();
QVERIFY(!widget1.isSelected());
}
void TestWidgetBase::test_clearSelected()
{
UMLFolder folder(QStringLiteral("folder"));
UMLView view(&folder);
UMLScene scene(&folder, &view);
UMLWidget widget1(&scene, WidgetBase::wt_Text, nullptr);
scene.addItem(&widget1);
UMLWidget widget2(&scene, WidgetBase::wt_Box, nullptr);
scene.addItem(&widget2);
widget2.setSelected(true);
widget1.setSelected(true);
QVERIFY(widget1.isSelected());
QVERIFY(widget2.isSelected());
scene.clearSelected();
QVERIFY(!widget1.isSelected());
QVERIFY(!widget2.isSelected());
widget2.setSelected(true);
widget1.setSelected(true);
QVERIFY(widget1.isSelected());
QVERIFY(widget2.isSelected());
scene.clearSelection();
}
QTEST_MAIN(TestWidgetBase)
| 1,559
|
C++
|
.cpp
| 49
| 27.897959
| 88
| 0.727212
|
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,230
|
testbasictypes.cpp
|
KDE_umbrello/unittests/testbasictypes.cpp
|
/*
SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testbasictypes.h"
// app includes
#include "basictypes.h"
// qt includes
#include <QtTest>
#include <QDomDocument>
//-----------------------------------------------------------------------------
class A
{
public:
virtual ~A () { }
};
class B : public A
{
};
B* asB(A* p)
{
return dynamic_cast<B*>(p);
}
A* getPointer()
{
return nullptr;
}
void TestBasicTypes::test_dynamic_cast()
{
QScopedPointer<A> a1(new A);
B* b1 = dynamic_cast<B*> (a1.data());
QVERIFY(!b1);
QScopedPointer<A> a2(new B);
B* b2 = dynamic_cast<B*> (a2.data());
QVERIFY(b2);
QScopedPointer<A> a3((B*)nullptr);
B* b3 = dynamic_cast<B*> (a3.data());
QVERIFY(!b3);
B* b4 = dynamic_cast<B*> (getPointer());
QVERIFY(!b4);
B* b5 = asB(getPointer());
QVERIFY(!b5);
}
void TestBasicTypes::test_QString_english()
{
QLocale _default = QLocale();
QLocale english(QLocale::English);
QLocale::setDefault(english);
QString value1String(QStringLiteral("123.456"));
float referenceValue = 123.456;
qreal referenceDValue = 123.456;
QString a = QString::number(referenceValue);
QCOMPARE(value1String, a);
bool ok;
float value = value1String.toFloat(&ok);
QVERIFY(ok);
QCOMPARE(value, referenceValue);
qreal dValue = value1String.toDouble(&ok);
QVERIFY(ok);
QCOMPARE(dValue, referenceDValue);
QLocale::setDefault(_default);
}
void TestBasicTypes::test_QString_non_english()
{
QLocale _default = QLocale();
QLocale hungarian(QLocale::Hungarian);
QLocale::setDefault(hungarian);
QString value1String(QStringLiteral("123.456"));
float referenceValue = 123.456;
qreal referenceDValue = 123.456;
QString a = QString::number(referenceValue);
QCOMPARE(value1String, a);
bool ok;
float value = value1String.toFloat(&ok);
QVERIFY(ok);
QCOMPARE(value, referenceValue);
qreal dValue = value1String.toDouble(&ok);
QVERIFY(ok);
QCOMPARE(dValue, referenceDValue);
QLocale::setDefault(_default);
}
void TestBasicTypes::test_DomDocument_english()
{
QLocale _default = QLocale();
QLocale locale(QLocale::English);
QLocale::setDefault(locale);
QCOMPARE(QChar(QLatin1Char('.')), locale.decimalPoint());
float fVar = 123.456;
double dVar = 123.456;
QString refValue(QStringLiteral("123.456"));
QString localeValue;
localeValue.replace(QLatin1Char('.'), _default.decimalPoint());
QDomDocument doc(QStringLiteral("test"));
QDomElement root = doc.createElement(QStringLiteral("test"));
doc.appendChild(root);
root.setAttribute(QStringLiteral("a"), fVar);
QString xml = doc.toString();
QVERIFY2(xml.contains(refValue), xml.toLatin1().constData());
// caused by bug in Qt xml
root.setAttribute(QStringLiteral("a"), dVar);
xml = doc.toString();
QVERIFY2(xml.contains(localeValue), xml.toLatin1().constData());
root.setAttribute(QStringLiteral("a"), QString::number(fVar));
xml = doc.toString();
QVERIFY(xml.contains(refValue));
root.setAttribute(QStringLiteral("a"), QString::number(dVar));
xml = doc.toString();
QVERIFY2(xml.contains(refValue), xml.toLatin1().constData());
QLocale::setDefault(_default);
}
void TestBasicTypes::test_DomDocument_non_english()
{
QLocale _default = QLocale();
QLocale locale(QLocale::Hungarian);
QLocale::setDefault(locale);
QCOMPARE(QChar(QLatin1Char(',')), locale.decimalPoint());
float fVar = 123.456;
double dVar = 123.456;
QString refValue(QStringLiteral("123.456"));
QString localeValue;
localeValue.replace(QLatin1Char('.'), _default.decimalPoint());
QDomDocument doc(QStringLiteral("test"));
QDomElement root = doc.createElement(QStringLiteral("test"));
doc.appendChild(root);
root.setAttribute(QStringLiteral("a"), fVar);
QString xml = doc.toString();
QVERIFY2(xml.contains(refValue), xml.toLatin1().constData());
// caused by bug in Qt xml
root.setAttribute(QStringLiteral("a"), dVar);
xml = doc.toString();
QVERIFY2(xml.contains(localeValue), xml.toLatin1().constData());
root.setAttribute(QStringLiteral("a"), QString::number(fVar));
xml = doc.toString();
QVERIFY2(xml.contains(refValue), xml.toLatin1().constData());
root.setAttribute(QStringLiteral("a"), QString::number(dVar));
xml = doc.toString();
QVERIFY2(xml.contains(refValue), xml.toLatin1().constData());
QLocale::setDefault(_default);
}
void TestBasicTypes::test_ModelType_toString()
{
Uml::ModelType::Enum model0 = Uml::ModelType::Logical;
QCOMPARE(Uml::ModelType::toString(model0), QStringLiteral("Logical"));
Uml::ModelType::Enum model1 = Uml::ModelType::UseCase;
QCOMPARE(Uml::ModelType::toString(model1), QStringLiteral("UseCase"));
Uml::ModelType::Enum model2(Uml::ModelType::Component);
QCOMPARE(Uml::ModelType::toString(model2), QStringLiteral("Component"));
Uml::ModelType::Enum model3(Uml::ModelType::Deployment);
QCOMPARE(Uml::ModelType::toString(model3), QStringLiteral("Deployment"));
Uml::ModelType::Enum model4(Uml::ModelType::EntityRelationship);
QCOMPARE(Uml::ModelType::toString(model4), QStringLiteral("EntityRelationship"));
}
void TestBasicTypes::test_ModelType_fromString()
{
QString modelStr;
Uml::ModelType::Enum model;
modelStr = QStringLiteral("Logical");
model = Uml::ModelType::fromString(modelStr);
QVERIFY(model == Uml::ModelType::Logical);
modelStr = QStringLiteral("UseCase");
model = Uml::ModelType::fromString(modelStr);
QVERIFY(model == Uml::ModelType::UseCase);
modelStr = QStringLiteral("Component");
model = Uml::ModelType::fromString(modelStr);
QVERIFY(model == Uml::ModelType::Component);
modelStr = QStringLiteral("Deployment");
model = Uml::ModelType::fromString(modelStr);
QVERIFY(model == Uml::ModelType::Deployment);
modelStr = QStringLiteral("EntityRelationship");
model = Uml::ModelType::fromString(modelStr);
QVERIFY(model == Uml::ModelType::EntityRelationship);
}
void TestBasicTypes::test_ModelType_forLoop()
{
Uml::ModelType::Enum list[Uml::ModelType::N_MODELTYPES];
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
list[i] = Uml::ModelType::fromInt(i);
}
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
QVERIFY(list[i] == Uml::ModelType::fromInt(i));
}
QVERIFY(list[0] == Uml::ModelType::Logical);
QVERIFY(list[1] == Uml::ModelType::UseCase);
QVERIFY(list[2] == Uml::ModelType::Component);
QVERIFY(list[3] == Uml::ModelType::Deployment);
QVERIFY(list[4] == Uml::ModelType::EntityRelationship);
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_Visibility_toString()
{
Uml::Visibility::Enum visibility1 = Uml::Visibility::Public;
QCOMPARE(Uml::Visibility::toString(visibility1), QStringLiteral("public"));
QCOMPARE(Uml::Visibility::toString(visibility1, true), QStringLiteral("+"));
Uml::Visibility::Enum visibility2 = Uml::Visibility::Private;
QCOMPARE(Uml::Visibility::toString(visibility2), QStringLiteral("private"));
QCOMPARE(Uml::Visibility::toString(visibility2, true), QStringLiteral("-"));
Uml::Visibility::Enum visibility3(Uml::Visibility::Protected);
QCOMPARE(Uml::Visibility::toString(visibility3), QStringLiteral("protected"));
QCOMPARE(Uml::Visibility::toString(visibility3, true), QStringLiteral("#"));
Uml::Visibility::Enum visibility4(Uml::Visibility::Implementation);
QCOMPARE(Uml::Visibility::toString(visibility4), QStringLiteral("implementation"));
QCOMPARE(Uml::Visibility::toString(visibility4, true), QStringLiteral("~"));
}
void TestBasicTypes::test_Visibility_fromString()
{
Uml::Visibility::Enum visibility;
visibility = Uml::Visibility::fromString(QStringLiteral("public"));
QVERIFY(visibility == Uml::Visibility::Public);
visibility = Uml::Visibility::fromString(QStringLiteral("+"));
QVERIFY(visibility == Uml::Visibility::Public);
visibility = Uml::Visibility::fromString(QStringLiteral("protected"));
QVERIFY(visibility == Uml::Visibility::Protected);
visibility = Uml::Visibility::fromString(QStringLiteral("#"));
QVERIFY(visibility == Uml::Visibility::Protected);
visibility = Uml::Visibility::fromString(QStringLiteral("private"));
QVERIFY(visibility == Uml::Visibility::Private);
visibility = Uml::Visibility::fromString(QStringLiteral("-"));
QVERIFY(visibility == Uml::Visibility::Private);
visibility = Uml::Visibility::fromString(QStringLiteral("signals"));
QVERIFY(visibility == Uml::Visibility::Protected);
visibility = Uml::Visibility::fromString(QStringLiteral("class"));
QVERIFY(visibility == Uml::Visibility::Private);
visibility = Uml::Visibility::fromString(QStringLiteral("anything else"));
QVERIFY(visibility == Uml::Visibility::Public);
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_DiagramType_toString()
{
Uml::DiagramType::Enum diagram0(Uml::DiagramType::Undefined);
QCOMPARE(Uml::DiagramType::toString(diagram0), QStringLiteral("Undefined"));
Uml::DiagramType::Enum diagram1(Uml::DiagramType::Class);
QCOMPARE(Uml::DiagramType::toString(diagram1), QStringLiteral("Class"));
Uml::DiagramType::Enum diagram2(Uml::DiagramType::UseCase);
QCOMPARE(Uml::DiagramType::toString(diagram2), QStringLiteral("UseCase"));
Uml::DiagramType::Enum diagram3(Uml::DiagramType::Sequence);
QCOMPARE(Uml::DiagramType::toString(diagram3), QStringLiteral("Sequence"));
Uml::DiagramType::Enum diagram4(Uml::DiagramType::Collaboration);
QCOMPARE(Uml::DiagramType::toString(diagram4), QStringLiteral("Collaboration"));
Uml::DiagramType::Enum diagram5(Uml::DiagramType::State);
QCOMPARE(Uml::DiagramType::toString(diagram5), QStringLiteral("State"));
Uml::DiagramType::Enum diagram6(Uml::DiagramType::Activity);
QCOMPARE(Uml::DiagramType::toString(diagram6), QStringLiteral("Activity"));
Uml::DiagramType::Enum diagram7(Uml::DiagramType::Component);
QCOMPARE(Uml::DiagramType::toString(diagram7), QStringLiteral("Component"));
Uml::DiagramType::Enum diagram8(Uml::DiagramType::Deployment);
QCOMPARE(Uml::DiagramType::toString(diagram8), QStringLiteral("Deployment"));
Uml::DiagramType::Enum diagram9(Uml::DiagramType::EntityRelationship);
QCOMPARE(Uml::DiagramType::toString(diagram9), QStringLiteral("EntityRelationship"));
}
void TestBasicTypes::test_DiagramType_fromString()
{
Uml::DiagramType::Enum diagram;
diagram = Uml::DiagramType::fromString(QStringLiteral("Undefined"));
QVERIFY(diagram == Uml::DiagramType::Undefined);
diagram = Uml::DiagramType::fromString(QStringLiteral("Class"));
QVERIFY(diagram == Uml::DiagramType::Class);
diagram = Uml::DiagramType::fromString(QStringLiteral("UseCase"));
QVERIFY(diagram == Uml::DiagramType::UseCase);
diagram = Uml::DiagramType::fromString(QStringLiteral("Sequence"));
QVERIFY(diagram == Uml::DiagramType::Sequence);
diagram = Uml::DiagramType::fromString(QStringLiteral("Collaboration"));
QVERIFY(diagram == Uml::DiagramType::Collaboration);
diagram = Uml::DiagramType::fromString(QStringLiteral("State"));
QVERIFY(diagram == Uml::DiagramType::State);
diagram = Uml::DiagramType::fromString(QStringLiteral("Activity"));
QVERIFY(diagram == Uml::DiagramType::Activity);
diagram = Uml::DiagramType::fromString(QStringLiteral("Component"));
QVERIFY(diagram == Uml::DiagramType::Component);
diagram = Uml::DiagramType::fromString(QStringLiteral("Deployment"));
QVERIFY(diagram == Uml::DiagramType::Deployment);
diagram = Uml::DiagramType::fromString(QStringLiteral("EntityRelationship"));
QVERIFY(diagram == Uml::DiagramType::EntityRelationship);
}
void TestBasicTypes::test_DiagramType_forLoop()
{
Uml::DiagramType::Enum list[Uml::DiagramType::N_DIAGRAMTYPES];
for (int i = 0; i < Uml::DiagramType::N_DIAGRAMTYPES; ++i) {
list[i] = Uml::DiagramType::fromInt(i);
}
for (int i = 0; i < Uml::DiagramType::N_DIAGRAMTYPES; ++i) {
QVERIFY(list[i] == Uml::DiagramType::fromInt(i));
}
QVERIFY(list[0] == Uml::DiagramType::Undefined);
QVERIFY(list[1] == Uml::DiagramType::Class);
QVERIFY(list[2] == Uml::DiagramType::UseCase);
QVERIFY(list[3] == Uml::DiagramType::Sequence);
QVERIFY(list[4] == Uml::DiagramType::Collaboration);
QVERIFY(list[5] == Uml::DiagramType::State);
QVERIFY(list[6] == Uml::DiagramType::Activity);
QVERIFY(list[7] == Uml::DiagramType::Component);
QVERIFY(list[8] == Uml::DiagramType::Deployment);
QVERIFY(list[9] == Uml::DiagramType::EntityRelationship);
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_AssociationType_toString_fromString()
{
for (int i = Uml::AssociationType::Generalization; i < Uml::AssociationType::Reserved; ++i) {
Uml::AssociationType::Enum at = Uml::AssociationType::fromString(
Uml::AssociationType::toString(
Uml::AssociationType::fromInt(i)));
QVERIFY(Uml::AssociationType::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_SignatureType_toString_fromString()
{
QVERIFY(Uml::SignatureType::NoSig ==
Uml::SignatureType::fromString(Uml::SignatureType::toString(Uml::SignatureType::NoSig)));
QVERIFY(Uml::SignatureType::ShowSig ==
Uml::SignatureType::fromString(Uml::SignatureType::toString(Uml::SignatureType::ShowSig)));
QVERIFY(Uml::SignatureType::SigNoVis ==
Uml::SignatureType::fromString(Uml::SignatureType::toString(Uml::SignatureType::SigNoVis)));
QVERIFY(Uml::SignatureType::NoSigNoVis ==
Uml::SignatureType::fromString(Uml::SignatureType::toString(Uml::SignatureType::NoSigNoVis)));
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_TextRole_toString_fromString()
{
for (int i = Uml::TextRole::Floating; i < Uml::TextRole::Reserved; ++i) {
Uml::TextRole::Enum at = Uml::TextRole::fromString(
Uml::TextRole::toString(
Uml::TextRole::fromInt(i)));
QVERIFY(Uml::TextRole::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_Changeability_toString_fromString()
{
for (int i = 900; i < 903; ++i) {
Uml::Changeability::Enum at = Uml::Changeability::fromString(
Uml::Changeability::toString(
Uml::Changeability::fromInt(i)));
QVERIFY(Uml::Changeability::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_SequenceMessage_toString_fromString()
{
for (int i = 1000; i < 1004; ++i) {
Uml::SequenceMessage::Enum at = Uml::SequenceMessage::fromString(
Uml::SequenceMessage::toString(
Uml::SequenceMessage::fromInt(i)));
QVERIFY(Uml::SequenceMessage::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_RoleType_toString_fromString()
{
for (int i = Uml::RoleType::A; i <= Uml::RoleType::B; ++i) {
Uml::RoleType::Enum at = Uml::RoleType::fromString(
Uml::RoleType::toString(
Uml::RoleType::fromInt(i)));
QVERIFY(Uml::RoleType::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_ParameterDirection_toString_fromString()
{
for (int i = Uml::ParameterDirection::In; i <= Uml::ParameterDirection::Out; ++i) {
Uml::ParameterDirection::Enum at = Uml::ParameterDirection::fromString(
Uml::ParameterDirection::toString(
Uml::ParameterDirection::fromInt(i)));
QVERIFY(Uml::ParameterDirection::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_ProgrammingLanguage_toString_fromString()
{
for (int i = Uml::ProgrammingLanguage::ActionScript; i < Uml::ProgrammingLanguage::Reserved; ++i) {
Uml::ProgrammingLanguage::Enum at = Uml::ProgrammingLanguage::fromString(
Uml::ProgrammingLanguage::toString(
Uml::ProgrammingLanguage::fromInt(i)));
QVERIFY(Uml::ProgrammingLanguage::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_Region_toString_fromString()
{
for (int i = Uml::Region::Error; i <= Uml::Region::SouthWest; ++i) {
Uml::Region::Enum at = Uml::Region::fromString(
Uml::Region::toString(
Uml::Region::fromInt(i)));
QVERIFY(Uml::Region::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
void TestBasicTypes::test_Corner_toString_fromString()
{
for (int i = Uml::Corner::TopLeft; i <= Uml::Corner::BottomLeft; i *= 2) {
Uml::Corner::Enum at = Uml::Corner::fromString(
Uml::Corner::toString(
Uml::Corner::fromInt(i)));
QVERIFY(Uml::Corner::fromInt(i) == at);
}
}
//-----------------------------------------------------------------------------
QTEST_MAIN(TestBasicTypes)
| 18,274
|
C++
|
.cpp
| 397
| 39.997481
| 106
| 0.637793
|
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,231
|
testumlroledialog.cpp
|
KDE_umbrello/unittests/testumlroledialog.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
*/
// app includes
#include "association.h"
#include "stereotype.h"
#include "uml.h"
#include "umlrole.h"
#include "umlroledialog.h"
// qt includes
#include <QApplication>
#include <QtDebug>
int main(int argc, char **argv)
{
QApplication a(argc, argv);
UMLApp app;
app.setup();
UMLStereotype object;
UMLAssociation assoc;
UMLRole role(&assoc, &object, Uml::RoleType::A);
QPointer<UMLRoleDialog> dlg = new UMLRoleDialog(nullptr, &role);
int result = dlg->exec();
delete dlg;
return result;
}
| 702
|
C++
|
.cpp
| 26
| 23.961538
| 88
| 0.719821
|
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,233
|
testbase.cpp
|
KDE_umbrello/unittests/testbase.cpp
|
/*
SPDX-FileCopyrightText: 2015-2020 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testbase.h"
// app includes
#include "codegenerationpolicy.h"
#include "uml.h"
#include "umldoc.h"
// qt includes
#include <QApplication>
#if !defined(QT_GUI_LIB)
#error umbrello unittests require QT_GUI_LIB to be present
#endif
#include <QTemporaryDir>
TestBase::TestBase(QObject *parent)
: QObject(parent)
{
}
void TestBase::initTestCase()
{
QWidget *w = new QWidget;
UMLApp *app = new UMLApp(w);
app->setup();
app->setActiveLanguage(Uml::ProgrammingLanguage::Cpp);
}
void TestBase::cleanupTestCase()
{
qDeleteAll(m_objectsToDelete);
delete UMLApp::app();
}
void TestBase::cleanupOnExit(QObject *p)
{
m_objectsToDelete.append(p);
}
void TestCodeGeneratorBase::initTestCase()
{
TestBase::initTestCase();
static QTemporaryDir tmpDir;
m_tempPath = tmpDir.path() + QStringLiteral("/");
UMLApp::app()->commonPolicy()->setOutputDirectory(m_tempPath);
}
/**
* Return temporary path usable to generated code.
* @return
*/
QString TestCodeGeneratorBase::temporaryPath()
{
return m_tempPath;
}
SetLoading::SetLoading()
{
_state = UMLApp::app()->document()->loading();
UMLApp::app()->document()->setLoading();
}
SetLoading::~SetLoading()
{
UMLApp::app()->document()->setLoading(_state);
}
| 1,444
|
C++
|
.cpp
| 59
| 21.983051
| 88
| 0.730657
|
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,234
|
testumlcanvasobject.cpp
|
KDE_umbrello/unittests/testumlcanvasobject.cpp
|
/*
SPDX-FileCopyrightText: 2019 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testumlcanvasobject.h"
// app include
#include "association.h"
#include "classifier.h"
#include "umlcanvasobject.h"
//-----------------------------------------------------------------------------
void TestUMLCanvasObject::test_addAssociationEnd()
{
UMLCanvasObject c1(QStringLiteral("Test A"));
UMLCanvasObject c2(QStringLiteral("Test B"));
UMLAssociation a(Uml::AssociationType::Generalization, &c1, &c2);
c1.addAssociationEnd(&a);
c2.addAssociationEnd(&a);
QCOMPARE(c1.associations(), 1);
QCOMPARE(c2.associations(), 1);
c1.addAssociationEnd(&a);
c2.addAssociationEnd(&a);
QCOMPARE(c1.associations(), 1);
QCOMPARE(c2.associations(), 1);
}
void TestUMLCanvasObject::test_getAssociations()
{
UMLCanvasObject c1(QStringLiteral("Test A"));
UMLCanvasObject c2(QStringLiteral("Test B"));
UMLAssociation a(Uml::AssociationType::Generalization, &c1, &c2);
c1.addAssociationEnd(&a);
c2.addAssociationEnd(&a);
QCOMPARE(c1.hasAssociation(&a), true);
QCOMPARE(c2.hasAssociation(&a), true);
c1.removeAssociationEnd(&a);
c2.removeAssociationEnd(&a);
QCOMPARE(c1.hasAssociation(&a), false);
QCOMPARE(c2.hasAssociation(&a), false);
}
void TestUMLCanvasObject::test_removeAllAssociationEnds()
{
UMLCanvasObject c1(QStringLiteral("Test A"));
UMLCanvasObject c2(QStringLiteral("Test B"));
UMLAssociation a(Uml::AssociationType::Generalization, &c1, &c2);
c1.addAssociationEnd(&a);
UMLAssociation b(Uml::AssociationType::Association, &c1, &c2);
c1.addAssociationEnd(&b);
QCOMPARE(c1.associations(), 2);
c1.removeAllAssociationEnds();
QCOMPARE(c1.associations(), 0);
}
void TestUMLCanvasObject::test_getSuperClasses()
{
UMLCanvasObject o1(QStringLiteral("Test Sup o"));
UMLCanvasObject o2(QStringLiteral("Test Super o"));
UMLAssociation a1(Uml::AssociationType::Generalization, &o1, &o2);
o1.addAssociationEnd(&a1);
o2.addAssociationEnd(&a1);
QCOMPARE(o1.getSuperClasses(false).size(), 0);
QCOMPARE(o1.getSubClasses().size(), 0);
QCOMPARE(o2.getSuperClasses().size(), 0);
QCOMPARE(o2.getSubClasses().size(), 0);
UMLClassifier c1(QStringLiteral("Test Sup c"));
UMLClassifier c2(QStringLiteral("Test Super c"));
UMLAssociation a2(Uml::AssociationType::Generalization, &c1, &c2);
c1.addAssociationEnd(&a2);
c2.addAssociationEnd(&a2);
QCOMPARE(c1.getSuperClasses(false).size(), 1);
QCOMPARE(c1.getSubClasses().size(), 0);
QCOMPARE(c2.getSuperClasses().size(), 0);
QCOMPARE(c2.getSubClasses().size(), 1);
UMLAssociation a3(Uml::AssociationType::Realization, &c1, &c2);
c1.addAssociationEnd(&a3);
c2.addAssociationEnd(&a3);
QCOMPARE(c1.getSuperClasses(false).size(), 1);
QCOMPARE(c1.getSuperClasses(true).size(), 2);
QCOMPARE(c1.getSubClasses().size(), 0);
QCOMPARE(c2.getSuperClasses().size(), 0);
QCOMPARE(c2.getSubClasses().size(), 2);
}
void TestUMLCanvasObject::test_getRealizations()
{
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
UMLAssociation a1(Uml::AssociationType::Realization, &c1, &c2);
UMLAssociation a2(Uml::AssociationType::Association, &c1, &c2);
c1.addAssociationEnd(&a1);
c2.addAssociationEnd(&a1);
QCOMPARE(c1.getRealizations().size(), 1);
c1.addAssociationEnd(&a2);
c2.addAssociationEnd(&a2);
QCOMPARE(c1.getRealizations().size(), 1);
c1.removeAssociationEnd(&a2);
c2.removeAssociationEnd(&a2);
QCOMPARE(c1.getRealizations().size(), 1);
}
void TestUMLCanvasObject::test_getAggregations()
{
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
UMLAssociation a1(Uml::AssociationType::Aggregation, &c1, &c2);
c1.addAssociationEnd(&a1);
c2.addAssociationEnd(&a1);
QCOMPARE(c1.getAggregations().size(), 1);
UMLAssociation a2(Uml::AssociationType::Association, &c1, &c2);
c1.addAssociationEnd(&a2);
c2.addAssociationEnd(&a2);
QCOMPARE(c1.getAggregations().size(), 1);
c1.removeAssociationEnd(&a1);
c2.removeAssociationEnd(&a1);
QCOMPARE(c1.getAggregations().size(), 0);
}
void TestUMLCanvasObject::test_getCompositions()
{
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
UMLAssociation a1(Uml::AssociationType::Composition, &c1, &c2);
c1.addAssociationEnd(&a1);
c2.addAssociationEnd(&a1);
QCOMPARE(c1.getCompositions().size(), 1);
UMLAssociation a2(Uml::AssociationType::Association, &c1, &c2);
c1.addAssociationEnd(&a2);
c2.addAssociationEnd(&a2);
QCOMPARE(c1.getCompositions().size(), 1);
c1.removeAssociationEnd(&a1);
c2.removeAssociationEnd(&a1);
QCOMPARE(c1.getCompositions().size(), 0);
}
void TestUMLCanvasObject::test_getRelationships()
{
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
UMLAssociation a1(Uml::AssociationType::Relationship, &c1, &c2);
c1.addAssociationEnd(&a1);
c2.addAssociationEnd(&a1);
QCOMPARE(c1.getRelationships().size(), 1);
UMLAssociation a2(Uml::AssociationType::Association, &c1, &c2);
c1.addAssociationEnd(&a2);
c2.addAssociationEnd(&a2);
QCOMPARE(c1.getRelationships().size(), 1);
c1.removeAssociationEnd(&a1);
c2.removeAssociationEnd(&a1);
QCOMPARE(c1.getRelationships().size(), 0);
}
QTEST_MAIN(TestUMLCanvasObject)
| 5,634
|
C++
|
.cpp
| 144
| 34.944444
| 88
| 0.710555
|
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,235
|
testpythonwriter.cpp
|
KDE_umbrello/unittests/testpythonwriter.cpp
|
/*
SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testpythonwriter.h"
// app includes
#include "classifier.h"
#include "pythonwriter.h"
const bool IS_NOT_IMPL = false;
//-----------------------------------------------------------------------------
class PythonWriterTest : public PythonWriter
{
public:
QString findFileName(UMLPackage* classifier, const QString &ext)
{
return PythonWriter::findFileName(classifier, ext);
}
};
void TestPythonWriter::test_language()
{
PythonWriter* py = new PythonWriter();
Uml::ProgrammingLanguage::Enum lang = py->language();
QVERIFY(lang == Uml::ProgrammingLanguage::Python);
}
void TestPythonWriter::test_writeClass()
{
PythonWriterTest* py = new PythonWriterTest();
UMLClassifier* c = new UMLClassifier(QStringLiteral("Customer"), "12345678");
UMLAttribute* attr;
attr = c->createAttribute(QStringLiteral("name_"));
attr = c->createAttribute(QStringLiteral("address_"));
c->addAttribute(attr);
py->writeClass(c);
// does the just created file exist?
QFile file(temporaryPath() + py->findFileName(c, QStringLiteral(".py")));
QCOMPARE(file.exists(), true);
}
void TestPythonWriter::test_reservedKeywords()
{
PythonWriter* py = new PythonWriter();
QStringList list = py->reservedKeywords();
QCOMPARE(list.empty(), false);
QCOMPARE(list[0], QStringLiteral("abs"));
QCOMPARE(list[11], QStringLiteral("class"));
QCOMPARE(list.last(), QStringLiteral("zip"));
}
QTEST_MAIN(TestPythonWriter)
| 1,654
|
C++
|
.cpp
| 47
| 31.765957
| 88
| 0.691729
|
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,236
|
testassociation.cpp
|
KDE_umbrello/unittests/testassociation.cpp
|
/*
SPDX-FileCopyrightText: 2019 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testassociation.h"
// app include
#include "association.h"
#include "classifier.h"
#include "folder.h"
#include "package.h"
#include "stereotype.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
#include "umlrole.h"
#include <QXmlStreamWriter>
//-----------------------------------------------------------------------------
void TestAssociation::test_equal()
{
const SignalBlocker sb(UMLApp::app()->document());
UMLPackage parent(QStringLiteral("Test Parent"));
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
a.setUMLPackage(&parent);
UMLAssociation b(Uml::AssociationType::Association, &o1, &o2);
b.setUMLPackage(&parent);
UMLAssociation c(Uml::AssociationType::Association, &o1, nullptr);
c.setUMLPackage(&parent);
UMLAssociation d(Uml::AssociationType::Association, nullptr, &o2);
d.setUMLPackage(&parent);
//QCOMPARE(a, b);
QCOMPARE(a == c, false);
QCOMPARE(b == c, false);
QCOMPARE(c == d, false);
}
void TestAssociation::test_toString()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, nullptr);
QString ar = QString(QStringLiteral("objectA: %1 null")).arg(Uml::AssociationType::toStringI18n(Uml::AssociationType::Association));
QCOMPARE(a.toString(), ar);
UMLAssociation b(Uml::AssociationType::Association, nullptr, &o2);
QString br = QString(QStringLiteral("null %1 objectB:")).arg(Uml::AssociationType::toStringI18n(Uml::AssociationType::Association));
QCOMPARE(b.toString(), br);
UMLAssociation c(Uml::AssociationType::Association, &o1, &o2);
QString cr = QString(QStringLiteral("objectA: %1 objectB:")).arg(Uml::AssociationType::toStringI18n(Uml::AssociationType::Association));
QCOMPARE(c.toString(), cr);
}
void TestAssociation::test_UMLRole()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QCOMPARE(a.getUMLRole(Uml::RoleType::A)->object(), &o1);
QCOMPARE(a.getUMLRole(Uml::RoleType::B)->object(), &o2);
}
void TestAssociation::test_associationType()
{
UMLAssociation a(Uml::AssociationType::Association);
QVERIFY(a.getAssocType() == Uml::AssociationType::Association);
a.setAssociationType(Uml::AssociationType::Aggregation);
QVERIFY(a.getAssocType() == Uml::AssociationType::Aggregation);
}
void TestAssociation::test_objectID()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QCOMPARE(a.getObjectId(Uml::RoleType::A), o1.id());
QCOMPARE(a.getObjectId(Uml::RoleType::B), o2.id());
}
void TestAssociation::test_visibility()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Public);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Public);
a.setVisibility(Uml::Visibility::Protected, Uml::RoleType::A);
a.setVisibility(Uml::Visibility::Protected, Uml::RoleType::B);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Protected);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Protected);
a.setVisibility(Uml::Visibility::Private, Uml::RoleType::A);
a.setVisibility(Uml::Visibility::Private, Uml::RoleType::B);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Private);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Private);
a.setVisibility(Uml::Visibility::Implementation, Uml::RoleType::A);
a.setVisibility(Uml::Visibility::Implementation, Uml::RoleType::B);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Implementation);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Implementation);
UMLAssociation b(Uml::AssociationType::Association);
}
void TestAssociation::test_changeability()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Public);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Public);
a.setVisibility(Uml::Visibility::Protected, Uml::RoleType::A);
a.setVisibility(Uml::Visibility::Protected, Uml::RoleType::B);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Protected);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Protected);
a.setVisibility(Uml::Visibility::Private, Uml::RoleType::A);
a.setVisibility(Uml::Visibility::Private, Uml::RoleType::B);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Private);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Private);
a.setVisibility(Uml::Visibility::Implementation, Uml::RoleType::A);
a.setVisibility(Uml::Visibility::Implementation, Uml::RoleType::B);
QVERIFY(a.visibility(Uml::RoleType::A) == Uml::Visibility::Implementation);
QVERIFY(a.visibility(Uml::RoleType::B) == Uml::Visibility::Implementation);
UMLAssociation b(Uml::AssociationType::Association);
QVERIFY(b.visibility(Uml::RoleType::A) == Uml::Visibility::Public);
QVERIFY(b.visibility(Uml::RoleType::B) == Uml::Visibility::Public);
}
void TestAssociation::test_multiplicity()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QCOMPARE(a.getMultiplicity(Uml::RoleType::A), QString());
QCOMPARE(a.getMultiplicity(Uml::RoleType::B), QString());
a.setMultiplicity(QStringLiteral("1"), Uml::RoleType::A);
a.setMultiplicity(QStringLiteral("2"), Uml::RoleType::B);
QCOMPARE(a.getMultiplicity(Uml::RoleType::A), QStringLiteral("1"));
QCOMPARE(a.getMultiplicity(Uml::RoleType::B), QStringLiteral("2"));
}
void TestAssociation::test_roleName()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QCOMPARE(a.getRoleName(Uml::RoleType::A), QString());
QCOMPARE(a.getRoleName(Uml::RoleType::B), QString());
a.setRoleName(QStringLiteral("test1"), Uml::RoleType::A);
a.setRoleName(QStringLiteral("test2"), Uml::RoleType::B);
QCOMPARE(a.getRoleName(Uml::RoleType::A), QStringLiteral("test1"));
QCOMPARE(a.getRoleName(Uml::RoleType::B), QStringLiteral("test2"));
}
void TestAssociation::test_roleDoc()
{
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
QCOMPARE(a.getRoleDoc(Uml::RoleType::A), QString());
QCOMPARE(a.getRoleDoc(Uml::RoleType::B), QString());
a.setRoleDoc(QStringLiteral("test1"), Uml::RoleType::A);
a.setRoleDoc(QStringLiteral("test2"), Uml::RoleType::B);
QCOMPARE(a.getRoleDoc(Uml::RoleType::A), QStringLiteral("test1"));
QCOMPARE(a.getRoleDoc(Uml::RoleType::B), QStringLiteral("test2"));
}
void TestAssociation::resolveRef()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLStereotype *stereotype1 = UMLApp::app()->document()->createStereotype(QStringLiteral("test1"));
UMLStereotype *stereotype2 = UMLApp::app()->document()->createStereotype(QStringLiteral("test2"));
UMLObject o1(nullptr, QStringLiteral("objectA"));
UMLObject o2(nullptr, QStringLiteral("objectB"));
UMLAssociation a(Uml::AssociationType::Association, &o1, &o2);
// no resolve
a.setUMLPackage(&parent);
QCOMPARE(a.resolveRef(), true);
// secondary
a.getUMLRole(Uml::RoleType::A)->setSecondaryId(Uml::ID::toString(stereotype1->id()));
a.getUMLRole(Uml::RoleType::B)->setSecondaryId(Uml::ID::toString(stereotype2->id()));
QCOMPARE(a.resolveRef(), true);
// secondary fallback
a.getUMLRole(Uml::RoleType::A)->setSecondaryId(QStringLiteral(""));
a.getUMLRole(Uml::RoleType::A)->setSecondaryFallback(Uml::ID::toString(stereotype1->id()));
a.getUMLRole(Uml::RoleType::B)->setSecondaryId(QStringLiteral(""));
a.getUMLRole(Uml::RoleType::B)->setSecondaryFallback(Uml::ID::toString(stereotype2->id()));
QCOMPARE(a.resolveRef(), true);
}
typedef TestUML<UMLAssociation, Uml::AssociationType::Enum> TestUMLAssociation;
void TestAssociation::test_saveAndLoad()
{
UMLPackage parent(QStringLiteral("Test Parent"));
UMLClassifier c1(QStringLiteral("Test A"));
UMLClassifier c2(QStringLiteral("Test B"));
c1.setUMLPackage(&parent);
c2.setUMLPackage(&parent);
c1.setStereotypeCmd(QStringLiteral("test"));
UMLFolder *root = UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical);
root->addObject(&c1);
root->addObject(&c2);
TestUMLAssociation a1(Uml::AssociationType::Association, &c1, &c2);
a1.setNameCmd(QStringLiteral("Test assoc"));
a1.setUMLPackage(&parent);
QString save = a1.testSave1();
//a1.testDump("save");
TestUMLAssociation a2;
a2.setUMLPackage(&parent);
QCOMPARE(a2.testLoad1(save), true);
QCOMPARE(a2.testSave1(), save);
//a2.testDump("load");
}
QTEST_MAIN(TestAssociation)
| 9,778
|
C++
|
.cpp
| 199
| 45.090452
| 140
| 0.717485
|
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,237
|
testpackage.cpp
|
KDE_umbrello/unittests/testpackage.cpp
|
/*
SPDX-FileCopyrightText: 2019 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "testpackage.h"
#include "classifier.h"
#include "package.h"
#include "stereotype.h"
void TestPackage::test_appendClassesAndInterfaces()
{
UMLPackage p(QStringLiteral("package"));
UMLClassifier c1(QStringLiteral("class A"));
UMLClassifier c2(QStringLiteral("class B"));
UMLClassifier c3(QStringLiteral("class C"));
p.addObject(&c1);
p.addObject(&c2);
p.addObject(&c3);
QCOMPARE(p.containedObjects().size(), 3);
UMLClassifierList items;
p.appendClassesAndInterfaces(items);
QCOMPARE(items.size(), 3);
}
typedef TestUML<UMLPackage, const QString &> TestUMLPackage;
void TestPackage::test_saveAndLoad()
{
UMLPackage parent(QStringLiteral("parent"));
TestUMLPackage p1(QStringLiteral("Package"));
p1.setUMLPackage(&parent);
UMLClassifier c1(QStringLiteral("Test A"));
c1.setUMLPackage(&p1);
UMLClassifier c2(QStringLiteral("Test B"));
c2.setUMLPackage(&p1);
p1.addObject(&c1);
p1.addObject(&c2);
p1.setStereotypeCmd(QStringLiteral("test"));
QString save = p1.testSave1();
//p1.testDump("save");
TestUMLPackage p2;
p2.setUMLPackage(&parent);
QCOMPARE(p2.testLoad1(save), true);
//p2.testDump("load");
QCOMPARE(p2.testSave1(), save);
}
QTEST_MAIN(TestPackage)
| 1,451
|
C++
|
.cpp
| 44
| 29.090909
| 88
| 0.721429
|
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,238
|
svg2png.cpp
|
KDE_umbrello/maintainer/svg2png.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016 Ralf Habacker <ralf.habacker@freenet.de>
*/
#include <QCoreApplication>
#include <QtSvg>
#include <QPainter>
#include <QImage>
#include <QtDebug>
#include <iostream>
bool verbose = false;
void usage()
{
std::cerr << "svg2png <svg-file> <png-file> <width> <height>" << std::endl;
std::cerr << "svg2png <svg-file> <png-file> <width> <height> <cursor-template-file>" << std::endl;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (a.arguments().count() < 5) {
std::cerr << "invalid number of arguments" << std::endl;
usage();
return -1;
}
QString svgFile = a.arguments().at(1);
QString pngFile = a.arguments().at(2);
int width = a.arguments().at(3).toInt();
int height = a.arguments().at(4).toInt();
QString templateFile;
bool useTemplate = false;
if (a.arguments().count() == 6) {
templateFile = a.arguments().at(5);
useTemplate = true;
}
if (useTemplate) {
QSvgRenderer cursorSvg(svgFile);
if (!cursorSvg.isValid()) {
std::cerr << "could not open svg file '" << qPrintable(svgFile) << std::endl;
return -2;
}
if (verbose)
std::cerr << cursorSvg.defaultSize().width() << "x" << cursorSvg.defaultSize().height() << std::endl;
QSvgRenderer templateSvg(templateFile);
if (!cursorSvg.isValid()) {
std::cerr << "could not open template file '" << qPrintable(templateFile) << std::endl;
return -3;
}
QPainter painter2;
QImage image2(21, 21, QImage::Format_ARGB32);
image2.fill(qRgba(0, 0, 0, 0));
painter2.begin(&image2);
cursorSvg.render(&painter2);
painter2.end();
QImage image(width, height, QImage::Format_ARGB32);
image.fill(qRgba(0, 0, 0, 0));
QPainter painter;
painter.begin(&image);
templateSvg.render(&painter);
painter.drawImage(11, 11, image2);
painter.end();
if (!image.save(pngFile)) {
std::cerr << "could not open png file '" << qPrintable(pngFile) << std::endl;
return -4;
}
}
else {
QSvgRenderer r(svgFile);
if (!r.isValid()) {
std::cerr << "could not open svg file '" << qPrintable(svgFile) << std::endl;
return -2;
}
QImage image(width, height, QImage::Format_ARGB32);
image.fill(qRgba(0, 0, 0, 0));
QPainter painter;
painter.begin(&image);
r.render(&painter);
painter.end();
if (!image.save(pngFile)) {
std::cerr << "could not open png file '" << qPrintable(pngFile) << std::endl;
return -4;
}
}
return 0;
}
| 2,844
|
C++
|
.cpp
| 84
| 26.535714
| 114
| 0.574863
|
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,239
|
umldoc.cpp
|
KDE_umbrello/umbrello/umldoc.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umldoc.h"
// app includes
#include "debug_utils.h"
#include "uniqueid.h"
#include "association.h"
#include "package.h"
#include "folder.h"
#include "codegenerator.h"
#include "classifier.h"
#include "dialog_utils.h"
#include "enum.h"
#include "entity.h"
#include "docwindow.h"
#include "operation.h"
#include "attribute.h"
#include "template.h"
#include "enumliteral.h"
#include "stereotype.h"
#include "datatype.h"
#include "classifierlistitem.h"
#include "object_factory.h"
#include "import_argo.h"
#include "import_rose.h"
#include "model_utils.h"
#include "uml.h"
#include "umllistview.h"
#include "umllistviewitem.h"
#include "umlview.h"
#include "entityconstraint.h"
#include "idchangelog.h"
#include "umllistviewpopupmenu.h"
#include "cmds.h"
#include "diagramprintpage.h"
#include "umlscene.h"
#include "version.h"
#include "worktoolbar.h"
#include "models/diagramsmodel.h"
#include "models/objectsmodel.h"
#include "models/stereotypesmodel.h"
// kde includes
#include <kio/job.h>
#include <KJobWidgets>
#include <KLocalizedString>
#include <KMessageBox>
#include <ktar.h>
// qt includes
#include <QApplication>
#include <QBuffer>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDir>
#include <QDomDocument>
#include <QDomElement>
#include <QListWidget>
#include <QMimeDatabase>
#include <QPainter>
#include <QPrinter>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTemporaryFile>
#include <QTextStream>
#include <QTimer>
#include <QXmlStreamWriter>
DEBUG_REGISTER(UMLDoc)
class UMLDoc::Private
{
public:
UMLDoc *parent;
QStringList errors; ///< holds loading errors
Private(UMLDoc *p) : parent(p) {}
};
/**
* Constructor for the fileclass of the application.
*/
UMLDoc::UMLDoc()
: m_d(new Private(this)),
m_datatypeRoot(nullptr),
m_stereoList(UMLStereotypeList()),
m_Name(i18n("UML Model")),
m_modelID("m1"),
m_count(0),
m_modified(false),
m_doc_url(QUrl()),
m_pChangeLog(nullptr),
m_bLoading(false),
m_importing(false),
m_Doc(QString()),
m_pAutoSaveTimer(nullptr),
m_nViewID(Uml::ID::None),
m_bTypesAreResolved(true),
m_pCurrentRoot(nullptr),
m_bClosing(false),
m_diagramsModel(new DiagramsModel),
m_objectsModel(new ObjectsModel),
m_stereotypesModel(new StereotypesModel(m_stereoList)),
m_resolution(0.0)
{
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i)
m_root[i] = nullptr;
}
/**
* Initialize the UMLDoc.
* To be called after the constructor, before anything else.
*/
void UMLDoc::init()
{
// Initialize predefined folders.
const char* nativeRootName[Uml::ModelType::N_MODELTYPES] = {
"Logical View",
"Use Case View",
"Component View",
"Deployment View",
"Entity Relationship Model"
};
const QString localizedRootName[Uml::ModelType::N_MODELTYPES] = {
i18n("Logical View"),
i18n("Use Case View"),
i18n("Component View"),
i18n("Deployment View"),
i18n("Entity Relationship Model")
};
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
const QString rootName = QString::fromLatin1(nativeRootName[i]);
QString id = rootName;
id.replace(QLatin1Char(' '), QLatin1Char('_'));
m_root[i] = new UMLFolder(rootName, Uml::ID::fromString(id));
m_root[i]->setLocalName(localizedRootName[i]);
}
createDatatypeFolder();
// Connect signals.
UMLApp * pApp = UMLApp::app();
connect(this, SIGNAL(sigDiagramCreated(Uml::ID::Type)), pApp, SLOT(slotUpdateViews()));
connect(this, SIGNAL(sigDiagramRemoved(Uml::ID::Type)), pApp, SLOT(slotUpdateViews()));
connect(this, SIGNAL(sigDiagramRenamed(Uml::ID::Type)), pApp, SLOT(slotUpdateViews()));
connect(this, SIGNAL(sigCurrentViewChanged()), pApp, SLOT(slotCurrentViewChanged()));
}
/**
* Create the datatype folder and add it to the logical folder.
*/
void UMLDoc::createDatatypeFolder()
{
delete m_datatypeRoot;
m_datatypeRoot = new UMLFolder(QStringLiteral("Datatypes"), "Datatypes");
m_datatypeRoot->setLocalName(i18n("Datatypes"));
m_datatypeRoot->setUMLPackage(m_root[Uml::ModelType::Logical]);
Q_ASSERT(m_root[Uml::ModelType::Logical]);
m_root[Uml::ModelType::Logical]->addObject(m_datatypeRoot);
}
/**
* Destructor for the fileclass of the application.
*/
UMLDoc::~UMLDoc()
{
UMLApp * pApp = UMLApp::app();
disconnect(this, SIGNAL(sigDiagramCreated(Uml::ID::Type)), pApp, SLOT(slotUpdateViews()));
disconnect(this, SIGNAL(sigDiagramRemoved(Uml::ID::Type)), pApp, SLOT(slotUpdateViews()));
disconnect(this, SIGNAL(sigDiagramRenamed(Uml::ID::Type)), pApp, SLOT(slotUpdateViews()));
disconnect(this, SIGNAL(sigCurrentViewChanged()), pApp, SLOT(slotCurrentViewChanged()));
disconnect(m_pAutoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
delete m_pAutoSaveTimer;
m_root[Uml::ModelType::Logical]->removeObject(m_datatypeRoot);
delete m_datatypeRoot;
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
delete m_root[i];
}
delete m_pChangeLog;
qDeleteAll(m_stereoList);
delete m_stereotypesModel;
delete m_diagramsModel;
delete m_objectsModel;
delete m_d;
}
/**
* Adds a view to the document which represents the document
* contents. Usually this is your main view.
*
* @param view Pointer to the UMLView to add.
*/
void UMLDoc::addView(UMLView *view)
{
if (view == nullptr) {
logError0("UMLDoc::addView argument is NULL");
return;
}
UMLFolder *f = view->umlScene()->folder();
if (f == nullptr) {
logError0("UMLDoc::addView view folder is not set");
return;
}
logDebug2("UMLDoc::addView %1 to folder %2", view->umlScene()->name(), f->name());
f->addView(view);
m_diagramsModel->addDiagram(view);
UMLApp * pApp = UMLApp::app();
if (pApp->listView()) {
connect(this, SIGNAL(sigObjectRemoved(UMLObject*)), view->umlScene(), SLOT(slotObjectRemoved(UMLObject*)));
}
if (!m_bLoading || pApp->currentView() == nullptr) {
pApp->setCurrentView(view);
}
if (!m_bLoading) {
view->show();
Q_EMIT sigDiagramChanged(view->umlScene()->type());
}
pApp->setDiagramMenuItemsState(true);
pApp->slotUpdateViews();
}
/**
* Removes a view from the list of currently connected views.
*
* @param view Pointer to the UMLView to remove.
* @param enforceCurrentView Switch to determine if we have a current view or not.
* Most of the time, we DO want this, except when exiting the program.
*/
void UMLDoc::removeView(UMLView *view, bool enforceCurrentView)
{
Q_UNUSED(enforceCurrentView)
if (!view) {
logWarn0("UMLDoc::removeView(UMLView *view) called with view = nullptr");
return;
}
logDebug1("UMLDoc::removeView %1", view->umlScene()->name());
if (UMLApp::app()->listView()) {
disconnect(this, SIGNAL(sigObjectRemoved(UMLObject*)),
view->umlScene(), SLOT(slotObjectRemoved(UMLObject*)));
}
view->hide();
UMLFolder *f = view->umlScene()->folder();
if (f == nullptr) {
logWarn1("UMLDoc::removeView %1 : view->getFolder() returns NULL", view->umlScene()->name());
return;
}
m_diagramsModel->removeDiagram(view);
f->removeView(view);
UMLView *currentView = UMLApp::app()->currentView();
if (currentView == view) {
UMLApp::app()->setCurrentView(nullptr);
#if 0
/* Enabling this code may result in crashes on closing models with many diagrams:
#0 in QListData::size (this=0x30) at /usr/include/qt5/QtCore/qlist.h:115
#1 in QList<QTreeWidgetItem*>::count (this=0x30) at /usr/include/qt5/QtCore/qlist.h:359
#2 in QTreeWidgetItem::childCount (this=0x0) at /usr/include/qt5/QtWidgets/qtreewidget.h:193
#3 in UMLListView::findView (this=0x13470e0, v=0x249dc80) at /umbrello/master/umbrello/umllistview.cpp:1382
#4 in UMLApp::setCurrentView (this=0xc767c0, view=0x249dc80, updateTreeView=true)
at /umbrello/master/umbrello/uml.cpp:3360
#5 in UMLDoc::changeCurrentView (this=0xe0de50, id="JBFSUyhmy1cS") at /umbrello/master/umbrello/umldoc.cpp:1839
#6 in UMLApp::slotTabChanged (this=0xc767c0, index=1) at /umbrello/master/umbrello/uml.cpp:3408
#7 in UMLApp::qt_static_metacall (_o=0xc767c0, _c=QMetaObject::InvokeMetaMethod, _id=81, _a=0x7fffffffb5e0)
at /umbrello/master/build/umbrello/libumbrello_autogen/EWIEGA46WW/moc_uml.cpp:564
#8 in doActivate<false> (sender=0x126dc70, signal_index=7, argv=0x7fffffffb5e0) at kernel/qobject.cpp:3898
#9 in QMetaObject::activate (sender=<optimized out>, m=m@entry=0x7ffff65c5560 <QTabWidget::staticMetaObject>,
local_signal_index=local_signal_index@entry=0, argv=argv@entry=0x7fffffffb5e0) at kernel/qobject.cpp:3946
#10 in QTabWidget::currentChanged (this=<optimized out>, _t1=<optimized out>) at .moc/moc_qtabwidget.cpp:326
#11 in doActivate<false> (sender=0x1276980, signal_index=7, argv=0x7fffffffb6e0) at kernel/qobject.cpp:3898
#12 in QMetaObject::activate (sender=<optimized out>, m=m@entry=0x7ffff65c3fc0 <QTabBar::staticMetaObject>,
local_signal_index=local_signal_index@entry=0, argv=argv@entry=0x7fffffffb6e0) at kernel/qobject.cpp:3946
#13 in QTabBar::currentChanged (this=<optimized out>, _t1=<optimized out>) at .moc/moc_qtabbar.cpp:338
#14 in UMLApp::setCurrentView (this=0xc767c0, view=0x249dc80, updateTreeView=true)
at /umbrello/master/umbrello/uml.cpp:3342
#15 in UMLDoc::changeCurrentView (this=0xe0de50, id="JBFSUyhmy1cS") at /umbrello/master/umbrello/umldoc.cpp:1839
#16 in UMLDoc::removeView (this=0xe0de50, view=0x23c0040, enforceCurrentView=false)
at /umbrello/master/umbrello/umldoc.cpp:334
#17 in UMLFolder::removeAllViews (this=0xe34e70) at /umbrello/master/umbrello/umlmodel/folder.cpp:242
#18 in UMLDoc::removeAllViews (this=0xe0de50) at /umbrello/master/umbrello/umldoc.cpp:2985
#19 in UMLDoc::closeDocument (this=0xe0de50) at /umbrello/master/umbrello/umldoc.cpp:462
#20 in UMLDoc::newDocument (this=0xe0de50) at /umbrello/master/umbrello/umldoc.cpp:495
#21 in UMLApp::slotFileNew (this=0xc767c0) at /umbrello/master/umbrello/uml.cpp:1371
#22 in UMLApp::slotFileClose (this=0xc767c0) at /umbrello/master/umbrello/uml.cpp:1556
*/
UMLViewList viewList;
m_root[Uml::ModelType::Logical]->appendViews(viewList);
UMLView *firstView = nullptr;
if (!viewList.isEmpty()) {
firstView = viewList.first();
/* Tried this:
if (firstView == view)
firstView = 0;
*********************** but it didn't help. */
}
if (!firstView && enforceCurrentView) { //create a diagram
QString name = createDiagramName(Uml::DiagramType::Class, false);
createDiagram(m_root[Uml::ModelType::Logical], Uml::DiagramType::Class, name);
qApp->processEvents();
m_root[Uml::ModelType::Logical]->appendViews(viewList);
firstView = viewList.first();
}
if (firstView) {
changeCurrentView(firstView->umlScene()->ID());
UMLApp::app()->setDiagramMenuItemsState(true);
}
#endif
}
blockSignals(true);
delete view;
blockSignals(false);
}
/**
* Sets the URL of the document.
*
* @param url The KUrl to set.
*/
void UMLDoc::setUrl(const QUrl &url)
{
m_doc_url = url;
}
/**
* Returns the KUrl of the document.
*
* @return The KUrl of this UMLDoc.
*/
const QUrl& UMLDoc::url() const
{
return m_doc_url;
}
/**
* Sets the URL of the document to "Untitled".
*/
void UMLDoc::setUrlUntitled()
{
m_doc_url.setUrl(m_doc_url.toString(QUrl::RemoveFilename) + i18n("Untitled"));
}
/**
* "save modified" - Asks the user for saving if the document
* is modified.
*
* @return True if document can be closed.
*/
bool UMLDoc::saveModified()
{
bool completed(true);
if (!m_modified) {
return completed;
}
UMLApp *win = UMLApp::app();
int want_save = KMessageBox::warningYesNoCancel(win,
i18n("The current file has been modified.\nDo you want to save it?"),
i18nc("warning message", "Warning"),
KStandardGuiItem::save(), KStandardGuiItem::discard());
switch(want_save) {
case KMessageBox::Yes:
if (m_doc_url.fileName() == i18n("Untitled")) {
if (win->slotFileSaveAs()) {
closeDocument();
completed=true;
} else {
completed=false;
}
} else {
saveDocument(url());
closeDocument();
completed=true;
}
break;
case KMessageBox::No:
setModified(false);
closeDocument();
completed=true;
break;
case KMessageBox::Cancel:
completed=false;
break;
default:
completed=false;
break;
}
return completed;
}
/**
* Closes the current document.
*/
void UMLDoc::closeDocument()
{
m_bClosing = true;
UMLApp::app()->setGenerator(Uml::ProgrammingLanguage::Reserved); // delete the codegen
m_Doc = QString();
DocWindow* dw = UMLApp::app()->docWindow();
if (dw) {
dw->reset();
}
UMLApp::app()->logWindow()->clear();
UMLListView *listView = UMLApp::app()->listView();
if (listView) {
listView->clean();
// store old setting - for restore of last setting
bool m_bLoading_old = m_bLoading;
m_bLoading = true; // This is to prevent document becoming modified.
// For reference, here is an example of a call sequence that would
// otherwise result in futile addToUndoStack() calls:
// removeAllViews() =>
// UMLView::removeAllAssociations() =>
// UMLView::removeAssoc() =>
// UMLDoc::setModified(true, true) =>
// addToUndoStack().
removeAllViews();
m_bLoading = m_bLoading_old;
// Remove all objects from the predefined folders.
// @fixme With advanced code generation enabled, this crashes.
removeAllObjects();
// Remove any stereotypes.
if (stereotypes().count() > 0) {
for(UMLStereotype *s : stereotypes()) {
m_stereotypesModel->removeStereotype(s);
//delete s;
// This may crash when selecting File -> Close with following stacktrace:
// #5 UMLDoc::closeDocument (this=0x2053620) at umbrello/umldoc.cpp:440
// #6 UMLDoc::newDocument (this=0x2053620) at umbrello/umldoc.cpp:463
// #7 UMLApp::slotFileNew (this=0x1aab900) at umbrello/uml.cpp:1239
// #8 UMLApp::slotFileClose (this=0x1aab900) at umbrello/uml.cpp:1395
// #9 UMLApp::qt_static_metacall (_o=0x1aab900, _c=QMetaObject::InvokeMetaMethod, _id=8, _a=0x7ffeb9ad1f10)
// at build/umbrello/libumbrello_autogen/EWIEGA46WW/moc_uml.cpp:490
}
m_stereoList.clear();
}
// Restore the datatype folder, it has been deleted above.
createDatatypeFolder();
// this creates too many items, only Logical View should be created
listView->init();
}
m_bClosing = false;
}
/**
* Initializes the document generally.
*
* @return True if operation successful.
*/
bool UMLDoc::newDocument()
{
bool state = UMLApp::app()->document()->loading();
UMLApp::app()->document()->setLoading(true);
closeDocument();
UMLApp::app()->setCurrentView(nullptr);
setUrlUntitled();
setResolution(qApp->desktop()->logicalDpiX());
//see if we need to start with a new diagram
Settings::OptionState optionState = Settings::optionState();
Uml::DiagramType::Enum dt = optionState.generalState.diagram;
Uml::ModelType::Enum mt = Model_Utils::convert_DT_MT(dt);
if (mt == Uml::ModelType::N_MODELTYPES) { // don't allow no diagram
dt = Uml::DiagramType::Class;
mt = Uml::ModelType::Logical;
}
QString name = createDiagramName(dt, false);
createDiagram(m_root[mt], dt, name);
UMLApp::app()->initGenerator();
setModified(false);
initSaveTimer();
UMLApp::app()->enableUndoAction(false);
UMLApp::app()->clearUndoStack();
UMLApp::app()->document()->setLoading(state);
return true;
}
/**
* Loads the document by filename and format and emits the
* updateViews() signal.
*
* @param url The filename in KUrl format.
* @param format The format (optional.)
* @return True if operation successful.
*/
bool UMLDoc::openDocument(const QUrl& url, const char *format /* = nullptr */)
{
Q_UNUSED(format);
if (url.fileName().length() == 0) {
newDocument();
return false;
}
m_doc_url = url;
closeDocument();
setResolution(0.0);
// IMPORTANT: set m_bLoading to true
// _AFTER_ the call of UMLDoc::closeDocument()
// as it sets m_bLoading to false after it was temporarily
// changed to true to block recording of changes in redo-buffer
m_bLoading = true;
m_d->errors.clear();
QTemporaryFile tmpfile;
tmpfile.open();
QUrl dest(QUrl::fromLocalFile(tmpfile.fileName()));
logDebug2("UMLDoc::openDocument: copy from %1 to %2", url.path(), dest.path());
KIO::FileCopyJob *job = KIO::file_copy(url, dest, -1, KIO::Overwrite);
KJobWidgets::setWindow(job, UMLApp::app());
job->exec();
QFile file(tmpfile.fileName());
if (job->error() || !file.exists()) {
if (!file.exists())
logDebug1("UMLDoc::openDocument: temporary file <%1> failed", file.fileName());
if (job->error())
logDebug1("UMLDoc::openDocument: %1", job->errorString());
KMessageBox::error(nullptr, i18n("The file <%1> does not exist.", url.toString()), i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
// status of XMI loading
bool status = false;
// check if the xmi file is a compressed archive like tar.bzip2 or tar.gz
QString filetype = m_doc_url.fileName();
QString mimetype;
if (filetype.endsWith(QStringLiteral(".tgz")) || filetype.endsWith(QStringLiteral(".tar.gz"))) {
mimetype = QStringLiteral("application/x-gzip");
} else if (filetype.endsWith(QStringLiteral(".tar.bz2"))) {
mimetype = QStringLiteral("application/x-bzip");
}
if (mimetype.isEmpty() == false) {
KTar archive(file.fileName(), mimetype);
if (archive.open(QIODevice::ReadOnly) == false) {
KMessageBox::error(nullptr, i18n("The file %1 seems to be corrupted.", url.toString()), i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
// get the root directory and all entries in
const KArchiveDirectory * rootDir = archive.directory();
const QStringList entries = rootDir->entries();
QString entryMimeType;
bool foundXMI = false;
QStringList::ConstIterator it;
QStringList::ConstIterator end(entries.end());
// now go through all entries till we find an xmi file
for (it = entries.begin(); it != end; ++it) {
// only check files, we do not go in subdirectories
if (rootDir->entry(*it)->isFile() == true) {
// we found a file, check the mimetype
QMimeDatabase db;
entryMimeType = db.mimeTypeForFile(*it, QMimeDatabase::MatchExtension).name();
if (entryMimeType == QStringLiteral("application/x-uml")) {
foundXMI = true;
break;
}
}
}
// if we found an XMI file, we have to extract it to a temporary file
if (foundXMI == true) {
QTemporaryDir tmp_dir;
KArchiveEntry * entry;
KArchiveFile * fileEntry;
// try to cast the file entry in the archive to an archive entry
entry = const_cast<KArchiveEntry*>(rootDir->entry(*it));
if (entry == nullptr) {
KMessageBox::error(nullptr, i18n("There was no XMI file found in the compressed file %1.", url.toString()),
i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
// now try to cast the archive entry to a file entry, so that we can
// extract the file
fileEntry = dynamic_cast<KArchiveFile*>(entry);
if (fileEntry == nullptr) {
KMessageBox::error(nullptr, i18n("There was no XMI file found in the compressed file %1.", url.toString()),
i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
// now we can extract the file to the temporary directory
fileEntry->copyTo(tmp_dir.path() + QLatin1Char('/'));
// now open the extracted file for reading
QFile xmi_file(tmp_dir.path() + QLatin1Char('/') + *it);
if(!xmi_file.open(QIODevice::ReadOnly)) {
KMessageBox::error(nullptr, i18n("There was a problem loading the extracted file: %1", url.toString()),
i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
m_bTypesAreResolved = false;
status = loadFromXMI(xmi_file, ENC_UNKNOWN);
// close the extracted file and the temporary directory
xmi_file.close();
} else {
KMessageBox::error(nullptr, i18n("There was no XMI file found in the compressed file %1.", url.toString()),
i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
archive.close();
} else {
// no, it seems to be an ordinary file
if (!file.open(QIODevice::ReadOnly)) {
KMessageBox::error(nullptr, i18n("There was a problem loading file: %1", url.toString()),
i18n("Load Error"));
setUrlUntitled();
m_bLoading = false;
newDocument();
return false;
}
if (filetype.endsWith(QStringLiteral(".mdl"))) {
setUrlUntitled();
m_bTypesAreResolved = false;
status = Import_Rose::loadFromMDL(file);
// qApp->processEvents(); // give UI events a chance
// activateAllViews();
if (status) {
if (UMLApp::app()->currentView() == nullptr) {
QString name = createDiagramName(Uml::DiagramType::Class, false);
createDiagram(m_root[Uml::ModelType::Logical], Uml::DiagramType::Class, name);
setCurrentRoot(Uml::ModelType::Logical);
}
}
}
else if (filetype.endsWith(QStringLiteral(".zargo"))) {
setUrlUntitled();
status = Import_Argo::loadFromZArgoFile(file);
}
else {
m_bTypesAreResolved = false;
status = loadFromXMI(file, ENC_UNKNOWN);
}
}
if (file.isOpen())
file.close();
m_bLoading = false;
m_bTypesAreResolved = true;
if (!status) {
QString msg = i18n("There was a problem loading file: %1", url.toString());
if (m_d->errors.size() > 0)
msg += QStringLiteral("<br/>") + i18n("Reason: %1", m_d->errors.join(QStringLiteral("<br/>")));
KMessageBox::error(nullptr, msg, i18n("Load Error"));
newDocument();
return false;
}
setModified(false);
initSaveTimer();
UMLApp::app()->enableUndoAction(false);
UMLApp::app()->clearUndoStack();
// for compatibility
addDefaultStereotypes();
return true;
}
/**
* Saves the document using the given filename and format.
*
* @param url The filename in KUrl format.
* @param format The format (optional.)
* @return True if operation successful.
*/
bool UMLDoc::saveDocument(const QUrl& url, const char * format)
{
Q_UNUSED(format);
m_doc_url = url;
bool uploaded = true;
// first, we have to find out which format to use
QString strFileName = url.path();
QFileInfo fileInfo(strFileName);
QString fileExt = fileInfo.completeSuffix();
QString fileFormat = QStringLiteral("xmi");
if (fileExt == QStringLiteral("xmi") || fileExt == QStringLiteral("bak.xmi")) {
fileFormat = QStringLiteral("xmi");
} else if (fileExt == QStringLiteral("xmi.tgz") || fileExt == QStringLiteral("bak.xmi.tgz")) {
fileFormat = QStringLiteral("tgz");
} else if (fileExt == QStringLiteral("xmi.tar.bz2") || fileExt == QStringLiteral("bak.xmi.tar.bz2")) {
fileFormat = QStringLiteral("bz2");
} else {
fileFormat = QStringLiteral("xmi");
}
initSaveTimer();
if (fileFormat == QStringLiteral("tgz") || fileFormat == QStringLiteral("bz2")) {
KTar * archive;
QTemporaryFile tmp_tgz_file;
tmp_tgz_file.setAutoRemove(false);
tmp_tgz_file.open();
// first we have to check if we are saving to a local or remote file
if (url.isLocalFile()) {
if (fileFormat == QStringLiteral("tgz")) { // check tgz or bzip
archive = new KTar(url.toLocalFile(), QStringLiteral("application/x-gzip"));
} else {
archive = new KTar(url.toLocalFile(), QStringLiteral("application/x-bzip"));
}
} else {
if (fileFormat == QStringLiteral("tgz")) { // check tgz or bzip2
archive = new KTar(tmp_tgz_file.fileName(), QStringLiteral("application/x-gzip"));
} else {
archive = new KTar(tmp_tgz_file.fileName(), QStringLiteral("application/x-bzip"));
}
}
// now check if we can write to the file
if (archive->open(QIODevice::WriteOnly) == false) {
logError1("UMLDoc::saveDocument could not open %1", archive->fileName());
KMessageBox::error(nullptr, i18n("There was a problem saving: %1", url.url(QUrl::PreferLocalFile)), i18n("Save Error"));
delete archive;
return false;
}
// we have to create a temporary xmi file
// we will add this file later to the archive
QTemporaryFile tmp_xmi_file;
tmp_xmi_file.setAutoRemove(false);
if (!tmp_xmi_file.open()) {
logError1("UMLDoc::saveDocument could not open %1", tmp_xmi_file.fileName());
KMessageBox::error(nullptr, i18n("There was a problem saving: %1", url.url(QUrl::PreferLocalFile)), i18n("Save Error"));
delete archive;
return false;
}
saveToXMI(tmp_xmi_file); // save XMI to this file...
// now add this file to the archive, but without the extension
QString tmpQString = url.fileName();
if (fileFormat == QStringLiteral("tgz")) {
tmpQString.remove(QRegularExpression(QStringLiteral("\\.tgz$")));
}
else {
tmpQString.remove(QRegularExpression(QStringLiteral("\\.tar\\.bz2$")));
}
archive->addLocalFile(tmp_xmi_file.fileName(), tmpQString);
if (!archive->close()) {
logError1("UMLDoc::saveDocument could not close %1", archive->fileName());
KMessageBox::error(nullptr, i18n("There was a problem saving: %1", url.url(QUrl::PreferLocalFile)), i18n("Save Error"));
delete archive;
return false;
}
// now the xmi file was added to the archive, so we can delete it
tmp_xmi_file.setAutoRemove(true);
// now we have to check, if we have to upload the file
if (!url.isLocalFile()) {
KIO::FileCopyJob *job = KIO::file_copy(QUrl::fromLocalFile(tmp_tgz_file.fileName()), m_doc_url);
KJobWidgets::setWindow(job, UMLApp::app());
job->exec();
uploaded = !job->error();
if (!uploaded) {
logError2("UMLDoc::saveDocument could not upload file %1 to %2", tmp_tgz_file.fileName(),
url.toString());
}
}
// now the archive was written to disk (or remote) so we can delete the
// objects
tmp_tgz_file.setAutoRemove(true);
delete archive;
}
else {
// save as normal uncompressed XMI
QTemporaryFile tmpfile; // we need this tmp file if we are writing to a remote file
tmpfile.setAutoRemove(false);
// save in _any_ case to a temp file
// -> if something goes wrong during saveToXMI, the
// original content is preserved
// (e.g. if umbrello dies in the middle of the document model parsing
// for saveToXMI due to some problems)
/// @todo insert some checks in saveToXMI to detect a failed save attempt
// lets open the file for writing
if (!tmpfile.open()) {
logError1("UMLDoc::saveDocument could not open %1", tmpfile.fileName());
KMessageBox::error(nullptr, i18n("There was a problem saving: %1", url.url(QUrl::PreferLocalFile)), i18n("Save Error"));
return false;
}
saveToXMI(tmpfile); // save the xmi stuff to it
tmpfile.close();
// if it is a remote file, we have to upload the tmp file
if (!url.isLocalFile()) {
KIO::FileCopyJob *job = KIO::file_copy(QUrl::fromLocalFile(tmpfile.fileName()), m_doc_url);
KJobWidgets::setWindow(job, UMLApp::app());
job->exec();
uploaded = !job->error();
if (!uploaded)
logError2("UMLDoc::saveDocument could not upload file %1 to %2", tmpfile.fileName(), url.toString());
}
else {
// now remove the original file
#ifdef Q_OS_WIN
tmpfile.setAutoRemove(true);
KIO::FileCopyJob* fcj = KIO::file_copy(QUrl::fromLocalFile(tmpfile.fileName()), url, -1, KIO::Overwrite);
#else
KIO::FileCopyJob* fcj = KIO::file_move(QUrl::fromLocalFile(tmpfile.fileName()), url, -1, KIO::Overwrite);
#endif
KJobWidgets::setWindow(fcj, (QWidget*)UMLApp::app());
fcj->exec();
if (fcj->error()) {
logError2("UMLDoc::saveDocument Could not move %1 to %2", tmpfile.fileName(), url.toString());
KMessageBox::error(nullptr, i18n("There was a problem saving: %1", url.url(QUrl::PreferLocalFile)), i18n("Save Error"));
setUrlUntitled();
return false;
}
}
}
if (!uploaded) {
KMessageBox::error(nullptr, i18n("There was a problem uploading: %1", url.url(QUrl::PreferLocalFile)), i18n("Save Error"));
setUrlUntitled();
}
setModified(false);
return uploaded;
}
/**
* Sets up the signals needed by the program for it to work.
*/
void UMLDoc::setupSignals()
{
WorkToolBar *tb = UMLApp::app()->workToolBar();
connect(this, SIGNAL(sigDiagramChanged(Uml::DiagramType::Enum)), tb, SLOT(slotCheckToolBar(Uml::DiagramType::Enum)));
}
/**
* Finds a view (diagram) by the ID given to method.
*
* @param id The ID of the view to search for.
* @return Pointer to the view found, or NULL if not found.
*/
UMLView * UMLDoc::findView(Uml::ID::Type id) const
{
UMLView *v = nullptr;
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
v = m_root[i]->findView(id);
if (v) {
break;
}
}
return v;
}
/**
* Finds a view (diagram) by the type and name given.
*
* @param type The type of view to find.
* @param name The name of the view to find.
* @param searchAllScopes Search in all subfolders (default: false.)
* @return Pointer to the view found, or NULL if not found.
*/
UMLView * UMLDoc::findView(Uml::DiagramType::Enum type, const QString &name,
bool searchAllScopes /* =false */) const
{
Uml::ModelType::Enum mt = Model_Utils::convert_DT_MT(type);
if (mt == Uml::ModelType::N_MODELTYPES) {
logWarn1("UMLDoc::findView : Returning null because DiagramType %1 cannot be mapped to ModelType", type);
return nullptr;
}
return m_root[mt]->findView(type, name, searchAllScopes);
}
/**
* Used to find a reference to a @ref UMLObject by its ID.
*
* @param id The @ref UMLObject to find.
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* UMLDoc::findObjectById(Uml::ID::Type id)
{
UMLObject *o = nullptr;
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
if (id == m_root[i]->id()) {
return m_root[i];
}
o = m_root[i]->findObjectById(id);
if (o) {
return o;
}
}
o = findStereotypeById(id);
return o;
}
/**
* Used to find a @ref UMLObject by its type and name.
*
* @param name The name of the @ref UMLObject to find.
* @param type ObjectType of the object to find (optional.)
* When the given type is ot_UMLObject the type is
* disregarded, i.e. the given name is the only
* search criterion.
* @param currentObj Object relative to which to search (optional.)
* If given then the enclosing scope(s) of this
* object are searched before the global scope.
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* UMLDoc::findUMLObject(const QString &name,
UMLObject::ObjectType type /* = ot_UMLObject */,
UMLObject *currentObj /* = nullptr */)
{
UMLObject *o = m_datatypeRoot->findObject(name);
if (o) {
return o;
}
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
UMLObjectList list = m_root[i]->containedObjects();
if (list.size() == 0)
continue;
o = Model_Utils::findUMLObject(list, name, type, currentObj);
if (o) {
return o;
}
if ((type == UMLObject::ot_UMLObject || type == UMLObject::ot_Folder) &&
name == m_root[i]->name()) {
return m_root[i];
}
}
return nullptr;
}
/**
* Used to find a @ref UMLObject by its type and raw name.
*
* @param modelType The model type in which to search for the object
* @param name The raw name of the @ref UMLObject to find.
* @param type ObjectType of the object to find
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* UMLDoc::findUMLObjectRaw(Uml::ModelType::Enum modelType,
const QString &name,
UMLObject::ObjectType type)
{
return findUMLObjectRaw(rootFolder(modelType), name, type);
}
/**
* Used to find a @ref UMLObject by its type and raw name.
*
* @param folder The UMLFolder in which to search for the object
* @param name The raw name of the @ref UMLObject to find.
* @param type ObjectType of the object to find
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* UMLDoc::findUMLObjectRaw(UMLFolder *folder,
const QString &name,
UMLObject::ObjectType type)
{
if (folder == nullptr)
return nullptr;
UMLObjectList list = folder->containedObjects();
if (list.size() == 0)
return nullptr;
return Model_Utils::findUMLObjectRaw(list, name, type, nullptr);
}
/**
* Used to find a @ref UMLObject by its type and raw name recursively
*
* @param modelType The model type in which to search for the object
* @param name The raw name of the @ref UMLObject to find.
* @param type ObjectType of the object to find
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* UMLDoc::findUMLObjectRecursive(Uml::ModelType::Enum modelType,
const QString &name,
UMLObject::ObjectType type)
{
return findUMLObjectRecursive(rootFolder(modelType), name, type);
}
/**
* Used to find a @ref UMLObject by its type and raw name recursively
*
* @param folder The UMLFolder in which to search for the object
* @param name The raw name of the @ref UMLObject to find.
* @param type ObjectType of the object to find
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* UMLDoc::findUMLObjectRecursive(UMLFolder *folder,
const QString &name,
UMLObject::ObjectType type)
{
if (folder == nullptr)
return nullptr;
UMLObjectList list = folder->containedObjects();
if (list.size() == 0)
return nullptr;
return Model_Utils::findUMLObjectRecursive(list, name, type);
}
/**
* Used to find a @ref UMLClassifier by its name.
*
* @param name The name of the @ref UMLObject to find.
*/
UMLClassifier* UMLDoc::findUMLClassifier(const QString &name)
{
//this is used only by code generator so we don't need to look at Datatypes
UMLObject * obj = findUMLObject(name);
return obj->asUMLClassifier();
}
/**
* Adds a UMLObject that is already created but doesn't change
* any ids or signal. Use AddUMLObjectPaste if pasting.
*
* @param object The object to add.
* @return True if the object was actually added.
*/
bool UMLDoc::addUMLObject(UMLObject* object)
{
if (object->isUMLStereotype()) {
logDebug2("UMLDoc::addUMLObject %1: not adding type %2",
object->name(), object->baseTypeStr());
return false;
}
UMLPackage *pkg = object->umlPackage();
if (pkg == nullptr) {
pkg = currentRoot();
logDebug2("UMLDoc::addUMLObject %1: no parent package set, assuming %2",
object->name(), pkg->name());
object->setUMLPackage(pkg);
}
// FIXME restore stereotype
UMLClassifierListItem *c = object->asUMLClassifierListItem();
if (c) {
if (!pkg->subordinates().contains(c))
pkg->subordinates().append(c);
return true;
}
return pkg->addObject(object);
}
/**
* Write text to the status bar.
* @param text the text to write
*/
void UMLDoc::writeToStatusBar(const QString &text)
{
Q_EMIT sigWriteToStatusBar(text);
}
/**
* Simple removal of an object.
* @param object the UMLObject to be removed
*/
void UMLDoc::slotRemoveUMLObject(UMLObject* object)
{
//m_objectList.remove(object);
UMLPackage *pkg = object->umlPackage();
if (pkg == nullptr) {
logError1("UMLDoc::slotRemoveUMLObject %1 : parent package is not set", object->name());
return;
}
pkg->removeObject(object);
}
/**
* Returns true if the given name is unique within its scope.
*
* @param name The name to check.
* @return True if name is unique.
*/
bool UMLDoc::isUnique(const QString &name) const
{
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem *currentItem = (UMLListViewItem*)listView->currentItem();
UMLListViewItem *parentItem = nullptr;
// check for current item, if its a package, then we do a check on that
// otherwise, if current item exists, find its parent and check if thats
// a package..
if (currentItem) {
// its possible that the current item *is* a package, then just
// do check now
if (Model_Utils::typeIsContainer(currentItem->type())) {
return isUnique (name, (UMLPackage*) currentItem->umlObject());
}
parentItem = (UMLListViewItem*)currentItem->parent();
}
// item is in a package so do check only in that
if (parentItem != nullptr && Model_Utils::typeIsContainer(parentItem->type())) {
UMLPackage *parentPkg = parentItem->umlObject()->asUMLPackage();
return isUnique(name, parentPkg);
}
logError1("UMLDoc::isUnique %1: Not currently in a package", name);
/* Check against all objects that _don't_ have a parent package.
for (UMLObjectListIt oit(m_objectList); oit.current(); ++oit) {
UMLObject *obj = oit.current();
if ((obj->getUMLPackage() == 0) && (obj->getName() == name))
return false;
}
*/
return true;
}
/**
* Returns true if the given name is unique within its scope of given package.
*
* @param name The name to check.
* @param package The UMLPackage in which we have to determine the unique-ness
* @return True if name is unique.
*/
bool UMLDoc::isUnique(const QString &name, UMLPackage *package) const
{
// if a package, then only do check in that
if (package) {
return (package->findObject(name) == nullptr);
}
// Not currently in a package: ERROR
logError1("UMLDoc::isUnique %1 (2): Not currently in a package", name);
/* Check against all objects that _don't_ have a parent package.
for (UMLObjectListIt oit(m_objectList); oit.current(); ++oit) {
UMLObject *obj = oit.current();
if ((obj->getUMLPackage() == 0) && (obj->getName() == name))
return false;
}
*/
return true;
}
/**
* Creates a stereotype for the parent object.
* @param name the name of the stereotype
*/
UMLStereotype* UMLDoc::createStereotype(const QString &name)
{
UMLStereotype *s = new UMLStereotype(name, Uml::ID::fromString(name));
addStereotype(s);
return s;
}
/**
* Finds a UMLStereotype by its name.
*
* @param name The name of the UMLStereotype to find.
* @return Pointer to the UMLStereotype found, or NULL if not found.
*/
UMLStereotype* UMLDoc::findStereotype(const QString &name) const
{
for(UMLStereotype *s : m_stereoList) {
if (s->name() == name) {
return s;
}
}
return nullptr;
}
/**
* Finds or creates a stereotype for the parent object.
* @param name the name of the stereotype
* @return the found stereotype object or a just created one
*/
UMLStereotype* UMLDoc::findOrCreateStereotype(const QString &name)
{
UMLStereotype *s = findStereotype(name);
if (s != nullptr) {
return s;
}
return createStereotype(name);
}
/**
* Find a UMLStereotype by its unique ID.
* @param id the unique ID
* @return the found stereotype or NULL
*/
UMLStereotype * UMLDoc::findStereotypeById(Uml::ID::Type id) const
{
for(UMLStereotype *s : m_stereoList) {
if (s->id() == id)
return s;
}
return nullptr;
}
/**
* Add a UMLStereotype to the application.
* @param s the stereotype to be added
*/
void UMLDoc::addStereotype(UMLStereotype *s)
{
if (m_stereotypesModel->addStereotype(s))
Q_EMIT sigObjectCreated(s);
}
/**
* Remove a UMLStereotype from the application.
* @param s the stereotype to be removed
*/
void UMLDoc::removeStereotype(UMLStereotype *s)
{
if (m_stereotypesModel->removeStereotype(s))
Q_EMIT sigObjectRemoved(s);
}
/**
* Add a stereotype if it doesn't already exist.
* Used by code generators, operations and attribute dialog.
*/
void UMLDoc::addDefaultStereotypes()
{
CodeGenerator *gen = UMLApp::app()->generator();
if (gen) {
gen->createDefaultStereotypes();
}
}
/**
* Returns a list of the stereotypes in this UMLDoc.
*
* @return List of UML stereotypes.
*/
const UMLStereotypeList& UMLDoc::stereotypes() const
{
return m_stereoList;
}
/**
* Removes an association.
*
* @param assoc Pointer to the UMLAssociation to remove.
* @param doSetModified Whether to mark the document as modified (default: true.)
*/
void UMLDoc::removeAssociation (UMLAssociation * assoc, bool doSetModified /*=true*/)
{
if (!assoc) {
return;
}
// Remove the UMLAssociation from m_objectList.
UMLPackage *pkg = assoc->umlPackage();
if (pkg == nullptr) {
logError1("UMLDoc::removeAssociation %1: parent package is not set", assoc->name());
return;
}
pkg->removeObject(assoc);
if (doSetModified) { // so we will save our document
setModified(true);
}
}
/**
* Finds an association.
*
* @param assocType Type of the UMLAssociation to seek.
* @param roleAObj Pointer to the role A UMLCanvasObject.
* @param roleBObj Pointer to the role B UMLCanvasObject.
* @param swap Optional pointer to boolean.
* The bool is set to true if the association
* matched with swapped roles, else it is set
* to false.
* @return Pointer to the UMLAssociation found or NULL if not found.
*/
UMLAssociation * UMLDoc::findAssociation(Uml::AssociationType::Enum assocType,
const UMLObject *roleAObj,
const UMLObject *roleBObj,
bool *swap) const
{
UMLAssociationList assocs = associations();
UMLAssociation *ret = nullptr;
for(UMLAssociation *a : assocs) {
if (a->getAssocType() != assocType) {
continue;
}
if (a->getObject(Uml::RoleType::A) == roleAObj && a->getObject(Uml::RoleType::B) == roleBObj) {
return a;
}
if (a->getObject(Uml::RoleType::A) == roleBObj && a->getObject(Uml::RoleType::B) == roleAObj) {
ret = a;
}
}
if (swap) {
*swap = (ret != nullptr);
}
return ret;
}
/**
* Creates AND adds an association between two UMLObjects.
* Used by refactoring assistant.
* NOTE: this method does not check if the association is valid / legal
*
* @param a The UMLObject "A" for the association (source)
* @param b The UMLObject "B" for the association (destination)
* @param type The association's type
* @return The Association created
*/
UMLAssociation* UMLDoc::createUMLAssociation(UMLObject *a, UMLObject *b,
Uml::AssociationType::Enum type)
{
bool swap;
UMLAssociation *assoc = findAssociation(type, a, b, &swap);
if (assoc == nullptr) {
assoc = new UMLAssociation(type, a, b);
assoc->setUMLPackage(a->umlPackage());
addAssociation(assoc);
}
return assoc;
}
/**
* Adds an association.
*
* @param assoc Pointer to the UMLAssociation to add.
*/
void UMLDoc::addAssociation(UMLAssociation *assoc)
{
if (assoc == nullptr) {
return;
}
// First, check that this association has not already been added.
// This may happen when loading old XMI files where all the association
// information was taken from the <UML:AssocWidget> tag.
UMLAssociationList assocs = associations();
for(UMLAssociation *a : assocs) {
// check if its already been added (shouldn't be the case right now
// as UMLAssociations only belong to one associationwidget at a time)
if (a == assoc) {
logDebug1("UMLDoc::addAssociation(%1) duplicate addition attempted",
assoc->name());
return;
}
}
// If we get here it's really a new association.
// Add the UMLAssociation at the owning UMLPackage.
UMLPackage *pkg = assoc->umlPackage();
if (pkg == nullptr) {
logError1("UMLDoc::addAssociation %1: parent package is not set", assoc->name());
return;
}
pkg->addObject(assoc);
// I don't believe this appropriate, UMLAssociations ARENT UMLWidgets -b.t.
// Q_EMIT sigObjectCreated(o);
setModified(true);
}
/**
* Returns a name for the new object, appended with a number
* if the default name is taken e.g. class diagram, class
* diagram_1 etc.
* @param type the diagram type
* @return the unique view name
*/
QString UMLDoc::uniqueViewName(const Uml::DiagramType::Enum type) const
{
QString dname;
switch (type) {
case Uml::DiagramType::UseCase:
dname = i18n("use case diagram");
break;
case Uml::DiagramType::Class:
dname = i18n("class diagram");
break;
case Uml::DiagramType::Sequence:
dname = i18n("sequence diagram");
break;
case Uml::DiagramType::Collaboration:
dname = i18n("communication diagram");
break;
case Uml::DiagramType::Object:
dname = i18n("object diagram");
break;
case Uml::DiagramType::State:
dname = i18n("state diagram");
break;
case Uml::DiagramType::Activity:
dname = i18n("activity diagram");
break;
case Uml::DiagramType::Component:
dname = i18n("component diagram");
break;
case Uml::DiagramType::Deployment:
dname = i18n("deployment diagram");
break;
case Uml::DiagramType::EntityRelationship:
dname = i18n("entity relationship diagram");
break;
default:
logWarn0("UMLDoc::uniqueViewName called with unknown diagram type");
break;
}
QString name = dname;
for (int number = 1; findView(type, name, true); ++number) {
name = dname + QLatin1Char('_') + QString::number(number);
}
return name;
}
/**
* Returns true when loading a document file.
* @return the value of the flag
*/
bool UMLDoc::loading() const
{
return m_bLoading || !m_bTypesAreResolved;
}
/**
* Sets loading boolean flag to the value given.
* @param state value to set
*/
void UMLDoc::setLoading(bool state /* = true */)
{
m_bLoading = state;
}
/**
* Returns true when importing file(s).
* @return the value of the flag
*/
bool UMLDoc::importing() const
{
return m_importing;
}
/**
* Sets importing boolean flag to the value given.
* @param state value to set
*/
void UMLDoc::setImporting(bool state /* = true */)
{
m_importing = state;
}
/**
* Returns the m_bClosing flag.
* @return the value of the flag
*/
bool UMLDoc::closing() const
{
return m_bClosing;
}
/**
* Creates the name of the given diagram type.
* @param type The type of diagram to create.
* @param askForName If true shows a dialog box asking for name,
* else uses a default name.
* @return name of the new diagram
*/
QString UMLDoc::createDiagramName(Uml::DiagramType::Enum type, bool askForName /*= true */)
{
QString defaultName = uniqueViewName(type);
QString name = defaultName;
while (true) {
if (askForName && !Dialog_Utils::askName(i18nc("diagram name", "Name"), i18n("Enter name:"), name))
break;
if (name.length() == 0) {
KMessageBox::error(nullptr, i18n("That is an invalid name for a diagram."), i18n("Invalid Name"));
} else if (findView(type, name)) {
KMessageBox::error(nullptr, i18n("A diagram is already using that name."), i18n("Not a Unique Name"));
} else {
return name;
}
} // end while
return QString();
}
/**
* Creates a diagram of the given type.
*
* @param folder the folder in which tp create the diagram.
* @param type the type of diagram to create
* @param name the name for the diagram to create
* @param id optional ID of new diagram
* @return pointer to the UMLView of the new diagram
*/
UMLView* UMLDoc::createDiagram(UMLFolder *folder, Uml::DiagramType::Enum type, const QString& name, Uml::ID::Type id)
{
logDebug3("UMLDoc::createDiagram folder=%1 / type=%2 / name=%3",
folder->name(), Uml::DiagramType::toString(type), name);
if (id == Uml::ID::None) {
id = UniqueID::gen();
}
if (name.length() > 0) {
UMLView* view = new UMLView(folder);
view->umlScene()->setOptionState(Settings::optionState());
view->umlScene()->setName(name);
view->umlScene()->setType(type);
view->umlScene()->setID(id);
addView(view);
Q_EMIT sigDiagramCreated(id);
setModified(true);
UMLApp::app()->enablePrint(true);
changeCurrentView(id);
return view;
}
return nullptr;
}
/**
* Used to rename a document. This method takes care of everything.
* You just need to give the ID of the diagram to the method.
*
* @param id The ID of the diagram to rename.
*/
void UMLDoc::renameDiagram(Uml::ID::Type id)
{
UMLView *view = findView(id);
Uml::DiagramType::Enum type = view->umlScene()->type();
QString name = view->umlScene()->name();
while (true) {
bool ok = Dialog_Utils::askName(i18nc("renaming diagram", "Name"),
i18n("Enter name:"),
name);
if (!ok) {
break;
}
if (name.length() == 0) {
KMessageBox::error(nullptr, i18n("That is an invalid name for a diagram."), i18n("Invalid Name"));
} else if (!findView(type, name)) {
view->umlScene()->setName(name);
Q_EMIT sigDiagramRenamed(id);
setModified(true);
break;
} else {
KMessageBox::error(nullptr, i18n("A diagram is already using that name."), i18n("Not a Unique Name"));
}
}
}
/**
* Used to rename a @ref UMLObject. The @ref UMLObject is to be an
* actor, use case or classifier.
*
* @param o The object to rename.
*/
void UMLDoc::renameUMLObject(UMLObject *o)
{
QString name = o->name();
while (true) {
bool ok = Dialog_Utils::askName(i18nc("renaming uml object", "Name"),
i18n("Enter name:"),
name);
if (!ok) {
break;
}
if (name.length() == 0) {
KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name"));
} else if (isUnique(name)) {
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(o, name));
setModified(true);
break;
} else {
KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name"));
}
}
return;
}
/**
* Used to rename an operation or attribute of a classifier.
*
* @param o The attribute or operation to rename.
*/
void UMLDoc::renameChildUMLObject(UMLObject *o)
{
UMLClassifier* p = o->umlParent()->asUMLClassifier();
if (!p) {
logDebug1("UMLDoc::renameChildUMLObject: Cannot process object, invalid parent %1",
o->umlParent()->name());
return;
}
QString name = o->name();
while (true) {
bool ok = Dialog_Utils::askName(i18nc("renaming child uml object", "Name"),
i18n("Enter name:"),
name);
if (!ok) {
break;
}
if (name.length() == 0) {
KMessageBox::error(nullptr, i18n("That is an invalid name."), i18n("Invalid Name"));
} else if (p->findChildObject(name) == nullptr
|| ((o->baseType() == UMLObject::ot_Operation) && KMessageBox::warningYesNo(nullptr,
i18n("The name you entered was not unique.\nIs this what you wanted?"),
i18n("Name Not Unique"), KGuiItem(i18n("Use Name")), KGuiItem(i18n("Enter New Name"))) == KMessageBox::Yes)) {
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(o, name));
setModified(true);
break;
} else {
KMessageBox::error(nullptr, i18n("That name is already being used."), i18n("Not a Unique Name"));
}
}
}
/**
* Changes the current view (diagram) to the view with the given ID.
*
* @param id The ID of the view to change to.
*/
void UMLDoc::changeCurrentView(Uml::ID::Type id)
{
logDebug1("UMLDoc::changeCurrentView id=%1", Uml::ID::toString(id));
UMLView* view = findView(id);
if (view) {
UMLScene* scene = view->umlScene();
scene->setIsOpen(true);
UMLApp::app()->setCurrentView(view);
Q_EMIT sigDiagramChanged(scene->type());
UMLApp::app()->setDiagramMenuItemsState(true);
setModified(true);
Q_EMIT sigCurrentViewChanged();
// when clicking on a tab, the documentation of diagram is upated in docwindow
UMLApp::app()->docWindow()->showDocumentation(scene);
}
else {
logWarn1("UMLDoc::changeCurrentView: New current view was not found with id %1", Uml::ID::toString(id));
}
}
/**
* Deletes a diagram from the current file.
*
* Undo command
*
* @param id The ID of the diagram to delete.
*/
void UMLDoc::removeDiagram(Uml::ID::Type id)
{
UMLView* umlView = findView(id);
if (!umlView) {
logError1("UMLDoc::removeDiagram : diagram with id %1 not found", Uml::ID::toString(id));
return;
}
UMLScene* umlScene = umlView->umlScene();
if (Dialog_Utils::askDeleteDiagram(umlScene->name())) {
UMLApp::app()->executeCommand(new Uml::CmdRemoveDiagram(
umlScene->folder(),
umlScene->type(),
umlScene->name(),
id
));
}
}
/**
* Deletes a diagram from the current file.
*
* @param id The ID of the diagram to delete.
*/
void UMLDoc::removeDiagramCmd(Uml::ID::Type id)
{
UMLApp::app()->docWindow()->updateDocumentation(true);
UMLView* umlview = findView(id);
if (!umlview) {
logError1("UMLDoc::removeDiagramCmd : diagram with id %1 not found", Uml::ID::toString(id));
return;
}
removeView(umlview);
Q_EMIT sigDiagramRemoved(id);
setModified(true);
}
/**
* Return the currently selected root folder.
* This will be an element from the m_root[] array.
* @return the currently selected root folder or NULL
*/
UMLFolder *UMLDoc::currentRoot() const
{
UMLView *currentView = UMLApp::app()->currentView();
if (currentView == nullptr) {
if (m_pCurrentRoot) {
return m_pCurrentRoot;
}
logError0("UMLDoc::currentRoot : m_pCurrentRoot is NULL");
return nullptr;
}
UMLFolder *f = currentView->umlScene()->folder();
while (f && f->umlPackage()) {
f = f->umlParent()->asUMLFolder();
}
return f;
}
/**
* Set the current root folder.
*
* @param rootType The type of the root folder to set.
* The element from m_root[] which is indexed
* by this type is selected.
*/
void UMLDoc::setCurrentRoot(Uml::ModelType::Enum rootType)
{
m_pCurrentRoot = m_root[rootType];
}
/**
* Removes an @ref UMLObject from the current file. If this object
* is being represented on a diagram it will also delete all those
* representations.
*
* @param umlobject Pointer to the UMLObject to delete.
* @param deleteObject Delete the UMLObject instance.
*/
void UMLDoc::removeUMLObject(UMLObject* umlobject, bool deleteObject)
{
if (umlobject == nullptr) {
logError0("UMLDoc::removeUMLObject called with NULL parameter");
return;
}
UMLApp::app()->docWindow()->updateDocumentation(true);
UMLObject::ObjectType type = umlobject->baseType();
umlobject->setUMLStereotype(nullptr); // triggers possible cleanup of UMLStereotype
if (umlobject->asUMLClassifierListItem()) {
UMLClassifier* parent = umlobject->umlParent()->asUMLClassifier();
if (parent == nullptr) {
logError0("UMLDoc::removeUMLObject: parent of umlobject is NULL");
return;
}
if (type == UMLObject::ot_Operation) {
parent->removeOperation(umlobject->asUMLOperation());
if (deleteObject)
delete umlobject->asUMLOperation();
} else if (type == UMLObject::ot_EnumLiteral) {
UMLEnum *e = parent->asUMLEnum();
e->removeEnumLiteral(umlobject->asUMLEnumLiteral());
} else if (type == UMLObject::ot_EntityAttribute) {
UMLEntity *ent = parent->asUMLEntity();
ent->removeEntityAttribute(umlobject->asUMLClassifierListItem());
} else if (type == UMLObject::ot_UniqueConstraint || type == UMLObject::ot_ForeignKeyConstraint ||
type == UMLObject::ot_CheckConstraint) {
UMLEntity* ent = parent->asUMLEntity();
ent->removeConstraint(umlobject->asUMLEntityConstraint());
} else {
UMLClassifier* pClass = parent->asUMLClassifier();
if (pClass == nullptr) {
logError1("UMLDoc::removeUMLObject: parent of umlobject has unexpected type %1",
parent->baseType());
return;
}
if (type == UMLObject::ot_Attribute) {
pClass->removeAttribute(umlobject->asUMLAttribute());
} else if (type == UMLObject::ot_Template) {
pClass->removeTemplate(umlobject->asUMLTemplate());
if (deleteObject)
delete umlobject->asUMLTemplate();
} else {
logError1("UMLDoc::removeUMLObject: umlobject has unexpected type %1", type);
}
}
} else if (type == UMLObject::ot_Association) {
UMLAssociation *a = umlobject->asUMLAssociation();
removeAssociation(a, false); // don't call setModified here, it's done below
Q_EMIT sigObjectRemoved(umlobject);
if (deleteObject)
delete a;
} else {
UMLPackage* pkg = umlobject->umlPackage();
if (pkg) {
// Remove associations that this object may participate in.
UMLCanvasObject *c = umlobject->asUMLCanvasObject();
if (c) {
// In the current implementation, all associations live in the
// root folder.
UMLPackage* rootPkg = Model_Utils::rootPackage(c);
if (rootPkg == nullptr) {
logError1("UMLDoc::removeUMLObject %1: root package is not set", umlobject->name());
return;
}
UMLObjectList rootObjects = rootPkg->containedObjects();
// Store the associations to remove in a buffer because we
// should not remove elements from m_objectList while it is
// being iterated over.
UMLAssociationList assocsToRemove;
for(UMLObject *obj : rootObjects) {
uIgnoreZeroPointer(obj);
if (obj->baseType() == UMLObject::ot_Association) {
UMLAssociation *assoc = obj->asUMLAssociation();
if (c->hasAssociation(assoc)) {
assocsToRemove.append(assoc);
}
}
}
for(UMLAssociation *a : assocsToRemove) {
removeAssociation(a, false);
}
}
pkg->removeObject(umlobject);
Q_EMIT sigObjectRemoved(umlobject);
if (deleteObject)
delete umlobject;
} else {
logError1("UMLDoc::removeUMLObject %1: parent package is not set", umlobject->name());
}
}
setModified(true);
}
/**
* Signal that a UMLObject has been created.
*
* @param o The object that has been created.
*/
void UMLDoc::signalUMLObjectCreated(UMLObject * o)
{
Q_EMIT sigObjectCreated(o);
/* This is the wrong place to do:
setModified(true);
Instead, that should be done by the callers when object creation and all
its side effects (e.g. new widget in view, new list view item, etc.) is
finalized.
*/
}
/**
* Set the name of this model.
*/
void UMLDoc::setName(const QString& name)
{
m_Name = name;
}
/**
* Return the name of this model.
*/
QString UMLDoc::name() const
{
return m_Name;
}
/**
* Set coordinates resolution for current document.
* @param resolution document resolution in DPI
*/
void UMLDoc::setResolution(qreal resolution)
{
m_resolution = resolution;
if (!qFuzzyIsNull(resolution)) {
const int logicalDpiX = qApp->desktop()->logicalDpiX();
logDebug3("UMLDoc::setResolution screen dpi: %1, file dpi: %2, scale: %3",
logicalDpiX, resolution, logicalDpiX / resolution);
}
}
/**
* Returns coordinates resolution for current document.
* @return document resolution in DPI
*/
qreal UMLDoc::resolution() const
{
return m_resolution;
}
/**
* Returns scale factor for recalculation of document coordinates.
* @return scale factor
*/
qreal UMLDoc::dpiScale() const
{
#ifdef ENABLE_XMIRESOLUTION
if (!qFuzzyIsNull(resolution()))
return (qreal)qApp->desktop()->logicalDpiX() / resolution();
else
#endif
return 1.0;
}
/**
* Return the m_modelID (currently this a fixed value:
* Umbrello supports only a single document.)
*/
Uml::ID::Type UMLDoc::modelID() const
{
return m_modelID;
}
/**
* This method is called for saving the given model as a XMI file.
* It is virtual and calls the corresponding saveToXMI() functions
* of the derived classes.
*
* @param file The file to be saved to.
*/
void UMLDoc::saveToXMI(QIODevice& file)
{
QXmlStreamWriter writer(&file);
writer.setCodec("UTF-8");
writer.setAutoFormatting(true);
if (Settings::optionState().generalState.uml2)
writer.setAutoFormattingIndent(2);
else
writer.setAutoFormattingIndent(1);
// writer.writeProcessingInstruction(QStringLiteral("xml"));
writer.writeStartDocument();
QString expoText(QStringLiteral("umbrello uml modeller "));
expoText += QLatin1String(umbrelloVersion());
expoText += QStringLiteral(" http://umbrello.kde.org");
if (Settings::optionState().generalState.uml2) {
writer.writeStartElement(QStringLiteral("xmi:XMI"));
writer.writeAttribute(QStringLiteral("xmi:version"), QStringLiteral("2.1"));
writer.writeAttribute(QStringLiteral("xmlns:xmi"), QStringLiteral("http://schema.omg.org/spec/XMI/2.1"));
writer.writeAttribute(QStringLiteral("xmlns:xsi"), QStringLiteral("http://www.w3.org/2001/XMLSchema-instance"));
writer.writeNamespace(QStringLiteral("http://schema.omg.org/spec/UML/2.1"), QStringLiteral("uml"));
writer.writeStartElement(QStringLiteral("xmi:Documentation"));
writer.writeAttribute(QStringLiteral("exporter"), expoText);
writer.writeAttribute(QStringLiteral("exporterVersion"), QStringLiteral(XMI2_FILE_VERSION));
writer.writeEndElement(); // xmi:Documentation
writer.writeStartElement(QStringLiteral("uml:Model"));
writer.writeAttribute(QStringLiteral("xmi:id"), Uml::ID::toString(m_modelID));
} else {
writer.writeStartElement(QStringLiteral("XMI"));
writer.writeAttribute(QStringLiteral("xmi.version"), QStringLiteral("1.2"));
QDateTime now = QDateTime::currentDateTime();
writer.writeAttribute(QStringLiteral("timestamp"), now.toString(Qt::ISODate));
writer.writeAttribute(QStringLiteral("verified"), QStringLiteral("false"));
writer.writeNamespace(QStringLiteral("http://schema.omg.org/spec/UML/1.4"), QStringLiteral("UML"));
writer.writeStartElement(QStringLiteral("XMI.header"));
writer.writeStartElement(QStringLiteral("XMI.documentation"));
writer.writeTextElement(QStringLiteral("XMI.exporter"), expoText);
writer.writeTextElement(QStringLiteral("XMI.exporterVersion"), QStringLiteral(XMI1_FILE_VERSION));
// all files are now saved with correct Unicode encoding, we add this
// information to the header, so that the file will be loaded correctly
writer.writeTextElement(QStringLiteral("XMI.exporterEncoding"), QStringLiteral("UnicodeUTF8"));
writer.writeEndElement(); // XMI.documentation
writer.writeStartElement(QStringLiteral("XMI.metamodel"));
writer.writeAttribute(QStringLiteral("xmi.name"), QStringLiteral("UML"));
writer.writeAttribute(QStringLiteral("xmi.version"), QStringLiteral("1.4"));
writer.writeAttribute(QStringLiteral("href"), QStringLiteral("UML.xml"));
writer.writeEndElement(); // XMI.metamodel
writer.writeEndElement(); // XMI.header
writer.writeStartElement(QStringLiteral("XMI.content")); // content
writer.writeStartElement(QStringLiteral("UML:Model"));
writer.writeAttribute(QStringLiteral("xmi.id"), Uml::ID::toString(m_modelID));
}
writer.writeAttribute(QStringLiteral("name"), m_Name);
if (! Settings::optionState().generalState.uml2) {
writer.writeAttribute(QStringLiteral("isSpecification"), QStringLiteral("false"));
writer.writeAttribute(QStringLiteral("isAbstract"), QStringLiteral("false"));
writer.writeAttribute(QStringLiteral("isRoot"), QStringLiteral("false"));
writer.writeAttribute(QStringLiteral("isLeaf"), QStringLiteral("false"));
writer.writeStartElement(QStringLiteral("UML:Namespace.ownedElement")); // ownedNS
}
// Save stereotypes and toplevel datatypes first so that upon loading
// they are known first.
// There is a bug causing duplication of the same stereotype in m_stereoList.
// As a workaround, we use a string list to memorize which stereotype has been saved.
QStringList stereoNames;
for(UMLStereotype *s : m_stereoList) {
QString stName = s->name();
if (!stereoNames.contains(stName)) {
s->saveToXMI(writer);
stereoNames.append(stName);
}
}
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_root[i]->saveToXMI(writer);
}
if (! Settings::optionState().generalState.uml2) {
writer.writeEndElement(); // UML:Namespace.ownedElement
}
writer.writeEndElement(); // uml:Model
if (! Settings::optionState().generalState.uml2) {
writer.writeEndElement(); // XMI.content
}
// Save the XMI extensions: docsettings, diagrams, listview, and codegeneration.
if (Settings::optionState().generalState.uml2) {
writer.writeStartElement(QStringLiteral("xmi:Extension"));
writer.writeAttribute(QStringLiteral("extender"), QStringLiteral("umbrello"));
} else {
writer.writeStartElement(QStringLiteral("XMI.extensions"));
writer.writeAttribute(QStringLiteral("xmi.extender"), QStringLiteral("umbrello"));
}
writer.writeStartElement(QStringLiteral("docsettings"));
Uml::ID::Type viewID = Uml::ID::None;
UMLView *currentView = UMLApp::app()->currentView();
if (currentView) {
viewID = currentView->umlScene()->ID();
}
writer.writeAttribute(QStringLiteral("viewid"), Uml::ID::toString(viewID));
writer.writeAttribute(QStringLiteral("documentation"), m_Doc);
writer.writeAttribute(QStringLiteral("uniqueid"), Uml::ID::toString(UniqueID::get()));
writer.writeEndElement(); // docsettings
// save listview
UMLApp::app()->listView()->saveToXMI(writer);
// save code generator
CodeGenerator *codegen = UMLApp::app()->generator();
if (codegen) {
writer.writeStartElement(QStringLiteral("codegeneration"));
codegen->saveToXMI(writer);
writer.writeEndElement(); // codegeneration
}
writer.writeEndElement(); // XMI.extensions
writer.writeEndElement(); // XMI
writer.writeEndDocument();
}
/**
* If the given XMI file has a processing instruction then extract the
* encoding info from the processing instruction. If that info is unrecognized
* then return ENC_OLD_ENC, else return the encoding found.
* If the file does not have a processing instruction then give a warning but
* return ENC_UNICODE. This is an optimistic assumption in the interest of
* best effort loading.
* The value ENC_UNKNOWN is only returned in case of a grave error.
*
* @param file The file to be checked.
*/
short UMLDoc::encoding(QIODevice & file)
{
QTextStream stream(&file);
stream.setCodec("UTF-8");
QString data = stream.readAll();
QString error;
int line;
QDomDocument doc;
if (!doc.setContent(data, false, &error, &line)) {
logWarn2("UMLDoc::encoding cannot set content : Error %1, line %2", error, line);
return ENC_UNKNOWN;
}
// we start at the beginning and go to the point in the header where we can
// find out if the file was saved using Unicode
QDomNode node = doc.firstChild();
short enc = ENC_UNKNOWN;
while (node.isComment() || node.isProcessingInstruction()) {
if (node.isProcessingInstruction()) {
const QDomProcessingInstruction& pi = node.toProcessingInstruction();
QRegularExpression rx(QStringLiteral("\\bencoding=['\"]([^'\"]+)['\"]"));
const int pos = pi.data().indexOf(rx);
if (pos >= 0) {
QRegularExpressionMatch rm = rx.match(pi.data());
const QString& encData = rm.captured(1);
if (QString::compare(encData, QStringLiteral("UTF-8"), Qt::CaseInsensitive) == 0) {
enc = ENC_UNICODE;
} else if (QString::compare(encData, QStringLiteral("windows-1252"), Qt::CaseInsensitive) == 0) {
enc = ENC_WINDOWS;
} else {
logDebug1("UMLDoc::encoding : ProcessingInstruction encoding=%1 is not yet implemented",
encData);
enc = ENC_OLD_ENC;
}
}
}
node = node.nextSibling();
}
if (enc == ENC_UNKNOWN) {
logWarn0("UMLDoc::encoding : No ProcessingInstruction found, assuming ENC_UNICODE");
enc = ENC_UNICODE;
}
return enc;
}
/**
* Load a given XMI model from a file. If the encoding of the file
* is already known it can be passed to the function. If this info
* isn't given, loadFromXMI will check which encoding was used.
*
* @param file The file to be loaded.
* @param encode The encoding used.
*/
bool UMLDoc::loadFromXMI(QIODevice & file, short encode)
{
// old Umbrello versions (version < 1.2) didn't save the XMI in Unicode
// this wasn't correct, because non Latin1 chars where lost
// to ensure backward compatibility we have to ensure to load the old files
// with non Unicode encoding
if (encode == ENC_UNKNOWN) {
if ((encode = encoding(file)) == ENC_UNKNOWN) {
return false;
}
file.reset();
}
QTextStream stream(&file);
if (encode == ENC_UNICODE) {
stream.setCodec("UTF-8");
} else if (encode == ENC_WINDOWS) {
stream.setCodec("windows-1252");
}
QString data = stream.readAll();
qApp->processEvents(); // give UI events a chance
QString error;
int line;
QDomDocument doc;
if (!doc.setContent(data, false, &error, &line)) {
logWarn2("UMLDoc::loadFromXMI cannot set content : Error %1, line %2", error, line);
return false;
}
qApp->processEvents(); // give UI events a chance
QDomNode node = doc.firstChild();
//Before Umbrello 1.1-rc1 we didn't add a <?xml heading
//so we allow the option of this being missing
while (node.isComment() || node.isProcessingInstruction()) {
node = node.nextSibling();
}
QDomElement root = node.toElement();
if (root.isNull()) {
return false;
}
m_nViewID = Uml::ID::None;
QString outerTag = root.tagName();
// The element <XMI> / <xmi:XMI> is optional
if (outerTag == QStringLiteral("XMI") || outerTag == QStringLiteral("xmi:XMI")) {
QString versionString = root.attribute(QStringLiteral("xmi.version"));
if (versionString.isEmpty())
versionString = root.attribute(QStringLiteral("xmi:version"));
if (! versionString.isEmpty()) {
double version = versionString.toDouble();
if (version < 1.0) {
QString error = i18n("Unsupported xmi file version: %1", versionString);
m_d->errors << error;
logDebug1("UMLDoc::loadFromXMI %1", error);
return false;
}
if (version >= 2.0) {
Settings::optionState().generalState.uml2 = true;
}
}
for (node = node.firstChild(); !node.isNull(); node = node.nextSibling()) {
if (node.isComment()) {
continue;
}
QDomElement element = node.toElement();
if (element.isNull()) {
logDebug0("loadFromXMI: skip empty elem");
continue;
}
bool recognized = false;
outerTag = element.tagName();
//check header
if (outerTag == QStringLiteral("XMI.header")) {
QDomNode headerNode = node.firstChild();
if (!validateXMI1Header(headerNode)) {
return false;
}
recognized = true;
} else if (outerTag == QStringLiteral("XMI.extensions") ||
outerTag == QStringLiteral("xmi:Extension")) {
QDomNode extensionsNode = node.firstChild();
while (! extensionsNode.isNull()) {
loadExtensionsFromXMI1(extensionsNode);
extensionsNode = extensionsNode.nextSibling();
}
recognized = true;
} else if (tagEq(outerTag, QStringLiteral("Model")) ||
tagEq(outerTag, QStringLiteral("Package")) ||
tagEq(outerTag, QStringLiteral("packagedElement"))) {
if (!loadUMLObjectsFromXMI(element)) {
logWarn1("loadUMLObjectsFromXMI returned false for outerTag %1", outerTag);
continue; //return false;
}
m_Name = element.attribute(QStringLiteral("name"), i18n("UML Model"));
UMLListView *lv = UMLApp::app()->listView();
lv->setTitle(0, m_Name);
recognized = true;
}
if (outerTag != QStringLiteral("XMI.content")) {
if (!recognized) {
logDebug1("UMLDoc::loadFromXMI skipping <%1>", outerTag);
}
continue;
}
bool seen_UMLObjects = false;
//process content
for (QDomNode child = node.firstChild(); !child.isNull();
child = child.nextSibling()) {
if (child.isComment()) {
continue;
}
element = child.toElement();
QString tag = element.tagName();
if (tag == QStringLiteral("umlobjects") // for bkwd compat.
|| tagEq(tag, QStringLiteral("Subsystem"))
|| tagEq(tag, QStringLiteral("Project")) // Embarcadero's Describe
|| tagEq(tag, QStringLiteral("Model"))) {
if (!loadUMLObjectsFromXMI(element)) {
logWarn0("UMLDoc::loadFromXMI failed load on objects");
return false;
}
m_Name = element.attribute(QStringLiteral("name"), i18n("UML Model"));
UMLListView *lv = UMLApp::app()->listView();
lv->setTitle(0, m_Name);
seen_UMLObjects = true;
} else if (tagEq(tag, QStringLiteral("Package")) ||
tagEq(tag, QStringLiteral("Class")) ||
tagEq(tag, QStringLiteral("Interface")) ||
tagEq(tag, QStringLiteral("DataType"))) {
// These tests are only for foreign XMI files that
// are missing the <Model> tag (e.g. NSUML)
QString stID = element.attribute(QStringLiteral("stereotype"));
UMLObject *pObject = Object_Factory::makeObjectFromXMI(tag, stID);
if (!pObject) {
logWarn1("UMLDoc::loadFromXMI Unknown type of umlobject to create: %1", tag);
// We want a best effort, therefore this is handled as a
// soft error.
continue;
}
UMLObject::ObjectType ot = pObject->baseType();
// Set the parent root folder.
UMLPackage *pkg = nullptr;
if (ot != UMLObject::ot_Stereotype) {
if (ot == UMLObject::ot_Datatype) {
pkg = m_datatypeRoot;
} else {
Uml::ModelType::Enum guess = Model_Utils::guessContainer(pObject);
if (guess != Uml::ModelType::N_MODELTYPES) {
pkg = m_root[guess];
}
else {
logError2("UMLDoc::loadFromXMI: guessContainer failed - package not set correctly for %1 / base type %2",
pObject->name(), pObject->baseTypeStr());
pkg = m_root[Uml::ModelType::Logical];
}
}
}
pObject->setUMLPackage(pkg);
bool status = pObject->loadFromXMI(element);
if (!status) {
delete pObject;
return false;
}
seen_UMLObjects = true;
} else if (tagEq(tag, QStringLiteral("TaggedValue"))) {
// This tag is produced here, i.e. outside of <UML:Model>,
// by the Unisys.JCR.1 Rose-to-XMI tool.
if (! seen_UMLObjects) {
logDebug0("skipping TaggedValue because not seen_UMLObjects");
continue;
}
tag = element.attribute(QStringLiteral("tag"));
if (tag != QStringLiteral("documentation")) {
continue;
}
QString modelElement = element.attribute(QStringLiteral("modelElement"));
if (modelElement.isEmpty()) {
logDebug0("skipping TaggedValue(documentation) because modelElement.isEmpty()");
continue;
}
UMLObject *o = findObjectById(Uml::ID::fromString(modelElement));
if (o == nullptr) {
logDebug1("TaggedValue(documentation): cannot find object for modelElement %1",
modelElement);
continue;
}
QString value = element.attribute(QStringLiteral("value"));
if (! value.isEmpty()) {
o->setDoc(value);
}
} else if (tagEq(tag, QStringLiteral("ownedComment"))) {
m_Doc = Model_Utils::loadCommentFromXMI(element);
} else {
// for backward compatibility
loadExtensionsFromXMI1(child);
}
}
}
} else if (tagEq(outerTag, QStringLiteral("Model")) ||
tagEq(outerTag, QStringLiteral("Package"))) {
if (!loadUMLObjectsFromXMI(root)) {
logWarn0("UMLDoc::loadFromXMI (without XMI element) failed load on objects");
return false;
}
m_Name = root.attribute(QStringLiteral("name"), i18n("UML Model"));
UMLListView *lv = UMLApp::app()->listView();
lv->setTitle(0, m_Name);
} else {
logError1("UMLDoc::loadFromXMI failed load: Unrecognized outer element %1", outerTag);
return false;
}
resolveTypes();
loadDiagrams1();
Q_EMIT sigWriteToStatusBar(i18n("Setting up the document..."));
qApp->processEvents(); // give UI events a chance
activateAllViews();
UMLView *viewToBeSet = nullptr;
if (m_nViewID != Uml::ID::None) {
viewToBeSet = findView(m_nViewID);
}
if (viewToBeSet) {
changeCurrentView(m_nViewID);
} else {
QString name = createDiagramName(Uml::DiagramType::Class, false);
createDiagram(m_root[Uml::ModelType::Logical], Uml::DiagramType::Class, name);
m_pCurrentRoot = m_root[Uml::ModelType::Logical];
}
Q_EMIT sigResetStatusbarProgress();
return true;
}
/**
* Type resolution pass.
*/
void UMLDoc::resolveTypes()
{
// Resolve the types.
// This is done in a separate pass because of possible forward references.
if (m_bTypesAreResolved) {
return;
}
writeToStatusBar(i18n("Resolving object references..."));
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
UMLFolder *obj = m_root[i];
#ifdef VERBOSE_DEBUGGING
logDebug2("UMLDoc::resolveTypes calling resolveRef for %1 (id=%2)",
obj->name(), Uml::ID::toString(obj->id()));
#endif
obj->resolveRef();
}
m_bTypesAreResolved = true;
qApp->processEvents(); // give UI events a chance
}
/**
* Load all diagrams collected from the xmi file.
*
* Loading diagrams is implemented as additional pass to avoid unresolved
* uml objects which are defined later in the xmi file.
*/
bool UMLDoc::loadDiagrams1()
{
bool result = true;
DiagramsMap::const_iterator i;
for (i = m_diagramsToLoad.constBegin(); i != m_diagramsToLoad.constEnd(); i++) {
UMLFolder *f = i.key();
for(QDomNode node : i.value())
if (!f->loadDiagramsFromXMI1(node))
result = false;
}
m_diagramsToLoad.clear();
return result;
}
/**
* Add a xml node containing a diagram to the list of diagrams to load.
* Helper function for loadDiagrams().
*
* @param folder pointer to UMFolder instance the diagrams belongs to
* @param node xml document node containing the diagram
*/
void UMLDoc::addDiagramToLoad(UMLFolder *folder, QDomNode node)
{
if (m_diagramsToLoad.contains(folder))
m_diagramsToLoad[folder].append(node);
else
m_diagramsToLoad[folder] = QList<QDomNode>() << node;
}
DiagramsModel *UMLDoc::diagramsModel() const
{
return m_diagramsModel;
}
ObjectsModel *UMLDoc::objectsModel() const
{
return m_objectsModel;
}
void UMLDoc::setLoadingError(const QString &text)
{
m_d->errors << text;
}
StereotypesModel *UMLDoc::stereotypesModel() const
{
return m_stereotypesModel;
}
/**
* Ensures the XMI file is a valid UML file.
* Currently only checks for metamodel=UML.
*
* @param headerNode The <XMI.header> node
*/
bool UMLDoc::validateXMI1Header(QDomNode& headerNode)
{
QDomElement headerElement = headerNode.toElement();
while (!headerNode.isNull()) {
/* //Seems older Umbrello files used a different metamodel, so don't validate it for now
if(!headerElement.isNull() && headerElement.tagName() == "XMI.metamodel") {
String metamodel = headerElement.attribute("xmi.name");
if (metamodel != "UML") {
return false;
}
}
*/
headerNode = headerNode.nextSibling();
headerElement = headerNode.toElement();
}
return true;
}
/**
* Loads all UML objects from XMI into the current UMLDoc.
*
* @return True if operation successful.
*/
bool UMLDoc::loadUMLObjectsFromXMI(QDomElement& element)
{
/* FIXME need a way to make status bar actually reflect
how much of the file has been loaded rather than just
counting to 10 (an arbitrary number)
Q_EMIT sigResetStatusbarProgress();
Q_EMIT sigSetStatusbarProgress(0);
Q_EMIT sigSetStatusbarProgressSteps(10);
m_count = 0;
*/
Q_EMIT sigWriteToStatusBar(i18n("Loading UML elements..."));
// For Umbrello native XMI files, when called from loadFromXMI() we
// get here with Element.tagName() == "UML:Model" from the XMI input:
// <UML:Model name="UML Model">
for (QDomNode node = element.firstChild(); !node.isNull();
node = node.nextSibling()) {
if (node.isComment()) {
continue;
}
QDomElement tempElement = node.toElement();
QString type = tempElement.tagName();
QString xmiType = tempElement.attribute(QStringLiteral("xmi:type"));
if (tagEq(type, QStringLiteral("packagedElement")) && !xmiType.isEmpty()) {
type = xmiType;
}
if (tagEq(type, QStringLiteral("Model"))) {
// Handling of Umbrello native XMI files:
// We get here from a recursive call to loadUMLObjectsFromXMI()
// a few lines below, see
// if (tagEq(type, "Namespace.ownedElement") ....
// Inside this Namespace.ownedElement envelope there are the
// four submodels.
// In UML2 mode:
// <packagedElement xmi:type="uml:Model" name="Logical View">
// <packagedElement xmi:type="uml:Model" name="Use Case View">
// <packagedElement xmi:type="uml:Model" name="Component View">
// <packagedElement xmi:type="uml:Model" name="Deployment View">
// In UML1 mode:
// <UML:Model name="Logical View">
// <UML:Model name="Use Case View">
// <UML:Model name="Component View">
// <UML:Model name="Deployment View">
// These are ultimately loaded by UMLFolder::loadFromXMI()
// Furthermore, in UML1 mode native XMI format this
// Namespace.ownedElement is the container of all stereotypes
// (<UML:Stereotype>).
bool foundUmbrelloRootFolder = false;
QString name = tempElement.attribute(QStringLiteral("name"));
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
if (name == m_root[i]->name()) {
UMLFolder *curRootSave = m_pCurrentRoot;
m_pCurrentRoot = m_root[i];
if (!m_pCurrentRoot->loadFromXMI(tempElement)) {
logWarn1("UMLDoc::loadUMLObjectsFromXMI failed load on %1", name);
m_pCurrentRoot = curRootSave;
return false;
}
foundUmbrelloRootFolder = true;
break;
}
}
if (foundUmbrelloRootFolder) {
continue;
}
}
if (Model_Utils::isCommonXMI1Attribute(type)) {
continue;
}
if (tagEq(type, QStringLiteral("Namespace.ownedElement")) ||
tagEq(type, QStringLiteral("Namespace.contents")) ||
tagEq(type, QStringLiteral("Element.ownedElement")) || // Embarcadero's Describe
tagEq(type, QStringLiteral("Model")) ||
type == QStringLiteral("ownedElement")) {
//CHECK: Umbrello currently assumes that nested elements
// are ownedElements anyway.
// Therefore the <UML:Namespace.ownedElement> tag is of no
// significance.
// The tagEq(type, "Namespace.contents") and tagEq(type, "Model")
// tests do not become true for Umbrello native files, only for
// some foreign XMI files.
if (!loadUMLObjectsFromXMI(tempElement)) {
logWarn1("UMLDoc::loadUMLObjectsFromXMI failed load on type %1", type);
}
continue;
}
// From here on, it's support for stereotypes, pre 1.5.5 versions,
// and foreign files
if (!tempElement.hasAttribute(QStringLiteral("xmi.id")) &&
!tempElement.hasAttribute(QStringLiteral("xmi:id"))) {
QString idref = tempElement.attribute(QStringLiteral("xmi.idref"));
if (! idref.isEmpty()) {
logDebug1("UMLDoc::loadUMLObjectsFromXMI resolution of xmi.idref %1"
" is not yet implemented", idref);
} else {
logError1("UMLDoc::loadUMLObjectsFromXMI cannot load type %1 because xmi.id is missing",
type);
}
continue;
}
if (UMLDoc::tagEq(type, QStringLiteral("ownedComment"))) {
m_Doc = Model_Utils::loadCommentFromXMI(tempElement);
continue;
}
QString stID = tempElement.attribute(QStringLiteral("stereotype"));
UMLObject *pObject = Object_Factory::makeObjectFromXMI(type, stID);
if (!pObject) {
logWarn1("UMLDoc::loadUMLObjectsFromXMI unknown type of umlobject to create: %1", type);
// We want a best effort, therefore this is handled as a
// soft error.
continue;
}
UMLObject::ObjectType ot = pObject->baseType();
// Set the parent root folder.
UMLPackage *pkg = nullptr;
if (ot != UMLObject::ot_Stereotype) {
if (ot == UMLObject::ot_Datatype) {
pkg = m_datatypeRoot;
} else {
Uml::ModelType::Enum guess = Model_Utils::guessContainer(pObject);
if (guess != Uml::ModelType::N_MODELTYPES) {
pkg = m_root[guess];
}
else {
logError2("UMLDoc::loadUMLObjectsFromXMI guessContainer failed - package not set correctly for %1 / base type %2",
pObject->name(), pObject->baseTypeStr());
pkg = m_root[Uml::ModelType::Logical];
}
}
}
pObject->setUMLPackage(pkg);
bool status = pObject->loadFromXMI(tempElement);
if (!status) {
delete pObject;
continue;
}
pkg = pObject->umlPackage();
if (ot == UMLObject::ot_Stereotype) {
UMLStereotype *s = pObject->asUMLStereotype();
UMLStereotype *exist = findStereotype(pObject->name());
if (exist) {
if (exist->id() == pObject->id()) {
delete pObject;
} else {
logDebug3("UMLDoc::loadUMLObjectsFromXMI Stereotype %1 (id=%2) "
"already exists with id=%3", pObject->name(),
Uml::ID::toString(pObject->id()), Uml::ID::toString(exist->id()));
addStereotype(s);
}
} else {
addStereotype(s);
}
continue;
}
if (pkg) {
UMLObjectList objects = pkg->containedObjects();
if (! objects.contains(pObject)) {
logDebug2("UMLDoc::loadUMLObjectsFromXMI CHECK: adding %1 to %2",
pObject->name(), pkg->name());
if (!pkg->addObject(pObject)) {
logDebug0("- pkg->addObject failed");
}
}
}
else if (ot != UMLObject::ot_Stereotype) {
logError1("UMLDoc::loadUMLObjectsFromXMI: Package is NULL for %1", pObject->name());
return false;
}
/* FIXME see comment at loadUMLObjectsFromXMI
Q_EMIT sigSetStatusbarProgress(++m_count);
*/
}
return true;
}
/**
* Sets m_nViewID.
*/
void UMLDoc::setMainViewID(Uml::ID::Type viewID)
{
m_nViewID = viewID;
}
/**
* Loads umbrello specific extensions from XMI to the UMLDoc.
* The extension tags are: "docsettings", "diagrams", "listview",
* and "codegeneration".
*/
void UMLDoc::loadExtensionsFromXMI1(QDomNode& node)
{
QDomElement element = node.toElement();
QString tag = element.tagName();
if (tag == QStringLiteral("docsettings")) {
QString viewID = element.attribute(QStringLiteral("viewid"), QStringLiteral("-1"));
m_Doc = element.attribute(QStringLiteral("documentation"));
QString uniqueid = element.attribute(QStringLiteral("uniqueid"), QStringLiteral("0"));
m_nViewID = Uml::ID::fromString(viewID);
UniqueID::set(Uml::ID::fromString(uniqueid));
UMLApp::app()->docWindow()->reset();
} else if (tag == QStringLiteral("diagrams") || tag == QStringLiteral("UISModelElement")) {
// For backward compatibility only:
// Since version 1.5.5 diagrams are saved as part of the UMLFolder.
QDomNode diagramNode = node.firstChild();
if (tag == QStringLiteral("UISModelElement")) { // Unisys.IntegratePlus.2
element = diagramNode.toElement();
tag = element.tagName();
if (tag != QStringLiteral("uisOwnedDiagram")) {
logError1("UMLDoc::loadExtensionsFromXMI1 unknown child node %1", tag);
return;
}
diagramNode = diagramNode.firstChild();
} else {
qreal resolution = 0.0;
QString res = node.toElement().attribute(QStringLiteral("resolution"), QStringLiteral(""));
if (!res.isEmpty()) {
resolution = res.toDouble();
}
if (!qFuzzyIsNull(resolution)) {
UMLApp::app()->document()->setResolution(resolution);
} else {
// see UMLFolder::loadDiagramsFromXMI()
UMLApp::app()->document()->setResolution(0.0);
}
}
if (!loadDiagramsFromXMI1(diagramNode)) {
logWarn0("UMLDoc::loadExtensionsFromXMI1 failed load on diagrams");
}
} else if (tag == QStringLiteral("listview")) {
//FIXME: Need to resolveTypes() before loading listview,
// else listview items are duplicated.
resolveTypes();
if (!UMLApp::app()->listView()->loadFromXMI(element)) {
logWarn0("UMLDoc::loadExtensionsFromXMI1 failed load on listview");
}
} else if (tag == QStringLiteral("codegeneration")) {
QDomNode cgnode = node.firstChild();
QDomElement cgelement = cgnode.toElement();
while (!cgelement.isNull()) {
QString nodeName = cgelement.tagName();
QString lang = cgelement.attribute(QStringLiteral("language"), QStringLiteral("UNKNOWN"));
Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromString(lang);
if (pl != Uml::ProgrammingLanguage::Reserved) {
CodeGenerator *g = UMLApp::app()->setGenerator(pl);
g->loadFromXMI(cgelement);
} else
logDebug0("UMLDoc::loadExtensionsFromXMI1 codegeneration : "
"no setup required for UML primitive types");
cgnode = cgnode.nextSibling();
cgelement = cgnode.toElement();
}
if (UMLApp::app()->generator() == nullptr) {
UMLApp::app()->setGenerator(UMLApp::app()->defaultLanguage());
}
}
}
/**
* Loads all diagrams from XMI into the current UMLDoc.
* For backward compatibility only:
* Since version 1.5.5 diagrams are saved as part of the UMLFolder.
*
* @return True if operation successful.
*/
bool UMLDoc::loadDiagramsFromXMI1(QDomNode & node)
{
Q_EMIT sigWriteToStatusBar(i18n("Loading diagrams..."));
Q_EMIT sigResetStatusbarProgress();
Q_EMIT sigSetStatusbarProgress(0);
Q_EMIT sigSetStatusbarProgressSteps(10); //FIX ME
QDomElement element = node.toElement();
if (element.isNull()) {
return true; //return ok as it means there is no umlobjects
}
const Settings::OptionState state = Settings::optionState();
UMLView *pView = nullptr;
int count = 0;
while (!element.isNull()) {
QString tag = element.tagName();
if (tag == QStringLiteral("diagram") || tag == QStringLiteral("UISDiagram")) {
pView = new UMLView(nullptr);
// IMPORTANT: Set OptionState of new UMLView _BEFORE_
// reading the corresponding diagram:
// + allow using per-diagram color and line-width settings
// + avoid crashes due to uninitialized values for lineWidth
pView->umlScene()->setOptionState(state);
bool success = false;
if (tag == QStringLiteral("UISDiagram")) {
success = pView->umlScene()->loadUISDiagram(element);
} else {
success = pView->umlScene()->loadFromXMI(element);
}
if (!success) {
logWarn0("UMLDoc::loadDiagramsFromXMI failed load on viewdata loadfromXMI");
delete pView;
return false;
}
// Put diagram in default predefined folder.
// @todo pass in the parent folder - it might be a user defined one.
Uml::ModelType::Enum mt = Model_Utils::convert_DT_MT(pView->umlScene()->type());
if (mt != Uml::ModelType::N_MODELTYPES) {
pView->umlScene()->setFolder(m_root[mt]);
pView->hide();
addView(pView);
} else {
logWarn2("UMLDoc::loadDiagramsFromXMI cannot add %1 because scene type %2 cannot be mapped to ModelType",
tag, pView->umlScene()->type());
}
Q_EMIT sigSetStatusbarProgress(++count);
qApp->processEvents(); // give UI events a chance
}
node = node.nextSibling();
element = node.toElement();
}
return true;
}
/**
* Call to remove all the views (diagrams) in the current file.
*/
void UMLDoc::removeAllViews()
{
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_root[i]->removeAllViews();
}
UMLApp::app()->setCurrentView(nullptr);
Q_EMIT sigDiagramChanged(Uml::DiagramType::Undefined);
UMLApp::app()->setDiagramMenuItemsState(false);
}
/**
* Call to remove all objects in the current file.
*/
void UMLDoc::removeAllObjects()
{
m_root[Uml::ModelType::Logical]->removeObject(m_datatypeRoot);
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_root[i]->removeAllObjects();
}
}
/**
* Returns a list of the packages in this UMLDoc,
*
* @return List of UMLPackages.
*/
UMLPackageList UMLDoc::packages(bool includeNested /* = true */, Uml::ModelType::Enum model) const
{
UMLPackageList packageList;
m_root[model]->appendPackages(packageList, includeNested);
return packageList;
}
/**
* Returns the datatype folder.
*
* @return Pointer to the predefined folder for datatypes.
*/
UMLFolder * UMLDoc::datatypeFolder() const
{
return m_datatypeRoot;
}
/**
* Returns a list of the concepts in this UMLDoc.
*
* @param includeNested Whether to include the concepts from
* nested packages (default: true.)
* @return List of UML concepts.
*/
UMLClassifierList UMLDoc::concepts(bool includeNested /* =true */) const
{
UMLClassifierList conceptList;
m_root[Uml::ModelType::Logical]->appendClassifiers(conceptList, includeNested);
return conceptList;
}
/**
* Returns a list of the classes, interfaces, and enumerations in this UMLDoc.
*
* @param includeNested Whether to include the concepts from
* nested packages (default: true.)
* @return List of UML concepts.
*/
UMLClassifierList UMLDoc::classesAndInterfaces(bool includeNested /* =true */) const
{
UMLClassifierList conceptList;
m_root[Uml::ModelType::Logical]->appendClassesAndInterfaces(conceptList, includeNested);
return conceptList;
}
/**
* Returns a list of the entities in this UMLDoc.
*
* @param includeNested Whether to include the entities from
* nested packages (default: true.)
* @return List of UML Entities.
*/
UMLEntityList UMLDoc::entities(bool includeNested /* =true */) const
{
UMLEntityList entityList;
m_root[Uml::ModelType::EntityRelationship]->appendEntities(entityList, includeNested);
return entityList;
}
/**
* Returns a list of the datatypes in this UMLDoc.
*
* @param includeInactive Include inactive datatypes which may have accrued by
* changing the active programming language.
* @return List of datatypes.
*/
UMLClassifierList UMLDoc::datatypes(bool includeInactive /* = false */) const
{
UMLObjectList objects = m_datatypeRoot->containedObjects(includeInactive);
UMLClassifierList datatypeList;
for(UMLObject *obj : objects) {
uIgnoreZeroPointer(obj);
if (obj->isUMLDatatype()) {
datatypeList.append(obj->asUMLClassifier());
}
}
return datatypeList;
}
/**
* Seek the datatype of the given name in the Datatypes folder.
*
* @param name Name of the datatype
* @param includeInactive Include inactive datatypes in the search.
* @return List of datatypes.
*/
UMLDatatype * UMLDoc::findDatatype(QString name, bool includeInactive /* = false */)
{
const bool caseSensitive = UMLApp::app()->activeLanguageIsCaseSensitive();
name = Model_Utils::normalize(name);
for(UMLClassifier *c : datatypes(includeInactive)) {
UMLDatatype *type = dynamic_cast<UMLDatatype*>(c);
if (!type)
continue;
if (caseSensitive) {
if (type->name() == name)
return type;
} else if (type->name().toLower() == name.toLower()) {
return type;
}
}
return nullptr;
}
/**
* Returns a list of the associations in this UMLDoc.
*
* @return List of UML associations.
*/
UMLAssociationList UMLDoc::associations() const
{
UMLAssociationList associationList;
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
UMLAssociationList assocs = m_root[i]->getAssociations();
for(UMLAssociation* a : assocs) {
associationList.append(a);
}
}
return associationList;
}
/**
* Controls the printing of the program.
*
* @param pPrinter The printer (object) to use.
* @param selectPage The DiagramPrintPage by which diagrams are selected for printing
*/
void UMLDoc::print(QPrinter * pPrinter, DiagramPrintPage * selectPage)
{
UMLView *printView = nullptr;
int count = selectPage->printUmlCount();
QPainter painter(pPrinter);
for (int i = 0; i < count; ++i) {
if (i>0) {
pPrinter->newPage();
}
QString sID = selectPage->printUmlDiagram(i);
Uml::ID::Type id = Uml::ID::fromString(sID);
printView = findView(id);
if (printView) {
printView->umlScene()->print(pPrinter, painter);
}
printView = nullptr;
}
painter.end();
}
/**
* Return the list of views for this document.
*
* @return List of UML views.
*/
UMLViewList UMLDoc::viewIterator() const
{
UMLViewList accumulator;
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_root[i]->appendViews(accumulator, true);
}
return accumulator;
}
/**
* Return a list of filtered views of this document by type.
* @param type diagram type to filter
* @return List of UML views.
*/
UMLViewList UMLDoc::views(Uml::DiagramType::Enum type) const
{
UMLViewList result;
for(UMLView *v : viewIterator()) {
if (type == Uml::DiagramType::Undefined || v->umlScene()->type() == type)
result.append(v);
}
return result;
}
/**
* Sets the modified flag for the document after a modifying
* action on the view connected to the document.
*
* @param modified The value to set the modified flag to.
*/
void UMLDoc::setModified(bool modified /*=true*/)
{
if (!m_bLoading) {
m_modified = modified;
UMLApp::app()->setModified(modified);
}
}
/**
* Returns if the document is modified or not. Use this to
* determine if your document needs saving by the user on
* closing.
*
* @return True if this UMLDoc is modified.
*/
bool UMLDoc::isModified() const
{
return m_modified;
}
/**
* Assigns an already created UMLObject a new ID.
* If the object is a classifier then the operations/attributes
* are also assigned new IDs.
*
* @param obj Pointer to the UMLObject to add.
* @return True if operation successful.
*/
bool UMLDoc::assignNewIDs(UMLObject* obj)
{
if (!obj || !m_pChangeLog) {
logDebug0("UMLDoc::assignNewIDs: no obj || Changelog");
return false;
}
Uml::ID::Type result = assignNewID(obj->id());
obj->setID(result);
//If it is a CONCEPT then change the ids of all its operations and attributes
if (obj->baseType() == UMLObject::ot_Class) {
UMLClassifier *c = obj->asUMLClassifier();
UMLClassifierListItemList attributes = c->getFilteredList(UMLObject::ot_Attribute);
for(UMLObject* listItem: attributes) {
result = assignNewID(listItem->id());
listItem->setID(result);
}
UMLClassifierListItemList templates = c->getFilteredList(UMLObject::ot_Template);
for(UMLObject* listItem : templates) {
result = assignNewID(listItem->id());
listItem->setID(result);
}
}
if (obj->baseType() == UMLObject::ot_Interface || obj->baseType() == UMLObject::ot_Class) {
UMLOperationList operations(((UMLClassifier*)obj)->getOpList());
for(UMLObject *listItem : operations) {
result = assignNewID(listItem->id());
listItem->setID(result);
}
}
setModified(true);
return true;
}
/**
* Return the predefined root folder of the given type.
*/
UMLFolder *UMLDoc::rootFolder(Uml::ModelType::Enum mt) const
{
if (mt < Uml::ModelType::Logical || mt >= Uml::ModelType::N_MODELTYPES) {
logError1("UMLDoc::rootFolder: illegal model type value %1", mt);
return nullptr;
}
return m_root[mt];
}
/**
* Return the corresponding Model_Type if the given object
* is one of the root folders.
* When the given object is not one of the root folders then
* return Uml::ModelType::N_MODELTYPES.
*/
Uml::ModelType::Enum UMLDoc::rootFolderType(UMLObject *obj) const
{
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
const Uml::ModelType::Enum m = Uml::ModelType::fromInt(i);
if (obj == m_root[m]) {
return m;
}
}
return Uml::ModelType::N_MODELTYPES;
}
/**
* Read property of IDChangeLog* m_pChangeLog.
*
* @return Pointer to the IDChangeLog object.
*/
IDChangeLog* UMLDoc::changeLog() const
{
return m_pChangeLog;
}
/**
* Opens a Paste session, deletes the old ChangeLog and
* creates an empty one.
*/
void UMLDoc::beginPaste()
{
if (m_pChangeLog) {
delete m_pChangeLog;
m_pChangeLog = nullptr;
}
m_pChangeLog = new IDChangeLog;
}
/**
* Closes a paste session, deletes the ChangeLog.
*/
void UMLDoc::endPaste()
{
if (m_pChangeLog) {
delete m_pChangeLog;
m_pChangeLog = nullptr;
}
}
/**
* Assigns a New ID to an Object, and also logs the assignment
* to its internal ChangeLog.
*
* @param oldID The present ID of the object.
* @return The new ID assigned to the object.
*/
Uml::ID::Type UMLDoc::assignNewID(Uml::ID::Type oldID)
{
Uml::ID::Type result = UniqueID::gen();
if (m_pChangeLog) {
m_pChangeLog->addIDChange(oldID, result);
}
return result;
}
/**
* Returns the documentation for the project.
*
* @return The documentation text of this UMLDoc.
*/
QString UMLDoc::documentation() const
{
return m_Doc;
}
/**
* Sets the documentation for the project.
*
* @param doc The documentation to set for this UMLDoc.
*/
void UMLDoc::setDocumentation(const QString &doc)
{
m_Doc = doc;
}
/**
* Adds an already created UMLView to the document, it gets
* assigned a new ID, if its name is already in use then the
* function appends a number to it to differentiate it from
* the others; this number is incremental so if number 1 is in
* use then it tries 2 and then 3 and so on
*
* @param pView Pointer to the UMLView to add.
* @return True if operation successful.
*/
bool UMLDoc::addUMLView(UMLView * pView)
{
if (!pView || !m_pChangeLog) {
return false;
}
Uml::ID::Type oldID = pView->umlScene()->ID();
int i = 0;
QString viewName = pView->umlScene()->name();
QString name = viewName;
while (findView(pView->umlScene()->type(), name) != nullptr) {
name = viewName + QLatin1Char('_') + QString::number(++i);
}
if (i) { //If name was modified
pView->umlScene()->setName(name);
}
Uml::ID::Type newID = assignNewID(oldID);
pView->umlScene()->setID(newID);
pView->umlScene()->activateAfterLoad(true);
pView->umlScene()->endPartialWidgetPaste();
pView->umlScene()->setOptionState(Settings::optionState());
addView(pView);
Q_EMIT sigDiagramCreated(pView->umlScene()->ID());
setModified(true);
return true;
}
/**
* Activate all the diagrams/views after loading so all their
* widgets keep their IDs.
*/
void UMLDoc::activateAllViews()
{
// store old setting - for restore of last setting
bool m_bLoading_old = m_bLoading;
m_bLoading = true; //this is to prevent document becoming modified when activating a view
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_root[i]->activateViews();
}
m_bLoading = m_bLoading_old;
}
/**
* Sets the default settings to the given settings.
* @param optionState settings
*/
void UMLDoc::settingsChanged(Settings::OptionState &optionState)
{
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_root[i]->setViewOptions(optionState);
}
initSaveTimer();
}
/**
* Sets up the autosave timer.
*/
void UMLDoc::initSaveTimer()
{
if (m_pAutoSaveTimer) {
m_pAutoSaveTimer->stop();
disconnect(m_pAutoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
delete m_pAutoSaveTimer;
m_pAutoSaveTimer = nullptr;
}
Settings::OptionState optionState = Settings::optionState();
if (optionState.generalState.autosave) {
m_pAutoSaveTimer = new QTimer(this);
connect(m_pAutoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
m_pAutoSaveTimer->setSingleShot(false);
m_pAutoSaveTimer->start(optionState.generalState.autosavetime * 60000);
}
}
/**
* Called after a specified time to autosave the document.
*/
void UMLDoc::slotAutoSave()
{
//Only save if modified.
if (!m_modified) {
return;
}
QUrl tempUrl = m_doc_url;
if (tempUrl.fileName() == i18n("Untitled")) {
tempUrl.setScheme(QStringLiteral("file"));
tempUrl.setPath(QDir::homePath() + i18n("/autosave%1", QStringLiteral(".xmi")));
saveDocument(tempUrl);
setUrlUntitled();
m_modified = true;
UMLApp::app()->setModified(m_modified);
} else {
// 2004-05-17 Achim Spangler
QUrl orgDocUrl = m_doc_url;
QString orgFileName = m_doc_url.fileName();
// don't overwrite manually saved file with autosave content
QString fileName = tempUrl.fileName();
Settings::OptionState optionState = Settings::optionState();
fileName.replace(QStringLiteral(".xmi"), optionState.generalState.autosavesuffix);
tempUrl.setUrl(tempUrl.toString(QUrl::RemoveFilename) + fileName);
// End Achim Spangler
saveDocument(tempUrl);
// 2004-05-17 Achim Spangler
// re-activate m_modified if autosave is writing to other file
// than the main project file->autosave-suffix != ".xmi"
if (optionState.generalState.autosavesuffix != QStringLiteral(".xmi")) {
m_modified = true;
UMLApp::app()->setModified(m_modified);
}
// restore original file name -
// UMLDoc::saveDocument() sets doc_url to filename which is given as autosave-filename
setUrl(orgDocUrl);
UMLApp * pApp = UMLApp::app();
pApp->setCaption(orgFileName, isModified());
// End Achim Spangler
}
}
/**
* Signal a view/diagram has been renamed.
*/
void UMLDoc::signalDiagramRenamed(UMLView* view)
{
if (view) {
Settings::OptionState optionState = Settings::optionState();
if (optionState.generalState.tabdiagrams) {
UMLApp::app()->tabWidget()->setTabText(UMLApp::app()->tabWidget()->indexOf(view), view->umlScene()->name());
}
Q_EMIT sigDiagramRenamed(view->umlScene()->ID());
}
else {
logError0("Cannot signal diagram renamed - view is NULL!");
}
}
/**
* Calls the active code generator to create its default datatypes.
*/
void UMLDoc::addDefaultDatatypes()
{
CodeGenerator *cg = UMLApp::app()->generator();
if (cg == nullptr) {
logDebug0("CodeGenerator is NULL : Assume UMLPrimitiveTypes");
for (int i = 0; i < Uml::PrimitiveTypes::n_types; i++) {
createDatatype(Uml::PrimitiveTypes::toString(i));
}
} else {
QStringList entries = cg->defaultDatatypes();
QStringList::Iterator end(entries.end());
for (QStringList::Iterator it = entries.begin(); it != end; ++it) {
createDatatype(*it);
}
}
UMLApp::app()->listView()->closeDatatypesFolder();
}
/**
* Add a datatype if it doesn't already exist.
* Used by addDefaultDatatypes().
*/
UMLDatatype * UMLDoc::createDatatype(const QString &name)
{
UMLObjectList datatypes = m_datatypeRoot->containedObjects(true);
UMLObject* umlobject = Model_Utils::findUMLObject(datatypes, name,
UMLObject::ot_Datatype, m_datatypeRoot);
UMLDatatype *dt = nullptr;
if (umlobject)
dt = umlobject->asUMLDatatype();
if (dt) {
dt->setActive(true);
signalUMLObjectCreated(umlobject);
qApp->processEvents();
} else {
if (umlobject) {
logWarn1("UMLDoc::createDatatype(%1) : Name already exists but is not a Datatype", name);
}
umlobject = Object_Factory::createUMLObject(UMLObject::ot_Datatype,
Model_Utils::normalize(name), m_datatypeRoot);
dt = dynamic_cast<UMLDatatype*>(umlobject);
}
return dt;
}
/**
* Remove a datatype by name.
* Used when changing the active programming language.
*/
void UMLDoc::removeDatatype(const QString &name)
{
UMLObjectList datatypes = m_datatypeRoot->containedObjects();
// We don't use Model_Utils::findUMLObject because that function considers
// case sensitivity of the active language, which we don't want here.
for(UMLObject *obj : datatypes) {
uIgnoreZeroPointer(obj);
if (obj->name() == name) {
removeUMLObject(obj);
break;
}
}
}
/**
* Make a popup menu for the tabs
* signalled from tabWidget's contextMenu().
*/
void UMLDoc::slotDiagramPopupMenu(QWidget* umlview, const QPoint& point)
{
UMLView* view = (UMLView*) umlview;
UMLListViewItem::ListViewType type = UMLListViewItem::lvt_Unknown;
switch (view->umlScene()->type()) {
case Uml::DiagramType::Class:
type = UMLListViewItem::lvt_Class_Diagram;
break;
case Uml::DiagramType::UseCase:
type = UMLListViewItem::lvt_UseCase_Diagram;
break;
case Uml::DiagramType::Sequence:
type = UMLListViewItem::lvt_Sequence_Diagram;
break;
case Uml::DiagramType::Collaboration:
type = UMLListViewItem::lvt_Collaboration_Diagram;
break;
case Uml::DiagramType::State:
type = UMLListViewItem::lvt_State_Diagram;
break;
case Uml::DiagramType::Activity:
type = UMLListViewItem::lvt_Activity_Diagram;
break;
case Uml::DiagramType::Component:
type = UMLListViewItem::lvt_Component_Diagram;
break;
case Uml::DiagramType::Deployment:
type = UMLListViewItem::lvt_Deployment_Diagram;
break;
case Uml::DiagramType::EntityRelationship:
type = UMLListViewItem::lvt_EntityRelationship_Diagram;
break;
default:
logWarn1("UMLDoc::slotDiagramPopupMenu: unknown diagram type %1", view->umlScene()->type());
return;
}//end switch
UMLListViewItem item((UMLListView *)0, QString(), type);
UMLListViewPopupMenu popup(UMLApp::app()->mainViewWidget(), &item);
QAction *triggered = popup.exec(point);
view->umlScene()->slotMenuSelection(triggered);
}
/**
* Function for comparing tags in XMI files.
*/
bool UMLDoc::tagEq (const QString& inTag, const QString& inPattern)
{
QString tag = inTag;
QString pattern = inPattern;
tag.remove(QRegularExpression(QStringLiteral("^\\w+:"))); // remove leading "UML:" or other
int patSections = pattern.count(QLatin1Char('.')) + 1;
QString tagEnd = tag.section(QLatin1Char('.'), -patSections);
return (tagEnd.toLower() == pattern.toLower());
}
| 122,129
|
C++
|
.cpp
| 3,214
| 30.51369
| 138
| 0.617882
|
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,240
|
object_factory.cpp
|
KDE_umbrello/umbrello/object_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 "object_factory.h"
// app includes
#include "actor.h"
#include "artifact.h"
#include "association.h"
#include "attribute.h"
#include "category.h"
#include "checkconstraint.h"
#include "classifier.h"
#include "cmds.h"
#include "codegenerator.h"
#include "component.h"
#include "datatype.h"
#define DBG_SRC QStringLiteral("Object_Factory")
#include "debug_utils.h"
#include "dialog_utils.h"
#include "enum.h"
#include "entity.h"
#include "folder.h"
#include "foreignkeyconstraint.h"
#include "instance.h"
#include "model_utils.h"
#include "node.h"
#include "package.h"
#include "port.h"
#include "operation.h"
#include "stereotype.h"
#include "usecase.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
#include "umlpackagelist.h"
#include "uniqueconstraint.h"
#include "uniqueid.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
// qt includes
#include <QApplication>
#include <QStringList>
DEBUG_REGISTER(Object_Factory)
namespace Object_Factory {
Uml::ID::Type g_predefinedId = Uml::ID::None;
/**
* Control whether the createUMLObject() solicits a new unique ID for the
* created object.
* By default, unique ID generation is turned on.
*
* @param yesno False turns UID generation off, true turns it on.
*/
void assignUniqueIdOnCreation(bool yesno)
{
if (yesno)
g_predefinedId = Uml::ID::None;
else
g_predefinedId = Uml::ID::Reserved;
}
/**
* Return whether unique ID generation is on or off.
*/
bool assignUniqueIdOnCreation()
{
return (g_predefinedId == Uml::ID::None);
}
/**
* Creates a new UMLObject of the given type.
* No check is made for whether the object named \a name already exists.
* If the name shall be checked then use @ref createUMLObject.
*
* @param type The type of @ref UMLObject to create.
* @param name Name to give to the object (mandatory.)
* @param parentPkg The object's parent package.
* @param undoable Whether to insert the object creation into the undo stack (default: true.)
*/
UMLObject* createNewUMLObject(UMLObject::ObjectType type, const QString &name,
UMLPackage *parentPkg, bool undoable /* = true */)
{
if (parentPkg == nullptr) {
logError1("Object_Factory::createNewUMLObject(%1): parentPkg is NULL", name);
return nullptr;
}
QPointer<UMLObject> o = nullptr;
switch (type) {
case UMLObject::ot_Actor:
o = new UMLActor(name, g_predefinedId);
break;
case UMLObject::ot_UseCase:
o = new UMLUseCase(name, g_predefinedId);
break;
case UMLObject::ot_Class:
o = new UMLClassifier(name, g_predefinedId);
break;
case UMLObject::ot_Package:
o = new UMLPackage(name, g_predefinedId);
break;
case UMLObject::ot_Component:
o = new UMLComponent(name, g_predefinedId);
break;
case UMLObject::ot_Port:
o = new UMLPort(name, g_predefinedId);
break;
case UMLObject::ot_Node:
o = new UMLNode(name, g_predefinedId);
break;
case UMLObject::ot_Artifact:
o = new UMLArtifact(name, g_predefinedId);
break;
case UMLObject::ot_Interface: {
UMLClassifier *c = new UMLClassifier(name, g_predefinedId);
c->setBaseType(UMLObject::ot_Interface);
o = c;
break;
}
case UMLObject::ot_Datatype: {
UMLDatatype *c = new UMLDatatype(name, g_predefinedId);
o = c;
break;
}
case UMLObject::ot_Instance:
o = new UMLInstance(name, g_predefinedId);
if (parentPkg->isUMLClassifier()) {
UMLClassifier *c = parentPkg->asUMLClassifier();
o->asUMLInstance()->setClassifierCmd(c, false);
parentPkg = c->umlPackage();
}
break;
case UMLObject::ot_Enum:
o = new UMLEnum(name, g_predefinedId);
break;
case UMLObject::ot_Entity:
o = new UMLEntity(name, g_predefinedId);
break;
case UMLObject::ot_Folder:
o = new UMLFolder(name, g_predefinedId);
break;
case UMLObject::ot_Category:
o = new UMLCategory(name, g_predefinedId);
break;
case UMLObject::ot_SubSystem: {
o = new UMLPackage(name, g_predefinedId);
o->setStereotypeCmd(QStringLiteral("subsystem"));
break;
}
default:
logWarn2("Object_Factory::createNewUMLObject(%1) error unknown type: %2",
name, UMLObject::toString(type));
return nullptr;
}
if (!undoable) {
logDebug1("Object_Factory::createNewUMLObject: undoable=%1", undoable);
o->setUMLPackage(parentPkg);
UMLApp::app()->document()->signalUMLObjectCreated(o);
qApp->processEvents();
return o;
}
// One user action can result in multiple commands when adding objects via
// the toolbar. E.g. "create uml object" and "create widget". Wrap all
// commands in one macro. When adding items via list view, this macro will
// contain only the "create uml object" command.
UMLApp::app()->beginMacro(i18n("Create UML object : %1", name));
o->setUMLPackage(parentPkg);
UMLApp::app()->executeCommand(new Uml::CmdCreateUMLObject(o));
UMLApp::app()->document()->signalUMLObjectCreated(o);
qApp->processEvents();
UMLApp::app()->endMacro();
return o;
}
/**
* Creates a UMLObject of the given type.
*
* @param type The type of @ref UMLObject to create.
* @param n A name to give to the object (optional.)
* If not given then an input dialog prompts
* the user to supply a name.
* @param parentPkg The object's parent package.
* @param solicitNewName Ask user for a different name if an object
* of the given name already exists.
* If set to false and the name already exists
* then the existing object is returned.
* The default is to ask for the new name.
* @return Pointer to object or nullptr if object creation was
* canceled by the user.
*/
UMLObject* createUMLObject(UMLObject::ObjectType type, const QString &n,
UMLPackage *parentPkg /* = nullptr */,
bool solicitNewName /* = true */)
{
UMLDoc *doc = UMLApp::app()->document();
if (parentPkg == nullptr) {
if (type == UMLObject::ot_Datatype) {
parentPkg = doc->datatypeFolder();
} else {
Uml::ModelType::Enum mt = Model_Utils::convert_OT_MT(type);
logDebug2("Object_Factory::createUMLObject(%1): parentPkg is not set, assuming Model_Type %2",
n, Uml::ModelType::toString(mt));
parentPkg = doc->rootFolder(mt);
}
}
if (!n.isEmpty()) {
UMLObject *o = doc->findUMLObject(n, type, parentPkg);
if (o == nullptr) {
o = createNewUMLObject(type, n, parentPkg);
return o;
}
if (!solicitNewName) {
if (type == UMLObject::ot_UMLObject || o->baseType() == type) {
logDebug1("Object_Factory::createUMLObject(%1) : already known - returning existing object",
o->name());
return o;
}
logWarn3("Object_Factory::createUMLObject(%1) exists but is of type %2 - creating new object of type %3",
o->name(), UMLObject::toString(o->baseType()), UMLObject::toString(type));
o = createNewUMLObject(type, n, parentPkg, false);
return o;
}
}
bool bValidNameEntered = false;
QString name = Model_Utils::uniqObjectName(type, parentPkg, n);
if (name == n) {
bValidNameEntered = true;
}
while (bValidNameEntered == false) {
bool ok = Dialog_Utils::askNewName(type, name);
if (!ok) {
return nullptr;
}
if (name.length() == 0) {
KMessageBox::error(nullptr, i18n("That is an invalid name."),
i18n("Invalid Name"));
continue;
}
if (type != UMLObject::ot_Datatype) {
CodeGenerator *codegen = UMLApp::app()->generator();
if (codegen != nullptr && codegen->isReservedKeyword(name)) {
KMessageBox::error(nullptr, i18n("This is a reserved keyword for the language of the configured code generator."),
i18n("Reserved Keyword"));
continue;
}
}
if (! doc->isUnique(name, parentPkg) && type != UMLObject::ot_Instance) {
KMessageBox::error(nullptr, i18n("That name is already being used."),
i18n("Not a Unique Name"));
continue;
}
bValidNameEntered = true;
}
UMLObject *o = createNewUMLObject(type, name, parentPkg);
return o;
}
UMLAttribute *createAttribute(UMLObject *parent, const QString& name, UMLObject *type)
{
UMLAttribute *attr = new UMLAttribute(parent);
attr->setName(name);
attr->setType(type);
if (g_predefinedId == Uml::ID::None)
attr->setID(UniqueID::gen());
return attr;
}
UMLOperation *createOperation(UMLClassifier *parent, const QString& name)
{
UMLOperation *op = new UMLOperation(parent, name, g_predefinedId);
return op;
}
/**
* Creates an operation, attribute, template, or enum literal
* for the parent classifier.
*
* @param parent The parent classifier
* @param type The type to create
* @param name Optional name of object (skips creation dialog)
* @return Pointer to the UMLClassifierListItem created
*/
UMLClassifierListItem* createChildObject(UMLClassifier* parent, UMLObject::ObjectType type, const QString& name)
{
UMLObject *returnObject = nullptr;
switch (type) {
case UMLObject::ot_Attribute: {
UMLClassifier *c = parent->asUMLClassifier();
if (c && !c->isInterface())
returnObject = c->createAttribute(name);
break;
}
case UMLObject::ot_EntityAttribute: {
UMLEntity *e = parent->asUMLEntity();
if (e) {
returnObject = e->createAttribute(name);
}
break;
}
case UMLObject::ot_Operation: {
UMLClassifier *c = parent->asUMLClassifier();
if (c)
returnObject = c->createOperation(name);
break;
}
case UMLObject::ot_Template: {
UMLClassifier *c = parent->asUMLClassifier();
if (c)
returnObject = c->createTemplate(name);
break;
}
case UMLObject::ot_EnumLiteral: {
UMLEnum* umlenum = parent->asUMLEnum();
if (umlenum) {
returnObject = umlenum->createEnumLiteral(name);
}
break;
}
case UMLObject::ot_UniqueConstraint: {
UMLEntity* umlentity = parent->asUMLEntity();
if (umlentity) {
returnObject = umlentity->createUniqueConstraint(name);
}
break;
}
case UMLObject::ot_ForeignKeyConstraint: {
UMLEntity* umlentity = parent->asUMLEntity();
if (umlentity) {
returnObject = umlentity->createForeignKeyConstraint(name);
}
break;
}
case UMLObject::ot_CheckConstraint: {
UMLEntity* umlentity = parent->asUMLEntity();
if (umlentity) {
returnObject = umlentity->createCheckConstraint(name);
}
break;
}
default:
break;
}
if (!returnObject) {
logError2("Object_Factory::createChildObject(%1) type %2: no object created",
name, UMLObject::toString(type));
return nullptr;
}
UMLClassifierListItem *ucli = returnObject->asUMLClassifierListItem();
if (!ucli) {
logError0("Object_Factory::createChildObject internal: result is not a UMLClassifierListItem");
}
return ucli;
}
/**
* Make a new UMLObject according to the given XMI tag.
* Used by loadFromXMI and clipboard paste.
*/
UMLObject* makeObjectFromXMI(const QString& xmiTag,
const QString& stereoID /* = QString() */)
{
UMLObject *pObject = nullptr;
if (UMLDoc::tagEq(xmiTag, QStringLiteral("UseCase"))) {
pObject = new UMLUseCase();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Actor"))) {
pObject = new UMLActor();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Class"))) {
pObject = new UMLClassifier();
} else if(UMLDoc::tagEq(xmiTag, QStringLiteral("Instance"))) {
pObject = new UMLInstance();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Package"))) {
if (!stereoID.isEmpty()) {
UMLDoc *doc = UMLApp::app()->document();
UMLObject *stereo = doc->findStereotypeById(Uml::ID::fromString(stereoID));
if (stereo && stereo->name() == QStringLiteral("folder"))
pObject = new UMLFolder();
}
if (pObject == nullptr)
pObject = new UMLPackage();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Component"))) {
pObject = new UMLComponent();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Port"))) {
pObject = new UMLPort();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Node"))) {
pObject = new UMLNode();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Artifact"))) {
pObject = new UMLArtifact();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Interface"))) {
UMLClassifier *c = new UMLClassifier();
c->setBaseType(UMLObject::ot_Interface);
pObject = c;
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("DataType"))
|| UMLDoc::tagEq(xmiTag, QStringLiteral("Datatype")) // for bkwd compat.
|| UMLDoc::tagEq(xmiTag, QStringLiteral("Primitive"))
|| UMLDoc::tagEq(xmiTag, QStringLiteral("PrimitiveType"))) {
UMLDatatype *c = new UMLDatatype();
pObject = c;
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Enumeration")) ||
UMLDoc::tagEq(xmiTag, QStringLiteral("Enum"))) { // for bkwd compat.
pObject = new UMLEnum();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Entity"))) {
pObject = new UMLEntity();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Category"))) {
pObject = new UMLCategory();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Stereotype"))) {
pObject = new UMLStereotype();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Association")) ||
UMLDoc::tagEq(xmiTag, QStringLiteral("AssociationClass"))) {
pObject = new UMLAssociation();
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Generalization")) ||
UMLDoc::tagEq(xmiTag, QStringLiteral("generalization"))) {
pObject = new UMLAssociation(Uml::AssociationType::Generalization);
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Realization")) ||
UMLDoc::tagEq(xmiTag, QStringLiteral("Abstraction")) ||
UMLDoc::tagEq(xmiTag, QStringLiteral("interfaceRealization"))) {
pObject = new UMLAssociation(Uml::AssociationType::Realization);
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Dependency"))) {
pObject = new UMLAssociation(Uml::AssociationType::Dependency);
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Aggregation"))) { // Embarcadero's Describe
pObject = new UMLAssociation(Uml::AssociationType::Aggregation);
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Child2Category"))) {
pObject = new UMLAssociation(Uml::AssociationType::Child2Category);
} else if (UMLDoc::tagEq(xmiTag, QStringLiteral("Category2Parent"))) {
pObject = new UMLAssociation(Uml::AssociationType::Category2Parent);
}
return pObject;
}
} // end namespace Object_Factory
| 16,502
|
C++
|
.cpp
| 423
| 31.172577
| 130
| 0.613382
|
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,241
|
uml.cpp
|
KDE_umbrello/umbrello/uml.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2023 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "uml.h"
// app includes
#include "birdview.h"
#include "umlappprivate.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umlviewlist.h"
#include "worktoolbar.h"
#include "umlviewimageexporter.h"
#include "umlviewimageexporterall.h"
#include "docwindow.h"
#include "optionstate.h"
#include "cmdlineexportallviewsevent.h"
#include "cmds.h"
#include "umbrellosettings.h"
#include "statusbartoolbutton.h"
#include "findresults.h"
#include "folder.h"
#include "models/diagramsmodel.h"
// code generation
#include "advancedcodegenerator.h"
#include "codegenerationpolicy.h"
#include "codegenfactory.h"
#include "codegenpolicyext.h"
#include "simplecodegenerator.h"
// utils
#include "debug_utils.h"
#include "widget_utils.h"
#include "icon_utils.h"
// dialogs
#include "classwizard.h"
#include "codegenerationwizard.h"
#include "codeimportingwizard.h"
#include "codeviewerdialog.h"
#include "diagramprintpage.h"
#include "diagramselectiondialog.h"
#include "settingsdialog.h"
#include "finddialog.h"
#include "classimport.h"
#include "refactoringassistant.h"
// clipboard
#include "umlclipboard.h"
#include "umldragdata.h"
// docgenerators
#include "docbookgenerator.h"
#include "xhtmlgenerator.h"
#include "umlscene.h"
// kde includes
#include <kactioncollection.h>
#include <kstandardaction.h>
#include <ktoggleaction.h>
#include <krecentfilesaction.h>
#include <kconfig.h>
#include <kcursor.h>
#include <KLocalizedString>
#include <KMessageBox>
#include <kactionmenu.h>
#include <kxmlguifactory.h>
// qt includes
#include <QApplication>
#include <QClipboard>
#include <QDesktopWidget>
#include <QDockWidget>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QKeyEvent>
#include <QLabel>
#include <QMenu>
#include <QPointer>
#include <QPrinter>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPushButton>
#include <QScrollBar>
#include <QSlider>
#include <QStatusBar>
#include <QStackedWidget>
#include <QTemporaryFile>
#include <QTimer>
#include <QToolButton>
#include <QUndoStack>
#include <QUndoView>
#include <QListWidget>
#include <cmath>
DEBUG_REGISTER(UMLApp)
/** Static pointer, holding the last created instance. */
UMLApp* UMLApp::s_instance;
/**
* Static flag returned by static function shuttingDown().
* It is intentionally an extra static member because it is queried
* after calling the UMLApp destructor.
* Member accesses shall be avoided during destruction.
*/
bool UMLApp::s_shuttingDown = false;
/**
* Searches for a menu with the given name.
* @todo This is an ugly _HACK_ to allow to compile umbrello.
* All the menu stuff should be ported to KDE4 (using actions)
*
* @param name The name of the menu to search for (name : not text)
*/
QMenu* UMLApp::findMenu(const QString& name)
{
QWidget* widget = factory()->container(name, this);
if (widget) {
return dynamic_cast<QMenu*>(widget);
}
logDebug1("UMLApp::findMenu factory()->container(%1) returns NULL", name);
return nullptr;
}
/**
* Constructor. Calls all init functions to create the application.
*/
UMLApp::UMLApp(QWidget* parent)
: KXmlGuiWindow(parent),
m_d(nullptr), // setup()
m_langSelect(nullptr),
m_zoomSelect(nullptr),
m_activeLanguage(Uml::ProgrammingLanguage::Reserved),
m_codegen(nullptr),
m_commoncodegenpolicy(new CodeGenerationPolicy()),
m_policyext(nullptr),
m_config(KSharedConfig::openConfig()),
m_view(nullptr),
m_doc(nullptr), // setup()
m_listView(nullptr),
m_mainDock(nullptr),
m_listDock(nullptr),
m_debugDock(nullptr),
m_documentationDock(nullptr),
m_cmdHistoryDock(nullptr),
m_propertyDock(nullptr),
m_logDock(nullptr),
m_birdViewDock(nullptr),
m_docWindow(nullptr),
m_birdView(nullptr),
m_pQUndoView(nullptr),
m_refactoringAssist(nullptr),
fileOpenRecent(nullptr),
printPreview(nullptr),
filePrint(nullptr),
editCut(nullptr),
editCopy(nullptr),
editPaste(nullptr),
editUndo(nullptr),
editRedo(nullptr),
viewShowTree(nullptr),
viewShowDebug(nullptr),
viewShowDoc(nullptr),
viewShowLog(nullptr),
viewShowCmdHistory(nullptr),
viewShowBirdView(nullptr),
newDiagram(nullptr),
viewClearDiagram(nullptr),
viewSnapToGrid(nullptr),
viewShowGrid(nullptr),
viewExportImage(nullptr),
viewProperties(nullptr),
zoom100Action(nullptr),
deleteSelectedWidget(nullptr),
deleteDiagram(nullptr),
m_newSessionButton(nullptr),
m_toolsbar(nullptr),
m_clipTimer(nullptr),
m_copyTimer(nullptr),
m_loading(false),
m_viewStack(nullptr),
m_tabWidget(nullptr),
m_layout(nullptr),
m_imageMimeType(QString()),
m_settingsDialog(nullptr),
m_imageExporterAll(nullptr), // setup()
m_zoomValueLbl(nullptr),
m_defaultZoomWdg(nullptr),
m_pZoomOutPB(nullptr),
m_pZoomInPB(nullptr),
m_pZoomFitSBTB(nullptr),
m_pZoomFullSBTB(nullptr),
m_pZoomSlider(nullptr),
m_statusBarMessage(nullptr),
m_xhtmlGenerator(nullptr),
m_pUndoStack(nullptr), // setup()
m_undoEnabled(true),
m_hasBegunMacro(false),
m_printSettings(nullptr),
m_printer(nullptr) // setup()
{
for (int i = 0; i <= (int)Uml::ProgrammingLanguage::Reserved; i++)
m_langAct[i] = nullptr;
}
/**
* Set up the UMLApp.
* To be called after the constructor, before anything else.
* Heavy weight initializations are factored from the constructor to here
* to avoid passing an UMLApp `this` pointer to other classes where the
* `this` pointer has not been fully constructed. In other words, it is
* safe for other classes to invoke UMLApp functions using the `this`
* pointer passed to them.
*/
void UMLApp::setup()
{
s_instance = this;
m_d = new UMLAppPrivate(this);
m_doc = new UMLDoc();
m_imageExporterAll = new UMLViewImageExporterAll();
m_pUndoStack = new QUndoStack(this);
m_printer = new QPrinter();
m_doc->init();
m_printer->setFullPage(true);
layout()->setSizeConstraint(QLayout::SetNoConstraint);
readOptionState();
initActions();
// call this here because the statusBar is shown/hidden by setupGUI()
initStatusBar();
// use the absolute path to your umbrelloui.rc file for testing purpose in setupGUI();
StandardWindowOptions opt = Default;
opt &= ~Save;
QString xmlFile = QStringLiteral(UMBRELLOUI_RC);
QFileInfo fi(xmlFile);
setupGUI(opt, fi.exists() ? xmlFile : QString());
statusBar()->addWidget(m_statusBarMessage);
statusBar()->addPermanentWidget(m_defaultZoomWdg);
statusBar()->addPermanentWidget(m_pZoomOutPB);
statusBar()->addPermanentWidget(m_pZoomSlider);
statusBar()->addPermanentWidget(m_pZoomInPB);
initView();
initClip();
readOptions();
//get a reference to the Code->Active Language and to the Diagram->Zoom menu
m_langSelect = findMenu(QStringLiteral("active_lang_menu"));
//in case langSelect hasn't been initialized we create the Popup menu.
//it will be hidden, but at least we wont crash if someone takes the entry away from the ui.rc file
if (m_langSelect == nullptr) {
m_langSelect = new QMenu(QStringLiteral("active_lang_menu"), this);
}
m_zoomSelect = findMenu(QStringLiteral("zoom_menu"));
//in case zoomSelect hasn't been initialized we create the Popup menu.
//it will be hidden, but at least we wont crash if some one takes the entry away from the ui.rc file
if (m_zoomSelect == nullptr) {
m_zoomSelect = new QMenu(QStringLiteral("zoom_menu"), this);
}
//connect zoomSelect menu
connect(m_zoomSelect, SIGNAL(aboutToShow()), this, SLOT(setupZoomMenu()));
connect(m_zoomSelect, SIGNAL(triggered(QAction*)), this, SLOT(slotSetZoom(QAction*)));
setAutoSaveSettings();
m_toolsbar->setToolButtonStyle(Qt::ToolButtonIconOnly); // too many items for text, really we want a toolbox widget
}
/**
* Standard deconstructor.
*/
UMLApp::~UMLApp()
{
s_shuttingDown = true;
disconnect(m_pZoomInPB, SIGNAL(clicked()), this, SLOT(slotZoomIn()));
disconnect(m_pZoomSlider, SIGNAL(valueChanged(int)), this, SLOT(slotZoomSliderMoved(int)));
disconnect(m_tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(slotCloseDiagram(int)));
disconnect(m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabChanged(int)));
disconnect(m_tabWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotDiagramPopupMenu(QPoint)));
delete m_birdView;
delete m_clipTimer;
delete m_copyTimer;
delete m_commoncodegenpolicy;
delete m_imageExporterAll;
delete m_printer;
delete m_policyext;
delete m_pUndoStack;
m_pUndoStack = nullptr;
delete m_refactoringAssist;
delete m_xhtmlGenerator;
delete m_listView;
delete m_doc;
delete m_d;
}
/**
* Get the last created instance of this class.
*/
UMLApp* UMLApp::app()
{
return s_instance;
}
/**
* Helper method to setup the programming language action.
*/
void UMLApp::setProgLangAction(Uml::ProgrammingLanguage::Enum pl, const char* name, const char* action)
{
m_langAct[pl] = actionCollection()->addAction(QString::fromLatin1(action));
m_langAct[pl]->setText(QString::fromLatin1(name));
m_langAct[pl]->setCheckable(true);
}
/**
* Initializes the KActions and the status bar of the application
* and calls setupGUI().
* Note: Check also the file umbrelloui.rc and add actions there too.
*/
void UMLApp::initActions()
{
QAction* fileNew = KStandardAction::openNew(this, SLOT(slotFileNew()), actionCollection());
QAction* fileOpen = KStandardAction::open(this, SLOT(slotFileOpen()), actionCollection());
fileOpenRecent = KStandardAction::openRecent(this, SLOT(slotFileOpenRecent(QUrl)), actionCollection());
QAction* fileSave = KStandardAction::save(this, SLOT(slotFileSave()), actionCollection());
QAction* fileSaveAs = KStandardAction::saveAs(this, SLOT(slotFileSaveAs()), actionCollection());
QAction* fileClose = KStandardAction::close(this, SLOT(slotFileClose()), actionCollection());
filePrint = KStandardAction::print(this, SLOT(slotFilePrint()), actionCollection());
KStandardAction::find(this, SLOT(slotFind()), actionCollection());
KStandardAction::findNext(this, SLOT(slotFindNext()), actionCollection());
KStandardAction::findPrev(this, SLOT(slotFindPrevious()), actionCollection());
printPreview = KStandardAction::printPreview(this, SLOT(slotPrintPreview()), actionCollection());
filePrint->setPriority(QAction::LowPriority); // icon only
printPreview->setPriority(QAction::LowPriority); // icon only
QAction* fileQuit = KStandardAction::quit(this, SLOT(slotFileQuit()), actionCollection());
editUndo = KStandardAction::undo(this, SLOT(slotEditUndo()), actionCollection());
editRedo = KStandardAction::redo(this, SLOT(slotEditRedo()), actionCollection());
editUndo->setPriority(QAction::LowPriority); // icon only
editRedo->setPriority(QAction::LowPriority); // icon only
disconnect(m_pUndoStack, SIGNAL(undoTextChanged(QString)), editUndo, nullptr);
disconnect(m_pUndoStack, SIGNAL(redoTextChanged(QString)), editRedo, nullptr);
editCut = KStandardAction::cut(this, SLOT(slotEditCut()), actionCollection());
editCopy = KStandardAction::copy(this, SLOT(slotEditCopy()), actionCollection());
editPaste = KStandardAction::paste(this, SLOT(slotEditPaste()), actionCollection());
createStandardStatusBarAction();
setStandardToolBarMenuEnabled(true);
/* QAction* selectAll = */ KStandardAction::selectAll(this, SLOT(slotSelectAll()), actionCollection());
QAction* fileExportDocbook = actionCollection()->addAction(QStringLiteral("file_export_docbook"));
fileExportDocbook->setText(i18n("&Export model to DocBook"));
connect(fileExportDocbook, SIGNAL(triggered(bool)), this, SLOT(slotFileExportDocbook()));
QAction* fileExportXhtml = actionCollection()->addAction(QStringLiteral("file_export_xhtml"));
fileExportXhtml->setText(i18n("&Export model to XHTML"));
connect(fileExportXhtml, SIGNAL(triggered(bool)), this, SLOT(slotFileExportXhtml()));
QAction* classWizard = actionCollection()->addAction(QStringLiteral("class_wizard"));
classWizard->setText(i18n("&New Class Wizard..."));
connect(classWizard, SIGNAL(triggered(bool)), this, SLOT(slotClassWizard()));
QAction* addDefDatatypes = actionCollection()->addAction(QStringLiteral("create_default_datatypes"));
addDefDatatypes->setText(i18n("&Add Default Datatypes for Active Language"));
connect(addDefDatatypes, SIGNAL(triggered(bool)), this, SLOT(slotAddDefaultDatatypes()));
QAction* preferences = KStandardAction::preferences(this, SLOT(slotPrefs()), actionCollection());
QAction* impWizard = actionCollection()->addAction(QStringLiteral("importing_wizard"));
impWizard->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Import_Files));
impWizard->setText(i18n("Code &Importing Wizard..."));
connect(impWizard, SIGNAL(triggered(bool)), this, SLOT(slotImportingWizard()));
QAction* importProject = actionCollection()->addAction(QStringLiteral("import_project"));
importProject->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Import_Project));
importProject->setText(i18n("Import from Directory..."));
connect(importProject, SIGNAL(triggered(bool)), this, SLOT(slotImportProject()));
QAction* genWizard = actionCollection()->addAction(QStringLiteral("generation_wizard"));
genWizard->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Export_Files));
genWizard->setText(i18n("&Code Generation Wizard..."));
connect(genWizard, SIGNAL(triggered(bool)), this, SLOT(slotExecGenerationWizard()));
QAction* genAll = actionCollection()->addAction(QStringLiteral("generate_all"));
genAll->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Export_Files));
genAll->setText(i18n("&Generate All Code"));
connect(genAll, SIGNAL(triggered(bool)), this, SLOT(slotGenerateAllCode()));
setProgLangAction(Uml::ProgrammingLanguage::ActionScript, "ActionScript", "setLang_actionscript");
setProgLangAction(Uml::ProgrammingLanguage::Ada, "Ada", "setLang_ada");
setProgLangAction(Uml::ProgrammingLanguage::Cpp, "C++", "setLang_cpp");
setProgLangAction(Uml::ProgrammingLanguage::CSharp, "C#", "setLang_csharp");
setProgLangAction(Uml::ProgrammingLanguage::D, "D", "setLang_d");
setProgLangAction(Uml::ProgrammingLanguage::IDL, "IDL", "setLang_idl");
setProgLangAction(Uml::ProgrammingLanguage::Java, "Java", "setLang_java");
setProgLangAction(Uml::ProgrammingLanguage::JavaScript, "JavaScript", "setLang_javascript");
setProgLangAction(Uml::ProgrammingLanguage::MySQL, "MySQL (SQL)", "setLang_mysql");
setProgLangAction(Uml::ProgrammingLanguage::Pascal, "Pascal", "setLang_pascal");
setProgLangAction(Uml::ProgrammingLanguage::Perl, "Perl", "setLang_perl");
setProgLangAction(Uml::ProgrammingLanguage::PHP, "PHP", "setLang_php");
setProgLangAction(Uml::ProgrammingLanguage::PHP5, "PHP5", "setLang_php5");
setProgLangAction(Uml::ProgrammingLanguage::PostgreSQL, "PostgreSQL(SQL)", "setLang_postgresql");
setProgLangAction(Uml::ProgrammingLanguage::Python, "Python", "setLang_python");
setProgLangAction(Uml::ProgrammingLanguage::Ruby, "Ruby", "setLang_ruby");
setProgLangAction(Uml::ProgrammingLanguage::SQL, "SQL", "setLang_sql");
setProgLangAction(Uml::ProgrammingLanguage::Tcl, "Tcl", "setLang_tcl");
setProgLangAction(Uml::ProgrammingLanguage::Vala, "Vala", "setLang_vala");
setProgLangAction(Uml::ProgrammingLanguage::XMLSchema, "XMLSchema", "setLang_xmlschema");
setProgLangAction(Uml::ProgrammingLanguage::Reserved, "none", "setLang_none");
connect(m_langAct[Uml::ProgrammingLanguage::ActionScript], SIGNAL(triggered()), this, SLOT(setLang_actionscript()));
connect(m_langAct[Uml::ProgrammingLanguage::Ada], SIGNAL(triggered()), this, SLOT(setLang_ada()));
connect(m_langAct[Uml::ProgrammingLanguage::Cpp], SIGNAL(triggered()), this, SLOT(setLang_cpp()));
connect(m_langAct[Uml::ProgrammingLanguage::CSharp], SIGNAL(triggered()), this, SLOT(setLang_csharp()));
connect(m_langAct[Uml::ProgrammingLanguage::D], SIGNAL(triggered()), this, SLOT(setLang_d()));
connect(m_langAct[Uml::ProgrammingLanguage::IDL], SIGNAL(triggered()), this, SLOT(setLang_idl()));
connect(m_langAct[Uml::ProgrammingLanguage::Java], SIGNAL(triggered()), this, SLOT(setLang_java()));
connect(m_langAct[Uml::ProgrammingLanguage::JavaScript], SIGNAL(triggered()), this, SLOT(setLang_javascript()));
connect(m_langAct[Uml::ProgrammingLanguage::MySQL], SIGNAL(triggered()), this, SLOT(setLang_mysql()));
connect(m_langAct[Uml::ProgrammingLanguage::Pascal], SIGNAL(triggered()), this, SLOT(setLang_pascal()));
connect(m_langAct[Uml::ProgrammingLanguage::Perl], SIGNAL(triggered()), this, SLOT(setLang_perl()));
connect(m_langAct[Uml::ProgrammingLanguage::PHP], SIGNAL(triggered()), this, SLOT(setLang_php()));
connect(m_langAct[Uml::ProgrammingLanguage::PHP5], SIGNAL(triggered()), this, SLOT(setLang_php5()));
connect(m_langAct[Uml::ProgrammingLanguage::PostgreSQL], SIGNAL(triggered()), this, SLOT(setLang_postgresql()));
connect(m_langAct[Uml::ProgrammingLanguage::Python], SIGNAL(triggered()), this, SLOT(setLang_python()));
connect(m_langAct[Uml::ProgrammingLanguage::Ruby], SIGNAL(triggered()), this, SLOT(setLang_ruby()));
connect(m_langAct[Uml::ProgrammingLanguage::SQL], SIGNAL(triggered()), this, SLOT(setLang_sql()));
connect(m_langAct[Uml::ProgrammingLanguage::Tcl], SIGNAL(triggered()), this, SLOT(setLang_tcl()));
connect(m_langAct[Uml::ProgrammingLanguage::Vala], SIGNAL(triggered()), this, SLOT(setLang_vala()));
connect(m_langAct[Uml::ProgrammingLanguage::XMLSchema], SIGNAL(triggered()), this, SLOT(setLang_xmlschema()));
connect(m_langAct[Uml::ProgrammingLanguage::Reserved], SIGNAL(triggered()), this, SLOT(setLang_none()));
fileNew->setToolTip(i18n("Creates a new document"));
fileOpen->setToolTip(i18n("Opens an existing document"));
fileOpenRecent->setToolTip(i18n("Opens a recently used file"));
fileSave->setToolTip(i18n("Saves the document"));
fileSaveAs->setToolTip(i18n("Saves the document as..."));
fileClose->setToolTip(i18n("Closes the document"));
filePrint->setToolTip(i18n("Prints out the document"));
printPreview->setToolTip(i18n("Print Preview of the document"));
fileQuit->setToolTip(i18n("Quits the application"));
fileExportDocbook->setToolTip(i18n("Exports the model to the docbook format"));
fileExportXhtml->setToolTip(i18n("Exports the model to the XHTML format"));
editCut->setToolTip(i18n("Cuts the selected section and puts it to the clipboard"));
editCopy->setToolTip(i18n("Copies the selected section to the clipboard"));
editPaste->setToolTip(i18n("Pastes the contents of the clipboard"));
editUndo->setToolTip(i18n("Undo last action"));
editRedo->setToolTip(i18n("Redo last undone action"));
preferences->setToolTip(i18n("Set the default program preferences"));
deleteSelectedWidget = actionCollection()->addAction(QStringLiteral("delete_selected"));
deleteSelectedWidget->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Delete));
deleteSelectedWidget->setText(i18nc("delete selected widget", "Delete &Selected"));
deleteSelectedWidget->setShortcut(QKeySequence(Qt::Key_Delete));
connect(deleteSelectedWidget, SIGNAL(triggered(bool)), this, SLOT(slotDeleteSelected()));
// The different views
newDiagram = actionCollection()->add<KActionMenu>(QStringLiteral("new_view"));
newDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_New));
newDiagram->setText(QStringLiteral("new_view"));
QAction* classDiagram = actionCollection()->addAction(QStringLiteral("new_class_diagram"));
classDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Class));
classDiagram->setText(i18n("&Class Diagram..."));
connect(classDiagram, SIGNAL(triggered(bool)), this, SLOT(slotClassDiagram()));
newDiagram->addAction(classDiagram);
#ifdef ENABLE_OBJECT_DIAGRAM
QAction* objectDiagram = actionCollection()->addAction(QStringLiteral("new_object_diagram"));
objectDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Object));
objectDiagram->setText(i18n("&Object Diagram..."));
connect(objectDiagram, SIGNAL(triggered()), this, SLOT(slotObjectDiagram()));
newDiagram->addAction(objectDiagram);
#endif
QAction* sequenceDiagram= actionCollection()->addAction(QStringLiteral("new_sequence_diagram"));
sequenceDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Sequence));
sequenceDiagram->setText(i18n("&Sequence Diagram..."));
connect(sequenceDiagram, SIGNAL(triggered(bool)), this, SLOT(slotSequenceDiagram()));
newDiagram->addAction(sequenceDiagram);
QAction* collaborationDiagram = actionCollection()->addAction(QStringLiteral("new_collaboration_diagram"));
collaborationDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Collaboration));
collaborationDiagram->setText(i18n("C&ommunication Diagram..."));
connect(collaborationDiagram, SIGNAL(triggered(bool)), this, SLOT(slotCollaborationDiagram()));
newDiagram->addAction(collaborationDiagram);
QAction* useCaseDiagram = actionCollection()->addAction(QStringLiteral("new_use_case_diagram"));
useCaseDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Usecase));
useCaseDiagram->setText(i18n("&Use Case Diagram..."));
connect(useCaseDiagram, SIGNAL(triggered(bool)), this, SLOT(slotUseCaseDiagram()));
newDiagram->addAction(useCaseDiagram);
QAction* stateDiagram = actionCollection()->addAction(QStringLiteral("new_state_diagram"));
stateDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_State));
stateDiagram->setText(i18n("S&tate Diagram..."));
connect(stateDiagram, SIGNAL(triggered(bool)), this, SLOT(slotStateDiagram()));
newDiagram->addAction(stateDiagram);
QAction* activityDiagram = actionCollection()->addAction(QStringLiteral("new_activity_diagram"));
activityDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Activity));
activityDiagram->setText(i18n("&Activity Diagram..."));
connect(activityDiagram, SIGNAL(triggered(bool)), this, SLOT(slotActivityDiagram()));
newDiagram->addAction(activityDiagram);
QAction* componentDiagram = actionCollection()->addAction(QStringLiteral("new_component_diagram"));
componentDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Component));
componentDiagram->setText(i18n("Co&mponent Diagram..."));
connect(componentDiagram, SIGNAL(triggered(bool)), this, SLOT(slotComponentDiagram()));
newDiagram->addAction(componentDiagram);
QAction* deploymentDiagram = actionCollection()->addAction(QStringLiteral("new_deployment_diagram"));
deploymentDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_Deployment));
deploymentDiagram->setText(i18n("&Deployment Diagram..."));
connect(deploymentDiagram, SIGNAL(triggered(bool)), this, SLOT(slotDeploymentDiagram()));
newDiagram->addAction(deploymentDiagram);
QAction* entityRelationshipDiagram = actionCollection()->addAction(QStringLiteral("new_entityrelationship_diagram"));
entityRelationshipDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Diagram_EntityRelationship));
entityRelationshipDiagram->setText(i18n("&Entity Relationship Diagram..."));
connect(entityRelationshipDiagram, SIGNAL(triggered(bool)), this, SLOT(slotEntityRelationshipDiagram()));
newDiagram->addAction(entityRelationshipDiagram);
viewShowTree = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_tree"));
viewShowTree->setText(i18n("&Tree View"));
connect(viewShowTree, SIGNAL(triggered(bool)), this, SLOT(slotShowTreeView(bool)));
viewShowDebug = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_debug"));
viewShowDebug->setText(i18n("&Debugging"));
connect(viewShowDebug, SIGNAL(triggered(bool)), this, SLOT(slotShowDebugView(bool)));
viewShowDoc = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_doc"));
viewShowDoc->setText(i18n("&Documentation"));
connect(viewShowDoc, SIGNAL(triggered(bool)), this, SLOT(slotShowDocumentationView(bool)));
viewShowLog = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_log"));
viewShowLog->setText(i18n("&Logging"));
connect(viewShowLog, SIGNAL(triggered(bool)), this, SLOT(slotShowLogView(bool)));
viewShowCmdHistory = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_undo"));
viewShowCmdHistory->setText(i18n("&Command history"));
connect(viewShowCmdHistory, SIGNAL(triggered(bool)), this, SLOT(slotShowCmdHistoryView(bool)));
viewShowBirdView = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_bird"));
viewShowBirdView->setText(i18n("&Bird's eye view"));
connect(viewShowBirdView, SIGNAL(triggered(bool)), this, SLOT(slotShowBirdView(bool)));
viewClearDiagram = actionCollection()->addAction(QStringLiteral("view_clear_diagram"));
viewClearDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Clear));
viewClearDiagram->setText(i18n("&Clear Diagram"));
connect(viewClearDiagram, SIGNAL(triggered(bool)), this, SLOT(slotCurrentViewClearDiagram()));
viewSnapToGrid = actionCollection()->add<KToggleAction>(QStringLiteral("view_snap_to_grid"));
viewSnapToGrid->setText(i18n("&Snap to Grid"));
connect(viewSnapToGrid, SIGNAL(triggered(bool)), this, SLOT(slotCurrentViewToggleSnapToGrid()));
viewShowGrid = actionCollection()->add<KToggleAction>(QStringLiteral("view_show_grid"));
viewShowGrid->setText(i18n("S&how Grid"));
connect(viewShowGrid, SIGNAL(triggered(bool)), this, SLOT(slotCurrentViewToggleShowGrid()));
deleteDiagram = actionCollection()->addAction(QStringLiteral("view_delete"));
deleteDiagram->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Delete));
deleteDiagram->setText(i18n("&Delete Diagram"));
connect(deleteDiagram, SIGNAL(triggered(bool)), this, SLOT(slotDeleteDiagram()));
viewExportImage = actionCollection()->addAction(QStringLiteral("view_export_image"));
viewExportImage->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Export_Picture));
viewExportImage->setText(i18n("&Export as Picture..."));
connect(viewExportImage, SIGNAL(triggered(bool)), this, SLOT(slotCurrentViewExportImage()));
QAction* viewExportImageAll = actionCollection()->addAction(QStringLiteral("view_export_images"));
viewExportImageAll->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Export_Picture));
viewExportImageAll->setText(i18n("Export &Diagrams as Pictures..."));
connect(viewExportImageAll, SIGNAL(triggered(bool)), this, SLOT(slotViewsExportImages()));
viewProperties = actionCollection()->addAction(QStringLiteral("view_properties"));
viewProperties->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Properties));
viewProperties->setText(i18n("&Properties"));
connect(viewProperties, SIGNAL(triggered(bool)), this, SLOT(slotCurrentProperties()));
viewSnapToGrid->setChecked(false);
viewShowGrid->setChecked(false);
viewClearDiagram->setEnabled(false);
viewSnapToGrid->setEnabled(false);
viewShowGrid->setEnabled(false);
deleteDiagram->setEnabled(false);
viewExportImage->setEnabled(false);
viewProperties->setEnabled(false);
zoom100Action = actionCollection()->addAction(QStringLiteral("zoom100"));
zoom100Action->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Zoom_100));
zoom100Action->setText(i18n("Z&oom to 100%"));
connect(zoom100Action, SIGNAL(triggered(bool)), this, SLOT(slotZoom100()));
QAction* alignRight = actionCollection()->addAction(QStringLiteral("align_right"));
alignRight->setText(i18n("Align Right"));
alignRight->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_Right));
connect(alignRight, SIGNAL(triggered(bool)), this, SLOT(slotAlignRight()));
QAction* alignLeft = actionCollection()->addAction(QStringLiteral("align_left"));
alignLeft->setText(i18n("Align Left"));
alignLeft->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_Left));
connect(alignLeft, SIGNAL(triggered(bool)), this, SLOT(slotAlignLeft()));
QAction* alignTop = actionCollection()->addAction(QStringLiteral("align_top"));
alignTop->setText(i18n("Align Top"));
alignTop->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_Top));
connect(alignTop, SIGNAL(triggered(bool)), this, SLOT(slotAlignTop()));
QAction* alignBottom = actionCollection()->addAction(QStringLiteral("align_bottom"));
alignBottom->setText(i18n("Align Bottom"));
alignBottom->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_Bottom));
connect(alignBottom, SIGNAL(triggered(bool)), this, SLOT(slotAlignBottom()));
QAction* alignVerticalMiddle = actionCollection()->addAction(QStringLiteral("align_vertical_middle"));
alignVerticalMiddle->setText(i18n("Align Vertical Middle"));
alignVerticalMiddle->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_VerticalMiddle));
connect(alignVerticalMiddle, SIGNAL(triggered(bool)), this, SLOT(slotAlignVerticalMiddle()));
QAction* alignHorizontalMiddle = actionCollection()->addAction(QStringLiteral("align_horizontal_middle"));
alignHorizontalMiddle->setText(i18n("Align Horizontal Middle"));
alignHorizontalMiddle->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_HorizontalMiddle));
connect(alignHorizontalMiddle, SIGNAL(triggered(bool)), this, SLOT(slotAlignHorizontalMiddle()));
QAction* alignVerticalDistribute = actionCollection()->addAction(QStringLiteral("align_vertical_distribute"));
alignVerticalDistribute->setText(i18n("Align Vertical Distribute"));
alignVerticalDistribute->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_VerticalDistribute));
connect(alignVerticalDistribute, SIGNAL(triggered(bool)), this, SLOT(slotAlignVerticalDistribute()));
QAction* alignHorizontalDistribute = actionCollection()->addAction(QStringLiteral("align_horizontal_distribute"));
alignHorizontalDistribute->setText(i18n("Align Horizontal Distribute"));
alignHorizontalDistribute->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Align_HorizontalDistribute));
connect(alignHorizontalDistribute, SIGNAL(triggered(bool)), this, SLOT(slotAlignHorizontalDistribute()));
QString moveTabLeftString = i18n("&Move Tab Left");
QString moveTabRightString = i18n("&Move Tab Right");
QAction* moveTabLeft = actionCollection()->addAction(QStringLiteral("move_tab_left"));
moveTabLeft->setIcon(Icon_Utils::SmallIcon(QApplication::layoutDirection() ? Icon_Utils::it_Go_Next : Icon_Utils::it_Go_Previous));
moveTabLeft->setText(QApplication::layoutDirection() ? moveTabRightString : moveTabLeftString);
moveTabLeft->setShortcut(QApplication::layoutDirection() ?
QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Right) : QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Left));
connect(moveTabLeft, SIGNAL(triggered(bool)), this, SLOT(slotMoveTabLeft()));
QAction* moveTabRight = actionCollection()->addAction(QStringLiteral("move_tab_right"));
moveTabRight->setIcon(Icon_Utils::SmallIcon(QApplication::layoutDirection() ? Icon_Utils::it_Go_Previous : Icon_Utils::it_Go_Next));
moveTabRight->setText(QApplication::layoutDirection() ? moveTabLeftString : moveTabRightString);
moveTabRight->setShortcut(QApplication::layoutDirection() ?
QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Left) : QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Right));
connect(moveTabRight, SIGNAL(triggered(bool)), this, SLOT(slotMoveTabRight()));
QString selectTabLeftString = i18n("Select Diagram on Left");
QString selectTabRightString = i18n("Select Diagram on Right");
QAction* changeTabLeft = actionCollection()->addAction(QStringLiteral("previous_tab"));
changeTabLeft->setText(QApplication::layoutDirection() ? selectTabRightString : selectTabLeftString);
changeTabLeft->setShortcut(QApplication::layoutDirection() ?
QKeySequence(Qt::SHIFT | Qt::Key_Right) : QKeySequence(Qt::SHIFT | Qt::Key_Left));
connect(changeTabLeft, SIGNAL(triggered(bool)), this, SLOT(slotChangeTabLeft()));
QAction* changeTabRight = actionCollection()->addAction(QStringLiteral("next_tab"));
changeTabRight->setText(QApplication::layoutDirection() ? selectTabLeftString : selectTabRightString);
changeTabRight->setShortcut(QApplication::layoutDirection() ?
QKeySequence(Qt::SHIFT | Qt::Key_Left) : QKeySequence(Qt::SHIFT | Qt::Key_Right));
connect(changeTabRight, SIGNAL(triggered(bool)), this, SLOT(slotChangeTabRight()));
// @todo Check if this should be ported
// QMenu* menu = findMenu(QStringLiteral("settings"));
// menu->insertItem(i18n("&Windows"), dockHideShowMenu(), -1, 0);
// disable actions at startup
fileSave->setEnabled(true);
fileSaveAs->setEnabled(true);
enablePrint(false);
editCut->setEnabled(false);
editCopy->setEnabled(false);
editPaste->setEnabled(false);
editUndo->setEnabled(false);
editRedo->setEnabled(false);
}
/**
* Connected to by the zoomAction, a value of between 300
* and 2200 is scaled to zoom to between 9% and 525%.
* The min and max values of the slider are hard coded in the statusbar slider.
*/
void UMLApp::slotZoomSliderMoved(int value)
{
setZoom(value);
}
/**
* Set zoom to fit the view.
*/
void UMLApp::slotZoomFit()
{
QRectF items = currentView()->umlScene()->itemsBoundingRect();
if (items.isNull()) {
setZoom(100);
return;
}
// TODO: QGraphicsView seems not to be informed about the scene rect update
currentView()->setSceneRect(items);
int scaleW = ceil(100.0 * currentView()->viewport()->width() / currentView()->umlScene()->width());
int scaleH = ceil(100.0 * currentView()->viewport()->height() / currentView()->umlScene()->height());
int scale = 100;
if (scaleW < scaleH) {
scale = scaleW;
}
else {
scale = scaleH;
}
if (scale < 0)
scale = 100;
else if (scale > 500)
scale = 500;
else
scale -= 2;
setZoom(scale);
}
/**
* Set zoom to 100%.
*/
void UMLApp::slotZoom100()
{
setZoom(100);
}
/**
* Decrease the zoom factor of the current diagram.
*/
void UMLApp::slotZoomOut()
{
setZoom(currentView()->zoom()-5);
}
/**
* Increase the zoom factor of the current diagram.
*/
void UMLApp::slotZoomIn()
{
setZoom(currentView()->zoom()+5);
}
/**
* Set the zoom factor of the current diagram.
*
* @param zoom Zoom factor in percentage.
* @param withView also setup the currently displayed diagram
*/
void UMLApp::setZoom(int zoom, bool withView)
{
if (withView)
currentView()->setZoom(zoom);
bool oldState = m_pZoomSlider->blockSignals(true);
m_pZoomSlider->setValue(zoom);
m_pZoomSlider->blockSignals(oldState);
m_zoomValueLbl->setText(QString::number(zoom) + QLatin1Char('%'));
}
/**
* Set the zoom factor of the current diagram.
*
* @param action Action which is called.
*/
void UMLApp::slotSetZoom(QAction* action)
{
QVariant var = action->data();
if (var.canConvert<int>()) {
setZoom(var.toInt());
}
}
/**
* Helper method to create the zoom actions.
*/
QAction* UMLApp::createZoomAction(int zoom, int currentZoom)
{
//IMPORTANT: The zoom value is added to the action.
QAction* action = new QAction(this);
action->setCheckable(true);
action->setText(i18nc("%1 percent value from 20 to 500", " &%1%", zoom));
action->setData(zoom);
if (zoom == currentZoom) {
action->setChecked(true);
}
return action;
}
/**
* Prepares the zoom menu for display.
*/
void UMLApp::setupZoomMenu()
{
m_zoomSelect->clear();
int currentZoom = currentView()->zoom();
m_zoomSelect->addAction(createZoomAction(33, currentZoom));
m_zoomSelect->addAction(createZoomAction(50, currentZoom));
m_zoomSelect->addAction(createZoomAction(75, currentZoom));
m_zoomSelect->addAction(createZoomAction(100, currentZoom));
m_zoomSelect->addAction(createZoomAction(150, currentZoom));
m_zoomSelect->addAction(createZoomAction(200, currentZoom));
m_zoomSelect->addAction(createZoomAction(300, currentZoom));
// if currentZoom is not a "standard zoom" (because of zoom in / zoom out step
// we add it for information
switch (currentZoom) {
case 33:
case 50:
case 75:
case 100:
case 150:
case 200:
case 300:
break;
default:
m_zoomSelect->addSeparator();
m_zoomSelect->addAction(createZoomAction(currentZoom, currentZoom));
}
}
/**
* Sets up the statusbar for the main window by
* initializing a statuslabel.
*/
void UMLApp::initStatusBar()
{
connect(m_doc, SIGNAL(sigWriteToStatusBar(QString)), this, SLOT(slotStatusMsg(QString)));
m_statusBarMessage = new QLabel(i18nc("init status bar", "Ready"));
m_defaultZoomWdg = new QWidget(this);
QHBoxLayout* zoomLayout = new QHBoxLayout(m_defaultZoomWdg);
zoomLayout->setContentsMargins(0, 0, 0, 0);
zoomLayout->setSpacing(0);
zoomLayout->addItem(new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
m_zoomValueLbl = new QLabel(i18n("100%"));
m_zoomValueLbl->setContentsMargins(10, 0, 10, 0);
zoomLayout->addWidget(m_zoomValueLbl);
m_pZoomFitSBTB = new StatusBarToolButton(this);
m_pZoomFitSBTB->setText(i18n("Fit"));
m_pZoomFitSBTB->setGroupPosition(StatusBarToolButton::GroupLeft);
zoomLayout->addWidget(m_pZoomFitSBTB);
m_pZoomFitSBTB->setContentsMargins(0, 0, 0, 0);
//m_pZoomFitSBTB->setDisabled(true);
connect(m_pZoomFitSBTB, SIGNAL(clicked()), this, SLOT(slotZoomFit()));
m_pZoomFullSBTB = new StatusBarToolButton(this);
m_pZoomFullSBTB->setText(i18n("100%"));
m_pZoomFullSBTB->setGroupPosition(StatusBarToolButton::GroupRight);
m_pZoomFullSBTB->setContentsMargins(0, 0, 0, 0);
zoomLayout->addWidget(m_pZoomFullSBTB);
connect(m_pZoomFullSBTB, SIGNAL(clicked()), this, SLOT(slotZoom100()));
m_pZoomOutPB = new QPushButton(this);
/* TODO: On the call to m_pZoomOutPB->setIcon Valgrind reports
"Conditional jump or move depends on uninitialised value(s)".
*/
m_pZoomOutPB->setIcon(QIcon(QStringLiteral("zoom-out")));
m_pZoomOutPB->setFlat(true);
m_pZoomOutPB->setMaximumSize(30, 30);
connect(m_pZoomOutPB, SIGNAL(clicked()), this, SLOT(slotZoomOut()));
m_pZoomSlider = new QSlider(Qt::Horizontal, this);
m_pZoomSlider->setMaximumSize(100, 50);
m_pZoomSlider->setMinimum (20);
m_pZoomSlider->setMaximum (480);
//m_pZoomSlider->setPageStep (1000);
m_pZoomSlider->setValue (100);
m_pZoomSlider->setContentsMargins(0, 0, 0, 0);
connect(m_pZoomSlider, SIGNAL(valueChanged(int)), this, SLOT(slotZoomSliderMoved(int)));
m_pZoomInPB = new QPushButton(this);
/* TODO: On the call to m_pZoomInPB->setIcon Valgrind reports
"Conditional jump or move depends on uninitialised value(s)".
*/
m_pZoomInPB->setIcon(QIcon(QStringLiteral("zoom-in")));
m_pZoomInPB->setFlat(true);
m_pZoomInPB->setMaximumSize(30, 30);
connect(m_pZoomInPB, SIGNAL(clicked()), this, SLOT(slotZoomIn()));
}
/**
* Creates the centerwidget of the KMainWindow instance and
* sets it as the view.
*/
void UMLApp::initView()
{
setCaption(m_doc->url().fileName(), false);
m_view = nullptr;
m_toolsbar = new WorkToolBar(this);
m_toolsbar->setWindowTitle(i18n("Diagram Toolbar"));
addToolBar(Qt::TopToolBarArea, m_toolsbar);
// m_mainDock = new QDockWidget(this);
// addDockWidget (Qt::RightDockWidgetArea, m_mainDock);
m_newSessionButton = nullptr;
// Prepare Stacked Diagram Representation
m_viewStack = new QStackedWidget(this);
// Prepare Tabbed Diagram Representation
m_tabWidget = new QTabWidget(this);
m_tabWidget->setMovable(true);
connect(m_tabWidget, SIGNAL(tabCloseRequested(int)), SLOT(slotCloseDiagram(int)));
connect(m_tabWidget, SIGNAL(currentChanged(int)), SLOT(slotTabChanged(int)));
connect(m_tabWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotDiagramPopupMenu(QPoint)));
m_tabWidget->setTabsClosable(true);
m_newSessionButton = new QToolButton(m_tabWidget);
m_newSessionButton->setIcon(Icon_Utils::SmallIcon(Icon_Utils::it_Tab_New));
m_newSessionButton->adjustSize();
m_newSessionButton->setAutoRaise(true);
m_newSessionButton->setPopupMode(QToolButton::InstantPopup);
m_newSessionButton->setMenu(newDiagram->menu());
m_tabWidget->setCornerWidget(m_newSessionButton, Qt::TopLeftCorner);
m_newSessionButton->installEventFilter(this);
m_layout = new QVBoxLayout;
m_layout->setMargin(0);
if (Settings::optionState().generalState.tabdiagrams) {
// Tabbed Diagram Representation
m_layout->addWidget(m_tabWidget);
m_viewStack->hide();
}
else {
// Stacked Diagram Representation
m_layout->addWidget(m_viewStack);
m_tabWidget->hide();
}
QWidget *widget = new QWidget;
widget->setLayout(m_layout);
setCentralWidget(widget);
// create the tree viewer
m_listDock = new QDockWidget(i18n("&Tree View"), this);
m_listDock->setObjectName(QStringLiteral("TreeViewDock"));
addDockWidget(Qt::LeftDockWidgetArea, m_listDock);
m_listView = new UMLListView(m_listDock);
//m_listView->setSorting(-1);
m_listView->setDocument(m_doc);
m_listView->init();
m_listDock->setWidget(m_listView);
connect(m_listDock, SIGNAL(visibilityChanged(bool)), viewShowTree, SLOT(setChecked(bool)));
// create the documentation viewer
m_documentationDock = new QDockWidget(i18n("Doc&umentation"), this);
m_documentationDock->setObjectName(QStringLiteral("DocumentationDock"));
addDockWidget(Qt::LeftDockWidgetArea, m_documentationDock);
m_docWindow = new DocWindow(m_doc, m_documentationDock);
m_docWindow->setObjectName(QStringLiteral("DOCWINDOW"));
m_documentationDock->setWidget(m_docWindow);
connect(m_documentationDock, SIGNAL(visibilityChanged(bool)), viewShowDoc, SLOT(setChecked(bool)));
m_doc->setupSignals(); // make sure gets signal from list view
// create the command history viewer
m_cmdHistoryDock = new QDockWidget(i18n("Co&mmand history"), this);
m_cmdHistoryDock->setObjectName(QStringLiteral("CmdHistoryDock"));
addDockWidget(Qt::LeftDockWidgetArea, m_cmdHistoryDock);
m_pQUndoView = new QUndoView(m_cmdHistoryDock);
m_pQUndoView->setCleanIcon(Icon_Utils::SmallIcon(Icon_Utils::it_UndoView));
m_pQUndoView->setStack(m_pUndoStack);
m_cmdHistoryDock->setWidget(m_pQUndoView);
connect(m_cmdHistoryDock, SIGNAL(visibilityChanged(bool)), viewShowCmdHistory, SLOT(setChecked(bool)));
m_d->createDiagramsWindow();
#ifdef ENABLE_UML_OBJECTS_WINDOW
m_d->createObjectsWindow();
#endif
m_d->createStereotypesWindow();
m_d->createWelcomeWindow();
m_debugDock = new QDockWidget(i18n("&Debug"), this);
m_debugDock->setObjectName(QStringLiteral("DebugDock"));
addDockWidget(Qt::LeftDockWidgetArea, m_debugDock);
m_debugDock->setWidget(Tracer::instance());
connect(m_debugDock, SIGNAL(visibilityChanged(bool)), viewShowLog, SLOT(setChecked(bool)));
// create the log viewer
m_logDock = new QDockWidget(i18n("&Log"), this);
m_logDock->setObjectName(QStringLiteral("LogDock"));
addDockWidget(Qt::LeftDockWidgetArea, m_logDock);
m_logDock->setWidget(m_d->logWindow);
connect(m_logDock, SIGNAL(visibilityChanged(bool)), viewShowLog, SLOT(setChecked(bool)));
// create the property viewer
//m_propertyDock = new QDockWidget(i18n("&Properties"), this);
//m_propertyDock->setObjectName(QStringLiteral("PropertyDock"));
//addDockWidget(Qt::LeftDockWidgetArea, m_propertyDock); //:TODO:
// create the bird's eye view
m_birdViewDock = new BirdViewDockWidget(i18n("&Bird's eye view"), this);
m_birdViewDock->setObjectName(QStringLiteral("BirdViewDock"));
addDockWidget(Qt::RightDockWidgetArea, m_birdViewDock);
connect(m_birdViewDock, SIGNAL(visibilityChanged(bool)), viewShowBirdView, SLOT(setChecked(bool)));
tabifyDockWidget(m_documentationDock, m_cmdHistoryDock);
tabifyDockWidget(m_cmdHistoryDock, m_logDock);
//tabifyDockWidget(m_cmdHistoryDock, m_propertyDock); //:TODO:
tabifyDockWidget(m_logDock, m_debugDock);
tabifyDockWidget(m_listDock, m_d->stereotypesWindow);
tabifyDockWidget(m_d->stereotypesWindow, m_d->diagramsWindow);
#ifdef ENABLE_UML_OBJECTS_WINDOW
tabifyDockWidget(m_d->diagramsWindow, m_d->objectsWindow);
#endif
if (m_d->welcomeWindow) {
tabifyDockWidget(m_d->welcomeWindow, m_birdViewDock);
m_d->welcomeWindow->raise();
}
m_listDock->raise();
}
/**
* Opens a file specified by commandline option.
*/
void UMLApp::openDocumentFile(const QUrl& url)
{
slotStatusMsg(i18n("Opening file..."));
m_doc->openDocument(url);
fileOpenRecent->addUrl(url);
resetStatusMsg();
setCaption(m_doc->url().fileName(), false);
enablePrint(true);
}
/**
* Returns a pointer to the current document connected to the
* KMainWindow instance.
* Used by the View class to access the document object's methods.
*/
UMLDoc *UMLApp::document() const
{
return m_doc;
}
/**
* Returns a pointer to the list view.
*
* @return The listview being used.
*/
UMLListView* UMLApp::listView() const
{
return m_listView;
}
/**
* Save general Options like all bar positions and status
* as well as the geometry and the recent file list to
* the configuration file.
*/
void UMLApp::saveOptions()
{
// The Toolbar settings will be handled by the respective classes (KToolBar)
KConfigGroup cg(m_config, QStringLiteral("toolbar"));
toolBar(QStringLiteral("mainToolBar"))->saveSettings(cg);
KConfigGroup workBarConfig(m_config, QStringLiteral("workbar"));
m_toolsbar->saveSettings(workBarConfig);
fileOpenRecent->saveEntries(m_config->group(QStringLiteral("Recent Files")));
KConfigGroup shortcutConfig(m_config, QStringLiteral("Shortcuts"));
actionCollection()->writeSettings(&shortcutConfig, false);
UmbrelloSettings::setGeometry(size());
Settings::OptionState& optionState = Settings::optionState();
optionState.save();
if(m_doc->url().fileName() == i18n("Untitled")) {
UmbrelloSettings::setLastFile(QString());
}
else {
UmbrelloSettings::setLastFile(m_doc->url().toDisplayString());
}
UmbrelloSettings::setImageMimeType(imageMimeType());
UmbrelloSettings::setShowDocWindow(m_documentationDock->isVisible());
// CodeGenerator *codegen = getGenerator();
// JavaCodeGenerator *javacodegen = dynamic_cast<JavaCodeGenerator*>(codegen);
// if (javacodegen)
// UmbrelloSettings::setBuildANTDocumentJava(javacodegen->getCreateANTBuildFile());
// now write the basic defaults to config
m_commoncodegenpolicy->writeConfig();
UmbrelloSettings::self()->save();
}
/**
* Read general Options again and initialize all variables
* like the recent file list.
*/
void UMLApp::readOptions()
{
// bar status settings
KToolBar *mainToolBar = toolBar(QStringLiteral("mainToolBar"));
mainToolBar->applySettings(m_config->group(QStringLiteral("toolbar")));
// Add the Undo/Redo actions:
// In KDE4 this was somehow done automatically but in KF5,
// it seems we need to code it explicitly.
mainToolBar->addSeparator();
const QString undoIconName = Icon_Utils::toString(Icon_Utils::it_Undo);
QIcon undoIcon = QIcon::fromTheme(undoIconName);
editUndo->setIcon(undoIcon);
mainToolBar->addAction(editUndo);
const QString redoIconName = Icon_Utils::toString(Icon_Utils::it_Redo);
QIcon redoIcon = QIcon::fromTheme(redoIconName);
editRedo->setIcon(redoIcon);
mainToolBar->addAction(editRedo);
// do config for work toolbar
m_toolsbar->applySettings(m_config->group(QStringLiteral("workbar")));
fileOpenRecent->loadEntries(m_config->group(QStringLiteral("Recent Files")));
setImageMimeType(UmbrelloSettings::imageMimeType());
QSize size = UmbrelloSettings::geometry();
if (size.width() == -1 && size.height() == -1)
size = QApplication::desktop()->screenGeometry().size();
resize(size);
enableUndo(Settings::optionState().generalState.undo);
KConfigGroup shortCutConfig(m_config, QStringLiteral("Shortcuts"));
actionCollection()->readSettings(&shortCutConfig);
m_toolsbar->setupActions();
}
/**
* Saves the window properties for each open window
* during session end to the session config file,
* including saving the currently opened file by a
* temporary filename provided by KApplication.
* @see KMainWindow#saveProperties
*/
void UMLApp::saveProperties(KConfigGroup & cfg)
{
if (m_doc->url().fileName() == i18n("Untitled") || m_doc->isModified()) {
QUrl url = m_doc->url();
cfg.writePathEntry("filename", url.toString());
cfg.writeEntry("modified", m_doc->isModified());
DEBUG() << "Save properties - filenam: " << url << " | modified: " << m_doc->isModified();
// saving to tempfile necessary
QTemporaryFile tmpfile(url.toString());
if (tmpfile.open()) {
QUrl dest(QUrl::fromLocalFile(tmpfile.fileName()));
m_doc->saveDocument(dest);
}
}
}
/**
* Reads the session config file and restores the
* application's state including the last opened files and
* documents by reading the temporary files saved by
* saveProperties()
* @see KMainWindow#readProperties
*/
void UMLApp::readProperties(const KConfigGroup & cfg) //:TODO: applyMainWindowSettings(const KConfigGroup& config, bool force = false)
{
QString filename = cfg.readPathEntry("filename", QString());
QUrl url(filename);
bool modified = cfg.readEntry("modified", false);
DEBUG() << "Read properties - filename: " << url << " | modified: " << modified;
if (modified) {
QTemporaryFile tmpfile(filename);
if (tmpfile.open()) {
QUrl _url(QUrl::fromLocalFile(tmpfile.fileName()));
m_doc->openDocument(_url);
m_doc->setModified();
enablePrint(true);
setCaption(_url.fileName() + QStringLiteral(" [*]"), true);
} else {
enablePrint(false);
}
} else {
if (!filename.isEmpty()) {
m_doc->openDocument(url);
enablePrint(true);
setCaption(url.fileName(), false);
} else {
enablePrint(false);
}
}
}
/**
* queryClose is called by KMainWindow on each closeEvent of a
* window. Counter to the default implementation (which only
* returns true), this calls saveModified() on the document object
* to ask if the document shall be saved if Modified; on cancel
* the closeEvent is rejected.
* @see KMainWindow#queryClose
* @see KMainWindow#closeEvent
*
* @return True if window may be closed.
*/
bool UMLApp::queryClose()
{
if (m_doc->saveModified()) {
saveOptions();
m_doc->closeDocument();
return true;
}
return false;
}
/**
* Clears the document in the actual view to reuse it as the new
* document.
*/
void UMLApp::slotFileNew()
{
slotStatusMsg(i18n("Creating new document..."));
if (m_doc->saveModified()) {
setDiagramMenuItemsState(false);
m_doc->newDocument();
setCaption(m_doc->url().fileName(), false);
fileOpenRecent->setCurrentItem(-1);
setModified(false);
enablePrint(false);
}
slotUpdateViews();
resetStatusMsg();
}
/**
* Open a file and load it into the document.
*/
void UMLApp::slotFileOpen()
{
slotStatusMsg(i18n("Opening file..."));
m_loading = true;
if (!m_doc->saveModified()) {
// here saving wasn't successful
}
else {
QUrl url = QFileDialog::getOpenFileUrl(this, i18n("Open File"), QUrl(),
i18n("*.xmi *.xmi.tgz *.xmi.tar.bz2 *.uml *.mdl *.zargo|All Supported Files (*.xmi, *.xmi.tgz, *.xmi.tar.bz2, *.uml, *.mdl, *.zargo)\n"
"*.xmi|Uncompressed XMI Files (*.xmi)\n"
"*.xmi.tgz|Gzip Compressed XMI Files (*.xmi.tgz)\n"
"*.xmi.tar.bz2|Bzip2 Compressed XMI Files (*.xmi.tar.bz2)\n"
"*.uml|Eclipse PapyrusUML files (*.uml)\n"
"*.mdl|Rose model files (*.mdl)\n"
"*.zargo|Compressed argo Files(*.zargo)\n"
)
.replace(QStringLiteral(","), QStringLiteral(""))
);
if (!url.isEmpty()) {
m_listView->setSortingEnabled(false);
if (m_doc->openDocument(url)) {
fileOpenRecent->addUrl(url);
}
enablePrint(true);
setCaption(m_doc->url().fileName(), false);
m_listView->setSortingEnabled(true);
}
}
slotUpdateViews();
m_loading = false;
resetStatusMsg();
}
/**
* Opens a file from the recent files menu.
*/
void UMLApp::slotFileOpenRecent(const QUrl &url)
{
slotStatusMsg(i18n("Opening file..."));
m_loading = true;
QUrl oldUrl = m_doc->url();
if (!m_doc->saveModified()) {
// here saving wasn't successful
}
else {
if (!m_doc->openDocument(url)) {
fileOpenRecent->removeUrl(url);
fileOpenRecent->setCurrentItem(-1);
}
else {
fileOpenRecent->addUrl(url);
}
enablePrint(true);
setCaption(m_doc->url().fileName(), false);
}
m_loading = false;
slotUpdateViews();
resetStatusMsg();
}
/**
* Save a document.
*/
void UMLApp::slotFileSave()
{
slotStatusMsg(i18n("Saving file..."));
if (m_doc->url().fileName() == i18n("Untitled")) {
slotFileSaveAs();
}
else {
m_doc->saveDocument(m_doc->url());
}
if (m_pUndoStack)
m_pUndoStack->setClean();
resetStatusMsg();
}
/**
* Save a document by a new filename.
*/
bool UMLApp::slotFileSaveAs()
{
slotStatusMsg(i18n("Saving file with a new filename..."));
bool cont = true;
QUrl url;
QString ext;
while (cont) {
url = QFileDialog::getSaveFileUrl(this, i18n("Save As"), QUrl(),
i18n("*.xmi | XMI File (*.xmi);;"
"*.xmi.tgz | Gzip Compressed XMI File (*.xmi.tgz);;"
"*.xmi.tar.bz2 | Bzip2 Compressed XMI File (*.xmi.tar.bz2);;"
"* | All Files (*)"));
if (url.isEmpty()) {
break;
}
if (!url.isLocalFile()) {
break;
}
QString file = url.toLocalFile();
if (!file.contains(QStringLiteral("."))) {
file.append(QStringLiteral(".xmi"));
url = QUrl::fromLocalFile(file);
}
if (!QFile::exists(file)) {
break;
}
int want_save = KMessageBox::warningContinueCancel(this, i18n("The file %1 exists.\nDo you wish to overwrite it?", file),
i18n("Warning"), KGuiItem(i18n("Overwrite")));
if (want_save == KMessageBox::Continue) {
cont = false;
}
}
if (!url.isEmpty()) {
bool b = m_doc->saveDocument(url);
if (b) {
fileOpenRecent->addUrl(url);
setCaption(url.fileName(), m_doc->isModified());
resetStatusMsg();
}
return b;
}
else {
resetStatusMsg();
return false;
}
}
/**
* Asks for saving if the file is modified, then closes the current
* file and window.
*/
void UMLApp::slotFileClose()
{
slotStatusMsg(i18n("Closing file..."));
m_doc->diagramsModel()->removeAllDiagrams();
slotFileNew();
}
/**
* find text
*/
void UMLApp::slotFind()
{
if (!m_d->findDialog.exec()) {
UMLApp::app()->document()->writeToStatusBar(i18n("No search term entered"));
return;
}
int count = m_d->findResults.collect(m_d->findDialog.filter(), m_d->findDialog.category(), m_d->findDialog.text());
UMLApp::app()->document()->writeToStatusBar(i18n("'%1': %2 found", m_d->findDialog.text(), count));
slotFindNext();
}
/**
* Slot for showing next find result
*/
void UMLApp::slotFindNext()
{
if (!m_d->findResults.displayNext())
m_d->findResults.displayNext();
}
/**
* Slot for showing previous find result
*/
void UMLApp::slotFindPrevious()
{
if (!m_d->findResults.displayPrevious())
m_d->findResults.displayPrevious();
}
/**
* Slot for showing a print settings dialog.
*/
bool UMLApp::slotPrintSettings()
{
if (m_printSettings) {
delete m_printSettings;
}
m_printSettings = new DiagramPrintPage(nullptr, m_doc);
QPointer<QDialog> dlg = new QDialog();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(m_printSettings);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok |
QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), dlg, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), dlg, SLOT(reject()));
layout->addWidget(buttonBox);
dlg->setLayout(layout);
bool result = dlg->exec() == QDialog::Accepted;
// keep settings
layout->removeWidget(m_printSettings);
m_printSettings->setParent(nullptr);
delete dlg;
return result;
}
/**
* Print preview
*/
void UMLApp::slotPrintPreview()
{
slotStatusMsg(i18n("Print Preview..."));
if (!slotPrintSettings())
return;
QPointer<QPrintPreviewDialog> preview = new QPrintPreviewDialog(m_printer, this);
connect(preview, SIGNAL(paintRequested(QPrinter*)), this, SLOT(slotPrintPreviewPaintRequested(QPrinter*)));
preview->exec();
delete preview;
delete m_printSettings;
m_printSettings = nullptr;
resetStatusMsg();
}
/**
* Print preview painting slot
*/
void UMLApp::slotPrintPreviewPaintRequested(QPrinter *printer)
{
m_doc->print(printer, m_printSettings);
}
/**
* Print the current file.
*/
void UMLApp::slotFilePrint()
{
slotStatusMsg(i18n("Printing..."));
if (!slotPrintSettings())
return;
QPointer<QPrintDialog> printDialog = new QPrintDialog(m_printer, this);
printDialog->setWindowTitle(i18n("Print %1", m_doc->url().toDisplayString()));
if (printDialog->exec()) {
m_doc->print(m_printer, m_printSettings);
}
delete m_printSettings;
m_printSettings = nullptr;
delete printDialog;
resetStatusMsg();
}
/**
* Closes all open windows by calling close() on each
* memberList item until the list is empty, then quits the
* application. If queryClose() returns false because the
* user canceled the saveModified() dialog, the closing
* aborts.
*/
void UMLApp::slotFileQuit()
{
slotStatusMsg(i18n("Exiting..."));
if (m_doc->saveModified()) {
saveOptions();
qApp->quit();
}
resetStatusMsg();
}
/**
* Exports the current model to docbook in a subdir of the
* current model directory named from the model name.
* @todo Let the user chose the destination directory and
* name, using network transparency.
*/
void UMLApp::slotFileExportDocbook()
{
QString path = QFileDialog::getExistingDirectory();
if (path.isEmpty()) {
return;
}
DocbookGenerator* docbookGenerator = new DocbookGenerator;
docbookGenerator->generateDocbookForProjectInto(QUrl::fromLocalFile(path));
connect(docbookGenerator, SIGNAL(finished(bool)), docbookGenerator, SLOT(deleteLater()));
}
/**
* Exports the current model to XHTML in a subdir of the
* current model directory named from the model name.
* @todo Let the user chose the destination directory and
* name, using network transparency.
*/
void UMLApp::slotFileExportXhtml()
{
QString path = QFileDialog::getExistingDirectory();
if (path.isEmpty()) {
return;
}
if (!m_xhtmlGenerator) {
m_xhtmlGenerator = new XhtmlGenerator;
}
m_xhtmlGenerator->generateXhtmlForProjectInto(QUrl::fromLocalFile(path));
connect(m_xhtmlGenerator, SIGNAL(finished(bool)), this, SLOT(slotXhtmlDocGenerationFinished(bool)));
}
/**
* Reverts the document back to the state it was prior to the
* last action performed by the user.
*/
void UMLApp::slotEditUndo()
{
undo();
resetStatusMsg();
}
/**
* Reverts the document back to the state it was prior to the
* last undo.
*/
void UMLApp::slotEditRedo()
{
redo();
resetStatusMsg();
}
/**
* Put the marked text/object into the clipboard and remove
* it from the document.
*/
void UMLApp::slotEditCut()
{
slotStatusMsg(i18n("Cutting selection..."));
//FIXME bug 59774 this fromview isn't very reliable.
//when cutting diagrams it is set to true even though it shouldn't be
bool fromview = (currentView() && currentView()->umlScene()->selectedCount());
// If not cutting diagram widgets, we did cut on a listview item
if (!fromview) {
m_listView->setStartedCut(true);
}
if (editCutCopy(fromview)) {
Q_EMIT sigCutSuccessful();
slotDeleteSelected();
m_doc->setModified(true);
}
resetStatusMsg();
}
/**
* Put the marked text/object into the clipboard.
*/
void UMLApp::slotEditCopy()
{
slotStatusMsg(i18n("Copying selection to clipboard..."));
bool fromview = (currentView() && currentView()->umlScene()->selectedCount());
editCutCopy(fromview);
resetStatusMsg();
m_doc->setModified(true);
}
/**
* Paste the clipboard into the document.
*/
void UMLApp::slotEditPaste()
{
slotStatusMsg(i18n("Inserting clipboard contents..."));
const QMimeData* data = QApplication::clipboard()->mimeData();
UMLClipboard clipboard;
setCursor(Qt::WaitCursor);
if (!clipboard.paste(data)) {
KMessageBox::information(this, i18n("Umbrello could not paste the clipboard contents. "
"The objects in the clipboard may be of the wrong "
"type to be pasted here."), i18n("Paste Error"));
}
resetStatusMsg();
setCursor(Qt::ArrowCursor);
editPaste->setEnabled(false);
m_doc->setModified(true);
}
/**
* Changes the statusbar contents for the standard label
* permanently, used to indicate current actions.
* @param text The text that is displayed in the statusbar
*/
void UMLApp::slotStatusMsg(const QString &text)
{
// change status message permanently
m_statusBarMessage->setText(text);
}
/**
* Helper method to reset the status bar message.
*/
void UMLApp::resetStatusMsg()
{
m_statusBarMessage->setText(i18nc("reset status bar", "Ready."));
}
/**
* Helper function to create diagram name and the diagram itself.
* @param type the type of diagram
*/
void UMLApp::createDiagram(Uml::DiagramType::Enum type)
{
QString diagramName = m_doc->createDiagramName(type);
if (!diagramName.isEmpty())
executeCommand(new Uml::CmdCreateDiagram(m_doc, type, diagramName));
}
/**
* Create this view.
*/
void UMLApp::slotClassDiagram()
{
createDiagram(Uml::DiagramType::Class);
}
/**
* Create this view.
*/
void UMLApp::slotObjectDiagram()
{
createDiagram(Uml::DiagramType::Object);
}
/**
* Create this view.
*/
void UMLApp::slotSequenceDiagram()
{
createDiagram(Uml::DiagramType::Sequence);
}
/**
* Create this view.
*/
void UMLApp::slotCollaborationDiagram()
{
createDiagram(Uml::DiagramType::Collaboration);
}
/**
* Create this view.
*/
void UMLApp::slotUseCaseDiagram()
{
createDiagram(Uml::DiagramType::UseCase);
}
/**
* Create this view.
*/
void UMLApp::slotStateDiagram()
{
createDiagram(Uml::DiagramType::State);
}
/**
* Create this view.
*/
void UMLApp::slotActivityDiagram()
{
createDiagram(Uml::DiagramType::Activity);
}
/**
* Create this view.
*/
void UMLApp::slotComponentDiagram()
{
createDiagram(Uml::DiagramType::Component);
}
/**
* Create this view.
*/
void UMLApp::slotDeploymentDiagram()
{
createDiagram(Uml::DiagramType::Deployment);
}
/**
* Create this view.
*/
void UMLApp::slotEntityRelationshipDiagram()
{
createDiagram(Uml::DiagramType::EntityRelationship);
}
/**
* Left Alignment
*/
void UMLApp::slotAlignLeft()
{
currentView()->umlScene()->alignLeft();
}
/**
* Right Alignment
*/
void UMLApp::slotAlignRight()
{
currentView()->umlScene()->alignRight();
}
/**
* Top Alignment
*/
void UMLApp::slotAlignTop()
{
currentView()->umlScene()->alignTop();
}
/**
* Bottom Alignment
*/
void UMLApp::slotAlignBottom()
{
currentView()->umlScene()->alignBottom();
}
/**
* Vertical Middle Alignment
*/
void UMLApp::slotAlignVerticalMiddle()
{
currentView()->umlScene()->alignVerticalMiddle();
}
/**
* Horizontal Middle Alignment
*/
void UMLApp::slotAlignHorizontalMiddle()
{
currentView()->umlScene()->alignHorizontalMiddle();
}
/**
* Vertical Distribute Alignment
*/
void UMLApp::slotAlignVerticalDistribute()
{
currentView()->umlScene()->alignVerticalDistribute();
}
/**
* Horizontal Distribute Alignment
*/
void UMLApp::slotAlignHorizontalDistribute()
{
currentView()->umlScene()->alignHorizontalDistribute();
}
/**
* Returns the toolbar being used.
*
* @return The toolbar being used.
*/
WorkToolBar* UMLApp::workToolBar() const
{
return m_toolsbar;
}
/**
* Returns the doc window used.
*
* @return the doc window being used
*/
DocWindow* UMLApp::docWindow() const
{
return m_docWindow;
}
/**
* Returns the log window used.
*
* @return the log window being used
*/
QListWidget* UMLApp::logWindow() const
{
return m_d->logWindow;
}
/**
* Returns true if the environment variable UMBRELLO_LOG_TO_CONSOLE is
* set to 1 or if the log dock is not visible.
* The default is to print info/warnings/error messages to the log dock.
*
* @return True if warnings/errors shall be logged to the console.
*/
bool UMLApp::logToConsole() const
{
return (Tracer::instance()->logToConsole() || !m_logDock || !m_logDock->isVisible());
}
/**
* Adds a line to the log window.
*/
void UMLApp::log(const QString& s)
{
logWindow()->addItem(s);
}
/**
* Logs a debug message, either to the log window or to the console.
* @todo This is not yet hooked up.
* Hooking it up entails vast changes because currently Umbrello uses
* the uDebug() stream and the stream usages (<<) need to be changed
* to normal function call syntax.
*/
void UMLApp::logDebug(const QString& s)
{
QString fmt = QStringLiteral("[D] ") + s;
if (logToConsole())
uDebug() << fmt;
else
log(fmt);
}
/**
* Logs an info message, either to the log window or to the console.
* @todo This is not yet hooked up but only because Umbrello does not have
* a uInfo() stream analogous to uDebug / uWarning / uError, i.e.
* hooking up does not imply a change avalanche in the existing code
* and can be done as needed.
*/
void UMLApp::logInfo(const QString& s)
{
QString fmt = QStringLiteral("[I] ") + s;
if (logToConsole())
uDebug() << fmt; // @todo add Umbrello uInfo(), see uWarning etc
else
log(fmt);
}
/**
* Logs a warning message, either to the log window or to the console.
*/
void UMLApp::logWarn(const QString& s)
{
QString fmt = QStringLiteral("[W] ") + s;
if (logToConsole())
uWarning() << fmt;
else
log(fmt);
}
/**
* Logs an error message, either to the log window or to the console.
*/
void UMLApp::logError(const QString& s)
{
QString fmt = QStringLiteral("[E] ") + s;
if (logToConsole())
uError() << fmt;
else
log(fmt);
}
/**
* Sets whether the program has been modified.
* This will change how the program saves/exits.
*
* @param modified true - modified.
*/
void UMLApp::setModified(bool modified)
{
//fileSave->setEnabled(modified);
//if anything else needs to be done on a modification, put it here
// printing should be possible whenever there is something to print
if (m_loading == false && modified == true && currentView()) {
enablePrint(true);
}
if (m_loading == false) {
if (m_doc) {
DEBUG() << "Modified file=" << m_doc->url().fileName();
setCaption(m_doc->url().fileName(), modified); //add disk icon to taskbar if modified
}
else {
DEBUG() << "m_doc is NULL!";
}
}
}
/**
* Set whether to allow printing.
* It will enable/disable the menu/toolbar options.
*
* @param enable Set whether to allow printing.
*/
void UMLApp::enablePrint(bool enable)
{
filePrint->setEnabled(enable);
printPreview->setEnabled(enable);
}
/**
* Initialize Qt's global clipboard support for the application.
*/
void UMLApp::initClip()
{
QClipboard* clip = QApplication::clipboard();
connect(clip, SIGNAL(dataChanged()), this, SLOT(slotClipDataChanged()));
// Don't poll the X11 clipboard every second. This is a little expensive and resulted
// in very annoying umbrello slowdowns / hangs. Qt will notify us about clipboard
// changes anyway (see dataChanged() signal above), albeit only when a Qt application
// changes the clipboard. Work is in progress to make this work with other toolkits
// as well. (pfeiffer)
// m_clipTimer = new QTimer(this, "timer");
// m_clipTimer->start(1000, false);
// connect(m_clipTimer, SIGNAL(timeout()), this, SLOT(slotClipDataChanged()));
m_copyTimer = new QTimer(this);
m_copyTimer->setSingleShot(false);
m_copyTimer->start(500);
connect(m_copyTimer, SIGNAL(timeout()), this, SLOT(slotCopyChanged()));
}
/**
* Returns whether we can decode the given mimesource
*/
bool UMLApp::canDecode(const QMimeData* mimeData)
{
QStringList supportedFormats = mimeData->formats();
for(const QString &format: supportedFormats) {
QByteArray fba = format.toLatin1();
const char* f = fba.constData();
if (!qstrnicmp(f,"application/x-uml-clip", 22)) {
//FIXME need to test for clip1, clip2, clip3, clip4 or clip5
//(the only valid clip types)
return true;
}
else if (!qstrnicmp(f,"text/plain", 10)) {
return true;
}
}
return false;
}
/**
* Notification of changed clipboard data.
*/
void UMLApp::slotClipDataChanged()
{
const QMimeData * data = QApplication::clipboard()->mimeData();
// Pass the MimeSource to the Doc
editPaste->setEnabled(data && canDecode(data));
}
/**
* Slot for enabling cut and copy to clipboard.
*/
void UMLApp::slotCopyChanged()
{
if (m_listView->selectedItemsCount() || (currentView() && currentView()->umlScene()->selectedCount())) {
editCopy->setEnabled(true);
editCut->setEnabled(true);
}
else {
editCopy->setEnabled(false);
editCut->setEnabled(false);
}
}
/**
* Shows the global preferences dialog.
*/
void UMLApp::slotPrefs(MultiPageDialogBase::PageType page)
{
Settings::OptionState& optionState = Settings::optionState();
m_settingsDialog = new SettingsDialog(this, &optionState);
m_settingsDialog->setCurrentPage(page);
connect(m_settingsDialog, SIGNAL(applyClicked()), this, SLOT(slotApplyPrefs()));
if (m_settingsDialog->exec() == QDialog::Accepted && m_settingsDialog->getChangesApplied()) {
slotApplyPrefs();
}
delete m_settingsDialog;
m_settingsDialog = nullptr;
}
/**
* Commits the changes from the global preferences dialog.
*/
void UMLApp::slotApplyPrefs()
{
if (m_settingsDialog) {
// we need this to sync both values
Settings::OptionState& optionState = Settings::optionState();
enableUndo(optionState.generalState.undo);
bool stackBrowsing = (m_layout->indexOf(m_tabWidget) != -1);
bool tabBrowsing = optionState.generalState.tabdiagrams;
DEBUG() << "stackBrowsing=" << stackBrowsing << " / tabBrowsing=" << tabBrowsing;
if (stackBrowsing != tabBrowsing) {
// Diagram Representation Modified
UMLView* currentView;
UMLViewList views = m_doc->viewIterator();
if (tabBrowsing) {
currentView = static_cast<UMLView*>(m_viewStack->currentWidget());
m_layout->removeWidget(m_viewStack);
m_viewStack->hide();
for(UMLView *view : views) {
UMLScene *scene = view->umlScene();
m_viewStack->removeWidget(view);
int tabIndex = m_tabWidget->addTab(view, scene->name());
m_tabWidget->setTabIcon(tabIndex, QIcon(Icon_Utils::iconSet(scene->type())));
m_tabWidget->setTabToolTip(tabIndex, scene->name());
}
m_layout->addWidget(m_tabWidget);
m_tabWidget->show();
}
else { // stackBrowsing
currentView = static_cast<UMLView*>(m_tabWidget->currentWidget());
m_layout->removeWidget(m_tabWidget);
m_tabWidget->hide();
for(UMLView *view : views) {
m_tabWidget->removeTab(m_tabWidget->indexOf(view));
m_viewStack->addWidget(view);
}
m_layout->addWidget(m_viewStack);
m_viewStack->show();
}
setCurrentView(currentView);
}
m_doc->settingsChanged(optionState);
const QString plStr = m_settingsDialog->getCodeGenerationLanguage();
Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromString(plStr);
setGenerator(pl);
}
}
/**
* Returns the paste state.
*
* @return True if Paste is enabled.
*/
bool UMLApp::isPasteState() const
{
return editPaste->isEnabled();
}
/**
* Returns the state on Cut/Copy.
*
* @return True if Cut/Copy is enabled.
*/
bool UMLApp::isCutCopyState() const
{
return editCopy->isEnabled();
}
/**
* Returns the state of undo support.
*
* @return True if undo is enabled.
*/
bool UMLApp::isUndoEnabled() const
{
return m_undoEnabled;
}
/**
* Set the state of undo support.
*
*/
void UMLApp::enableUndo(bool enable)
{
m_undoEnabled = enable;
editRedo->setVisible(enable);
editUndo->setVisible(enable);
viewShowCmdHistory->setVisible(enable);
clearUndoStack();
slotShowCmdHistoryView(enable);
}
/**
* Returns the undo state. Is used for popupmenu of a view.
*
* @return True if Undo is enabled.
*/
bool UMLApp::isUndoActionEnabled() const
{
return editUndo->isEnabled();
}
/**
* Set whether to allow Undo.
* It will enable/disable the menu/toolbar options.
*
* @param enable Set whether to allow printing.
*/
void UMLApp::enableUndoAction(bool enable)
{
editUndo->setEnabled(enable);
}
/**
* Returns the redo state.
*
* @return True if Redo is enabled. Is used for popupmenu of a view.
*/
bool UMLApp::isRedoActionEnabled() const
{
return editRedo->isEnabled();
}
/**
* Set whether to allow Redo.
* It will enable/disable the menu/toolbar options.
*
* @param enable Set whether to allow printing.
*/
void UMLApp::enableRedoAction(bool enable)
{
editRedo->setEnabled(enable);
}
/**
* Carries out the cut/copy command with different action performed
* depending on if from view or list view.
* Cut/Copy are the same. It is up to the caller to delete/cut the selection..
*
* If the operation is successful, the signal sigCutSuccessful() is emitted.
*
* Callers should connect to this signal to know what to do next.
*/
bool UMLApp::editCutCopy(bool bFromView)
{
UMLClipboard clipboard;
QMimeData *clipdata = nullptr;
// If not from-view, list items are copied. This flag is
// used in UMLDragData to determine whether to assign new IDs
if (!bFromView) {
listView()->setStartedCopy(true);
}
if ((clipdata = clipboard.copy(bFromView)) != nullptr) {
QClipboard* clip = QApplication::clipboard();
clip->setMimeData(clipdata);//the global clipboard takes ownership of the clipdata memory
connect(clip, SIGNAL(dataChanged()), this, SLOT(slotClipDataChanged()));
return true;
}
return false;
}
/**
* Reads from the config file the options state.
* Not in @ref readOptions as it needs to be read earlier than some
* of the other options, before some items are created.
*/
void UMLApp::readOptionState() const
{
Settings::OptionState& optionState = Settings::optionState();
UmbrelloSettings::self()->load();
optionState.load();
// general config options will be read when created
}
/**
* Call the code viewing assistant on a given UMLClassifier.
*
* @param classifier Pointer to the classifier to view.
*/
void UMLApp::viewCodeDocument(UMLClassifier* classifier)
{
CodeGenerator * currentGen = generator();
if (currentGen && classifier) {
AdvancedCodeGenerator *generator = dynamic_cast<AdvancedCodeGenerator*>(currentGen);
if (generator) {
CodeDocument *cdoc = generator->findCodeDocumentByClassifier(classifier);
if (cdoc) {
Settings::OptionState& optionState = Settings::optionState();
CodeViewerDialog * dialog = generator->getCodeViewerDialog(this, cdoc, optionState.codeViewerState);
dialog->exec();
optionState.codeViewerState = dialog->state();
delete dialog;
dialog = nullptr;
} else {
// shouldn't happen..
KMessageBox::information(nullptr, i18n("Cannot view code until you generate some first."), i18n("Cannot View Code"));
}
} else {
KMessageBox::information(nullptr, i18n("Cannot view code from simple code writer."), i18n("Cannot View Code"));
}
} else {
uWarning() << "No CodeGenerator or UMLClassifier given!";
}
}
/**
* Call the refactoring assistant on a classifier.
*
* @param classifier Pointer to the classifier to refactor.
*/
void UMLApp::refactor(UMLClassifier* classifier)
{
if (!m_refactoringAssist) {
m_refactoringAssist = new RefactoringAssistant(m_doc, nullptr, nullptr,
QStringLiteral("refactoring_assistant"));
}
m_refactoringAssist->refactor(classifier);
m_refactoringAssist->show();
}
/**
* Returns the default code generation policy.
*/
CodeGenerationPolicy *UMLApp::commonPolicy() const
{
return m_commoncodegenpolicy;
}
/**
* Sets the CodeGenPolicyExt object.
*/
void UMLApp::setPolicyExt(CodeGenPolicyExt *policy)
{
m_policyext = policy;
}
/**
* Returns the CodeGenPolicyExt object.
*/
CodeGenPolicyExt *UMLApp::policyExt() const
{
return m_policyext;
}
/**
* Auxiliary function for UMLDoc::loadExtensionsFromXMI():
* Return the code generator of the given language if it already
* exists; if it does not yet exist then create it and return
* the newly created generator. It is the caller's responsibility
* to load XMI into the newly created generator.
*/
CodeGenerator *UMLApp::setGenerator(Uml::ProgrammingLanguage::Enum pl)
{
if (m_codegen) {
UMLFolder *dtFolder = m_doc->datatypeFolder();
UMLObjectList dataTypes = dtFolder->containedObjects();
UMLObjectList::Iterator end(dataTypes.end());
if (m_codegen->language() == pl) {
const QStringList predefTypes = m_codegen->defaultDatatypes();
const Qt::CaseSensitivity cs =
(activeLanguageIsCaseSensitive() ? Qt::CaseSensitive : Qt::CaseInsensitive);
for (UMLObjectList::Iterator it = dataTypes.begin(); it != end; ++it) {
if (!predefTypes.contains((*it)->name(), cs)) {
m_doc->removeUMLObject(*it);
}
}
return m_codegen;
}
for (UMLObjectList::Iterator it = dataTypes.begin(); it != end; ++it) {
m_doc->removeUMLObject(*it);
}
delete m_codegen; // ATTENTION! remove all refs to it or its policy first
m_codegen = nullptr;
}
m_activeLanguage = pl;
if (pl != Uml::ProgrammingLanguage::Reserved) {
m_codegen = CodeGenFactory::createObject(pl);
}
updateLangSelectMenu(pl);
slotAddDefaultDatatypes();
if (pl != Uml::ProgrammingLanguage::Reserved) {
m_codegen->createDefaultStereotypes();
if (m_policyext) {
m_policyext->setDefaults(false); // picks up language specific stuff
}
}
return m_codegen;
}
/**
* Gets the appropriate CodeGenerator.
*
* @return Pointer to the CodeGenerator.
*/
CodeGenerator* UMLApp::generator() const
{
return m_codegen;
}
/**
* Determines if SimpleCodeGenerator is active.
*
* @return true if SimpleCodeGenerator is active.
*/
bool UMLApp::isSimpleCodeGeneratorActive() const
{
if (m_codegen && dynamic_cast<SimpleCodeGenerator*>(m_codegen)) {
return true;
}
else {
return false;
}
}
/**
* Generate code for all classes.
*/
void UMLApp::slotGenerateAllCode()
{
if (m_codegen) {
m_codegen->writeCodeToFile();
}
}
/**
* Runs the code generation wizard.
*/
void UMLApp::slotExecGenerationWizard()
{
QPointer<CodeGenerationWizard> wizard = new CodeGenerationWizard(nullptr /*classList*/);
wizard->exec();
delete wizard;
}
/**
* Slots for connection to the QActions of the m_langSelect menu.
*/
void UMLApp::setLang_actionscript()
{
setActiveLanguage(Uml::ProgrammingLanguage::ActionScript);
}
void UMLApp::setLang_ada()
{
setActiveLanguage(Uml::ProgrammingLanguage::Ada);
}
void UMLApp::setLang_cpp()
{
setActiveLanguage(Uml::ProgrammingLanguage::Cpp);
}
void UMLApp::setLang_csharp()
{
setActiveLanguage(Uml::ProgrammingLanguage::CSharp);
}
void UMLApp::setLang_d()
{
setActiveLanguage(Uml::ProgrammingLanguage::D);
}
void UMLApp::setLang_idl()
{
setActiveLanguage(Uml::ProgrammingLanguage::IDL);
}
void UMLApp::setLang_java()
{
setActiveLanguage(Uml::ProgrammingLanguage::Java);
}
void UMLApp::setLang_javascript()
{
setActiveLanguage(Uml::ProgrammingLanguage::JavaScript);
}
void UMLApp::setLang_mysql()
{
setActiveLanguage(Uml::ProgrammingLanguage::MySQL);
}
void UMLApp::setLang_pascal()
{
setActiveLanguage(Uml::ProgrammingLanguage::Pascal);
}
void UMLApp::setLang_perl()
{
setActiveLanguage(Uml::ProgrammingLanguage::Perl);
}
void UMLApp::setLang_php()
{
setActiveLanguage(Uml::ProgrammingLanguage::PHP);
}
void UMLApp::setLang_php5()
{
setActiveLanguage(Uml::ProgrammingLanguage::PHP5);
}
void UMLApp::setLang_postgresql()
{
setActiveLanguage(Uml::ProgrammingLanguage::PostgreSQL);
}
void UMLApp::setLang_python()
{
setActiveLanguage(Uml::ProgrammingLanguage::Python);
}
void UMLApp::setLang_ruby()
{
setActiveLanguage(Uml::ProgrammingLanguage::Ruby);
}
void UMLApp::setLang_sql()
{
setActiveLanguage(Uml::ProgrammingLanguage::SQL);
}
void UMLApp::setLang_tcl()
{
setActiveLanguage(Uml::ProgrammingLanguage::Tcl);
}
void UMLApp::setLang_vala()
{
setActiveLanguage(Uml::ProgrammingLanguage::Vala);
}
void UMLApp::setLang_xmlschema()
{
setActiveLanguage(Uml::ProgrammingLanguage::XMLSchema);
}
void UMLApp::setLang_none()
{
setActiveLanguage(Uml::ProgrammingLanguage::Reserved);
}
/**
* Called when right clicking on tab widget.
* @param point the point where the right mouse button was clicked
*/
void UMLApp::slotDiagramPopupMenu(const QPoint& point)
{
QTabBar* tabBar = m_tabWidget->tabBar();
int index = tabBar->tabAt(point);
UMLView* view = (UMLView*)m_tabWidget->widget(index);
QPoint globalPoint = m_tabWidget->mapToGlobal(point);
m_doc->slotDiagramPopupMenu(view, globalPoint);
}
/**
* Set the language for which code will be generated.
*
* @param pl The name of the language to set
*/
void UMLApp::setActiveLanguage(Uml::ProgrammingLanguage::Enum pl)
{
//updateLangSelectMenu(pl); //:TODO:checkit - is already called in setGenerator
setGenerator(pl);
}
/**
* Get the language for import and code generation.
*/
Uml::ProgrammingLanguage::Enum UMLApp::activeLanguage() const
{
return m_activeLanguage;
}
/**
* Return true if the active language is case sensitive.
*/
bool UMLApp::activeLanguageIsCaseSensitive() const
{
Uml::ProgrammingLanguage::Enum pl = activeLanguage();
return Uml::ProgrammingLanguage::isCaseSensitive(pl);
}
/**
* Return the target language depedent scope separator.
*/
QString UMLApp::activeLanguageScopeSeparator() const
{
Uml::ProgrammingLanguage::Enum pl = activeLanguage();
return Uml::ProgrammingLanguage::scopeSeparator(pl);
}
void UMLApp::slotShowTreeView(bool state)
{
m_listDock->setVisible(state);
viewShowTree->setChecked(state);
}
void UMLApp::slotShowDebugView(bool state)
{
m_debugDock->setVisible(state);
viewShowDebug->setChecked(state);
}
void UMLApp::slotShowDocumentationView(bool state)
{
m_documentationDock->setVisible(state);
viewShowDoc->setChecked(state);
}
void UMLApp::slotShowCmdHistoryView(bool state)
{
m_cmdHistoryDock->setVisible(state);
viewShowCmdHistory->setChecked(state);
}
void UMLApp::slotShowLogView(bool state)
{
m_logDock->setVisible(state);
viewShowLog->setChecked(state);
}
void UMLApp::slotShowBirdView(bool state)
{
m_birdViewDock->setVisible(state);
viewShowBirdView->setChecked(state);
}
/**
* Menu selection for clear current view.
*/
void UMLApp::slotCurrentViewClearDiagram()
{
currentView()->umlScene()->clearDiagram();
}
/**
* Menu selection for current view snap to grid property.
*/
void UMLApp::slotCurrentViewToggleSnapToGrid()
{
currentView()->umlScene()->toggleSnapToGrid();
viewSnapToGrid->setChecked(currentView()->umlScene()->snapToGrid());
}
/**
* Menu selection for current view show grid property.
*/
void UMLApp::slotCurrentViewToggleShowGrid()
{
currentView()->umlScene()->toggleShowGrid();
viewShowGrid->setChecked(currentView()->umlScene()->isSnapGridVisible());
}
/**
* Menu selection for exporting current view as an image.
*/
void UMLApp::slotCurrentViewExportImage()
{
currentView()->umlScene()->getImageExporter()->exportView();
}
/**
* Menu selection for exporting all views as images.
*/
void UMLApp::slotViewsExportImages()
{
//delete m_printSettings;
m_printSettings = new DiagramPrintPage(nullptr, m_doc);
DiagramSelectionDialog dlg(m_printSettings);
if (dlg.exec() == QDialog::Accepted)
m_imageExporterAll->exportViews(m_printSettings);
}
/**
* Menu selection for current view and contained widgets properties.
*/
void UMLApp::slotCurrentProperties()
{
UMLWidgetList items = currentView()->umlScene()->selectedWidgets();
if (items.count() == 0)
currentView()->showPropertiesDialog();
else if (items.count() == 1)
items.at(0)->showPropertiesDialog();
}
/**
* Sets the state of the view properties menu item.
*
* @param bState Boolean, true to enable the view properties item.
*/
void UMLApp::setDiagramMenuItemsState(bool bState)
{
viewClearDiagram->setEnabled(bState);
viewSnapToGrid->setEnabled(bState);
viewShowGrid->setEnabled(bState);
deleteDiagram->setEnabled(bState);
viewExportImage->setEnabled(bState);
viewProperties->setEnabled(bState);
filePrint->setEnabled(bState);
if (currentView()) {
viewSnapToGrid->setChecked(currentView()->umlScene()->snapToGrid());
viewShowGrid->setChecked(currentView()->umlScene()->isSnapGridVisible());
}
}
/**
* Register new views (aka diagram) with the GUI so they show up
* in the menu.
*/
void UMLApp::slotUpdateViews()
{
QMenu* menu = findMenu(QStringLiteral("views"));
if (!menu) {
uWarning() << "view menu not found";
return;
}
menu = findMenu(QStringLiteral("show_view"));
if (!menu) {
uWarning() << "show menu not found";
return;
}
menu->clear();
UMLViewList views = m_doc->viewIterator();
for(UMLView *view : views) {
menu->addAction(view->umlScene()->name(), view->umlScene(), SLOT(slotShowView()));
view->umlScene()->fileLoaded();
}
}
/**
* Import the source files that are in fileList.
*/
void UMLApp::importFiles(QStringList &fileList, const QString &rootPath)
{
if (!fileList.isEmpty()) {
bool really_visible = !listView()->parentWidget()->visibleRegion().isEmpty();
bool saveState = listView()->parentWidget()->isVisible();
listView()->parentWidget()->setVisible(false);
logWindow()->parentWidget()->setVisible(true);
logWindow()->clear();
const QString& firstFile = fileList.first();
ClassImport *classImporter = ClassImport::createImporterByFileExt(firstFile);
classImporter->setRootPath(rootPath);
classImporter->importFiles(fileList);
delete classImporter;
m_doc->setLoading(false);
// Modification is set after the import is made, because the file was modified when adding the classes.
// Allowing undo of the whole class importing. I think it eats a lot of memory.
// Setting the modification, but without allowing undo.
m_doc->setModified(true);
listView()->setUpdatesEnabled(true);
logWindow()->setUpdatesEnabled(true);
listView()->parentWidget()->setVisible(saveState);
if (really_visible)
m_listDock->raise();
}
}
/**
* Import class menu selection.
*/
void UMLApp::slotImportClass()
{
QStringList filters = Uml::ProgrammingLanguage::toExtensions(UMLApp::app()->activeLanguage());
QString f = filters.join(QStringLiteral(" ")) + QStringLiteral("|") +
Uml::ProgrammingLanguage::toExtensionsDescription(UMLApp::app()->activeLanguage());
QStringList files = QFileDialog::getOpenFileNames(this, i18n("Select file(s) to import:"), QString(), f);
if (!files.isEmpty()) {
importFiles(files);
}
}
/**
* @brief getFiles
* @param files
* @param path
* @param filters
*/
void getFiles(QStringList& files, const QString& path, QStringList& filters)
{
QDir searchDir(path);
if (searchDir.exists()) {
for (const QString &file: searchDir.entryList(QDir::Files))
files.append(searchDir.absoluteFilePath(file));
for (const QString &subDir: searchDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks))
getFiles(files, searchDir.absoluteFilePath(subDir), filters);
}
}
/**
* Import project menu selection.
*/
void UMLApp::slotImportProject()
{
QStringList listFile;
QString dir = QFileDialog::getExistingDirectory(this, i18n("Select directory to import:"));
if (!dir.isEmpty()) {
QStringList filter = Uml::ProgrammingLanguage::toExtensions(UMLApp::app()->activeLanguage());
getFiles(listFile, dir, filter);
importFiles(listFile, dir);
}
}
/**
* Runs the code importing wizard.
*/
void UMLApp::slotImportingWizard()
{
QPointer<CodeImportingWizard> wizard = new CodeImportingWizard();
wizard->setupPages();
wizard->exec();
delete wizard;
}
/**
* Class wizard menu selection.
*/
void UMLApp::slotClassWizard()
{
QPointer<ClassWizard> dlg = new ClassWizard(m_doc);
dlg->exec();
delete dlg;
}
/**
* Calls the active code generator to add its default datatypes.
*/
void UMLApp::slotAddDefaultDatatypes()
{
m_doc->addDefaultDatatypes();
}
/**
* The displayed diagram has changed.
*/
void UMLApp::slotCurrentViewChanged()
{
UMLView *view = currentView();
if (view) {
connect(view->umlScene(), SIGNAL(sigShowGridToggled(bool)),
this, SLOT(slotShowGridToggled(bool)));
connect(view->umlScene(), SIGNAL(sigSnapToGridToggled(bool)),
this, SLOT(slotSnapToGridToggled(bool)));
}
}
/**
* The snap to grid value has been changed.
*/
void UMLApp::slotSnapToGridToggled(bool gridOn)
{
viewSnapToGrid->setChecked(gridOn);
}
/**
* The show grid value has been changed.
*/
void UMLApp::slotShowGridToggled(bool gridOn)
{
viewShowGrid->setChecked(gridOn);
}
/**
* Select all widgets on the current diagram.
*/
void UMLApp::slotSelectAll()
{
currentView()->umlScene()->selectAll();
}
/**
* Deletes selected widgets or list view items.
*/
void UMLApp::slotDeleteSelected()
{
// deleteSelectedWidget grabs DEL key as shortcut,
// which prevents routing DEL key through the regular
// key press event handler
QWidget *f = focusWidget();
if (f == m_listView) {
QWidgetAction *o = static_cast<QWidgetAction *>(sender());
if (o && o->objectName() == QStringLiteral("delete_selected")) {
m_listView->slotDeleteSelectedItems();
}
return;
}
if (currentView()) {
currentView()->umlScene()->deleteSelection();
}
else {
uWarning() << " trying to delete widgets when there is no current view (see bug 59774)";
}
}
/**
* Deletes the current diagram. Called from menu action.
*/
void UMLApp::slotDeleteDiagram()
{
m_doc->removeDiagram(currentView()->umlScene()->ID());
}
/**
* Close the current diagram. Clicked on tab close button.
* @param index widget's index to close
*/
void UMLApp::slotCloseDiagram(int index)
{
UMLView* view = (UMLView*)m_tabWidget->widget(index);
if (view) {
if (view != currentView()) {
setCurrentView(view);
}
m_tabWidget->removeTab(index);
view->umlScene()->setIsOpen(false);
}
}
/**
* Return the default code generation language as configured by KConfig.
* If the activeLanguage is not found in the KConfig then use Uml::ProgrammingLanguage::Cpp
* as the default.
*/
Uml::ProgrammingLanguage::Enum UMLApp::defaultLanguage() const
{
Settings::OptionState& optionState = Settings::optionState();
return optionState.generalState.defaultLanguage;
}
/**
* Reads the activeLanguage from the KConfig and calls updateLangSelectMenu()
*/
void UMLApp::initGenerator()
{
if (m_codegen) {
delete m_codegen;
m_codegen = nullptr;
}
Uml::ProgrammingLanguage::Enum defLanguage = defaultLanguage();
setActiveLanguage(defLanguage);
}
/**
* Updates the Menu for language selection and sets the
* active language. If no active language is found or if it is
* not one of the registered languages it tries to fall back
* to Cpp
*/
void UMLApp::updateLangSelectMenu(Uml::ProgrammingLanguage::Enum activeLanguage)
{
//m_langSelect->clear();
for (int i = 0; i <= Uml::ProgrammingLanguage::Reserved; ++i) {
m_langAct[i]->setChecked(i == activeLanguage);
}
}
/**
* Return true during shutdown, i.e. during ~UMLApp().
*/
bool UMLApp::shuttingDown()
{
return s_shuttingDown;
}
/**
* Event handler to receive key press events.
*/
void UMLApp::keyPressEvent(QKeyEvent *e)
{
switch(e->key()) {
case Qt::Key_Shift:
//m_toolsbar->setOldTool();
e->accept();
break;
default:
e->ignore();
}
}
/**
* Event handler to receive custom events.
* It handles events such as exporting all views from command line (in
* that case, it executes the exportAllViews method in the event).
*/
void UMLApp::customEvent(QEvent* e)
{
if (e->type() == CmdLineExportAllViewsEvent::eventType()) {
CmdLineExportAllViewsEvent* exportAllViewsEvent = static_cast<CmdLineExportAllViewsEvent*>(e);
exportAllViewsEvent->exportAllViews();
}
}
/**
* Helper method for handling cursor key release events (refactoring).
* TODO Move this to UMLWidgetController?
*/
void UMLApp::handleCursorKeyReleaseEvent(QKeyEvent* e)
{
// in case we have selected something in the diagram, move it by one pixel
// to the direction pointed by the cursor key
if (m_view == nullptr || !m_view->umlScene()->selectedCount() || e->modifiers() != Qt::AltModifier) {
e->ignore();
return;
}
int dx = 0;
int dy = 0;
switch (e->key()) {
case Qt::Key_Left:
dx = -1;
break;
case Qt::Key_Right:
dx = 1;
break;
case Qt::Key_Up:
dy = -1;
break;
case Qt::Key_Down:
dy = 1;
break;
default:
e->ignore();
return;
}
m_view->umlScene()->moveSelectedBy(dx, dy);
// notify about modification only at the first key release of possible sequence of auto repeat key releases,
// this reduces the slow down caused by setModified() and makes the cursor moving of widgets smoother
if (!e->isAutoRepeat()) {
m_doc->setModified();
}
e->accept();
}
/**
* Event handler for key release.
*/
void UMLApp::keyReleaseEvent(QKeyEvent *e)
{
switch(e->key()) {
case Qt::Key_Backspace:
if (!m_docWindow->isTyping()) {
m_toolsbar->setOldTool();
}
e->accept();
break;
case Qt::Key_Escape:
m_toolsbar->setDefaultTool();
e->accept();
break;
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Up:
case Qt::Key_Down:
handleCursorKeyReleaseEvent(e);
break;
default:
e->ignore();
}
}
/**
* Calls the UMLDoc method to create a new Document.
*/
void UMLApp::newDocument()
{
m_doc->newDocument();
slotUpdateViews();
}
/**
* Returns the widget used as the parent for UMLViews.
* @return The main view widget.
*/
QWidget* UMLApp::mainViewWidget() const
{
Settings::OptionState& optionState = Settings::optionState();
if (optionState.generalState.tabdiagrams) {
return m_tabWidget;
}
else {
return m_viewStack;
}
}
/**
* Create bird's view window in a dock widget.
*/
void UMLApp::createBirdView(UMLView *view)
{
if (m_birdView) {
delete m_birdView;
}
m_birdView = new BirdView(m_birdViewDock, view);
connect(m_birdView, SIGNAL(viewPositionChanged(QPointF)), this, SLOT(slotBirdViewChanged(QPointF)));
connect(m_birdViewDock, SIGNAL(sizeChanged(QSize)), m_birdView, SLOT(slotDockSizeChanged(QSize)));
}
/**
* Slot for changes of the bird view's rectangle by moving.
* @param delta change value for a move
*/
void UMLApp::slotBirdViewChanged(const QPointF& delta)
{
m_birdView->setSlotsEnabled(false);
UMLView* view = currentView();
QPointF oldCenter = view->mapToScene(view->viewport()->rect().center());
QPointF newCenter = oldCenter + delta;
view->centerOn(newCenter);
// DEBUG() << "view moved with: " << delta;
m_birdView->setSlotsEnabled(true);
}
/**
* Puts this view to the top of the viewStack, i.e. makes it
* visible to the user.
*
* @param view Pointer to the UMLView to push.
* @param updateTreeView A false value disables updating of the tree view
*/
void UMLApp::setCurrentView(UMLView* view, bool updateTreeView)
{
m_view = view;
if (view == nullptr) {
DEBUG() << "view is NULL";
docWindow()->reset();
return;
}
Settings::OptionState optionState = Settings::optionState();
if (optionState.generalState.tabdiagrams) {
int tabIndex = m_tabWidget->indexOf(view);
if ((tabIndex < 0) && (view->umlScene()->isOpen())) {
tabIndex = m_tabWidget->addTab(view, view->umlScene()->name());
m_tabWidget->setTabIcon(tabIndex, QIcon(Icon_Utils::iconSet(view->umlScene()->type())));
m_tabWidget->setTabToolTip(tabIndex, view->umlScene()->name());
}
if (!updateTreeView)
disconnect(m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabChanged(int)));
m_tabWidget->setCurrentIndex(tabIndex);
if (!updateTreeView)
connect(m_tabWidget, SIGNAL(currentChanged(int)), SLOT(slotTabChanged(int)));
}
else {
if (m_viewStack->indexOf(view) < 0) {
m_viewStack->addWidget(view);
}
m_viewStack->setCurrentWidget(view);
view->show();
}
setZoom(view->zoom());
slotStatusMsg(view->umlScene()->name());
if (updateTreeView) {
UMLListViewItem* lvitem = m_listView->findView(view);
if (lvitem) {
m_listView->setCurrentItem(lvitem);
}
}
DEBUG() << "Changed view to" << view->umlScene();
createBirdView(view);
}
/**
* Get the current view.
* This may return a null pointer (when no view was previously
* specified.)
*/
UMLView* UMLApp::currentView() const
{
return m_view;
}
/**
* Sets the default mime type for all diagrams that are exported as images.
* @param mimeType the mime type
*/
void UMLApp::setImageMimeType(const QString& mimeType)
{
m_imageMimeType = mimeType;
}
/**
* Gets the default mime type for all diagrams that are exported as
* images.
* @return The default MIME type for images.
*/
QString UMLApp::imageMimeType() const
{
return m_imageMimeType;
}
/**
* Called when the tab has changed.
* @param index the index of the changed tab widget
*/
void UMLApp::slotTabChanged(int index)
{
UMLView* view = (UMLView*)m_tabWidget->widget(index);
if (view && !m_doc->closing() && !s_shuttingDown) {
m_doc->changeCurrentView(view->umlScene()->ID());
}
}
/**
* Make the tab on the left of the current one the active one.
*/
void UMLApp::slotChangeTabLeft()
{
//DEBUG() << "currentIndex = " << m_tabWidget->currentIndex() << " of " << m_tabWidget->count();
if (Settings::optionState().generalState.tabdiagrams && m_tabWidget) {
m_tabWidget->setCurrentIndex(m_tabWidget->currentIndex() - 1);
return;
}
UMLViewList views = m_doc->viewIterator();
UMLView *currView = m_view;
int viewIndex = 0;
if ((viewIndex = views.indexOf(currView)) < 0) {
uError() << "currView not found in viewlist";
return;
}
UMLView *prevView = nullptr;
if (viewIndex != 0) {
prevView = views.begin()[viewIndex -1 ];
}
if ((currView = prevView) != nullptr) {
setCurrentView(currView);
}
else {
setCurrentView(views.last());
}
}
/**
* Make the tab on the right of the current one the active one.
*/
void UMLApp::slotChangeTabRight()
{
//DEBUG() << "currentIndex = " << m_tabWidget->currentIndex() << " of " << m_tabWidget->count();
if (Settings::optionState().generalState.tabdiagrams && m_tabWidget) {
m_tabWidget->setCurrentIndex(m_tabWidget->currentIndex() + 1);
return;
}
UMLViewList views = m_doc->viewIterator();
UMLView *currView = m_view;
int viewIndex = 0;
if ((viewIndex = views.indexOf(currView)) < 0) {
uError() << "currView not found in viewlist";
return;
}
UMLView *nextView = nullptr;
if (viewIndex < views.count()-1) {
nextView = views.begin()[viewIndex + 1];
setCurrentView(nextView);
}
else
setCurrentView(views.first());
}
/* for debugging only
static void showTabTexts(KTabWidget* tabWidget)
{
QString out = QStringLiteral("tab texts ");
for (int i = 0; i < tabWidget->count(); ++i) {
out += " <" + tabWidget->tabText(i) + '>';
}
DEBUG() << out;
}
*/
/**
* Move the current tab left.
*/
void UMLApp::slotMoveTabLeft()
{
//DEBUG() << "currentIndex = " << m_tabWidget->currentIndex() << " of " << m_tabWidget->count();
//showTabTexts(m_tabWidget);
int from = m_tabWidget->currentIndex();
int to = -1;
if (from > 0) {
to = from - 1;
}
else {
to = m_tabWidget->count() - 1;
}
m_tabWidget->tabBar()->moveTab(from, to);
}
/**
* Move the current tab right.
*/
void UMLApp::slotMoveTabRight()
{
//DEBUG() << "currentIndex = " << m_tabWidget->currentIndex() << " of " << m_tabWidget->count();
//showTabTexts(m_tabWidget);
int from = m_tabWidget->currentIndex();
int to = -1;
if (from < m_tabWidget->count() - 1) {
to = from + 1;
}
else {
to = 0;
}
m_tabWidget->tabBar()->moveTab(from, to);
}
/**
* This slot deletes the current XHTML documentation generator as soon as
* this one signals that it has finished.
* @param status true if successful else false
*/
void UMLApp::slotXhtmlDocGenerationFinished(bool status)
{
if (!status) {
m_doc->writeToStatusBar(i18n("XHTML Generation failed ."));
}
delete m_xhtmlGenerator;
m_xhtmlGenerator = nullptr;
}
/**
* open file in internal editor
* @param file path to the file to open
* @param startCursor cursor position for selection start
* @param endCursor cursor position for selection end
* @return true file could be loaded
* @return false file could not be loaded
*/
bool UMLApp::slotOpenFileInEditor(const QUrl &file, int startCursor, int endCursor)
{
return m_d->openFileInEditor(file, startCursor, endCursor);
}
/**
* Return the tab widget.
*/
QTabWidget* UMLApp::tabWidget()
{
return m_tabWidget;
}
/**
* Returns the current text in the status bar.
*
* @return The text in the status bar.
*/
QString UMLApp::statusBarMsg() const
{
return m_statusBarMessage->text();
}
/**
* Removes all entries from the UndoStack and RedoStack and disables the
* undo and redo actions.
*/
void UMLApp::clearUndoStack()
{
if (m_pUndoStack)
m_pUndoStack->clear();
}
/**
* Undo last command. Is called from popupmenu of a view.
*/
void UMLApp::undo()
{
if (!m_pUndoStack)
return;
if (!isUndoEnabled())
return;
DEBUG() << m_pUndoStack->undoText() << " [" << m_pUndoStack->count() << "]";
m_pUndoStack->undo();
if (m_pUndoStack->canUndo()) {
UMLApp::app()->enableUndoAction(true);
}
else {
UMLApp::app()->enableUndoAction(false);
}
UMLApp::app()->enableRedoAction(true);
}
/**
* Redo last 'undone' command. Is called from popupmenu of a view.
*/
void UMLApp::redo()
{
if (!m_pUndoStack)
return;
if (!isUndoEnabled())
return;
DEBUG() << m_pUndoStack->redoText() << " [" << m_pUndoStack->count() << "]";
m_pUndoStack->redo();
if (m_pUndoStack->canRedo()) {
UMLApp::app()->enableRedoAction(true);
}
else {
UMLApp::app()->enableRedoAction(false);
}
UMLApp::app()->enableUndoAction(true);
}
/**
* Execute a command and push it on the undo stack.
*/
void UMLApp::executeCommand(QUndoCommand* cmd)
{
if (!m_pUndoStack)
return;
if (cmd == nullptr)
return;
if (isUndoEnabled()) {
m_pUndoStack->push(cmd);
DEBUG() << cmd->text() << " [" << m_pUndoStack->count() << "]";
UMLApp::app()->enableUndoAction(true);
} else {
cmd->redo();
delete cmd;
}
m_doc->setModified(true);
}
/**
* Begin a U/R command macro
*/
void UMLApp::beginMacro(const QString & text)
{
if (!m_pUndoStack)
return;
if (!isUndoEnabled()) {
return;
}
if (m_hasBegunMacro) {
return;
}
m_hasBegunMacro = true;
m_pUndoStack->beginMacro(text);
}
/**
* End an U/R command macro
*/
void UMLApp::endMacro()
{
if (!m_pUndoStack)
return;
if (!isUndoEnabled()) {
return;
}
if (m_hasBegunMacro) {
m_pUndoStack->endMacro();
}
m_hasBegunMacro = false;
}
/**
* Return the config data.
*/
KConfig* UMLApp::config()
{
return m_config.data();
}
| 108,844
|
C++
|
.cpp
| 3,062
| 31.080013
| 147
| 0.69179
|
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,242
|
toolbarstateother.cpp
|
KDE_umbrello/umbrello/toolbarstateother.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstateother.h"
// app includes
#include "activitywidget.h"
#include "boxwidget.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "regionwidget.h"
#include "floatingtextwidget.h"
#include "forkjoinwidget.h"
#include "notewidget.h"
#include "object_factory.h"
#include "preconditionwidget.h"
#include "combinedfragmentwidget.h"
#include "statewidget.h"
#include "signalwidget.h"
#include "uml.h"
#include "umlview.h"
#include "umldoc.h"
#include "objectwidget.h"
#include "objectnodewidget.h"
#include "pinwidget.h"
#include "umlscene.h"
#include "widget_utils.h"
// kde includes
#include <KLocalizedString>
using namespace Uml;
/**
* Creates a new ToolBarStateOther.
* @param umlScene The UMLScene to use.
*/
ToolBarStateOther::ToolBarStateOther(UMLScene *umlScene)
: ToolBarStatePool(umlScene)
{
}
/**
* Destroys this ToolBarStateOther.
*/
ToolBarStateOther::~ToolBarStateOther()
{
}
/**
* Overridden from base class to ignore associations and widgets and treat
* them as empty spaces to create widgets on it.
* Sets nothing.
*/
void ToolBarStateOther::setCurrentElement()
{
}
/**
* Called when the release event happened on an empty space.
* Associations, widgets and actual empty spaces are all treated as empty
* spaces. It creates a new widget if the left button was released.
* The widget to create depends on the type of the toolbar button selected.
* If the widget is the visual representation of a UMLObject, the object
* factory handles its creation. Otherwise, the widget is created using
* newWidget().
*/
void ToolBarStateOther::mouseReleaseEmpty()
{
if (m_pMouseEvent->button() == Qt::LeftButton) {
if (!newWidget()) {
// Is UMLObject?
m_pUMLScene->setCreateObject(true);
Object_Factory::createUMLObject(getObjectType());
}
}
}
/**
* Returns the object type of this tool.
* @return The object type of this tool.
*/
UMLObject::ObjectType ToolBarStateOther::getObjectType() const
{
UMLObject::ObjectType ot;
switch(getButton()) {
case WorkToolBar::tbb_Actor:
ot = UMLObject::ot_Actor;
break;
case WorkToolBar::tbb_UseCase:
ot = UMLObject::ot_UseCase;
break;
case WorkToolBar::tbb_Class:
ot = UMLObject::ot_Class;
break;
case WorkToolBar::tbb_Object:
ot = UMLObject::ot_Class;
break; // Object is a class.
case WorkToolBar::tbb_Package:
ot = UMLObject::ot_Package;
break;
case WorkToolBar::tbb_Component:
ot = UMLObject::ot_Component;
break;
case WorkToolBar::tbb_Node:
ot = UMLObject::ot_Node;
break;
case WorkToolBar::tbb_Artifact:
ot = UMLObject::ot_Artifact;
break;
case WorkToolBar::tbb_Interface:
ot = UMLObject::ot_Interface;
break;
case WorkToolBar::tbb_Interface_Provider:
ot = UMLObject::ot_Interface;
break;
case WorkToolBar::tbb_Enum:
ot = UMLObject::ot_Enum;
break;
case WorkToolBar::tbb_Entity:
ot = UMLObject::ot_Entity;
break;
case WorkToolBar::tbb_Datatype:
ot = UMLObject::ot_Datatype;
break;
case WorkToolBar::tbb_Category:
ot = UMLObject::ot_Category;
break;
case WorkToolBar::tbb_Instance:
ot = UMLObject::ot_Instance;
break;
case WorkToolBar::tbb_SubSystem:
ot = UMLObject::ot_SubSystem;
break;
default:
ot = UMLObject::ot_UMLObject;
break;
}
return ot;
}
/**
* Creates and adds a new widget to the UMLView (if widgets of that type
* don't have an associated UMLObject).
* If the type of the widget doesn't use an UMLObject (for example, a note
* or a box), it creates the widget, adds it to the view and returns true.
* Otherwise, it returns false.
*
* @return True if the widget was created, false otherwise.
* @todo Rename to something more clear. The name is a bit confusing.
*/
bool ToolBarStateOther::newWidget()
{
UMLWidget *umlWidget = nullptr;
switch (getButton()) {
case WorkToolBar::tbb_Note:
umlWidget = new NoteWidget(m_pUMLScene, NoteWidget::Normal);
break;
case WorkToolBar::tbb_Box:
umlWidget = new BoxWidget(m_pUMLScene);
break;
case WorkToolBar::tbb_Text:
umlWidget = new FloatingTextWidget(m_pUMLScene, Uml::TextRole::Floating, QString());
break;
// Activity buttons
case WorkToolBar::tbb_Initial_Activity:
umlWidget = new ActivityWidget(m_pUMLScene, ActivityWidget::Initial);
break;
case WorkToolBar::tbb_Activity:
umlWidget = new ActivityWidget(m_pUMLScene, ActivityWidget::Normal);
break;
case WorkToolBar::tbb_End_Activity:
umlWidget = new ActivityWidget(m_pUMLScene, ActivityWidget::End);
break;
case WorkToolBar::tbb_Final_Activity:
umlWidget = new ActivityWidget(m_pUMLScene, ActivityWidget::Final);
break;
case WorkToolBar::tbb_Branch:
umlWidget = new ActivityWidget(m_pUMLScene, ActivityWidget::Branch);
break;
case WorkToolBar::tbb_Fork:
umlWidget = new ForkJoinWidget(m_pUMLScene);
break;
case WorkToolBar::tbb_Initial_State:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::Initial);
break;
case WorkToolBar::tbb_State:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::Normal);
break;
case WorkToolBar::tbb_End_State:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::End);
break;
case WorkToolBar::tbb_StateFork:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::Fork);
break;
case WorkToolBar::tbb_StateJoin:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::Join);
break;
case WorkToolBar::tbb_Junction:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::Junction);
break;
case WorkToolBar::tbb_DeepHistory:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::DeepHistory);
break;
case WorkToolBar::tbb_ShallowHistory:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::ShallowHistory);
break;
case WorkToolBar::tbb_Choice:
umlWidget = new StateWidget(m_pUMLScene, StateWidget::Choice);
break;
case WorkToolBar::tbb_Send_Signal:
umlWidget = new SignalWidget(m_pUMLScene, SignalWidget::Send);
break;
case WorkToolBar::tbb_Accept_Signal:
umlWidget = new SignalWidget(m_pUMLScene, SignalWidget::Accept);
break;
case WorkToolBar::tbb_Accept_Time_Event:
umlWidget = new SignalWidget(m_pUMLScene, SignalWidget::Time);
break;
case WorkToolBar::tbb_Region:
umlWidget = new RegionWidget(m_pUMLScene);
break;
case WorkToolBar::tbb_Seq_Combined_Fragment:
umlWidget = new CombinedFragmentWidget(m_pUMLScene);
break;
case WorkToolBar::tbb_Object_Node:
umlWidget = new ObjectNodeWidget(m_pUMLScene, ObjectNodeWidget::Data);
break;
case WorkToolBar::tbb_PrePostCondition:
umlWidget = new NoteWidget(m_pUMLScene, NoteWidget::Normal);
break;
default:
break;
}
// Return false if we didn't find a suitable widget.
if (umlWidget == nullptr) {
return false;
}
// Special treatment for some buttons
switch (getButton()) {
case WorkToolBar::tbb_Activity:
{
Dialog_Utils::askNameForWidget(
umlWidget, i18n("Enter Activity Name"),
i18n("Enter the name of the new activity:"), i18n("new activity"));
}
break;
case WorkToolBar::tbb_Accept_Signal:
case WorkToolBar::tbb_Send_Signal:
{
Dialog_Utils::askNameForWidget(
umlWidget, i18n("Enter Signal Name"),
i18n("Enter Signal"), i18n("new Signal"));
}
break;
case WorkToolBar::tbb_Accept_Time_Event:
{
Dialog_Utils::askNameForWidget(
umlWidget, i18n("Enter Time Event Name"),
i18n("Enter Time Event"), i18n("new time event"));
}
break;
case WorkToolBar::tbb_Seq_Combined_Fragment:
{
umlWidget->asCombinedFragmentWidget()->askNameForWidgetType(
umlWidget, i18n("Enter Combined Fragment Name"),
i18n("Enter the Combined Fragment"), i18n("new Combined Fragment"));
}
break;
case WorkToolBar::tbb_State:
{
Dialog_Utils::askNameForWidget(
umlWidget, i18n("Enter State Name"),
i18n("Enter the name of the new state:"), i18n("new state"));
}
break;
case WorkToolBar::tbb_Text:
{
// It is pretty invisible otherwise.
FloatingTextWidget* ft = (FloatingTextWidget*) umlWidget;
ft->showChangeTextDialog();
}
break;
case WorkToolBar::tbb_Object_Node:
{
umlWidget->asObjectNodeWidget()->askForObjectNodeType(umlWidget);
}
break;
case WorkToolBar::tbb_PrePostCondition:
{
umlWidget->asNoteWidget()->askForNoteType(umlWidget);
}
break;
case WorkToolBar::tbb_Note:
{
umlWidget->showPropertiesDialog();
}
break;
default:
logWarn1("ToolBarStateOther::newWidget unknown ToolBar_Buttons: %1",
QLatin1String(ENUM_NAME(WorkToolBar, WorkToolBar::ToolBar_Buttons, getButton())));
break;
}
// Create the widget. Some setup functions can remove the widget.
if (umlWidget != nullptr) {
m_pUMLScene->setupNewWidget(umlWidget);
}
return true;
}
| 10,293
|
C++
|
.cpp
| 302
| 26.529801
| 99
| 0.640732
|
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,243
|
toolbarstatefactory.cpp
|
KDE_umbrello/umbrello/toolbarstatefactory.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "toolbarstatefactory.h"
#include "toolbarstate.h"
#include "toolbarstatepool.h"
#include "toolbarstateother.h"
#include "toolbarstatearrow.h"
#include "toolbarstatemessages.h"
#include "toolbarstateassociation.h"
#include "toolbarstateonewidget.h"
#include "umlview.h"
ToolBarStateFactory::ToolBarStateFactory()
{
for (int i = 0; i < NR_OF_TOOLBAR_STATES; ++i)
{
m_states[i] = nullptr;
}
}
ToolBarStateFactory::~ToolBarStateFactory()
{
for (int i = 0; i < NR_OF_TOOLBAR_STATES; ++i)
{
if (m_states[i])
delete m_states[i];
}
}
ToolBarState* ToolBarStateFactory::getState(const WorkToolBar::ToolBar_Buttons &toolbarButton, UMLScene *umlScene)
{
int key = getKey(toolbarButton);
if (m_states[key] == nullptr)
{
switch (key)
{
// When you add a new state, make sure you also increase the
// NR_OF_TOOLBAR_STATES
case 0: m_states[0] = new ToolBarStateOther(umlScene); break;
case 1: m_states[1] = new ToolBarStateAssociation(umlScene); break;
case 2: m_states[2] = new ToolBarStateMessages(umlScene); break;
// This case has no pool.
case 3: m_states[3] = new ToolBarStateArrow(umlScene); break;
case 4: m_states[4] = new ToolBarStateOneWidget(umlScene); break;
}
}
// Make explicit the selected button. This is only necessary for states with a pool.
if (key != 3) ((ToolBarStatePool*) m_states[key].data())->setButton(toolbarButton);
return m_states[key];
}
int ToolBarStateFactory::getKey(const WorkToolBar::ToolBar_Buttons &toolbarButton) const
{
switch (toolbarButton)
{
// Associations
case WorkToolBar::tbb_Dependency: return 1;
case WorkToolBar::tbb_Aggregation: return 1;
case WorkToolBar::tbb_Relationship: return 1;
case WorkToolBar::tbb_Generalization: return 1;
case WorkToolBar::tbb_Association: return 1;
case WorkToolBar::tbb_UniAssociation: return 1;
case WorkToolBar::tbb_Composition: return 1;
case WorkToolBar::tbb_Containment: return 1;
case WorkToolBar::tbb_Anchor: return 1;
case WorkToolBar::tbb_Coll_Mesg_Sync: return 1;
case WorkToolBar::tbb_Coll_Mesg_Async: return 1;
case WorkToolBar::tbb_State_Transition: return 1;
case WorkToolBar::tbb_Activity_Transition: return 1;
case WorkToolBar::tbb_Exception: return 1;
case WorkToolBar::tbb_Category2Parent: return 1;
case WorkToolBar::tbb_Child2Category: return 1;
// Messages
case WorkToolBar::tbb_Seq_Message_Creation: return 2;
case WorkToolBar::tbb_Seq_Message_Destroy: return 2;
case WorkToolBar::tbb_Seq_Message_Synchronous: return 2;
case WorkToolBar::tbb_Seq_Message_Asynchronous: return 2;
case WorkToolBar::tbb_Seq_Message_Found: return 2;
case WorkToolBar::tbb_Seq_Message_Lost: return 2;
case WorkToolBar::tbb_Seq_Precondition: return 4;
case WorkToolBar::tbb_Pin: return 4;
case WorkToolBar::tbb_Port: return 4;
// Arrow pointer
case WorkToolBar::tbb_Arrow: return 3;
// Other.
default: return 0;
}
}
| 3,579
|
C++
|
.cpp
| 86
| 36.465116
| 114
| 0.644131
|
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,244
|
toolbarstatemessages.cpp
|
KDE_umbrello/umbrello/toolbarstatemessages.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstatemessages.h"
// local includes
#include "cmds.h"
#include "debug_utils.h"
#include "floatingtextwidget.h"
#include "messagewidget.h"
#include "objectwidget.h"
#include "object_factory.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
#include "umlscene.h"
#include "widget_factory.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
DEBUG_REGISTER(ToolBarStateMessages)
/**
* Creates a new ToolBarStateMessages.
*
* @param umlScene The UMLScene to use.
*/
ToolBarStateMessages::ToolBarStateMessages(UMLScene *umlScene)
: ToolBarStatePool(umlScene),
m_firstObject(nullptr),
m_messageLine(nullptr),
m_isObjectWidgetLine(false),
xclick(0),
yclick(0)
{
}
/**
* Destroys this ToolBarStateMessages.
*/
ToolBarStateMessages::~ToolBarStateMessages()
{
cleanMessage();
}
/**
* Goes back to the initial state.
*/
void ToolBarStateMessages::init()
{
ToolBarStatePool::init();
cleanMessage();
}
/**
* Called when the current tool is changed to use another tool.
* Executes base method and cleans the message.
*/
void ToolBarStateMessages::cleanBeforeChange()
{
ToolBarStatePool::cleanBeforeChange();
cleanMessage();
}
/**
* Called when a mouse event happened.
* It executes the base method and then updates the position of the
* message line, if any.
*/
void ToolBarStateMessages::mouseMove(QGraphicsSceneMouseEvent* ome)
{
ToolBarStatePool::mouseMove(ome);
if (m_messageLine) {
QPointF sp = m_messageLine->line().p1();
m_messageLine->setLine(sp.x(), sp.y(), m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y());
}
}
/**
* 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 ToolBarStateMessages::slotWidgetRemoved(UMLWidget* widget)
{
ToolBarState::slotWidgetRemoved(widget);
if (widget == m_firstObject) {
cleanMessage();
}
}
/**
* 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 ToolBarStateMessages::setCurrentElement()
{
m_isObjectWidgetLine = false;
ObjectWidget* objectWidgetLine = m_pUMLScene->onWidgetLine(m_pMouseEvent->scenePos());
const QString funcInfo(QString::fromLatin1(Q_FUNC_INFO));
if (objectWidgetLine) {
logDebug1("ToolBarStateMessages::setCurrentElement %1 Object detected", funcInfo);
setCurrentWidget(objectWidgetLine);
m_isObjectWidgetLine = true;
return;
}
logDebug1("ToolBarStateMessages::setCurrentElement %1 Object NOT detected", funcInfo);
//commit 515177 fixed a setting creation messages only working properly at 100% zoom
//However, the applied patch doesn't seem to be necessary no more, so it was removed
//The widgets weren't got from UMLView, but from a method in this class similarto the
//one in UMLView but containing special code to handle the zoom
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 ToolBarStateMessages::mouseReleaseWidget()
{
//TODO When an association between UMLObjects of invalid types is made, an error message
//is shown. Shouldn't also a message be used here?
if (m_pMouseEvent->button() != Qt::LeftButton ||
!currentWidget()->isObjectWidget()) {
cleanMessage();
return;
}
if (!m_isObjectWidgetLine && !m_firstObject) {
return;
}
if (!m_isObjectWidgetLine) {
setSecondWidget(static_cast<ObjectWidget*>(currentWidget()), CreationMessage);
return;
}
if (!m_firstObject) {
setFirstWidget(static_cast<ObjectWidget*>(currentWidget()));
} else {
setSecondWidget(static_cast<ObjectWidget*>(currentWidget()), NormalMessage);
}
}
/**
* 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 ToolBarStateMessages::mouseReleaseEmpty()
{
Uml::SequenceMessage::Enum msgType = getMessageType();
if (m_firstObject && msgType == Uml::SequenceMessage::Creation) {
xclick = m_pMouseEvent->scenePos().x();
yclick = m_pMouseEvent->scenePos().y();
bool state = m_pUMLScene->getCreateObject();
m_pUMLScene->setCreateObject(false);
UMLObject *object = Object_Factory::createUMLObject(UMLObject::ot_Class);
m_pUMLScene->setCreateObject(state);
if (object) {
ObjectWidget *widget = (ObjectWidget *)Widget_Factory::createWidget(m_pUMLScene, object);
widget->setX(xclick);
widget->activate();
m_pUMLScene->addWidgetCmd(widget);
MessageWidget* message = new MessageWidget(m_pUMLScene, m_firstObject, widget, yclick, msgType);
setupMessageWidget(message, false);
}
cleanMessage();
xclick = 0;
yclick = 0;
} else if (m_firstObject && msgType == Uml::SequenceMessage::Lost) {
xclick = m_pMouseEvent->scenePos().x();
yclick = m_pMouseEvent->scenePos().y();
MessageWidget* message = new MessageWidget(m_pUMLScene, m_firstObject, xclick, yclick, msgType);
setupMessageWidget(message);
cleanMessage();
xclick = 0;
yclick = 0;
}
else if (!m_firstObject && msgType == Uml::SequenceMessage::Found && xclick == 0 && yclick == 0) {
xclick = m_pMouseEvent->scenePos().x();
yclick = m_pMouseEvent->scenePos().y();
cleanMessage();
m_messageLine = new QGraphicsLineItem();
m_pUMLScene->addItem(m_messageLine);
qreal x = m_pMouseEvent->scenePos().x();
qreal y = m_pMouseEvent->scenePos().y();
m_messageLine->setLine(x, y, x, y);
m_messageLine->setPen(QPen(m_pUMLScene->lineColor(), m_pUMLScene->lineWidth(), Qt::DashLine));
m_messageLine->setVisible(true);
m_pUMLScene->activeView()->viewport()->setMouseTracking(true);
}
else {
cleanMessage();
}
}
/**
* 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 ToolBarStateMessages::setFirstWidget(ObjectWidget* firstObject)
{
m_firstObject = firstObject;
Uml::SequenceMessage::Enum msgType = getMessageType();
if (msgType == Uml::SequenceMessage::Found && xclick!=0 && yclick!=0) {
MessageWidget* message = new MessageWidget(m_pUMLScene, m_firstObject, xclick, yclick, msgType);
setupMessageWidget(message);
cleanMessage();
xclick = 0;
yclick = 0;
}
else {
// TODO use cleanMessage()
if (m_messageLine)
delete m_messageLine;
m_messageLine = new QGraphicsLineItem();
m_pUMLScene->addItem(m_messageLine);
qreal x = m_pMouseEvent->scenePos().x();
qreal y = m_pMouseEvent->scenePos().y();
m_messageLine->setLine(x, y, x, y);
m_messageLine->setPen(QPen(m_pUMLScene->lineColor(), m_pUMLScene->lineWidth(), Qt::DashLine));
m_messageLine->setVisible(true);
m_pUMLScene->activeView()->viewport()->setMouseTracking(true);
}
}
/**
* Sets the second object of the message using the specified widget and
* creates the message.
* The association is created and added to the view. The dialog to select
* the operation of the message is shown.
*
* @param secondObject The second object of the message.
* @param messageType The type of the message to create.
*/
void ToolBarStateMessages::setSecondWidget(ObjectWidget* secondObject, MessageType messageType)
{
Uml::SequenceMessage::Enum msgType = getMessageType();
//There shouldn't be second widget for a lost or a found message
if (msgType == Uml::SequenceMessage::Lost || msgType == Uml::SequenceMessage::Found) {
cleanMessage();
xclick = 0;
yclick = 0;
return;
}
qreal y = m_messageLine->line().p1().y();
if (messageType == CreationMessage) {
msgType = Uml::SequenceMessage::Creation;
}
MessageWidget* message = new MessageWidget(m_pUMLScene, m_firstObject,
secondObject, y, msgType);
setupMessageWidget(message);
cleanMessage();
}
/**
* Returns the message type of this tool.
*
* @return The message type of this tool.
*/
Uml::SequenceMessage::Enum ToolBarStateMessages::getMessageType()
{
if (getButton() == WorkToolBar::tbb_Seq_Message_Creation) {
return Uml::SequenceMessage::Creation;
}
else if (getButton() == WorkToolBar::tbb_Seq_Message_Destroy) {
return Uml::SequenceMessage::Destroy;
}
else if (getButton() == WorkToolBar::tbb_Seq_Message_Synchronous) {
return Uml::SequenceMessage::Synchronous;
}
else if (getButton() == WorkToolBar::tbb_Seq_Message_Found) {
return Uml::SequenceMessage::Found;
}
else if (getButton() == WorkToolBar::tbb_Seq_Message_Lost) {
return Uml::SequenceMessage::Lost;
}
return Uml::SequenceMessage::Asynchronous;
}
/**
* Cleans the first widget and the temporary message line, if any.
* Both are set to null, and the message line is also deleted.
*/
void ToolBarStateMessages::cleanMessage()
{
m_firstObject = nullptr;
if (m_messageLine) {
delete m_messageLine;
m_messageLine = nullptr;
}
}
void ToolBarStateMessages::setupMessageWidget(MessageWidget *message, bool showOperationDialog)
{
if (showOperationDialog) {
FloatingTextWidget *ft = message->floatingTextWidget();
//TODO cancel doesn't cancel the creation of the message, only cancels setting an operation.
//Shouldn't it cancel also the whole creation?
if (message->sequenceMessageType() == Uml::SequenceMessage::Destroy) {
message->setOperationText(i18n("destroy"));
} else {
ft->showOperationDialog();
m_pUMLScene->addWidgetCmd(ft);
}
message->setTextPosition();
}
UMLApp::app()->executeCommand(new Uml::CmdCreateWidget(message));
Q_EMIT finished();
}
| 11,240
|
C++
|
.cpp
| 313
| 30.884984
| 109
| 0.688493
|
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,245
|
birdview.cpp
|
KDE_umbrello/umbrello/birdview.cpp
|
/*
SPDX-FileCopyrightText: 2014 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "birdview.h"
#include "debug_utils.h"
#include "uml.h"
#include "umlscene.h"
#include "umlview.h"
#include <QDockWidget>
#include <QGraphicsView>
#include <QMouseEvent>
#include <QScrollBar>
#include <QTimer>
// Currently this file is not using debug statements. Activate this line when inserting them:
//DEBUG_REGISTER_DISABLED(BirdView)
#define VERBOSE_DBG_OUT 0
/**
* @brief Constructor.
* @param parent the dock widget where the bird view is loaded
* @param view the view to show
*/
BirdView::BirdView(QDockWidget *parent, UMLView* view)
: QFrame(),
m_view(view)
{
// create view and add it to the container frame
UMLScene* scene = m_view->umlScene();
m_birdView = new QGraphicsView(scene);
m_birdView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_birdView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_birdView->setFrameStyle(QFrame::Box); //:TODO: remove this line - only for debugging
// create a frame on top of the view to hide it from the mouse
m_protectFrame = new QFrame(m_birdView);
m_protectFrame->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
setBackgroundColor(m_protectFrame, QColor(255, 255, 220, 0));
// draw window frame in the size of shown scene
setParent(m_birdView);
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
setLineWidth(1);
setMidLineWidth(2);
setFrameStyle(Box | Raised);
setBackgroundColor(this, QColor(115, 205, 240, 100));
setFocusPolicy(Qt::StrongFocus); // enable key press event
slotDockSizeChanged(parent->rect().size());
setSlotsEnabled(true);
parent->setWidget(m_birdView); // must be the last command
connect(m_view, SIGNAL(destroyed(QObject*)), this, SLOT(slotDestroyed(QObject*)));
slotViewChanged();
}
/**
* Destructor.
*/
BirdView::~BirdView()
{
disconnect(m_view, SIGNAL(destroyed(QObject*)), this, SLOT(slotDestroyed(QObject*)));
setParent(nullptr);
delete m_protectFrame;
delete m_birdView;
}
/**
* Handle destroyed view.
*/
void BirdView::slotDestroyed(QObject *object)
{
if (m_view == object) {
m_birdView->setScene(nullptr);
m_view = nullptr;
}
}
/**
* Event handler for size changed events of the dock window.
* @param size new size to which the dock window was resized
*
*/
void BirdView::slotDockSizeChanged(const QSize& size)
{
if (!m_view)
return;
QRectF itemsRect = m_birdView->scene()->itemsBoundingRect();
m_birdView->setSceneRect(itemsRect);
m_birdView->fitInView(itemsRect, Qt::KeepAspectRatio);
QRect frameRect = QRect(0, 0, size.width(), size.height());
m_protectFrame->setGeometry(frameRect);
qreal scaleW = frameRect.width() / m_birdView->scene()->width();
qreal scaleH = frameRect.height() / m_birdView->scene()->height();
qreal scale = scaleH;
if (scaleW < scaleH) {
scale = scaleW;
}
QTransform wm;
wm.scale(scale, scale);
m_birdView->setTransform(wm);
#if VERBOSE_DBG_OUT
DEBUG() << "setting the size to the scene: " << itemsRect
<< " / to the frame: " << frameRect
<< " / scaleW: " << scaleW << " / scaleH: " << scaleH << " / scale: " << scale;
#endif
QTimer::singleShot(0, this, SLOT(slotViewChanged()));
}
/**
* Event handler for view changed events of the graphics view.
* This is done by changing the scroll bars.
*/
void BirdView::slotViewChanged()
{
if (!m_view) {
return;
}
QRectF r = m_view->mapToScene(m_view->viewport()->rect()).boundingRect();
QRect v = m_birdView->mapFromScene(r).boundingRect();
setGeometry(v);
}
/**
* Event handler for mouse press events.
* Keep the start position for later.
* @param event mouse event
*/
void BirdView::mousePressEvent(QMouseEvent *event)
{
m_moveStartPos = event->globalPos();
}
/**
* Event handler for mouse move events.
* Move the frame which represents the viewable window to a new position.
* Move is only done inside the container.
* @param event mouse event
*/
void BirdView::mouseMoveEvent(QMouseEvent *event)
{
const QPoint delta = m_view->mapFromGlobal(event->globalPos()) - m_view->mapFromGlobal(m_moveStartPos);
QSizeF scale(m_view->viewport()->rect().width() / rect().width(), m_view->viewport()->rect().height() / rect().height());
QPoint scaledDelta(delta.x() * scale.width(), delta.y() * scale.height());
QPointF oldCenter = m_view->mapToScene(m_view->viewport()->rect().center());
QPointF newCenter = m_view->mapToScene(m_view->viewport()->rect().center() + scaledDelta);
Q_EMIT viewPositionChanged(newCenter - oldCenter);
slotViewChanged();
m_moveStartPos = event->globalPos();
}
/**
* Event handler for mouse release events.
* @param event mouse event
*/
void BirdView::mouseReleaseEvent(QMouseEvent *event)
{
mouseMoveEvent(event);
}
/**
* Event handler for key press events.
* @param event key press event
*/
void BirdView::keyPressEvent(QKeyEvent *event)
{
const int STEP = 10;
QPoint point = pos();
m_moveStartPos = mapToGlobal(point);
QString key;
bool doMove = true;
QPoint newPoint;
switch (event->key()) {
case Qt::Key_Left:
key = QStringLiteral("LEFT");
newPoint = QPoint(point.x() - STEP, point.y());
break;
case Qt::Key_Right:
key = QStringLiteral("RIGHT");
newPoint = QPoint(point.x() + STEP, point.y());
break;
case Qt::Key_Up:
key = QStringLiteral("UP");
newPoint = QPoint(point.x(), point.y() - STEP);
break;
case Qt::Key_Down:
key = QStringLiteral("DOWN");
newPoint = QPoint(point.x(), point.y() + STEP);
break;
default:
QFrame::keyPressEvent(event);
doMove = false;
break;
}
if (doMove) {
event->accept();
#if VERBOSE_DBG_OUT
DEBUG() << key << " pressed. start=" << m_moveStartPos << ", " << point << " / new=" << newPoint;
#endif
QMouseEvent* e = new QMouseEvent(QEvent::MouseMove, newPoint, mapToGlobal(newPoint),
Qt::NoButton, Qt::NoButton, Qt::NoModifier);
mouseMoveEvent(e);
}
}
/**
* Enable or disable the value changed slots of the scroll bars of the view.
* @param enabled flag whether to enable or disable the slots
*
*/
void BirdView::setSlotsEnabled(bool enabled)
{
UMLView* view = UMLApp::app()->currentView();
if (enabled) {
connect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
this, SLOT(slotViewChanged()));
connect(view->horizontalScrollBar(), SIGNAL(valueChanged(int)),
this, SLOT(slotViewChanged()));
}
else {
disconnect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
this, SLOT(slotViewChanged()));
disconnect(view->horizontalScrollBar(), SIGNAL(valueChanged(int)),
this, SLOT(slotViewChanged()));
}
}
/**
* Method to set the background color of a frame to a new color.
* @param frame frame where the new color has to be set
* @param color new color, which has to be set to the frame
*/
void BirdView::setBackgroundColor(QFrame *frame, const QColor& color)
{
QPalette newPalette = frame->palette();
newPalette.setColor(frame->backgroundRole(), color);
frame->setPalette(newPalette);
frame->setAutoFillBackground(true);
}
//------------------------------------------------------------------------------
/**
* Constructor.
*/
BirdViewDockWidget::BirdViewDockWidget(const QString& title, QWidget* parent, Qt::WindowFlags flags)
: QDockWidget(title, parent, flags)
{
}
/**
* Handle resize event of the dock widget.
* Emits size changed signal.
*/
void BirdViewDockWidget::resizeEvent(QResizeEvent *event)
{
Q_EMIT sizeChanged(event->size());
}
| 8,086
|
C++
|
.cpp
| 240
| 29.366667
| 125
| 0.667775
|
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,246
|
layoutgenerator.cpp
|
KDE_umbrello/umbrello/layoutgenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "layoutgenerator.h"
#include "associationline.h"
#include "associationwidget.h"
#include "cmds.h"
#define DBG_SRC QStringLiteral("LayoutGenerator")
#include "debug_utils.h"
#include "floatingtextwidget.h"
#include "uml.h"
#include "umlwidget.h"
// kde includes
#include <KConfigGroup>
#include <KDesktopFile>
#include <KLocalizedString>
// qt includes
#include <QDir>
#include <QFile>
#include <QHash>
#include <QProcess>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QString>
#include <QTemporaryFile>
//#include <QTextStream>
//#define USE_XDOT
//#define START_PNGVIEWER
#define LAYOUTGENERATOR_DEBUG
//#define LAYOUTGENERATOR_DATA_DEBUG
//#define SHOW_CONTROLPOINTS
#ifdef LAYOUTGENERATOR_DEBUG
static QString pngViewer()
{
#ifdef Q_OS_WIN
return QStringLiteral("start");
#else
#ifdef Q_OS_MAC
return QStringLiteral("unknown");
#else
return QStringLiteral("okular");
#endif
#endif
}
static QString textViewer()
{
#ifdef Q_OS_WIN
return QStringLiteral("start");
#else
#ifdef Q_OS_MAC
return QStringLiteral("unknown");
#else
return QStringLiteral("mcedit");
#endif
#endif
}
#endif
#ifdef SHOW_CONTROLPOINTS
static QGraphicsPathItem *s_debugItems;
static QPainterPath s_path;
#endif
// Currently this file is not using debug statements. Activate this line when inserting them:
//DEBUG_REGISTER(LayoutGenerator)
/**
* constructor
*/
LayoutGenerator::LayoutGenerator()
{
setUseFullNodeLabels(false);
}
/**
* Return state if layout generator is enabled.
* It is enabled when the dot application has been found.
*
* @return true if enabled
*/
bool LayoutGenerator::isEnabled() const
{
return !m_dotPath.isEmpty();
}
/**
* generate layout and apply it to the given diagram.
*
* @return true if generating succeeded
*/
bool LayoutGenerator::generate(UMLScene *scene, const QString &variant)
{
QTemporaryFile in;
QTemporaryFile out;
QTemporaryFile xdotOut;
if (!isEnabled()) {
logWarn0("LayoutGenerator::generate: Could not apply autolayout because graphviz not found.");
return false;
}
#ifdef SHOW_CONTROLPOINTS
if (!s_debugItems) {
s_debugItems = new QGraphicsPathItem;
scene->addItem(s_debugItems);
}
s_path = QPainterPath();
s_debugItems->setPath(s_path);
#endif
#ifdef LAYOUTGENERATOR_DEBUG
in.setAutoRemove(false);
out.setAutoRemove(false);
xdotOut.setAutoRemove(false);
#endif
// generate filenames
in.open();
in.close();
out.open();
out.close();
xdotOut.open();
xdotOut.close();
#ifdef LAYOUTGENERATOR_DEBUG
qDebug() << textViewer() << in.fileName();
qDebug() << textViewer() << out.fileName();
qDebug() << textViewer() << xdotOut.fileName();
#endif
if (!createDotFile(scene, in.fileName(), variant))
return false;
QString executable = generatorFullPath();
QProcess p;
QStringList args;
args << QStringLiteral("-o") << out.fileName() << QStringLiteral("-Tplain-ext") << in.fileName();
p.start(executable, args);
p.waitForFinished();
args.clear();
args << QStringLiteral("-o") << xdotOut.fileName() << QStringLiteral("-Txdot") << in.fileName();
p.start(executable, args);
p.waitForFinished();
#ifdef LAYOUTGENERATOR_DEBUG
QTemporaryFile pngFile;
pngFile.setAutoRemove(false);
pngFile.setFileTemplate(QDir::tempPath() + QStringLiteral("/umbrello-layoutgenerator-XXXXXX.png"));
pngFile.open();
pngFile.close();
args.clear();
args << QStringLiteral("-o") << pngFile.fileName() << QStringLiteral("-Tpng") << in.fileName();
p.start(executable, args);
p.waitForFinished();
qDebug() << pngViewer() << pngFile.fileName();
#ifdef START_PNGVIEWER
args.clear();
args << pngFile.fileName();
p.startDetached(pngViewer(), args);
#endif
#endif
#ifndef USE_XDOT
if (!readGeneratedDotFile(out.fileName()))
#else
if (!readGeneratedDotFile(xdotOut.fileName()))
#endif
return false;
return true;
}
/**
* apply auto layout to the given scene
* @param scene
* @return true if autolayout has been applied
*/
bool LayoutGenerator::apply(UMLScene *scene)
{
for(AssociationWidget *assoc : scene->associationList()) {
AssociationLine& path = assoc->associationLine();
QString type = Uml::AssociationType::toString(assoc->associationType()).toLower();
QString key = QStringLiteral("type::") + type;
QString id;
if (m_edgeParameters.contains(QStringLiteral("id::") + key) && m_edgeParameters[QStringLiteral("id::") + key] == QStringLiteral("swap"))
id = fixID(Uml::ID::toString(assoc->widgetLocalIDForRole(Uml::RoleType::A)) + Uml::ID::toString(assoc->widgetLocalIDForRole(Uml::RoleType::B)));
else
id = fixID(Uml::ID::toString(assoc->widgetLocalIDForRole(Uml::RoleType::B)) + Uml::ID::toString(assoc->widgetLocalIDForRole(Uml::RoleType::A)));
// adjust associations not used in the dot file
if (!m_edges.contains(id)) {
// shorten line path
if (path.count() > 2 && assoc->widgetLocalIDForRole(Uml::RoleType::A) != assoc->widgetLocalIDForRole(Uml::RoleType::B)) {
while (path.count() > 2)
path.removePoint(1);
}
continue;
}
// set label position
QPointF &l = m_edgeLabelPosition[id];
FloatingTextWidget *tw = assoc->nameWidget();
if (tw) {
tw->setPos(mapToScene(l));
}
// setup line points
EdgePoints &p = m_edges[id];
int len = p.size();
#ifdef SHOW_CONTROLPOINTS
QPolygonF pf;
QFont f;
for (int i=0; i < len; i++) {
pf << mapToScene(p[i]);
s_path.addText(mapToScene(p[i] + QPointF(5,0)), f, QString::number(i));
}
s_path.addPolygon(pf);
s_path.addEllipse(mapToScene(l), 5, 5);
s_debugItems->setPath(s_path);
#endif
if (m_version <= 20130928) {
path.setLayout(Uml::LayoutType::Direct);
path.cleanup();
path.setEndPoints(mapToScene(p[0]), mapToScene(p[len-1]));
} else {
path.setLayout(Settings::optionState().generalState.layoutType);
path.cleanup();
if (Settings::optionState().generalState.layoutType == Uml::LayoutType::Polyline) {
for (int i = 0; i < len; i++) {
if (i > 0 && p[i] == p[i-1])
continue;
path.addPoint(mapToScene(p[i]));
}
} else if(Settings::optionState().generalState.layoutType == Uml::LayoutType::Spline) {
for (int i = 0; i < len; i++) {
path.addPoint(mapToScene(p[i]));
}
} else if (Settings::optionState().generalState.layoutType == Uml::LayoutType::Orthogonal) {
for (int i = 0; i < len; i++) {
path.addPoint(mapToScene(p[i]));
}
} else
path.setEndPoints(mapToScene(p[0]), mapToScene(p[len-1]));
}
}
UMLApp::app()->beginMacro(i18n("Apply layout"));
for(UMLWidget *widget : scene->widgetList()) {
QString id = Uml::ID::toString(widget->localID());
if (!m_nodes.contains(id))
continue;
if (widget->isPortWidget() || widget->isPinWidget())
continue;
#ifdef SHOW_CONTROLPOINTS
s_path.addRect(QRectF(mapToScene(m_nodes[id].bottomLeft()), m_nodes[id].size()));
s_path.addRect(QRectF(origin(id), m_nodes[id].size()));
s_debugItems->setPath(s_path);
#endif
QPointF p = origin(id);
widget->setStartMovePosition(widget->pos());
widget->setX(p.x());
widget->setY(p.y()-widget->height());
widget->adjustAssocs(widget->x(), widget->y()); // adjust assoc lines
UMLApp::app()->executeCommand(new Uml::CmdMoveWidget(widget));
}
UMLApp::app()->endMacro();
for(AssociationWidget *assoc : scene->associationList()) {
assoc->calculateEndingPoints();
assoc->associationLine().update();
assoc->resetTextPositions();
assoc->saveIdealTextPositions();
}
return true;
}
/**
* Return a list of available templates for a given scene type
*
* @param scene The diagram
* @param configFiles will contain the collected list of config files
* @return true if collecting succeeds
*/
bool LayoutGenerator::availableConfigFiles(UMLScene *scene, QHash<QString,QString> &configFiles)
{
QString diagramType = Uml::DiagramType::toString(scene->type()).toLower();
const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("umbrello5/layouts"), QStandardPaths::LocateDirectory);
QStringList fileNames;
for(const QString& dir : dirs) {
const QStringList entries = QDir(dir).entryList(QStringList() << QString::fromLatin1("%1*.desktop").arg(diagramType));
for(const QString& file : entries) {
fileNames.append(dir + QLatin1Char('/') + file);
}
}
for(const QString &fileName : fileNames) {
QFileInfo fi(fileName);
QString baseName;
if (fi.baseName().contains(QStringLiteral("-")))
baseName = fi.baseName().remove(diagramType + QLatin1Char('-'));
else if (fi.baseName() == diagramType)
baseName = fi.baseName();
else
baseName = QStringLiteral("default");
KDesktopFile desktopFile(fileName);
configFiles[baseName] = desktopFile.readName();
}
return true;
}
/**
* Return the origin of node based on the bottom/left corner
*
* @param id The widget id to fetch the origin from
* @return QPoint instance with the coordinates
*/
QPointF LayoutGenerator::origin(const QString &id)
{
QString key = fixID(id);
if (!m_nodes.contains(key)) {
#ifdef LAYOUTGENERATOR_DATA_DEBUG
DEBUG() << "LayoutGenerator::origin(" << id << "): " << key;
#endif
return QPoint(0,0);
}
QRectF &r = m_nodes[key];
QPointF p(m_origin.x() + r.x() - r.width()/2, m_boundingRect.height() - r.y() + r.height()/2 + m_origin.y());
#ifdef LAYOUTGENERATOR_DATA_DEBUG
DEBUG() << r << p;
#endif
return p;
}
/**
* Read generated dot file and extract positions
* of the contained widgets.
*
* @return true if extracting succeeded
*/
bool LayoutGenerator::readGeneratedDotFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
while(line.endsWith(QLatin1Char(',')))
line += in.readLine();
parseLine(line);
}
return true;
}
#ifndef USE_XDOT
/**
* Parse line from dot generated plain-ext output format
*
* The format is documented at https://graphviz.gitlab.io/_pages/doc/info/output.html and looks like:
*
* graph 1 28.083 10.222
* node ITfDmJvJE00m 8.0833 8.7361 0.86111 0.45833 QObject solid box black lightgrey
* edge sL4cKPpHnJkU sL4cKPpHnJkU 7 8.1253 7.2568 8.2695 7.2687 8.375 7.3127 8.375 7.3889 8.375 7.4377 8.3317 7.4733 8.2627 7.4957 Aggregation 8.8472 7.3889 solid black
*
* @param line line in dot plain-ext output format
* @return true if line could be parsed successfully
*/
bool LayoutGenerator::parseLine(const QString &line)
{
QStringList a = line.split(QLatin1Char(' '));
if (a[0] == QStringLiteral("graph")) {
m_boundingRect = QRectF(0, 0, a[2].toDouble()*m_scale, a[3].toDouble()*m_scale);
return true;
} else if (a[0] == QStringLiteral("node")) {
QString key = fixID(a[1]);
m_nodes[key] = QRectF(a[2].toDouble()*m_scale, a[3].toDouble()*m_scale,
a[4].toDouble()*m_scale, a[5].toDouble()*m_scale);
return true;
} else if (a[0] == QStringLiteral("edge")) {
QString key = fixID(a[1]+a[2]);
EdgePoints p;
int len = a[3].toInt();
for(int i = 0; i < len; i++)
p.append(QPointF(a[i*2+4].toDouble()*m_scale, a[i*2+5].toDouble()*m_scale));
m_edges[key] = p;
int b = len*2 + 4;
bool ok;
double x = a[b+1].toDouble(&ok);
if (!ok)
return true;
double y = a[b+2].toDouble(&ok);
if (!ok)
return true;
m_edgeLabelPosition[key] = QPointF(x*m_scale, y*m_scale);
return true;
} else if (a[0] == QStringLiteral("stop")) {
return true;
}
return false;
}
#else
typedef QMap<QString,QStringList> ParameterList;
bool LayoutGenerator::splitParameters(QMap<QString,QStringList> &map, const QString &s)
{
// FIXME: add shape=box without '"'
static QRegularExpression rx(QStringLiteral("([a-zA-Z_]+)=\"([a-zA-Z0-9.- #]+)\""));
static QRegularExpression rx2(QStringLiteral("([a-zA-Z_]+)=([a-zA-Z0-9.- #]+)"));
int pos = 0;
int count = 0;
/*
* while ((pos = rx2.indexIn(s, pos)) != -1) {
* QString key = rx2.cap(1);
* QString value = rx2.cap(2);
* ++count;
* pos += rx2.matchedLength();
* //qDebug() << key << value;
* if (map.contains(key))
* map[key] << value;
* else
* map[key] = QStringList() << value;
}
*/
pos = 0;
while ((pos = rx.indexIn(s, pos)) != -1) {
QString key = rx.cap(1);
QString value = rx.cap(2);
++count;
pos += rx.matchedLength();
//qDebug() << key << value;
QStringList data;
if (key == QStringLiteral("pos")) {
value.remove(QStringLiteral("e,"));
data = value.split(QLatin1Char(' '));
} else if (key.startsWith(QLatin1Char('_'))) {
data = value.split(QLatin1Char(' '));
}
else if (key == QStringLiteral("label"))
data = QStringList() << value;
else
data = value.split(QLatin1Char(','));
if (map.contains(key))
map[key] << data;
else
map[key] = data;
}
return true;
}
/**
*
digraph G {
graph [splines=polyline, rankdir=BT, outputorder=nodesfirst, ranksep="0.5", nodesep="0.5"];
node [label="\N"];
graph [bb="0,0,2893,638",
_draw_="c 9 -#ffffffff C 9 -#ffffffff P 4 0 -1 0 638 2894 638 2894 -1 ",
xdotversion="1.2"];
XC0weWhArzOJ [label=note, shape=box, width="2.5833", height="0.86111", pos="93,31", _draw_="c 9 -#000000ff p 4 186 62 0 62 0 0 186 0 ", _ldraw_="F 14.000000 11 -Times-Roman c 9 -#000000ff T 93 27 0 24 4 -note "];
sL4cKPpHnJkU -> ITfDmJvJE00m [arrowhead=normal, weight="1.0", label=" ", pos="e,2326.3,600.47 2299.7,543.57 2306.1,557.22 2314.9,575.99 2322.1,591.39", lp="2319,572", _draw_="c 9 -#000000ff B 4 2300 544 2306 557 2315 576 2322 591 ", _hdraw_="S 5 -solid c 9 -#000000ff C 9 -#000000ff P 3 2319 593 2326 600 2325 590 ", _ldraw_="F 14.000000 11 -Times-Roman c 9 -#000000ff T 2319 568 0 4 1 - "];
sL4cKPpHnJkU -> sL4cKPpHnJkU [label=" ", arrowtail=odiamond, dir=back, constraint=false, pos="s,2339.3,516.43 2351.5,516.59 2365.1,517.35 2375,520.16 2375,525 2375,531.2 2358.7,534.06 2339.3,533.57", lp="2377,525", _draw_="c 9 -#000000ff B 7 2351 517 2365 517 2375 520 2375 525 2375 531 2359 534 2339 534 ", _tdraw_="S 5 -solid c 9 -#000000ff p 4 2351 517 2345 521 2339 516 2345 513 ", _ldraw_="F 14.000000 11 -Times-Roman c 9 -#000000ff T 2377 521 0 4 1 - "];
*/
bool LayoutGenerator::parseLine(const QString &line)
{
static QRegularExpression m_cols(QStringLiteral("^[\t ]*(.*)[\t ]*\\[(.*)\\]"));
static int m_level = -1;
if (line.contains(QLatin1Char('{'))) {
m_level++;
return true;
}
else if (line.contains(QLatin1Char('}'))) {
m_level--;
return true;
}
int pos = 0;
if (m_cols.indexIn(line, pos) == -1)
return false;
QString keyword = m_cols.cap(1).trimmed();
QString attributeString = m_cols.cap(2);
DEBUG() << "LayoutGenerator::parseLine " << keyword << attributeString;
ParameterList attributes;
splitParameters(attributes, attributeString);
DEBUG() << attributes;
if (keyword == QStringLiteral("graph")) {
if (attributes.contains(QStringLiteral("bb"))) {
QStringList &a = attributes[QStringLiteral("bb")];
m_boundingRect.setLeft(a[0].toDouble());
m_boundingRect.setTop(a[1].toDouble());
m_boundingRect.setRight(a[2].toDouble());
m_boundingRect.setBottom(a[3].toDouble());
}
} else if (keyword == QStringLiteral("node")) {
return true;
} else if (keyword == QStringLiteral("edge")) {
return true;
// transition
} else if (line.contains(QStringLiteral("->"))) {
QStringList k = keyword.split(QLatin1Char(' '));
if (k.size() < 3)
return false;
QString key = fixID(k[0]+k[2]);
if (attributes.contains(QStringLiteral("pos"))) {
QStringList &a = attributes[QStringLiteral("pos")];
EdgePoints points;
for(int i = 1; i < a.size(); i++) {
QStringList b = a[i].split(QLatin1Char(','));
QPointF p(b[0].toDouble(), b[1].toDouble());
points.append(p);
}
QStringList b = a[0].split(QLatin1Char(','));
QPointF p(b[0].toDouble(), b[1].toDouble());
points.append(p);
m_edges[key] = points;
}
if (0 && attributes.contains(QStringLiteral("_draw_"))) {
QStringList &a = attributes[QStringLiteral("_draw_")];
if (a.size() < 5 || (a[3] != QStringLiteral("L") && a[3] != QStringLiteral("p")))
return false;
int size = a[4].toInt();
EdgePoints points;
for(int i = 0; i < size; i++) {
QPointF p(a[i*2+5].toDouble(), a[i*2+6].toDouble());
points.append(p);
}
m_edges[key] = points;
}
return true;
// single node
} else {
double scale = 72.0;
QRectF f(0, 0, 0, 0);
QString id = fixID(keyword);
if (attributes.contains(QStringLiteral("pos"))) {
QStringList &a = attributes[QStringLiteral("pos")];
QStringList b = a[0].split(QLatin1Char(','));
f.setLeft(b[0].toDouble());
f.setTop(b[1].toDouble());
}
if (attributes.contains(QStringLiteral("height"))) {
QStringList &a = attributes[QStringLiteral("height")];
f.setHeight(a[0].toDouble()*scale);
}
if (attributes.contains(QStringLiteral("width"))) {
QStringList &a = attributes[QStringLiteral("width")];
f.setWidth(a[0].toDouble()*scale);
}
DEBUG() << "LayoutGenerator::parseLine adding " << id << f;
m_nodes[id] = f;
}
return true;
}
#endif
/**
* map dot coordinate to scene coordinate
* @param p dot point to map
* @return uml scene coordinate
*/
QPointF LayoutGenerator::mapToScene(const QPointF &p)
{
return QPointF(p.x()+ m_origin.x(), m_boundingRect.height() - p.y() + m_origin.y());
}
#if 0
static QDebug operator<<(QDebug out, LayoutGenerator &c)
{
out << "LayoutGenerator:"
<< "m_boundingRect:" << c.m_boundingRect
<< "m_nodes:" << c.m_nodes
<< "m_edges:" << c.m_edges
<< "m_scale:" << c.m_scale
<< "m_executable:" << c.m_executable;
return out;
}
#endif
| 19,808
|
C++
|
.cpp
| 545
| 30.038532
| 465
| 0.613029
|
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,247
|
cmdlineexportallviewsevent.cpp
|
KDE_umbrello/umbrello/cmdlineexportallviewsevent.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cmdlineexportallviewsevent.h"
// app includes
#define DBG_SRC QStringLiteral("CmdLineExportAllViewsEvent")
#include "debug_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "umlviewimageexportermodel.h"
// qt includes
#include <QApplication>
#include <QCloseEvent>
#include <QStringList>
DEBUG_REGISTER(CmdLineExportAllViewsEvent)
const QEvent::Type CmdLineExportAllViewsEvent::type_ =
(QEvent::Type)QEvent::registerEventType(QEvent::User + 1);
/**
* Returns the type of the event.
* @return event type
*/
QEvent::Type CmdLineExportAllViewsEvent::eventType()
{
return type_;
}
/**
* Constructor.
* @param imageType The type of the images the views will be exported to.
* @param directory The url of the directory where the images will be saved.
* @param useFolders If the tree structure of the views in the document must be created
* in the target directory.
*/
CmdLineExportAllViewsEvent::CmdLineExportAllViewsEvent(const QString &imageType, const QUrl &directory, const bool useFolders)
: QEvent(type_),
m_imageType(imageType),
m_directory(directory),
m_useFolders(useFolders)
{
logDebug1("CmdLineExportAllViewsEvent created with type value %1", type_);
}
/**
* Destructor for CmdLineExportAllViewsEvent
*/
CmdLineExportAllViewsEvent::~CmdLineExportAllViewsEvent()
{
}
/**
* Exports all the views using UMLViewImageExporterModel, prints the errors
* occurred in the error output and quits the application.
* To export the views, it uses the attributes set when the event was created.
*/
void CmdLineExportAllViewsEvent::exportAllViews()
{
UMLViewList views = UMLApp::app()->document()->viewIterator();
QStringList errors = UMLViewImageExporterModel().exportViews(views, m_imageType, m_directory, m_useFolders);
if (!errors.isEmpty()) {
logError0("CmdLineExportAllViewsEvent::exportAllViews(): Errors while exporting:");
for (QStringList::Iterator it = errors.begin(); it != errors.end(); ++it) {
logError1("- %1", *it);
}
}
qApp->quit();
}
| 2,241
|
C++
|
.cpp
| 65
| 31.707692
| 126
| 0.747922
|
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,248
|
codeviewerstate.cpp
|
KDE_umbrello/umbrello/codeviewerstate.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "codeviewerstate.h"
#include "umbrellosettings.h"
namespace Settings {
void CodeViewerState::load()
{
height = UmbrelloSettings::height();
width = UmbrelloSettings::width();
font = UmbrelloSettings::codeViewerFont();
showHiddenBlocks = UmbrelloSettings::showHiddenBlocks();
blocksAreHighlighted = UmbrelloSettings::blocksAreHighlighted();
selectedColor = UmbrelloSettings::selectedColor();
paperColor = UmbrelloSettings::paperColor();
fontColor = UmbrelloSettings::fontColor();
editBlockColor = UmbrelloSettings::editBlockColor();
umlObjectColor = UmbrelloSettings::umlObjectColor();
nonEditBlockColor = UmbrelloSettings::nonEditBlockColor();
hiddenColor = UmbrelloSettings::hiddenColor();
}
void CodeViewerState::save()
{
UmbrelloSettings::setHeight(height);
UmbrelloSettings::setWidth(width);
UmbrelloSettings::setCodeViewerFont(font);
UmbrelloSettings::setFontColor(fontColor);
UmbrelloSettings::setPaperColor(paperColor);
UmbrelloSettings::setSelectedColor(selectedColor);
UmbrelloSettings::setEditBlockColor(editBlockColor);
UmbrelloSettings::setNonEditBlockColor(nonEditBlockColor);
UmbrelloSettings::setUmlObjectColor(umlObjectColor);
UmbrelloSettings::setBlocksAreHighlighted(blocksAreHighlighted);
UmbrelloSettings::setShowHiddenBlocks(showHiddenBlocks);
UmbrelloSettings::setHiddenColor(hiddenColor);
}
}
| 1,583
|
C++
|
.cpp
| 38
| 37.763158
| 92
| 0.788174
|
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,249
|
model_utils.cpp
|
KDE_umbrello/umbrello/model_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 "model_utils.h"
// app includes
#include "floatingtextwidget.h"
#define DBG_SRC QStringLiteral("Model_Utils")
#include "debug_utils.h"
#include "umlobject.h"
#include "umlpackagelist.h"
#include "uniqueconstraint.h"
#include "package.h"
#include "folder.h"
#include "classifier.h"
#include "enum.h"
#include "instance.h"
#include "entity.h"
#include "template.h"
#include "operation.h"
#include "attribute.h"
#include "association.h"
#include "umlrole.h"
#include "umldoc.h"
#include "uml.h"
#include "umllistview.h"
#include "umllistviewitem.h"
#include "umlscene.h"
#include "umlview.h"
#include "codegenerator.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QRegularExpression>
#include <QStringList>
DEBUG_REGISTER(Model_Utils)
namespace Model_Utils {
/**
* Determines whether the given widget type is cloneable.
*
* @param type The input WidgetType.
* @return True if the given type is cloneable.
*/
bool isCloneable(WidgetBase::WidgetType type)
{
switch (type) {
case WidgetBase::wt_Actor:
case WidgetBase::wt_UseCase:
case WidgetBase::wt_Class:
case WidgetBase::wt_Interface:
case WidgetBase::wt_Enum:
case WidgetBase::wt_Datatype:
case WidgetBase::wt_Package:
case WidgetBase::wt_Component:
case WidgetBase::wt_Port:
case WidgetBase::wt_Node:
case WidgetBase::wt_Artifact:
case WidgetBase::wt_Instance:
case WidgetBase::wt_Entity:
return true;
default:
return false;
}
}
/**
* Normalize a type name with respect to interspersed spaces.
* @param type Input type name e.g. from a user text entry dialog.
* @return Normalized type name.
*/
QString normalize(QString type)
{
QString str = type.simplified();
int pos;
// Remove space between word and non word
QRegularExpression word_nonword(QStringLiteral("\\w \\W"));
pos = 0;
while ((pos = str.indexOf(word_nonword, pos)) != -1) {
str.remove(++pos, 1);
}
// Remove space between non word and word
QRegularExpression nonword_word(QStringLiteral("\\W \\w"));
pos = 0;
while ((pos = str.indexOf(nonword_word, pos)) != -1) {
str.remove(++pos, 1);
}
// Remove space between non word and non word
QRegularExpression nonword_nonword(QStringLiteral("\\W \\W"));
pos = 0;
while ((pos = str.indexOf(nonword_nonword, pos)) != -1) {
str.remove(++pos, 1);
}
return str;
}
/**
* Seek the given id in the given list of objects.
* Each list element may itself contain other objects
* and the search is done recursively.
*
* @param id The unique ID to seek.
* @param inList The UMLObjectList in which to search.
* @return Pointer to the UMLObject that matches the ID (NULL if none matches).
*/
UMLObject* findObjectInList(Uml::ID::Type id, const UMLObjectList& inList)
{
for (UMLObjectListIt oit(inList); oit.hasNext();) {
UMLObject *obj = oit.next();
uIgnoreZeroPointer(obj);
if (obj->id() == id)
return obj;
UMLObject *o;
UMLObject::ObjectType t = obj->baseType();
switch (t) {
case UMLObject::ot_Folder:
case UMLObject::ot_Package:
case UMLObject::ot_Component:
o = obj->asUMLPackage()->findObjectById(id);
if (o)
return o;
break;
case UMLObject::ot_Interface:
case UMLObject::ot_Class:
case UMLObject::ot_Enum:
o = obj->asUMLClassifier()->findChildObjectById(id);
if (o == nullptr &&
(t == UMLObject::ot_Interface || t == UMLObject::ot_Class))
o = obj->asUMLPackage()->findObjectById(id);
if (o)
return o;
break;
case UMLObject::ot_Instance:
o = obj->asUMLInstance()->findChildObjectById(id);
if (o)
return o;
break;
case UMLObject::ot_Entity:
o = obj->asUMLEntity()->findChildObjectById(id);
if (o)
return o;
o = obj->asUMLPackage()->findObjectById(id);
if (o)
return o;
break;
case UMLObject::ot_Association:
{
UMLAssociation *assoc = obj->asUMLAssociation();
UMLRole *rA = assoc->getUMLRole(Uml::RoleType::A);
if (rA->id() == id)
return rA;
UMLRole *rB = assoc->getUMLRole(Uml::RoleType::B);
if (rB->id() == id)
return rB;
}
break;
default:
break;
}
}
return nullptr;
}
/**
* Find the UML object of the given type and name in the passed-in list.
*
* @param inList List in which to seek the object.
* @param inName Name of the object to find.
* @param type ObjectType of the object to find (optional.)
* When the given type is ot_UMLObject the type is
* disregarded, i.e. the given name is the only
* search criterion.
* @param currentObj Object relative to which to search (optional.)
* If given then the enclosing scope(s) of this
* object are searched before the global scope.
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* findUMLObject(const UMLObjectList& inList,
const QString& inName,
UMLObject::ObjectType type /* = ot_UMLObject */,
UMLObject *currentObj /* = nullptr */)
{
const bool caseSensitive = UMLApp::app()->activeLanguageIsCaseSensitive();
QString name = normalize(inName);
const bool atGlobalScope = name.startsWith(QStringLiteral("::"));
if (atGlobalScope) {
name = name.mid(2);
currentObj = nullptr;
}
QStringList components;
#ifdef TRY_BUGFIX_120862
// If we have a pointer or a reference in cpp we need to remove
// the asterisks and ampersands in order to find the appropriate object
if (UMLApp::app()->getActiveLanguage() == Uml::pl_Cpp) {
if (name.endsWith(QLatin1Char('*')))
name.remove(QLatin1Char('*'));
else if (name.contains(QLatin1Char('&')))
name.remove(QLatin1Char('&'));
}
#endif
QString scopeSeparator = UMLApp::app()->activeLanguageScopeSeparator();
if (name.contains(scopeSeparator))
components = name.split(scopeSeparator);
QString nameWithoutFirstPrefix;
if (components.size() > 1) {
name = components.front();
components.pop_front();
nameWithoutFirstPrefix = components.join(scopeSeparator);
}
if (currentObj) {
UMLPackage *pkg = nullptr;
if (currentObj->asUMLClassifierListItem()) {
currentObj = currentObj->umlParent();
}
pkg = currentObj->asUMLPackage();
if (pkg == nullptr || pkg->baseType() == UMLObject::ot_Association)
pkg = currentObj->umlPackage();
// Remember packages that we've seen - for avoiding cycles.
UMLPackageList seenPkgs;
for (; pkg; pkg = currentObj->umlPackage()) {
if (nameWithoutFirstPrefix.isEmpty()
&& (type == UMLObject::ot_UMLObject ||
type == UMLObject::ot_Folder ||
type == UMLObject::ot_Package || type == pkg->baseType())) {
if (caseSensitive) {
if (pkg->name() == name)
return pkg;
} else if (pkg->name().toLower() == name.toLower()) {
return pkg;
}
}
if (seenPkgs.indexOf(pkg) != -1) {
logError2("Model_Utils::findUMLObject(%1): breaking out of cycle involving %2",
name, pkg->name());
break;
}
seenPkgs.append(pkg);
// exclude non package type
// pg->asUMLPackage() fails for unknown reason
// see https://bugs.kde.org/show_bug.cgi?id=341709
UMLObject::ObjectType foundType = pkg->baseType();
if (foundType != UMLObject::ot_Package &&
foundType != UMLObject::ot_Folder &&
foundType != UMLObject::ot_Class &&
foundType != UMLObject::ot_Interface &&
foundType != UMLObject::ot_Component) {
continue;
}
UMLObjectList objectsInCurrentScope = pkg->containedObjects();
for (UMLObjectListIt oit(objectsInCurrentScope); oit.hasNext();) {
UMLObject *obj = oit.next();
uIgnoreZeroPointer(obj);
if (caseSensitive) {
if (obj->name() != name)
continue;
} else if (obj->name().toLower() != name.toLower()) {
continue;
}
UMLObject::ObjectType foundType = obj->baseType();
if (nameWithoutFirstPrefix.isEmpty()) {
if (type != UMLObject::ot_UMLObject && type != foundType) {
logDebug3("findUMLObject type mismatch for %1 (seeking type: %2, found type: %3)",
name, UMLObject::toString(type), UMLObject::toString(foundType));
// Class, Interface, and Datatype are all Classifiers
// and are considered equivalent.
// The caller must be prepared to handle possible mismatches.
if ((type == UMLObject::ot_Class ||
type == UMLObject::ot_Interface ||
type == UMLObject::ot_Datatype) &&
(foundType == UMLObject::ot_Class ||
foundType == UMLObject::ot_Interface ||
foundType == UMLObject::ot_Datatype)) {
return obj;
}
// Code import may set <<class-or-package>> stereotype
if ((type == UMLObject::ot_Package || type == UMLObject::ot_Class)
&& obj->stereotype() == QStringLiteral("class-or-package")) {
return obj;
}
continue;
}
return obj;
}
if (foundType != UMLObject::ot_Package &&
foundType != UMLObject::ot_Folder &&
foundType != UMLObject::ot_Class &&
foundType != UMLObject::ot_Interface &&
foundType != UMLObject::ot_Component) {
logDebug2("findUMLObject found %1 %2 is not a package (?)", UMLObject::toString(foundType), name);
continue;
}
UMLPackage *pkg = obj->asUMLPackage();
return findUMLObject(pkg->containedObjects(),
nameWithoutFirstPrefix, type);
}
currentObj = pkg;
}
}
for (UMLObjectListIt oit(inList); oit.hasNext();) {
UMLObject *obj = oit.next();
uIgnoreZeroPointer(obj);
if (caseSensitive) {
if (obj->name() != name)
continue;
} else if (obj->name().toLower() != name.toLower()) {
continue;
}
UMLObject::ObjectType foundType = obj->baseType();
if (nameWithoutFirstPrefix.isEmpty()) {
if (type != UMLObject::ot_UMLObject && type != foundType) {
// Code import may set <<class-or-package>> stereotype
if ((type == UMLObject::ot_Package || type == UMLObject::ot_Class)
&& obj->stereotype() == QStringLiteral("class-or-package")) {
return obj;
}
logDebug3("findUMLObject type mismatch for %1 (seeking type: %2, found type: %3)",
name, UMLObject::toString(type), UMLObject::toString(foundType));
continue;
}
return obj;
}
if (foundType != UMLObject::ot_Package &&
foundType != UMLObject::ot_Folder &&
foundType != UMLObject::ot_Class &&
foundType != UMLObject::ot_Interface &&
foundType != UMLObject::ot_Component) {
logDebug2("findUMLObject found %1 (%2) is not a package (?)", name, UMLObject::toString(foundType));
continue;
}
const UMLPackage *pkg = obj->asUMLPackage();
return findUMLObject(pkg->containedObjects(),
nameWithoutFirstPrefix, type);
}
return nullptr;
}
/**
* Find the UML object of the given type and name in the passed-in list.
* This method searches for the raw name.
*
* @param inList List in which to seek the object.
* @param name Name of the object to find.
* @param type ObjectType of the object to find (optional.)
* When the given type is ot_UMLObject the type is
* disregarded, i.e. the given name is the only
* search criterion.
* @param currentObj Object relative to which to search (optional.)
* If given then the enclosing scope(s) of this
* object are searched before the global scope.
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* findUMLObjectRaw(const UMLObjectList& inList,
const QString& name,
UMLObject::ObjectType type /* = ot_UMLObject */,
UMLObject *currentObj /*= nullptr*/)
{
Q_UNUSED(currentObj);
for (UMLObjectListIt oit(inList); oit.hasNext();) {
UMLObject *obj = oit.next();
if (obj->name() == name && type == obj->baseType())
return obj;
}
return nullptr;
}
/**
* Find the UML object of the given type and name in the passed-in list.
* This method searches for the raw name.
*
* @param inList List in which to seek the object.
* @param name Name of the object to find.
* @param type ObjectType of the object to find (optional.)
* When the given type is ot_UMLObject the type is
* disregarded, i.e. the given name is the only
* search criterion.
* @return Pointer to the UMLObject found, or NULL if not found.
*/
UMLObject* findUMLObjectRecursive(const UMLObjectList& inList,
const QString& name,
UMLObject::ObjectType type /* = ot_UMLObject */)
{
for(UMLObject *obj : inList) {
if (obj->name() == name && type == obj->baseType())
return obj;
const UMLPackage *pkg = obj->asUMLPackage();
if (pkg && pkg->containedObjects().size() > 0) {
UMLObject *o = findUMLObjectRecursive(pkg->containedObjects(), name, type);
if (o)
return o;
}
}
return nullptr;
}
/**
* Get the root folder of the given UMLObject.
*/
UMLPackage* rootPackage(UMLObject* obj)
{
if (obj == nullptr)
return nullptr;
UMLPackage* root = obj->umlPackage();
if (root == nullptr) {
root = obj->asUMLPackage();
} else {
while (root->umlPackage() != nullptr) {
root = root->umlPackage();
}
}
return root;
}
/**
* Add the given list of views to the tree view.
* @param viewList the list of views to add
*/
void treeViewAddViews(const UMLViewList& viewList)
{
UMLListView* tree = UMLApp::app()->listView();
for(UMLView *v : viewList) {
if (tree->findItem(v->umlScene()->ID()) != nullptr) {
continue;
}
tree->createDiagramItem(v);
}
}
/**
* Change an icon of an object in the tree view.
* @param object the object in the treeViewAddViews
* @param to the new icon type for the given object
*/
void treeViewChangeIcon(UMLObject* object, Icon_Utils::IconType to)
{
UMLListView* tree = UMLApp::app()->listView();
tree->changeIconOf(object, to);
}
/**
* Set the given object to the current item in the tree view.
* @param object the object which will be the current item
*/
void treeViewSetCurrentItem(UMLObject* object)
{
UMLListView* tree = UMLApp::app()->listView();
UMLListViewItem* item = tree->findUMLObject(object);
tree->setCurrentItem(item);
}
/**
* Move an object to a new container in the tree view.
* @param container the new container for the object
* @param object the to be moved object
*/
void treeViewMoveObjectTo(UMLObject* container, UMLObject* object)
{
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem *newParent = listView->findUMLObject(container);
listView->moveObject(object->id(),
Model_Utils::convert_OT_LVT(object),
newParent);
}
/**
* Return the current UMLObject from the tree view.
* @return the UML object of the current item
*/
UMLObject* treeViewGetCurrentObject()
{
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem *current = dynamic_cast<UMLListViewItem*>(listView->currentItem());
if (current == nullptr)
return nullptr;
return current->umlObject();
}
/**
* Return the UMLPackage if the current item
* in the tree view is a package. Return the
* closest package in the tree view or NULL otherwise
*
* @return the package or NULL
*/
UMLPackage* treeViewGetPackageFromCurrent()
{
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem *parentItem = (UMLListViewItem*)listView->currentItem();
while (parentItem) {
UMLListViewItem::ListViewType lvt = parentItem->type();
if (Model_Utils::typeIsContainer(lvt)) {
UMLObject *o = parentItem->umlObject();
return o->asUMLPackage();
}
// selected item is not a container, try to find the
// container higher up in the tree view
parentItem = static_cast<UMLListViewItem*>(parentItem->parent());
}
return nullptr;
}
/**
* Build the diagram name from the tree view.
* The function returns a relative path constructed from the folder hierarchy.
* @param id the id of the diaram
* @return the constructed diagram name
*/
QString treeViewBuildDiagramName(Uml::ID::Type id)
{
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem* listViewItem = listView->findItem(id);
if (listViewItem) {
QString name = listViewItem->text(0);
listViewItem = static_cast<UMLListViewItem*>(listViewItem->parent());
// Relies on the tree structure of the UMLListView. There are a base "Views" folder
// and five children, one for each view type (Logical, use case, components, deployment
// and entity relationship)
while (listView->rootView(listViewItem->type()) == nullptr) {
name.insert(0, listViewItem->text(0) + QLatin1Char('/'));
listViewItem = static_cast<UMLListViewItem*>(listViewItem->parent());
if (listViewItem == nullptr)
break;
}
return name;
}
else {
logWarn1("Model_Utils::treeViewBuildDiagramName: diagram with id %1 not found",
Uml::ID::toString(id));
return QString();
}
}
/**
* Returns a name for the new object, appended with a number
* if the default name is taken e.g. new_actor, new_actor_1
* etc.
* @param type The object type.
* @param parentPkg The package in which to compare the name.
* @param prefix The prefix to use (optional)
* If no prefix is given then a type related
* prefix will be chosen internally.
*/
QString uniqObjectName(UMLObject::ObjectType type, UMLPackage *parentPkg, QString prefix)
{
QString currentName = prefix;
if (currentName.isEmpty()) {
switch(type) {
case UMLObject::ot_Actor: currentName = i18n("new_actor"); break;
case UMLObject::ot_Artifact: currentName = i18n("new_artifact"); break;
case UMLObject::ot_Association: currentName = i18n("new_association"); break;
case UMLObject::ot_Attribute: currentName = i18n("new_attribute"); break;
case UMLObject::ot_Category: currentName = i18n("new_category"); break;
case UMLObject::ot_CheckConstraint: currentName = i18n("new_check_constraint"); break;
case UMLObject::ot_Class: currentName = i18n("new_class"); break;
case UMLObject::ot_Component: currentName = i18n("new_component"); break;
case UMLObject::ot_Datatype: currentName = i18n("new_datatype"); break;
case UMLObject::ot_Entity: currentName = i18n("new_entity"); break;
case UMLObject::ot_EntityAttribute: currentName = i18n("new_entity_attribute"); break;
case UMLObject::ot_EntityConstraint: currentName = i18n("new_entity_constraint"); break;
case UMLObject::ot_Enum: currentName = i18n("new_enum"); break;
case UMLObject::ot_EnumLiteral: currentName = i18n("new_enum_literal"); break;
case UMLObject::ot_Folder: currentName = i18n("new_folder"); break;
case UMLObject::ot_ForeignKeyConstraint:currentName = i18n("new_foreign_key_constraint"); break;
case UMLObject::ot_Instance: currentName = i18n("new_instance"); break;
case UMLObject::ot_InstanceAttribute: currentName = i18n("new_instance_attribute"); break;
case UMLObject::ot_Interface: currentName = i18n("new_interface"); break;
case UMLObject::ot_Node: currentName = i18n("new_node"); break;
case UMLObject::ot_Operation: currentName = i18n("new_operation"); break;
case UMLObject::ot_Package: currentName = i18n("new_package"); break;
case UMLObject::ot_Port: currentName = i18n("new_port"); break;
case UMLObject::ot_Role: currentName = i18n("new_role"); break;
case UMLObject::ot_Stereotype: currentName = i18n("new_stereotype"); break;
case UMLObject::ot_Template: currentName = i18n("new_template"); break;
case UMLObject::ot_UniqueConstraint: currentName = i18n("new_unique_constraint"); break;
case UMLObject::ot_UseCase: currentName = i18n("new_use_case"); break;
default:
currentName = i18n("new_object");
logWarn1("Model_Utils::uniqObjectName unknown object type %1", UMLObject::toString(type));
}
}
UMLDoc *doc = UMLApp::app()->document();
QString name = currentName;
for (int number = 1; !doc->isUnique(name, parentPkg); ++number) {
name = currentName + QLatin1Char('_') + QString::number(number);
}
return name;
}
/**
* Returns translated title string used by uml object related dialogs
* @param type uml object type
* @return translated title string
*/
QString newTitle(UMLObject::ObjectType type)
{
switch(type) {
case UMLObject::ot_Actor: return i18n("New actor");
case UMLObject::ot_Artifact: return i18n("New artifact");
case UMLObject::ot_Association: return i18n("New association");
case UMLObject::ot_Attribute: return i18n("New attribute");
case UMLObject::ot_Category: return i18n("New category");
case UMLObject::ot_CheckConstraint: return i18n("New check constraint");
case UMLObject::ot_Class: return i18n("New class");
case UMLObject::ot_Component: return i18n("New component");
case UMLObject::ot_Datatype: return i18n("New datatype");
case UMLObject::ot_Entity: return i18n("New entity");
case UMLObject::ot_EntityAttribute: return i18n("New entity attribute");
case UMLObject::ot_EntityConstraint: return i18n("New entity constraint");
case UMLObject::ot_Enum: return i18n("New enum");
case UMLObject::ot_EnumLiteral: return i18n("New enum literal");
case UMLObject::ot_Folder: return i18n("New folder");
case UMLObject::ot_ForeignKeyConstraint:return i18n("New foreign key constraint");
case UMLObject::ot_Instance: return i18n("New instance");
case UMLObject::ot_InstanceAttribute: return i18n("New instance attribute");
case UMLObject::ot_Interface: return i18n("New interface");
case UMLObject::ot_Node: return i18n("New node");
case UMLObject::ot_Operation: return i18n("New operation");
case UMLObject::ot_Package: return i18n("New package");
case UMLObject::ot_Port: return i18n("New port");
case UMLObject::ot_Role: return i18n("New role");
case UMLObject::ot_Stereotype: return i18n("New stereotype");
case UMLObject::ot_Template: return i18n("New template");
case UMLObject::ot_UniqueConstraint: return i18n("New unique constraint");
case UMLObject::ot_UseCase: return i18n("New use case");
default:
logWarn1("Model_Utils::newTitle unknown object type %1", UMLObject::toString(type));
return i18n("New UML object");
}
}
/**
* Returns translated text string used by uml object related dialogs
* @param type uml object type
* @return translated text string
*/
QString newText(UMLObject::ObjectType type)
{
switch(type) {
case UMLObject::ot_Actor: return i18n("Enter the name of the new actor:");
case UMLObject::ot_Artifact: return i18n("Enter the name of the new artifact:");
case UMLObject::ot_Association: return i18n("Enter the name of the new association:");
case UMLObject::ot_Attribute: return i18n("Enter the name of the new attribute:");
case UMLObject::ot_Category: return i18n("Enter the name of the new category:");
case UMLObject::ot_CheckConstraint: return i18n("Enter the name of the new check constraint:");
case UMLObject::ot_Class: return i18n("Enter the name of the new class:");
case UMLObject::ot_Component: return i18n("Enter the name of the new component:");
case UMLObject::ot_Datatype: return i18n("Enter the name of the new datatype:");
case UMLObject::ot_Entity: return i18n("Enter the name of the new entity:");
case UMLObject::ot_EntityAttribute: return i18n("Enter the name of the new entity attribute:");
case UMLObject::ot_EntityConstraint: return i18n("Enter the name of the new entity constraint:");
case UMLObject::ot_Enum: return i18n("Enter the name of the new enum:");
case UMLObject::ot_EnumLiteral: return i18n("Enter the name of the new enum literal:");
case UMLObject::ot_Folder: return i18n("Enter the name of the new folder:");
case UMLObject::ot_ForeignKeyConstraint:return i18n("Enter the name of the new foreign key constraint:");
case UMLObject::ot_Instance: return i18n("Enter the name of the new instance:");
case UMLObject::ot_InstanceAttribute: return i18n("Enter the name of the new instance attribute:");
case UMLObject::ot_Interface: return i18n("Enter the name of the new interface:");
case UMLObject::ot_Node: return i18n("Enter the name of the new node:");
case UMLObject::ot_Operation: return i18n("Enter the name of the new operation:");
case UMLObject::ot_Package: return i18n("Enter the name of the new package:");
case UMLObject::ot_Port: return i18n("Enter the name of the new port:");
case UMLObject::ot_Role: return i18n("Enter the name of the new role:");
case UMLObject::ot_Stereotype: return i18n("Enter the name of the new stereotype:");
case UMLObject::ot_Template: return i18n("Enter the name of the new template:");
case UMLObject::ot_UniqueConstraint: return i18n("Enter the name of the new unique constraint:");
case UMLObject::ot_UseCase: return i18n("Enter the name of the new use case:");
default:
logWarn1("Model_utilS::newText unknown object type %1", UMLObject::toString(type));
return i18n("Enter the name of the new UML object");
}
}
/**
* Returns translated title string used by uml object related dialogs
* @param type uml object type
* @return translated title string
*/
QString renameTitle(UMLObject::ObjectType type)
{
switch(type) {
case UMLObject::ot_Actor: return i18n("Rename actor");
case UMLObject::ot_Artifact: return i18n("Rename artifact");
case UMLObject::ot_Association: return i18n("Rename association");
case UMLObject::ot_Attribute: return i18n("Rename attribute");
case UMLObject::ot_Category: return i18n("Rename category");
case UMLObject::ot_CheckConstraint: return i18n("Rename check constraint");
case UMLObject::ot_Class: return i18n("Rename class");
case UMLObject::ot_Component: return i18n("Rename component");
case UMLObject::ot_Datatype: return i18n("Rename datatype");
case UMLObject::ot_Entity: return i18n("Rename entity");
case UMLObject::ot_EntityAttribute: return i18n("Rename entity attribute");
case UMLObject::ot_EntityConstraint: return i18n("Rename entity constraint");
case UMLObject::ot_Enum: return i18n("Rename enum");
case UMLObject::ot_EnumLiteral: return i18n("Rename enum literal");
case UMLObject::ot_Folder: return i18n("Rename folder");
case UMLObject::ot_ForeignKeyConstraint:return i18n("Rename foreign key constraint");
case UMLObject::ot_Instance: return i18n("Rename instance");
case UMLObject::ot_InstanceAttribute: return i18n("Rename instance attribute");
case UMLObject::ot_Interface: return i18n("Rename interface");
case UMLObject::ot_Node: return i18n("Rename node");
case UMLObject::ot_Operation: return i18n("Rename operation");
case UMLObject::ot_Package: return i18n("Rename package");
case UMLObject::ot_Port: return i18n("Rename port");
case UMLObject::ot_Role: return i18n("Rename role");
case UMLObject::ot_Stereotype: return i18n("Rename stereotype");
case UMLObject::ot_Template: return i18n("Rename template");
case UMLObject::ot_UniqueConstraint: return i18n("Rename unique constraint");
case UMLObject::ot_UseCase: return i18n("Rename use case");
default:
logWarn1("Model_Utils::renameTitle unknown object type %1", UMLObject::toString(type));
return i18n("Rename UML object");
}
}
/**
* Returns translated text string used by uml object related dialogs
* @param type uml object type
* @return translated text string
*/
QString renameText(UMLObject::ObjectType type)
{
switch(type) {
case UMLObject::ot_Actor: return i18n("Enter the new name of the actor:");
case UMLObject::ot_Artifact: return i18n("Enter the new name of the artifact:");
case UMLObject::ot_Association: return i18n("Enter the new name of the association:");
case UMLObject::ot_Attribute: return i18n("Enter the new name of the attribute:");
case UMLObject::ot_Category: return i18n("Enter the new name of the category:");
case UMLObject::ot_CheckConstraint: return i18n("Enter the new name of the check constraint:");
case UMLObject::ot_Class: return i18n("Enter the new name of the class:");
case UMLObject::ot_Component: return i18n("Enter the new name of the component:");
case UMLObject::ot_Datatype: return i18n("Enter the new name of the datatype:");
case UMLObject::ot_Entity: return i18n("Enter the new name of the entity:");
case UMLObject::ot_EntityAttribute: return i18n("Enter the new name of the entity attribute:");
case UMLObject::ot_EntityConstraint: return i18n("Enter the new name of the entity constraint:");
case UMLObject::ot_Enum: return i18n("Enter the new name of the enum:");
case UMLObject::ot_EnumLiteral: return i18n("Enter the new name of the enum literal:");
case UMLObject::ot_Folder: return i18n("Enter the new name of the folder:");
case UMLObject::ot_ForeignKeyConstraint:return i18n("Enter the new name of the foreign key constraint:");
case UMLObject::ot_Instance: return i18n("Enter the new name of the instance:");
case UMLObject::ot_InstanceAttribute: return i18n("Enter the new name of the instance attribute:");
case UMLObject::ot_Interface: return i18n("Enter the new name of the interface:");
case UMLObject::ot_Node: return i18n("Enter the new name of the node:");
case UMLObject::ot_Operation: return i18n("Enter the new name of the operation:");
case UMLObject::ot_Package: return i18n("Enter the new name of the package:");
case UMLObject::ot_Port: return i18n("Enter the new name of the port:");
case UMLObject::ot_Role: return i18n("Enter the new name of the role:");
case UMLObject::ot_Stereotype: return i18n("Enter the new name of the stereotype:");
case UMLObject::ot_Template: return i18n("Enter the new name of the template:");
case UMLObject::ot_UniqueConstraint: return i18n("Enter the new name of the unique constraint:");
case UMLObject::ot_UseCase: return i18n("Enter the new name of the use case:");
default:
logWarn1("Model_Utils::renameText unknown object type %1", UMLObject::toString(type));
return i18n("Enter the new name of the UML object");
}
}
/**
* Return the xmi.id (XMI-1) or xmi:id (XMI-2) of a QDomElement.
*/
QString getXmiId(QDomElement element)
{
QString idStr = element.attribute(QStringLiteral("xmi:id"));
if (idStr.isEmpty())
idStr = element.attribute(QStringLiteral("xmi.id"));
return idStr;
}
/**
* Return the text of an \<ownedComment\> XMI element from a QDomElement.
*/
QString loadCommentFromXMI(QDomElement elem)
{
QString body = elem.attribute(QStringLiteral("body"));
if (body.isEmpty()) {
QDomNode innerNode = elem.firstChild();
QDomElement innerElem = innerNode.toElement();
while (!innerElem.isNull()) {
QString innerTag = innerElem.tagName();
if (UMLDoc::tagEq(innerTag, QStringLiteral("body"))) {
body = innerElem.text();
break;
}
innerNode = innerNode.nextSibling();
innerElem = innerNode.toElement();
}
}
return body;
}
/**
* Return true if the given tag is one of the common XMI
* attributes, such as:
* "name" | "visibility" | "isRoot" | "isLeaf" | "isAbstract" |
* "isActive" | "ownerScope"
*/
bool isCommonXMI1Attribute(const QString &tag)
{
bool retval = (UMLDoc::tagEq(tag, QStringLiteral("name")) ||
UMLDoc::tagEq(tag, QStringLiteral("visibility")) ||
UMLDoc::tagEq(tag, QStringLiteral("isRoot")) ||
UMLDoc::tagEq(tag, QStringLiteral("isLeaf")) ||
UMLDoc::tagEq(tag, QStringLiteral("isAbstract")) ||
UMLDoc::tagEq(tag, QStringLiteral("isSpecification")) ||
UMLDoc::tagEq(tag, QStringLiteral("isActive")) ||
UMLDoc::tagEq(tag, QStringLiteral("namespace")) ||
UMLDoc::tagEq(tag, QStringLiteral("ownerScope")) ||
UMLDoc::tagEq(tag, QStringLiteral("ModelElement.stereotype")) ||
UMLDoc::tagEq(tag, QStringLiteral("GeneralizableElement.generalization")) ||
UMLDoc::tagEq(tag, QStringLiteral("specialization")) || //NYI
UMLDoc::tagEq(tag, QStringLiteral("clientDependency")) || //NYI
UMLDoc::tagEq(tag, QStringLiteral("supplierDependency")) //NYI
);
return retval;
}
/**
* Return true if the given type is common among the majority
* of programming languages, such as "bool" or "boolean".
*/
bool isCommonDataType(QString type)
{
CodeGenerator *gen = UMLApp::app()->generator();
if (gen == nullptr) {
// When no code generator is set we use UMLPrimitiveTypes
for (int i = 0; i < Uml::PrimitiveTypes::Reserved; i++) {
if (type == Uml::PrimitiveTypes::toString(i))
return true;
}
return false;
}
const bool caseSensitive = UMLApp::app()->activeLanguageIsCaseSensitive();
const QStringList dataTypes = gen->defaultDatatypes();
QStringList::ConstIterator end(dataTypes.end());
for (QStringList::ConstIterator it = dataTypes.begin(); it != end; ++it) {
if (caseSensitive) {
if (type == *it)
return true;
} else if (type.toLower() == (*it).toLower()) {
return true;
}
}
return false;
}
/**
* Return true if the given object type is a classifier list item type.
*/
bool isClassifierListitem(UMLObject::ObjectType type)
{
if (type == UMLObject::ot_Attribute ||
type == UMLObject::ot_Operation ||
type == UMLObject::ot_Template ||
type == UMLObject::ot_EntityAttribute ||
type == UMLObject::ot_EnumLiteral ||
type == UMLObject::ot_UniqueConstraint ||
type == UMLObject::ot_ForeignKeyConstraint ||
type == UMLObject::ot_CheckConstraint) {
// UMLObject::ot_InstanceAttribute needs to be handled separately
// because UMLInstanceAttribute is not a UMLClassifierListItem.
return true;
} else {
return false;
}
}
/**
* Try to guess the correct container folder type of a UMLObject.
* Object types that can't be guessed are mapped to Uml::ModelType::Logical.
* NOTE: This function exists mainly for handling pre-1.5.5 files
* and should not be used for new code.
*/
Uml::ModelType::Enum guessContainer(UMLObject *o)
{
UMLObject::ObjectType ot = o->baseType();
if (ot == UMLObject::ot_Package && o->stereotype() == QStringLiteral("subsystem"))
return Uml::ModelType::Component;
Uml::ModelType::Enum mt = Uml::ModelType::N_MODELTYPES;
switch (ot) {
case UMLObject::ot_Package: // trouble: package can also appear in Component view
case UMLObject::ot_Interface:
case UMLObject::ot_Datatype:
case UMLObject::ot_Enum:
case UMLObject::ot_Class:
case UMLObject::ot_Attribute:
case UMLObject::ot_Operation:
case UMLObject::ot_EnumLiteral:
case UMLObject::ot_Template:
case UMLObject::ot_Instance:
case UMLObject::ot_InstanceAttribute:
mt = Uml::ModelType::Logical;
break;
case UMLObject::ot_Actor:
case UMLObject::ot_UseCase:
mt = Uml::ModelType::UseCase;
break;
case UMLObject::ot_Component:
case UMLObject::ot_Port:
case UMLObject::ot_Artifact: // trouble: artifact can also appear at Deployment
mt = Uml::ModelType::Component;
break;
case UMLObject::ot_Node:
mt = Uml::ModelType::Deployment;
break;
case UMLObject::ot_Entity:
case UMLObject::ot_EntityAttribute:
case UMLObject::ot_UniqueConstraint:
case UMLObject::ot_ForeignKeyConstraint:
case UMLObject::ot_CheckConstraint:
case UMLObject::ot_Category:
mt = Uml::ModelType::EntityRelationship;
break;
case UMLObject::ot_Association:
{
UMLAssociation *assoc = o->asUMLAssociation();
UMLDoc *umldoc = UMLApp::app()->document();
for (int r = Uml::RoleType::A; r <= Uml::RoleType::B; ++r) {
UMLObject *roleObj = assoc->getObject(Uml::RoleType::fromInt(r));
if (roleObj == nullptr) {
// Ouch! we have been called while types are not yet resolved
return Uml::ModelType::N_MODELTYPES;
}
UMLPackage *pkg = roleObj->umlPackage();
if (pkg) {
while (pkg->umlPackage()) { // wind back to root
pkg = pkg->umlPackage();
}
const Uml::ModelType::Enum m = umldoc->rootFolderType(pkg);
if (m != Uml::ModelType::N_MODELTYPES)
return m;
}
mt = guessContainer(roleObj);
if (mt != Uml::ModelType::Logical)
break;
}
}
break;
default:
break;
}
return mt;
}
/**
* Parse a direction string into the Uml::ParameterDirection::Enum.
*
* @param input The string to parse: "in", "out", or "inout"
* optionally followed by whitespace.
* @param result The corresponding Uml::ParameterDirection::Enum.
* @return Length of the string matched, excluding the optional
* whitespace.
*/
int stringToDirection(QString input, Uml::ParameterDirection::Enum & result)
{
QRegularExpression dirx(QStringLiteral("^(in|out|inout)"));
int pos = input.indexOf(dirx);
if (pos == -1)
return 0;
QRegularExpressionMatch dirxmatch = dirx.match(input);
const QString dirStr = dirxmatch.capturedTexts().first();
int dirLen = dirStr.length();
if (input.length() > dirLen && !input[dirLen].isSpace())
return 0; // no match after all.
if (dirStr == QStringLiteral("out"))
result = Uml::ParameterDirection::Out;
else if (dirStr == QStringLiteral("inout"))
result = Uml::ParameterDirection::InOut;
else
result = Uml::ParameterDirection::In;
return dirLen;
}
/**
* Parses a template parameter given in UML syntax.
*
* @param t Input text of the template parameter.
* Example: parname : partype
* or just: parname (for class type)
* @param nmTp NameAndType returned by this method.
* @param owningScope Pointer to the owning scope of the template param.
* @return Error status of the parse, PS_OK for success.
*/
Parse_Status parseTemplate(QString t, NameAndType& nmTp, UMLClassifier *owningScope)
{
UMLDoc *pDoc = UMLApp::app()->document();
t = t.trimmed();
if (t.isEmpty())
return PS_Empty;
QStringList nameAndType = t.split(QRegularExpression(QStringLiteral("\\s*:\\s*")));
if (nameAndType.count() == 2) {
UMLObject *pType = nullptr;
if (nameAndType[1] != QStringLiteral("class")) {
pType = pDoc->findUMLObject(nameAndType[1], UMLObject::ot_UMLObject, owningScope);
if (pType == nullptr)
return PS_Unknown_ArgType;
}
nmTp = NameAndType(nameAndType[0], pType);
} else {
nmTp = NameAndType(t, nullptr);
}
return PS_OK;
}
/**
* Parses an attribute given in UML syntax.
*
* @param a Input text of the attribute in UML syntax.
* Example: argname : argtype
* @param nmTp NameAndType returned by this method.
* @param owningScope Pointer to the owning scope of the attribute.
* @param vis Optional pointer to visibility (return value.)
* The visibility may be given at the beginning of the
* attribute text in mnemonic form as follows:
* "+" stands for public
* "#" stands for protected
* "-" stands for private
* "~" stands for implementation level visibility
*
* @return Error status of the parse, PS_OK for success.
*/
Parse_Status parseAttribute(QString a, NameAndType& nmTp, UMLClassifier *owningScope,
Uml::Visibility::Enum *vis /* = nullptr */)
{
UMLDoc *pDoc = UMLApp::app()->document();
a = a.simplified();
if (a.isEmpty())
return PS_Empty;
int colonPos = a.indexOf(QLatin1Char(':'));
if (colonPos < 0) {
nmTp = NameAndType(a, nullptr);
return PS_OK;
}
QString name = a.left(colonPos).trimmed();
if (vis) {
QRegularExpression mnemonicVis(QStringLiteral("^([\\+\\#\\-\\~] *)"));
int pos = name.indexOf(mnemonicVis);
if (pos == -1) {
*vis = Uml::Visibility::Private; // default value
} else {
QRegularExpressionMatch regMat = mnemonicVis.match(name);
QString caption = regMat.captured(1);
QString strVis = caption.left(1);
if (strVis == QStringLiteral("+"))
*vis = Uml::Visibility::Public;
else if (strVis == QStringLiteral("#"))
*vis = Uml::Visibility::Protected;
else if (strVis == QStringLiteral("-"))
*vis = Uml::Visibility::Private;
else
*vis = Uml::Visibility::Implementation;
}
name.remove(mnemonicVis);
}
Uml::ParameterDirection::Enum pd = Uml::ParameterDirection::In;
if (name.startsWith(QStringLiteral("in "))) {
pd = Uml::ParameterDirection::In;
name = name.mid(3);
} else if (name.startsWith(QStringLiteral("inout "))) {
pd = Uml::ParameterDirection::InOut;
name = name.mid(6);
} else if (name.startsWith(QStringLiteral("out "))) {
pd = Uml::ParameterDirection::Out;
name = name.mid(4);
}
a = a.mid(colonPos + 1).trimmed();
if (a.isEmpty()) {
nmTp = NameAndType(name, nullptr, pd);
return PS_OK;
}
QStringList typeAndInitialValue = a.split(QRegularExpression(QStringLiteral("\\s*=\\s*")));
const QString &type = typeAndInitialValue[0];
UMLObject *pType = pDoc->findUMLObject(type, UMLObject::ot_UMLObject, owningScope);
if (pType == nullptr) {
nmTp = NameAndType(name, nullptr, pd);
return PS_Unknown_ArgType;
}
QString initialValue;
if (typeAndInitialValue.count() == 2) {
initialValue = typeAndInitialValue[1];
}
nmTp = NameAndType(name, pType, pd, initialValue);
return PS_OK;
}
/**
* Parses an operation given in UML syntax.
*
* @param m Input text of the operation in UML syntax.
* Example of a two-argument operation returning "void":
* methodname (arg1name : arg1type, arg2name : arg2type) : void
* @param desc OpDescriptor returned by this method.
* @param owningScope Pointer to the owning scope of the operation.
* @return Error status of the parse, PS_OK for success.
*/
Parse_Status parseOperation(QString m, OpDescriptor& desc, UMLClassifier *owningScope)
{
UMLDoc *pDoc = UMLApp::app()->document();
m = m.simplified();
if (m.isEmpty())
return PS_Empty;
if (m.contains(QRegularExpression(QStringLiteral("operator *()")))) {
// C++ special case: two sets of parentheses
desc.m_name = QStringLiteral("operator()");
m.remove(QRegularExpression(QStringLiteral("operator *()")));
} else {
/**
* The search pattern includes everything up to the opening parenthesis
* because UML also permits non programming-language oriented designs
* using narrative names, for example "check water temperature".
*/
QRegularExpression beginningUpToOpenParenth(QStringLiteral("^([^\\(]+)"));
int pos = m.indexOf(beginningUpToOpenParenth);
if (pos == -1)
return PS_Illegal_MethodName;
QRegularExpressionMatch regMat = beginningUpToOpenParenth.match(m);
desc.m_name = regMat.captured(1);
}
desc.m_pReturnType = nullptr;
QRegularExpression pat = QRegularExpression(QStringLiteral("\\) *:(.*)$"));
int pos = m.indexOf(pat);
if (pos != -1) { // return type is optional
QRegularExpressionMatch regMat = pat.match(m);
QString retType = regMat.captured(1);
retType = retType.trimmed();
if (retType != QStringLiteral("void")) {
UMLObject *pRetType = owningScope ? owningScope->findTemplate(retType) : nullptr;
if (pRetType == nullptr) {
pRetType = pDoc->findUMLObject(retType, UMLObject::ot_UMLObject, owningScope);
if (pRetType == nullptr)
return PS_Unknown_ReturnType;
}
desc.m_pReturnType = pRetType;
}
}
// Remove possible empty parentheses ()
m.remove(QRegularExpression(QStringLiteral("\\s*\\(\\s*\\)")));
desc.m_args.clear();
pat = QRegularExpression(QStringLiteral("\\((.*)\\)"));
pos = m.indexOf(pat);
if (pos == -1) // argument list is optional
return PS_OK;
QRegularExpressionMatch patMat = pat.match(m);
QString arglist = patMat.captured(1);
arglist = arglist.trimmed();
if (arglist.isEmpty())
return PS_OK;
const QStringList args = arglist.split(QRegularExpression(QStringLiteral("\\s*, \\s*")));
for (QStringList::ConstIterator lit = args.begin(); lit != args.end(); ++lit) {
NameAndType nmTp;
Parse_Status ps = parseAttribute(*lit, nmTp, owningScope);
if (ps)
return ps;
desc.m_args.append(nmTp);
}
return PS_OK;
}
/**
* Parses a constraint.
*
* @param m Input text of the constraint
*
* @param name The name returned by this method
* @param owningScope Pointer to the owning scope of the constraint
* @return Error status of the parse, PS_OK for success.
*/
Parse_Status parseConstraint(QString m, QString& name, UMLEntity* owningScope)
{
Q_UNUSED(owningScope);
m = m.simplified();
if (m.isEmpty())
return PS_Empty;
int colonPos = m.indexOf(QLatin1Char(':'));
if (colonPos < 0) {
name = m;
return PS_OK;
}
name = m.left(colonPos).trimmed();
return PS_OK;
}
/**
* Returns the Parse_Status as a text.
*/
QString psText(Parse_Status value)
{
const QString text[] = {
i18n("OK"), i18nc("parse status", "Empty"), i18n("Malformed argument"),
i18n("Unknown argument type"), i18n("Illegal method name"),
i18n("Unknown return type"), i18n("Unspecified error")
};
return text[(unsigned) value];
}
/**
* Return true if the listview type is one of the predefined root views
* (root, logical, usecase, component, deployment, datatype, or entity-
* relationship view.)
*/
bool typeIsRootView(UMLListViewItem::ListViewType type)
{
switch (type) {
case UMLListViewItem::lvt_View:
case UMLListViewItem::lvt_Logical_View:
case UMLListViewItem::lvt_UseCase_View:
case UMLListViewItem::lvt_Component_View:
case UMLListViewItem::lvt_Deployment_View:
case UMLListViewItem::lvt_EntityRelationship_Model:
return true;
break;
default:
break;
}
return false;
}
/**
* Return true if the listview type also has a widget representation in diagrams.
*/
bool typeIsCanvasWidget(UMLListViewItem::ListViewType type)
{
switch (type) {
case UMLListViewItem::lvt_Actor:
case UMLListViewItem::lvt_UseCase:
case UMLListViewItem::lvt_Class:
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Logical_Folder:
case UMLListViewItem::lvt_UseCase_Folder:
case UMLListViewItem::lvt_Component_Folder:
case UMLListViewItem::lvt_Deployment_Folder:
case UMLListViewItem::lvt_EntityRelationship_Folder:
case UMLListViewItem::lvt_Subsystem:
case UMLListViewItem::lvt_Component:
case UMLListViewItem::lvt_Port:
case UMLListViewItem::lvt_Node:
case UMLListViewItem::lvt_Artifact:
case UMLListViewItem::lvt_Interface:
case UMLListViewItem::lvt_Datatype:
case UMLListViewItem::lvt_Enum:
case UMLListViewItem::lvt_Instance:
case UMLListViewItem::lvt_Entity:
case UMLListViewItem::lvt_Category:
return true;
break;
default:
break;
}
return false;
}
/**
* Return true if the listview type is a logical, usecase or component folder.
*/
bool typeIsFolder(UMLListViewItem::ListViewType type)
{
if (typeIsRootView(type) ||
type == UMLListViewItem::lvt_Datatype_Folder ||
type == UMLListViewItem::lvt_Logical_Folder ||
type == UMLListViewItem::lvt_UseCase_Folder ||
type == UMLListViewItem::lvt_Component_Folder ||
type == UMLListViewItem::lvt_Deployment_Folder ||
type == UMLListViewItem::lvt_EntityRelationship_Folder) {
return true;
} else {
return false;
}
}
/**
* Return true if the listview type may act as a container for other objects,
* i.e. if it is a folder, package, subsystem, or component.
*/
bool typeIsContainer(UMLListViewItem::ListViewType type)
{
if (typeIsFolder(type))
return true;
return (type == UMLListViewItem::lvt_Package ||
type == UMLListViewItem::lvt_Subsystem ||
type == UMLListViewItem::lvt_Component ||
type == UMLListViewItem::lvt_Class ||
type == UMLListViewItem::lvt_Interface);
}
/**
* Return true if the listview type is an attribute, operation, or template.
*/
bool typeIsClassifierList(UMLListViewItem::ListViewType type)
{
if (type == UMLListViewItem::lvt_Attribute ||
type == UMLListViewItem::lvt_Operation ||
type == UMLListViewItem::lvt_Template ||
type == UMLListViewItem::lvt_EntityAttribute ||
type == UMLListViewItem::lvt_UniqueConstraint ||
type == UMLListViewItem::lvt_ForeignKeyConstraint ||
type == UMLListViewItem::lvt_PrimaryKeyConstraint ||
type == UMLListViewItem::lvt_CheckConstraint ||
type == UMLListViewItem::lvt_EnumLiteral) {
// UMLListViewItem::lvt_InstanceAttribute must be handled separately
// because UMLInstanceAttribute is not a UMLClassifierListItem.
return true;
} else {
return false;
}
}
/**
* Return true if the listview type is a classifier (Class, Entity, Enum)
*/
bool typeIsClassifier(UMLListViewItem::ListViewType type)
{
if (type == UMLListViewItem::lvt_Class ||
type == UMLListViewItem::lvt_Interface ||
type == UMLListViewItem::lvt_Entity ||
type == UMLListViewItem::lvt_Enum) {
return true;
}
return false;
}
/**
* Return true if the listview type is a settings entry.
*/
bool typeIsProperties(UMLListViewItem::ListViewType type)
{
switch (type) {
case UMLListViewItem::lvt_Properties:
case UMLListViewItem::lvt_Properties_AutoLayout:
case UMLListViewItem::lvt_Properties_Class:
case UMLListViewItem::lvt_Properties_CodeImport:
case UMLListViewItem::lvt_Properties_CodeGeneration:
case UMLListViewItem::lvt_Properties_CodeViewer:
case UMLListViewItem::lvt_Properties_Font:
case UMLListViewItem::lvt_Properties_General:
case UMLListViewItem::lvt_Properties_UserInterface:
return true;
break;
default:
break;
}
return false;
}
/**
* Check if a listviewitem of type childType is allowed
* as child of type parentType
*/
bool typeIsAllowedInType(UMLListViewItem::ListViewType childType,
UMLListViewItem::ListViewType parentType)
{
switch (childType) {
case UMLListViewItem::lvt_Class:
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Interface:
case UMLListViewItem::lvt_Enum:
case UMLListViewItem::lvt_Instance:
return parentType == UMLListViewItem::lvt_Logical_View ||
parentType == UMLListViewItem::lvt_Class ||
parentType == UMLListViewItem::lvt_Package ||
parentType == UMLListViewItem::lvt_Logical_Folder;
case UMLListViewItem::lvt_Attribute:
return parentType == UMLListViewItem::lvt_Class;
case UMLListViewItem::lvt_EnumLiteral:
return parentType == UMLListViewItem::lvt_Enum;
case UMLListViewItem::lvt_EntityAttribute:
return parentType == UMLListViewItem::lvt_Entity;
case UMLListViewItem::lvt_InstanceAttribute:
return parentType == UMLListViewItem::lvt_Instance;
case UMLListViewItem::lvt_Operation:
return parentType == UMLListViewItem::lvt_Class ||
parentType == UMLListViewItem::lvt_Interface;
case UMLListViewItem::lvt_Datatype:
return parentType == UMLListViewItem::lvt_Logical_Folder ||
parentType == UMLListViewItem::lvt_Datatype_Folder ||
parentType == UMLListViewItem::lvt_Class ||
parentType == UMLListViewItem::lvt_Interface ||
parentType == UMLListViewItem::lvt_Package;
case UMLListViewItem::lvt_Class_Diagram:
case UMLListViewItem::lvt_Collaboration_Diagram:
case UMLListViewItem::lvt_State_Diagram:
case UMLListViewItem::lvt_Activity_Diagram:
case UMLListViewItem::lvt_Sequence_Diagram:
case UMLListViewItem::lvt_Object_Diagram:
return parentType == UMLListViewItem::lvt_Logical_Folder ||
parentType == UMLListViewItem::lvt_Logical_View;
case UMLListViewItem::lvt_Logical_Folder:
return parentType == UMLListViewItem::lvt_Package ||
parentType == UMLListViewItem::lvt_Logical_Folder ||
parentType == UMLListViewItem::lvt_Logical_View;
case UMLListViewItem::lvt_UseCase_Folder:
return parentType == UMLListViewItem::lvt_UseCase_Folder ||
parentType == UMLListViewItem::lvt_UseCase_View;
case UMLListViewItem::lvt_Component_Folder:
return parentType == UMLListViewItem::lvt_Component_Folder ||
parentType == UMLListViewItem::lvt_Component_View;
case UMLListViewItem::lvt_Deployment_Folder:
return parentType == UMLListViewItem::lvt_Deployment_Folder ||
parentType == UMLListViewItem::lvt_Deployment_View;
case UMLListViewItem::lvt_EntityRelationship_Folder:
return parentType == UMLListViewItem::lvt_EntityRelationship_Folder ||
parentType == UMLListViewItem::lvt_EntityRelationship_Model;
case UMLListViewItem::lvt_Actor:
case UMLListViewItem::lvt_UseCase:
case UMLListViewItem::lvt_UseCase_Diagram:
return parentType == UMLListViewItem::lvt_UseCase_Folder ||
parentType == UMLListViewItem::lvt_UseCase_View;
case UMLListViewItem::lvt_Subsystem:
return parentType == UMLListViewItem::lvt_Component_Folder ||
parentType == UMLListViewItem::lvt_Subsystem ||
parentType == UMLListViewItem::lvt_Component_View;
case UMLListViewItem::lvt_Component:
return parentType == UMLListViewItem::lvt_Component_Folder ||
parentType == UMLListViewItem::lvt_Component ||
parentType == UMLListViewItem::lvt_Subsystem ||
parentType == UMLListViewItem::lvt_Component_View;
case UMLListViewItem::lvt_Port:
return parentType == UMLListViewItem::lvt_Component ||
parentType == UMLListViewItem::lvt_Subsystem;
case UMLListViewItem::lvt_Artifact:
case UMLListViewItem::lvt_Component_Diagram:
return parentType == UMLListViewItem::lvt_Component_Folder ||
parentType == UMLListViewItem::lvt_Component_View;
case UMLListViewItem::lvt_Node:
case UMLListViewItem::lvt_Deployment_Diagram:
return parentType == UMLListViewItem::lvt_Deployment_Folder ||
parentType == UMLListViewItem::lvt_Deployment_View;
case UMLListViewItem::lvt_Entity:
case UMLListViewItem::lvt_EntityRelationship_Diagram:
case UMLListViewItem::lvt_Category:
return parentType == UMLListViewItem::lvt_EntityRelationship_Folder ||
parentType == UMLListViewItem::lvt_EntityRelationship_Model;
default:
return false;
}
}
/**
* Return true if the listview type is a diagram.
*/
bool typeIsDiagram(UMLListViewItem::ListViewType type)
{
if (type == UMLListViewItem::lvt_Class_Diagram ||
type == UMLListViewItem::lvt_Collaboration_Diagram ||
type == UMLListViewItem::lvt_State_Diagram ||
type == UMLListViewItem::lvt_Activity_Diagram ||
type == UMLListViewItem::lvt_Sequence_Diagram ||
type == UMLListViewItem::lvt_UseCase_Diagram ||
type == UMLListViewItem::lvt_Component_Diagram ||
type == UMLListViewItem::lvt_Deployment_Diagram ||
type == UMLListViewItem::lvt_EntityRelationship_Diagram ||
type == UMLListViewItem::lvt_Object_Diagram) {
return true;
} else {
return false;
}
}
/**
* Return the Model_Type which corresponds to the given DiagramType.
*/
Uml::ModelType::Enum convert_DT_MT(Uml::DiagramType::Enum dt)
{
Uml::ModelType::Enum mt;
switch (dt) {
case Uml::DiagramType::UseCase:
mt = Uml::ModelType::UseCase;
break;
case Uml::DiagramType::Collaboration:
case Uml::DiagramType::Class:
case Uml::DiagramType::Object:
case Uml::DiagramType::Sequence:
case Uml::DiagramType::State:
case Uml::DiagramType::Activity:
mt = Uml::ModelType::Logical;
break;
case Uml::DiagramType::Component:
mt = Uml::ModelType::Component;
break;
case Uml::DiagramType::Deployment:
mt = Uml::ModelType::Deployment;
break;
case Uml::DiagramType::EntityRelationship:
mt = Uml::ModelType::EntityRelationship;
break;
default:
logError1("Model_Utils::convert_DT_MT: illegal input value %1", dt);
mt = Uml::ModelType::N_MODELTYPES;
break;
}
return mt;
}
/**
* Return the ListViewType which corresponds to the given Model_Type.
*/
UMLListViewItem::ListViewType convert_MT_LVT(Uml::ModelType::Enum mt)
{
UMLListViewItem::ListViewType lvt = UMLListViewItem::lvt_Unknown;
switch (mt) {
case Uml::ModelType::Logical:
lvt = UMLListViewItem::lvt_Logical_View;
break;
case Uml::ModelType::UseCase:
lvt = UMLListViewItem::lvt_UseCase_View;
break;
case Uml::ModelType::Component:
lvt = UMLListViewItem::lvt_Component_View;
break;
case Uml::ModelType::Deployment:
lvt = UMLListViewItem::lvt_Deployment_View;
break;
case Uml::ModelType::EntityRelationship:
lvt = UMLListViewItem::lvt_EntityRelationship_Model;
break;
default:
break;
}
return lvt;
}
/**
* Return the Model_Type which corresponds to the given ListViewType.
* Returns Uml::N_MODELTYPES if the list view type given does not map
* to a Model_Type.
*/
Uml::ModelType::Enum convert_LVT_MT(UMLListViewItem::ListViewType lvt)
{
Uml::ModelType::Enum mt = Uml::ModelType::N_MODELTYPES;
switch (lvt) {
case UMLListViewItem::lvt_Logical_View:
mt = Uml::ModelType::Logical;
break;
case UMLListViewItem::lvt_UseCase_View:
mt = Uml::ModelType::UseCase;
break;
case UMLListViewItem::lvt_Component_View:
mt = Uml::ModelType::Component;
break;
case UMLListViewItem::lvt_Deployment_View:
mt = Uml::ModelType::Deployment;
break;
case UMLListViewItem::lvt_EntityRelationship_Model:
mt = Uml::ModelType::EntityRelationship;
break;
default:
break;
}
return mt;
}
/**
* Convert a diagram type enum to the equivalent list view type.
*/
UMLListViewItem::ListViewType convert_DT_LVT(Uml::DiagramType::Enum dt)
{
UMLListViewItem::ListViewType type = UMLListViewItem::lvt_Unknown;
switch(dt) {
case Uml::DiagramType::UseCase:
type = UMLListViewItem::lvt_UseCase_Diagram;
break;
case Uml::DiagramType::Class:
type = UMLListViewItem::lvt_Class_Diagram;
break;
case Uml::DiagramType::Object:
type = UMLListViewItem::lvt_Object_Diagram;
break;
case Uml::DiagramType::Sequence:
type = UMLListViewItem::lvt_Sequence_Diagram;
break;
case Uml::DiagramType::Collaboration:
type = UMLListViewItem::lvt_Collaboration_Diagram;
break;
case Uml::DiagramType::State:
type = UMLListViewItem::lvt_State_Diagram;
break;
case Uml::DiagramType::Activity:
type = UMLListViewItem::lvt_Activity_Diagram;
break;
case Uml::DiagramType::Component:
type = UMLListViewItem::lvt_Component_Diagram;
break;
case Uml::DiagramType::Deployment:
type = UMLListViewItem::lvt_Deployment_Diagram;
break;
case Uml::DiagramType::EntityRelationship:
type = UMLListViewItem::lvt_EntityRelationship_Diagram;
break;
default:
logWarn1("Model_Utils::convert_DT_LVT() called on unknown diagram type %1", dt);
}
return type;
}
/**
* Convert an object's type to the equivalent list view type
*
* @param o Pointer to the UMLObject whose type shall be converted
* to the equivalent ListViewType. We cannot just
* pass in a UMLObject::ObjectType because a UMLFolder is mapped
* to different ListViewType values, depending on its
* location in one of the predefined modelviews (Logical/
* UseCase/etc.)
* @return The equivalent ListViewType.
*/
UMLListViewItem::ListViewType convert_OT_LVT(UMLObject *o)
{
UMLObject::ObjectType ot = o->baseType();
UMLListViewItem::ListViewType type = UMLListViewItem::lvt_Unknown;
switch(ot) {
case UMLObject::ot_UseCase:
type = UMLListViewItem::lvt_UseCase;
break;
case UMLObject::ot_Actor:
type = UMLListViewItem::lvt_Actor;
break;
case UMLObject::ot_Class:
type = UMLListViewItem::lvt_Class;
break;
case UMLObject::ot_Package:
if (o->stereotype() == QStringLiteral("subsystem"))
type = UMLListViewItem::lvt_Subsystem;
else
type = UMLListViewItem::lvt_Package;
break;
case UMLObject::ot_Folder:
{
UMLDoc *umldoc = UMLApp::app()->document();
UMLPackage *p = o->asUMLPackage();
do {
const Uml::ModelType::Enum mt = umldoc->rootFolderType(p);
if (mt != Uml::ModelType::N_MODELTYPES) {
switch (mt) {
case Uml::ModelType::Logical:
type = UMLListViewItem::lvt_Logical_Folder;
break;
case Uml::ModelType::UseCase:
type = UMLListViewItem::lvt_UseCase_Folder;
break;
case Uml::ModelType::Component:
type = UMLListViewItem::lvt_Component_Folder;
break;
case Uml::ModelType::Deployment:
type = UMLListViewItem::lvt_Deployment_Folder;
break;
case Uml::ModelType::EntityRelationship:
type = UMLListViewItem::lvt_EntityRelationship_Folder;
break;
default:
break;
}
return type;
}
} while ((p = p->umlPackage()) != nullptr);
logError1("Model_Utils::convert_OT_LVT(%1): internal error - "
"object is not properly nested in folder", o->name());
}
break;
case UMLObject::ot_Component:
type = UMLListViewItem::lvt_Component;
break;
case UMLObject::ot_Port:
type = UMLListViewItem::lvt_Port;
break;
case UMLObject::ot_Node:
type = UMLListViewItem::lvt_Node;
break;
case UMLObject::ot_Artifact:
type = UMLListViewItem::lvt_Artifact;
break;
case UMLObject::ot_Interface:
type = UMLListViewItem::lvt_Interface;
break;
case UMLObject::ot_Datatype:
type = UMLListViewItem::lvt_Datatype;
break;
case UMLObject::ot_Enum:
type = UMLListViewItem::lvt_Enum;
break;
case UMLObject::ot_EnumLiteral:
type = UMLListViewItem::lvt_EnumLiteral;
break;
case UMLObject::ot_Entity:
type = UMLListViewItem::lvt_Entity;
break;
case UMLObject::ot_Category:
type = UMLListViewItem::lvt_Category;
break;
case UMLObject::ot_EntityAttribute:
type = UMLListViewItem::lvt_EntityAttribute;
break;
case UMLObject::ot_UniqueConstraint: {
const UMLEntity* ent = o->umlParent()->asUMLEntity();
const UMLUniqueConstraint* uc = o->asUMLUniqueConstraint();
if (ent->isPrimaryKey(uc)) {
type = UMLListViewItem::lvt_PrimaryKeyConstraint;
} else {
type = UMLListViewItem::lvt_UniqueConstraint;
}
break;
}
case UMLObject::ot_ForeignKeyConstraint:
type = UMLListViewItem::lvt_ForeignKeyConstraint;
break;
case UMLObject::ot_CheckConstraint:
type = UMLListViewItem::lvt_CheckConstraint;
break;
case UMLObject::ot_Attribute:
type = UMLListViewItem::lvt_Attribute;
break;
case UMLObject::ot_Operation:
type = UMLListViewItem::lvt_Operation;
break;
case UMLObject::ot_Template:
type = UMLListViewItem::lvt_Template;
break;
case UMLObject::ot_Association:
type = UMLListViewItem::lvt_Association;
break;
case UMLObject::ot_Instance:
type = UMLListViewItem::lvt_Instance;
break;
case UMLObject::ot_InstanceAttribute:
type = UMLListViewItem::lvt_InstanceAttribute;
break;
default:
break;
}
return type;
}
/**
* Converts a list view type enum to the equivalent object type.
*
* @param lvt The ListViewType to convert.
* @return The converted ObjectType if the listview type
* has a UMLObject::ObjectType representation, else 0.
*/
UMLObject::ObjectType convert_LVT_OT(UMLListViewItem::ListViewType lvt)
{
UMLObject::ObjectType ot = (UMLObject::ObjectType)0;
switch (lvt) {
case UMLListViewItem::lvt_UseCase:
ot = UMLObject::ot_UseCase;
break;
case UMLListViewItem::lvt_Actor:
ot = UMLObject::ot_Actor;
break;
case UMLListViewItem::lvt_Class:
ot = UMLObject::ot_Class;
break;
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Subsystem:
ot = UMLObject::ot_Package;
break;
case UMLListViewItem::lvt_Component:
ot = UMLObject::ot_Component;
break;
case UMLListViewItem::lvt_Port:
ot = UMLObject::ot_Port;
break;
case UMLListViewItem::lvt_Node:
ot = UMLObject::ot_Node;
break;
case UMLListViewItem::lvt_Artifact:
ot = UMLObject::ot_Artifact;
break;
case UMLListViewItem::lvt_Interface:
ot = UMLObject::ot_Interface;
break;
case UMLListViewItem::lvt_Datatype:
ot = UMLObject::ot_Datatype;
break;
case UMLListViewItem::lvt_Enum:
ot = UMLObject::ot_Enum;
break;
case UMLListViewItem::lvt_Entity:
ot = UMLObject::ot_Entity;
break;
case UMLListViewItem::lvt_Category:
ot = UMLObject::ot_Category;
break;
case UMLListViewItem::lvt_EntityAttribute:
ot = UMLObject::ot_EntityAttribute;
break;
case UMLListViewItem::lvt_UniqueConstraint:
ot = UMLObject::ot_UniqueConstraint;
break;
case UMLListViewItem::lvt_PrimaryKeyConstraint:
ot = UMLObject::ot_UniqueConstraint;
break;
case UMLListViewItem::lvt_ForeignKeyConstraint:
ot = UMLObject::ot_ForeignKeyConstraint;
break;
case UMLListViewItem::lvt_CheckConstraint:
ot = UMLObject::ot_CheckConstraint;
break;
case UMLListViewItem::lvt_Attribute:
ot = UMLObject::ot_Attribute;
break;
case UMLListViewItem::lvt_Operation:
ot = UMLObject::ot_Operation;
break;
case UMLListViewItem::lvt_Template:
ot = UMLObject::ot_Template;
break;
case UMLListViewItem::lvt_EnumLiteral:
ot = UMLObject::ot_EnumLiteral;
break;
case UMLListViewItem::lvt_Instance:
ot = UMLObject::ot_Instance;
break;
case UMLListViewItem::lvt_InstanceAttribute:
ot = UMLObject::ot_InstanceAttribute;
break;
default:
if (typeIsFolder(lvt))
ot = UMLObject::ot_Folder;
break;
}
return ot;
}
/**
* Return the IconType which corresponds to the given listview type.
*
* @param lvt ListViewType to convert.
* @param o Optional UMLObject pointer is only used if @p lvt is lvt_Class:
* If the stereotype <<class-or-package>> is applied on the object
* then Icon_Utils::it_ClassOrPackage is returned.
* @return The Icon_Utils::IconType corresponding to the lvt.
* Returns it_Home in case no mapping to IconType exists.
*/
Icon_Utils::IconType convert_LVT_IT(UMLListViewItem::ListViewType lvt, UMLObject *o)
{
Icon_Utils::IconType icon = Icon_Utils::it_Home;
switch (lvt) {
case UMLListViewItem::lvt_UseCase_View:
case UMLListViewItem::lvt_UseCase_Folder:
icon = Icon_Utils::it_Folder_Grey;
break;
case UMLListViewItem::lvt_Logical_View:
case UMLListViewItem::lvt_Logical_Folder:
icon = Icon_Utils::it_Folder_Green;
break;
case UMLListViewItem::lvt_Datatype_Folder:
icon = Icon_Utils::it_Folder_Orange;
break;
case UMLListViewItem::lvt_Component_View:
case UMLListViewItem::lvt_Component_Folder:
icon = Icon_Utils::it_Folder_Red;
break;
case UMLListViewItem::lvt_Deployment_View:
case UMLListViewItem::lvt_Deployment_Folder:
icon = Icon_Utils::it_Folder_Violet;
break;
case UMLListViewItem::lvt_EntityRelationship_Model:
case UMLListViewItem::lvt_EntityRelationship_Folder:
icon = Icon_Utils::it_Folder_Cyan;
break;
case UMLListViewItem::lvt_Actor:
icon = Icon_Utils::it_Actor;
break;
case UMLListViewItem::lvt_Association:
icon = Icon_Utils::it_Association;
break;
case UMLListViewItem::lvt_UseCase:
icon = Icon_Utils::it_UseCase;
break;
case UMLListViewItem::lvt_Class:
if (o && o->stereotype() == QStringLiteral("class-or-package"))
icon = Icon_Utils::it_ClassOrPackage;
else
icon = Icon_Utils::it_Class;
break;
case UMLListViewItem::lvt_Package:
icon = Icon_Utils::it_Package;
break;
case UMLListViewItem::lvt_Subsystem:
icon = Icon_Utils::it_Subsystem;
break;
case UMLListViewItem::lvt_Component:
icon = Icon_Utils::it_Component;
break;
case UMLListViewItem::lvt_Port:
icon = Icon_Utils::it_Port;
break;
case UMLListViewItem::lvt_Node:
icon = Icon_Utils::it_Node;
break;
case UMLListViewItem::lvt_Artifact:
icon = Icon_Utils::it_Artifact;
break;
case UMLListViewItem::lvt_Interface:
icon = Icon_Utils::it_Interface;
break;
case UMLListViewItem::lvt_Datatype:
icon = Icon_Utils::it_Datatype;
break;
case UMLListViewItem::lvt_Enum:
icon = Icon_Utils::it_Enum;
break;
case UMLListViewItem::lvt_Entity:
icon = Icon_Utils::it_Entity;
break;
case UMLListViewItem::lvt_Category:
icon = Icon_Utils::it_Category;
break;
case UMLListViewItem::lvt_Template:
icon = Icon_Utils::it_Template;
break;
case UMLListViewItem::lvt_Attribute:
icon = Icon_Utils::it_Private_Attribute;
break;
case UMLListViewItem::lvt_EntityAttribute:
icon = Icon_Utils::it_Private_Attribute;
break;
case UMLListViewItem::lvt_EnumLiteral:
icon = Icon_Utils::it_Public_Attribute;
break;
case UMLListViewItem::lvt_Operation:
icon = Icon_Utils::it_Public_Method;
break;
case UMLListViewItem::lvt_UniqueConstraint:
icon = Icon_Utils::it_Unique_Constraint;
break;
case UMLListViewItem::lvt_PrimaryKeyConstraint:
icon = Icon_Utils::it_PrimaryKey_Constraint;
break;
case UMLListViewItem::lvt_ForeignKeyConstraint:
icon = Icon_Utils::it_ForeignKey_Constraint;
break;
case UMLListViewItem::lvt_CheckConstraint:
icon = Icon_Utils::it_Check_Constraint;
break;
case UMLListViewItem::lvt_Class_Diagram:
icon = Icon_Utils::it_Diagram_Class;
break;
case UMLListViewItem::lvt_Object_Diagram:
icon = Icon_Utils::it_Diagram_Object;
break;
case UMLListViewItem::lvt_UseCase_Diagram:
icon = Icon_Utils::it_Diagram_Usecase;
break;
case UMLListViewItem::lvt_Sequence_Diagram:
icon = Icon_Utils::it_Diagram_Sequence;
break;
case UMLListViewItem::lvt_Collaboration_Diagram:
icon = Icon_Utils::it_Diagram_Collaboration;
break;
case UMLListViewItem::lvt_State_Diagram:
icon = Icon_Utils::it_Diagram_State;
break;
case UMLListViewItem::lvt_Activity_Diagram:
icon = Icon_Utils::it_Diagram_Activity;
break;
case UMLListViewItem::lvt_Component_Diagram:
icon = Icon_Utils::it_Diagram_Component;
break;
case UMLListViewItem::lvt_Deployment_Diagram:
icon = Icon_Utils::it_Diagram_Deployment;
break;
case UMLListViewItem::lvt_EntityRelationship_Diagram:
icon = Icon_Utils::it_Diagram_EntityRelationship;
break;
case UMLListViewItem::lvt_Properties:
icon = Icon_Utils::it_Properties;
break;
case UMLListViewItem::lvt_Properties_AutoLayout:
icon = Icon_Utils::it_Properties_AutoLayout;
break;
case UMLListViewItem::lvt_Properties_Class:
icon = Icon_Utils::it_Properties_Class;
break;
case UMLListViewItem::lvt_Properties_CodeImport:
icon = Icon_Utils::it_Properties_CodeImport;
break;
case UMLListViewItem::lvt_Properties_CodeGeneration:
icon = Icon_Utils::it_Properties_CodeGeneration;
break;
case UMLListViewItem::lvt_Properties_CodeViewer:
icon = Icon_Utils::it_Properties_CodeViewer;
break;
case UMLListViewItem::lvt_Properties_Font:
icon = Icon_Utils::it_Properties_Font;
break;
case UMLListViewItem::lvt_Properties_General:
icon = Icon_Utils::it_Properties_General;
break;
case UMLListViewItem::lvt_Properties_UserInterface:
icon = Icon_Utils::it_Properties_UserInterface;
break;
case UMLListViewItem::lvt_Instance:
icon = Icon_Utils::it_Instance;
break;
case UMLListViewItem::lvt_InstanceAttribute:
icon = Icon_Utils::it_Private_Attribute;
break;
default:
break;
}
return icon;
}
/**
* Return the DiagramType which corresponds to the given listview type.
*
* @param lvt ListViewType to convert.
* @return The Uml::DiagramType corresponding to the lvt.
* Returns dt_Undefined in case no mapping to DiagramType exists.
*/
Uml::DiagramType::Enum convert_LVT_DT(UMLListViewItem::ListViewType lvt)
{
Uml::DiagramType::Enum dt = Uml::DiagramType::Undefined;
switch (lvt) {
case UMLListViewItem::lvt_Class_Diagram:
dt = Uml::DiagramType::Class;
break;
case UMLListViewItem::lvt_UseCase_Diagram:
dt = Uml::DiagramType::UseCase;
break;
case UMLListViewItem::lvt_Sequence_Diagram:
dt = Uml::DiagramType::Sequence;
break;
case UMLListViewItem::lvt_Collaboration_Diagram:
dt = Uml::DiagramType::Collaboration;
break;
case UMLListViewItem::lvt_State_Diagram:
dt = Uml::DiagramType::State;
break;
case UMLListViewItem::lvt_Activity_Diagram:
dt = Uml::DiagramType::Activity;
break;
case UMLListViewItem::lvt_Component_Diagram:
dt = Uml::DiagramType::Component;
break;
case UMLListViewItem::lvt_Deployment_Diagram:
dt = Uml::DiagramType::Deployment;
break;
case UMLListViewItem::lvt_EntityRelationship_Diagram:
dt = Uml::DiagramType::EntityRelationship;
break;
case UMLListViewItem::lvt_Object_Diagram:
dt = Uml::DiagramType::Object;
break;
default:
break;
}
return dt;
}
/**
* Converts a list view type enum to the equivalent settings dialog type.
*
* @param type The ListViewType to convert.
* @return The converted settings dialog type
*/
MultiPageDialogBase::PageType convert_LVT_PT(UMLListViewItem::ListViewType type)
{
MultiPageDialogBase::PageType pt = MultiPageDialogBase::GeneralPage;
switch (type) {
case UMLListViewItem::lvt_Properties:
pt = MultiPageDialogBase::GeneralPage;
break;
case UMLListViewItem::lvt_Properties_AutoLayout:
pt = MultiPageDialogBase::AutoLayoutPage;
break;
case UMLListViewItem::lvt_Properties_Class:
pt = MultiPageDialogBase::ClassPage;
break;
case UMLListViewItem::lvt_Properties_CodeImport:
pt = MultiPageDialogBase::CodeImportPage;
break;
case UMLListViewItem::lvt_Properties_CodeGeneration:
pt = MultiPageDialogBase::CodeGenerationPage;
break;
case UMLListViewItem::lvt_Properties_CodeViewer:
pt = MultiPageDialogBase::CodeViewerPage;
break;
case UMLListViewItem::lvt_Properties_Font:
pt = MultiPageDialogBase::FontPage;
break;
case UMLListViewItem::lvt_Properties_General:
pt = MultiPageDialogBase::GeneralPage;
break;
case UMLListViewItem::lvt_Properties_UserInterface:
pt = MultiPageDialogBase::UserInterfacePage;
break;
default:
break;
}
return pt;
}
/**
* Return the Model_Type which corresponds to the given ObjectType.
*/
Uml::ModelType::Enum convert_OT_MT(UMLObject::ObjectType ot)
{
Uml::ModelType::Enum mt = Uml::ModelType::N_MODELTYPES;
switch (ot) {
case UMLObject::ot_Actor:
case UMLObject::ot_UseCase:
mt = Uml::ModelType::UseCase;
break;
case UMLObject::ot_Component:
case UMLObject::ot_Port:
case UMLObject::ot_Artifact:
case UMLObject::ot_SubSystem:
mt = Uml::ModelType::Component;
break;
case UMLObject::ot_Node:
mt = Uml::ModelType::Deployment;
break;
case UMLObject::ot_Entity:
case UMLObject::ot_EntityAttribute:
case UMLObject::ot_UniqueConstraint:
case UMLObject::ot_ForeignKeyConstraint:
case UMLObject::ot_CheckConstraint:
case UMLObject::ot_Category:
mt = Uml::ModelType::EntityRelationship;
break;
default:
mt = Uml::ModelType::Logical;
break;
}
return mt;
}
/**
* Converts from the UpdateDeleteAction enum to a QString
* @param uda The UpdateDeleteAction enum literal
*/
QString updateDeleteActionToString(UMLForeignKeyConstraint::UpdateDeleteAction uda)
{
switch(uda) {
case UMLForeignKeyConstraint::uda_NoAction:
return QStringLiteral("NO ACTION");
case UMLForeignKeyConstraint::uda_Restrict:
return QStringLiteral("RESTRICT");
case UMLForeignKeyConstraint::uda_Cascade:
return QStringLiteral("CASCADE");
case UMLForeignKeyConstraint::uda_SetNull:
return QStringLiteral("SET NULL");
case UMLForeignKeyConstraint::uda_SetDefault:
return QStringLiteral("SET DEFAULT");
default:
return QString();
}
}
/**
* Return true if the object type is allowed in the related diagram
* @param o UML object instance
* @param scene diagram instance
* @return true type is allowed
* @return false type is not allowed
*/
bool typeIsAllowedInDiagram(UMLObject* o, UMLScene *scene)
{
//make sure dragging item onto correct diagram
// classifier - class, seq, coll diagram
// actor, usecase - usecase diagram
UMLObject::ObjectType ot = o->baseType();
Uml::ID::Type id = o->id();
Uml::DiagramType::Enum diagramType = scene->type();
bool bAccept = true;
switch (diagramType) {
case Uml::DiagramType::UseCase:
if ((scene->widgetOnDiagram(id) && ot == UMLObject::ot_Actor) ||
(ot != UMLObject::ot_Actor && ot != UMLObject::ot_UseCase))
bAccept = false;
break;
case Uml::DiagramType::Class:
if (scene->widgetOnDiagram(id) ||
(ot != UMLObject::ot_Class &&
ot != UMLObject::ot_Package &&
ot != UMLObject::ot_Interface &&
ot != UMLObject::ot_Enum &&
ot != UMLObject::ot_Datatype &&
ot != UMLObject::ot_Instance)) {
bAccept = false;
}
break;
case Uml::DiagramType::Object:
if (scene->widgetOnDiagram(id) || ot != UMLObject::ot_Instance)
bAccept = false;
break;
case Uml::DiagramType::Sequence:
if (ot != UMLObject::ot_Class &&
ot != UMLObject::ot_Interface &&
ot != UMLObject::ot_Actor)
bAccept = false;
break;
case Uml::DiagramType::Collaboration:
if (ot != UMLObject::ot_Class &&
ot != UMLObject::ot_Interface &&
ot != UMLObject::ot_Instance &&
ot != UMLObject::ot_Actor)
bAccept = false;
break;
case Uml::DiagramType::Deployment:
if (scene->widgetOnDiagram(id))
bAccept = false;
else if (ot != UMLObject::ot_Interface &&
ot != UMLObject::ot_Package &&
ot != UMLObject::ot_Component &&
ot != UMLObject::ot_Class &&
ot != UMLObject::ot_Node)
bAccept = false;
else if (ot == UMLObject::ot_Package &&
o->stereotype() != QStringLiteral("subsystem"))
bAccept = false;
break;
case Uml::DiagramType::Component:
if (scene->widgetOnDiagram(id) ||
(ot != UMLObject::ot_Interface &&
ot != UMLObject::ot_Package &&
ot != UMLObject::ot_Component &&
ot != UMLObject::ot_Port &&
ot != UMLObject::ot_Artifact &&
ot != UMLObject::ot_Class))
bAccept = false;
else if (ot == UMLObject::ot_Class && !o->isAbstract())
bAccept = false;
else if (ot == UMLObject::ot_Port) {
const bool componentOnDiagram = scene->widgetOnDiagram(o->umlPackage()->id());
bAccept = componentOnDiagram;
}
break;
case Uml::DiagramType::EntityRelationship:
if (scene->widgetOnDiagram(id) ||
(ot != UMLObject::ot_Entity &&
ot != UMLObject::ot_Category))
bAccept = false;
break;
default:
break;
}
return bAccept;
}
/**
* Return true if the widget type is allowed in the related diagram
* @param w UML widget object
* @param scene diagram instance
* @return true type is allowed
* @return false type is not allowed
*/
bool typeIsAllowedInDiagram(UMLWidget* w, UMLScene *scene)
{
UMLWidget::WidgetType wt = w->baseType();
Uml::DiagramType::Enum diagramType = scene->type();
bool bAccept = true;
// TODO: check additional widgets
switch (diagramType) {
case Uml::DiagramType::Activity:
case Uml::DiagramType::Class:
case Uml::DiagramType::Object:
case Uml::DiagramType::Collaboration:
case Uml::DiagramType::Component:
case Uml::DiagramType::Deployment:
case Uml::DiagramType::EntityRelationship:
case Uml::DiagramType::Sequence:
case Uml::DiagramType::State:
case Uml::DiagramType::UseCase:
default:
switch(wt) {
case WidgetBase::wt_Note:
break;
case WidgetBase::wt_Text:
{
FloatingTextWidget *ft = w->asFloatingTextWidget();
if (ft && ft->textRole() != Uml::TextRole::Floating) {
bAccept = false;
}
}
break;
default:
bAccept = false;
break;
}
break;
}
return bAccept;
}
/**
* return true if given object type supports associations
* @param type uml object type to check
*/
bool hasAssociations(UMLObject::ObjectType type)
{
switch (type) {
case UMLObject::ot_Actor:
case UMLObject::ot_UseCase:
case UMLObject::ot_Class:
case UMLObject::ot_Package:
case UMLObject::ot_Component:
case UMLObject::ot_Node:
case UMLObject::ot_Artifact:
case UMLObject::ot_Interface:
case UMLObject::ot_Enum:
case UMLObject::ot_Entity:
case UMLObject::ot_Datatype:
case UMLObject::ot_Category:
case UMLObject::ot_Instance:
return true;
default:
return false;
}
}
} // namespace Model_Utils
| 92,038
|
C++
|
.cpp
| 2,256
| 32.723848
| 118
| 0.615458
|
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,250
|
assocrules.cpp
|
KDE_umbrello/umbrello/assocrules.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "assocrules.h"
// local includes
#define DBG_SRC QStringLiteral("AssocRules")
#include "debug_utils.h"
#include "uml.h"
#include "umlview.h"
#include "umlwidget.h"
#include "umlobject.h"
#include "associationwidgetlist.h"
#include "associationwidget.h"
#include "statewidget.h"
#include "activitywidget.h"
#include "signalwidget.h"
#include "forkjoinwidget.h"
#include "umlscene.h"
#include "umllistview.h"
#include "model_utils.h"
// kde includes
#include <typeinfo>
#include <KMessageBox>
DEBUG_REGISTER(AssocRules)
/**
* Constructor.
*/
AssocRules::AssocRules()
{
}
/**
* Destructor.
*/
AssocRules::~AssocRules()
{
}
/**
* Returns whether an association is going to be allowed for the given
* values. This method is used to test if you can start an association.
*/
bool AssocRules::allowAssociation(Uml::AssociationType::Enum assocType, UMLWidget * widget)
{
WidgetBase::WidgetType widgetType = widget->baseType();
if (widgetType == WidgetBase::wt_Datatype &&
Model_Utils::isCommonDataType(widget->name())) {
// cannot add association to programming language predefined type
return false;
}
bool bValid = false;
for (int i = 0; i < m_nNumRules; ++i) {
const Assoc_Rule& rule = m_AssocRules[i];
if (!rule.isValid())
continue;
if (assocType != rule.assoc_type)
continue;
if (widgetType == rule.widgetA_type ||
(widgetType == rule.widgetB_type && rule.bidirectional)) {
bValid = true;
break;
}
}
if(!bValid) {
// Special case: Subsystem realizes interface in component diagram
UMLView *view = UMLApp::app()->currentView();
if (view && view->umlScene()->isComponentDiagram() &&
widgetType == WidgetBase::wt_Package &&
(assocType == Uml::AssociationType::Generalization ||
assocType == Uml::AssociationType::Realization)) {
logDebug2("allowAssociation(widget %1, assoc %2) : Exception for subsystem "
"realizing interface in component diagram", widgetType, assocType);
} else {
logDebug2("allowAssociation(widget %1, assoc %2) : no permission rule found",
widgetType, assocType);
return false;
}
}
AssociationWidgetList list = widget->associationWidgetList();
switch(assocType) {
case Uml::AssociationType::Association:
case Uml::AssociationType::UniAssociation:
case Uml::AssociationType::Dependency:
case Uml::AssociationType::Coll_Mesg_Sync:
case Uml::AssociationType::Coll_Mesg_Async:
case Uml::AssociationType::Generalization://can have many sub/super types
case Uml::AssociationType::Aggregation:
case Uml::AssociationType::Relationship:
case Uml::AssociationType::Composition:
case Uml::AssociationType::Containment:
return true;//doesn't matter whats already connected to widget
break;
case Uml::AssociationType::Association_Self:
return true;// we should really check that connection is to same object
break;
case Uml::AssociationType::Realization: // one connected to widget only (a or b)
for(AssociationWidget* assoc : list) {
if (assoc->associationType() == Uml::AssociationType::Realization) {
logDebug2("allowAssociation(widget %1, assoc %2) : disallowing more "
"than one realization to object", widgetType, assocType);
return false;
}
}
return true;
break;
case Uml::AssociationType::State:
{
StateWidget *pState = widget->asStateWidget();
if (pState == nullptr || pState->stateType() != StateWidget::End)
return true;
logDebug2("allowAssociation(widget %1, assoc %2) : disallowing because "
"state type is not 'End'", widgetType, assocType);
}
break;
case Uml::AssociationType::Activity:
case Uml::AssociationType::Exception:
{
ActivityWidget *pActivity = widget->asActivityWidget();
if (pActivity == nullptr || pActivity->activityType() != ActivityWidget::End)
return true;
logDebug2("allowAssociation(widget %1, assoc %2) : disallowing because "
"activity type is not 'End'", widgetType, assocType);
}
break;
case Uml::AssociationType::Anchor:
return true;
break;
case Uml::AssociationType::Category2Parent:
if (widgetType == WidgetBase::wt_Category)
return true;
logDebug2("allowAssociation(widget %1, assoc %2) : disallowing because "
"widget is not Category", widgetType, assocType);
break;
case Uml::AssociationType::Child2Category:
if (widgetType == WidgetBase::wt_Entity)
return true;
logDebug2("allowAssociation(widget %1, assoc %2) : disallowing because "
"widget is not Entity", widgetType, assocType);
break;
default:
logWarn1("AssocRules::allowAssociation() on unknown type %1", assocType);
break;
}
return false;
}
/**
* Returns whether an association is valid with the given variables.
* This method is used to finish an association.
* When we know what we are going to connect both ends of the association to, we can
* use this method.
*/
bool AssocRules::allowAssociation(Uml::AssociationType::Enum assocType,
UMLWidget * widgetA, UMLWidget * widgetB)
{
WidgetBase::WidgetType widgetTypeA = widgetA->baseType();
WidgetBase::WidgetType widgetTypeB = widgetB->baseType();
bool bValid = false;
if (widgetA->umlObject() && widgetA->umlObject() == widgetB->umlObject()) {
return allowSelf(assocType, widgetTypeA);
}
for (int i = 0; i < m_nNumRules; ++i) {
const Assoc_Rule& rule = m_AssocRules[i];
if (!rule.isValid())
continue;
if (assocType != rule.assoc_type)
continue;
if ((widgetTypeA == rule.widgetA_type &&
widgetTypeB == rule.widgetB_type) ||
(rule.bidirectional &&
widgetTypeB == rule.widgetA_type &&
widgetTypeA == rule.widgetB_type)) {
bValid = true;
break;
}
}
if (!bValid) {
return false;
}
//Prevent against a package containing its own parent! #packageception.
if (assocType == Uml::AssociationType::Containment) {
UMLListViewItem* listItemA = UMLApp::app()->listView()->findUMLObject(widgetA->umlObject());
UMLListViewItem* listItemB = UMLApp::app()->listView()->findUMLObject(widgetB->umlObject());
if (listItemA && listItemB) {
// Great, we have our listviewitems, now check to make sure that they don't become recursive.
if (listItemA->parent() == static_cast<QTreeWidgetItem*>(listItemB)) {
// The user is trying to make the parent the child and the child the parent. Stop them!
return false;
}
}
// This was just a little assertion for safety, don't return yet!
}
AssociationWidgetList list = widgetB->associationWidgetList();
switch(assocType) {
case Uml::AssociationType::Association_Self:
if (widgetA->umlObject() == widgetB->umlObject())
return true;
break;
case Uml::AssociationType::Association:
case Uml::AssociationType::UniAssociation:
case Uml::AssociationType::Dependency:
case Uml::AssociationType::Coll_Mesg_Sync:
case Uml::AssociationType::Coll_Mesg_Async:
case Uml::AssociationType::Aggregation:
case Uml::AssociationType::Relationship:
return true; // doesn't matter what's already connected to widget
break;
case Uml::AssociationType::Composition:
case Uml::AssociationType::Containment:
return true;
break;
case Uml::AssociationType::Generalization://can have many sub/super types but can't sup/sub each
for(AssociationWidget * assoc : list) {
if((widgetA == assoc->widgetForRole(Uml::RoleType::A) ||
widgetA == assoc->widgetForRole(Uml::RoleType::B))
&& assoc->associationType() == assocType)
return false;
}
return true;
break;
case Uml::AssociationType::Realization: // can only connect to abstract (interface) classes
for(AssociationWidget * assoc : list) {
if((widgetA == assoc->widgetForRole(Uml::RoleType::A) ||
widgetA == assoc->widgetForRole(Uml::RoleType::B))
&& assoc->associationType() == Uml::AssociationType::Realization) {
return false;
}
}
if (widgetB->isClassWidget()) {
return widgetB->umlObject()->isAbstract();
} else if (widgetB->isInterfaceWidget() ||
widgetB->isPackageWidget()) {
return true;
}
break;
case Uml::AssociationType::State:
{
StateWidget *stateA = widgetA->asStateWidget();
StateWidget *stateB = widgetB->asStateWidget();
if (stateA && stateB) {
if (stateB->stateType() == StateWidget::Initial)
return false;
if (stateB->stateType() == StateWidget::End &&
stateA->stateType() != StateWidget::Normal)
return false;
}
}
return true;
break;
case Uml::AssociationType::Activity:
case Uml::AssociationType::Exception:
{
ActivityWidget *actA = widgetA->asActivityWidget();
ActivityWidget *actB = widgetB->asActivityWidget();
bool isSignal = false;
bool isObjectNode = false;
if (widgetTypeA == WidgetBase::wt_Signal)
isSignal = true;
else if (widgetTypeA == WidgetBase::wt_ObjectNode)
isObjectNode = true;
// no transitions to initial activity allowed
if (actB && actB->activityType() == ActivityWidget::Initial) {
return false;
}
// actType -1 here means "not applicable".
int actTypeA = -1;
if (actA)
actTypeA = actA->activityType();
int actTypeB = -1;
if (actB)
actTypeB = actB->activityType();
// only from a signalwidget, an objectnode widget, a normal activity, branch or fork activity, to the end
if ((actTypeB == ActivityWidget::End || actTypeB == ActivityWidget::Final) &&
actTypeA != ActivityWidget::Normal &&
actTypeA != ActivityWidget::Branch &&
widgetA->asForkJoinWidget() == nullptr && !isSignal &&!isObjectNode) {
return false;
}
// only Forks and Branches can have more than one "outgoing" transition
if (actA != nullptr && actTypeA != ActivityWidget::Branch) {
AssociationWidgetList list = widgetA->associationWidgetList();
for(AssociationWidget* assoc : list) {
if (assoc->widgetForRole(Uml::RoleType::A) == widgetA) {
return false;
}
}
}
}
return true;
break;
case Uml::AssociationType::Anchor:
return true;
break;
case Uml::AssociationType::Category2Parent:
if (widgetTypeA == WidgetBase::wt_Category && widgetTypeB == WidgetBase::wt_Entity) {
return true;
}
break;
case Uml::AssociationType::Child2Category:
if (widgetTypeA == WidgetBase::wt_Entity && widgetTypeB == WidgetBase::wt_Category) {
return true;
}
break;
default:
logWarn1("AssocRules::allowAssociation(2) on unknown type %1", assocType);
break;
}
return false;
}
/**
* Returns whether to allow a role text for the given association type.
*/
bool AssocRules::allowRole(Uml::AssociationType::Enum assocType)
{
for(int i = 0; i < m_nNumRules; ++i) {
const Assoc_Rule& rule = m_AssocRules[i];
if (!rule.isValid())
continue;
if(assocType == rule.assoc_type)
return rule.role;
}
return false;
}
/**
* Returns whether to allow a multiplicity text for the given
* association and widget type.
*/
bool AssocRules::allowMultiplicity(Uml::AssociationType::Enum assocType, WidgetBase::WidgetType widgetType)
{
for(int i = 0; i < m_nNumRules; ++i) {
const Assoc_Rule& rule = m_AssocRules[i];
if (!rule.isValid())
continue;
if(assocType == rule.assoc_type)
if(widgetType == rule.widgetA_type || widgetType == rule.widgetB_type)
return rule.multiplicity;
}
return false;
}
/**
* Returns whether to allow an association to self for given variables.
*/
bool AssocRules::allowSelf(Uml::AssociationType::Enum assocType, WidgetBase::WidgetType widgetType)
{
for(int i = 0; i < m_nNumRules; ++i) {
const Assoc_Rule& rule = m_AssocRules[i];
if (!rule.isValid())
continue;
if(assocType == rule.assoc_type)
if(widgetType == rule.widgetA_type || widgetType == rule.widgetB_type)
return rule.self;
}
return false;
}
/**
* Returns whether an implements association should be a Realisation or
* a Generalisation.
* as defined in m_AssocRules.
*/
Uml::AssociationType::Enum AssocRules::isGeneralisationOrRealisation(UMLWidget* widgetA, UMLWidget* widgetB)
{
WidgetBase::WidgetType widgetTypeA = widgetA->baseType();
WidgetBase::WidgetType widgetTypeB = widgetB->baseType();
for (int i = 0; i < m_nNumRules; ++i) {
const Assoc_Rule &rule = m_AssocRules[i];
if (!rule.isValid())
continue;
if (rule.assoc_type == Uml::AssociationType::Realization &&
widgetTypeA == rule.widgetA_type &&
widgetTypeB == rule.widgetB_type) {
return Uml::AssociationType::Realization;
}
}
return Uml::AssociationType::Generalization;
}
const AssocRules::Assoc_Rule AssocRules::m_AssocRules[] = {
// Language Association widgetA widgetB role multi bidir. self level
//----+---------------------------------------+--------------------------+---------------------------+-------+-------+-------+-----+----
{ All, Uml::AssociationType::Association_Self, WidgetBase::wt_Class, WidgetBase::wt_Class, true, true, true, true, Any },
{ All, Uml::AssociationType::Association_Self, WidgetBase::wt_Object, WidgetBase::wt_Object, true, true, true, true, Any },
{ All, Uml::AssociationType::Association_Self, WidgetBase::wt_Interface, WidgetBase::wt_Interface, true, true, true, true, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Class, WidgetBase::wt_Class, true, true, true, true, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Object, WidgetBase::wt_Object, true, true, true, true, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Instance, WidgetBase::wt_Instance, true, true, true, true, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Interface, WidgetBase::wt_Interface, true, true, true, true, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Class, WidgetBase::wt_Interface, true, true, true, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Class, WidgetBase::wt_Datatype, true, true, true, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Class, WidgetBase::wt_Enum, true, true, true, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Actor, WidgetBase::wt_UseCase, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_UseCase, WidgetBase::wt_UseCase, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Actor, WidgetBase::wt_Actor, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Actor, WidgetBase::wt_UseCase, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Component, WidgetBase::wt_Interface, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Port, WidgetBase::wt_Interface, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Interface, WidgetBase::wt_Artifact, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Interface, WidgetBase::wt_Component, true, false, false, false, UML2 },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Interface, WidgetBase::wt_Port, true, false, false, false, UML2 },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Node, WidgetBase::wt_Node, true, false, false, false, Any },
{ All, Uml::AssociationType::Association, WidgetBase::wt_Node, WidgetBase::wt_Node, true, false, false, false, Any },
{Java, Uml::AssociationType::Association, WidgetBase::wt_Enum, WidgetBase::wt_Enum, true, false, false, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Class, WidgetBase::wt_Class, true, true, true, true, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Object, WidgetBase::wt_Object, true, true, true, true, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Interface, WidgetBase::wt_Interface, true, true, true, true, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Class, WidgetBase::wt_Interface, true, true, true, true, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Class, WidgetBase::wt_Datatype, true, true, true, true, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Class, WidgetBase::wt_Enum, true, true, true, true, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Actor, WidgetBase::wt_Actor, true, false, false, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_UseCase, WidgetBase::wt_UseCase, true, false, false, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_UseCase, WidgetBase::wt_Actor, true, false, false, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Component, WidgetBase::wt_Interface, true, false, false, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Component, WidgetBase::wt_Artifact, true, false, true, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Port, WidgetBase::wt_Interface, true, false, false, false, Any },
{ All, Uml::AssociationType::UniAssociation, WidgetBase::wt_Node, WidgetBase::wt_Node, true, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Class, WidgetBase::wt_Datatype, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Class, WidgetBase::wt_Class, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Datatype, WidgetBase::wt_Datatype, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Interface, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Interface, WidgetBase::wt_Class, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_UseCase, WidgetBase::wt_UseCase, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Actor, WidgetBase::wt_Actor, false, false, false, false, Any },
{ All, Uml::AssociationType::Generalization, WidgetBase::wt_Component, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Aggregation, WidgetBase::wt_Class, WidgetBase::wt_Class, true, true, false, true, Any },
{ All, Uml::AssociationType::Aggregation, WidgetBase::wt_Class, WidgetBase::wt_Interface, true, true, false, false, Any },
{ All, Uml::AssociationType::Aggregation, WidgetBase::wt_Class, WidgetBase::wt_Enum, true, true, false, false, Any },
{ All, Uml::AssociationType::Aggregation, WidgetBase::wt_Class, WidgetBase::wt_Datatype, true, true, false, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Class, WidgetBase::wt_Class, true, false, false, true, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Datatype, WidgetBase::wt_Datatype, true, false, false, true, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_UseCase, WidgetBase::wt_UseCase, true, false, false, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Actor, WidgetBase::wt_Actor, true, false, false, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Actor, WidgetBase::wt_UseCase, true, false, false, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Package, WidgetBase::wt_Package, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Class, WidgetBase::wt_Package, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Interface, WidgetBase::wt_Package, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Interface, WidgetBase::wt_Interface, true, true, true, true, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Class, WidgetBase::wt_Interface, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Class, WidgetBase::wt_Datatype, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Class, WidgetBase::wt_Enum, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Interface, WidgetBase::wt_Enum, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Component, WidgetBase::wt_Component, true, true, true, true, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Component, WidgetBase::wt_Interface, true, true, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Component, WidgetBase::wt_Artifact, true, false, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Component, WidgetBase::wt_Package, true, false, false, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Port, WidgetBase::wt_Interface, true, false, false, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Package, WidgetBase::wt_Artifact, true, false, true, false, Any },
{ All, Uml::AssociationType::Dependency, WidgetBase::wt_Node, WidgetBase::wt_Node, true, false, false, false, Any },
{ All, Uml::AssociationType::Realization, WidgetBase::wt_Class, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Realization, WidgetBase::wt_Interface, WidgetBase::wt_Package, false, false, false, false, Any },
{ All, Uml::AssociationType::Realization, WidgetBase::wt_Interface, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Realization, WidgetBase::wt_Component, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Realization, WidgetBase::wt_Package, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Composition, WidgetBase::wt_Class, WidgetBase::wt_Class, true, true, false, true, Any },
{ All, Uml::AssociationType::Composition, WidgetBase::wt_Interface, WidgetBase::wt_Interface, true, true, false, false, Any },
{ All, Uml::AssociationType::Composition, WidgetBase::wt_Class, WidgetBase::wt_Interface, true, true, false, false, Any },
{ All, Uml::AssociationType::Composition, WidgetBase::wt_Class, WidgetBase::wt_Enum, true, true, false, false, Any },
{ All, Uml::AssociationType::Composition, WidgetBase::wt_Class, WidgetBase::wt_Datatype, false, false, false, false, Any },
{ All, Uml::AssociationType::Composition, WidgetBase::wt_Class, WidgetBase::wt_Class, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Package, WidgetBase::wt_Class, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Package, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Package, WidgetBase::wt_Enum, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Package, WidgetBase::wt_Datatype, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Package, WidgetBase::wt_Package, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Package, WidgetBase::wt_Component, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Class, WidgetBase::wt_Class, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Class, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Class, WidgetBase::wt_Enum, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Class, WidgetBase::wt_Datatype, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Interface, WidgetBase::wt_Class, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Interface, WidgetBase::wt_Interface, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Interface, WidgetBase::wt_Enum, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Interface, WidgetBase::wt_Datatype, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Component, WidgetBase::wt_Component, false, false, false, false, Any },
{ All, Uml::AssociationType::Containment, WidgetBase::wt_Component, WidgetBase::wt_Artifact, false, false, false, false, Any },
{ All, Uml::AssociationType::Coll_Mesg_Sync, WidgetBase::wt_Object, WidgetBase::wt_Object, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Sync, WidgetBase::wt_Instance, WidgetBase::wt_Instance, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Sync, WidgetBase::wt_Object, WidgetBase::wt_Instance, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Sync, WidgetBase::wt_Instance, WidgetBase::wt_Object, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Async, WidgetBase::wt_Object, WidgetBase::wt_Object, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Async, WidgetBase::wt_Instance, WidgetBase::wt_Instance, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Async, WidgetBase::wt_Object, WidgetBase::wt_Instance, true, false, true, true, Any },
{ All, Uml::AssociationType::Coll_Mesg_Async, WidgetBase::wt_Instance, WidgetBase::wt_Object, true, false, true, true, Any },
{ All, Uml::AssociationType::State, WidgetBase::wt_State, WidgetBase::wt_State, true, false, true, true, Any },
{ All, Uml::AssociationType::State, WidgetBase::wt_ForkJoin, WidgetBase::wt_State, true, false, true, true, Any },
{ All, Uml::AssociationType::State, WidgetBase::wt_State, WidgetBase::wt_ForkJoin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Signal, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Activity, WidgetBase::wt_Signal, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_ObjectNode, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Activity, WidgetBase::wt_ObjectNode, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Activity, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_ForkJoin, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Activity, WidgetBase::wt_ForkJoin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Signal, WidgetBase::wt_ForkJoin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_ForkJoin, WidgetBase::wt_Signal, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_ForkJoin, WidgetBase::wt_ObjectNode, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_ObjectNode, WidgetBase::wt_ForkJoin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Pin, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Pin, WidgetBase::wt_Pin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Activity, WidgetBase::wt_Pin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_Pin, WidgetBase::wt_ForkJoin, true, false, true, true, Any },
{ All, Uml::AssociationType::Activity, WidgetBase::wt_ForkJoin, WidgetBase::wt_Pin, true, false, true, true, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Activity, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Actor, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Artifact, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Class, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Component, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Datatype, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Entity, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Enum, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Interface, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Message, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Object, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_Package, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_State, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Anchor, WidgetBase::wt_UseCase, WidgetBase::wt_Note, false, false, true, false, Any },
{ All, Uml::AssociationType::Relationship, WidgetBase::wt_Entity, WidgetBase::wt_Entity, true, true, true, true, Any },
{ All, Uml::AssociationType::Exception, WidgetBase::wt_Activity, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Exception, WidgetBase::wt_Activity, WidgetBase::wt_Signal, true, false, true, true, Any },
{ All, Uml::AssociationType::Exception, WidgetBase::wt_Signal, WidgetBase::wt_Activity, true, false, true, true, Any },
{ All, Uml::AssociationType::Exception, WidgetBase::wt_Signal, WidgetBase::wt_Signal, true, false, true, true, Any },
{ All, Uml::AssociationType::Category2Parent, WidgetBase::wt_Category, WidgetBase::wt_Entity, false, false, true, false, Any },
{ All, Uml::AssociationType::Child2Category, WidgetBase::wt_Entity, WidgetBase::wt_Category, false, false, true, false, Any }
};
const int AssocRules::m_nNumRules = sizeof(m_AssocRules) / sizeof(AssocRules::Assoc_Rule);
bool AssocRules::Assoc_Rule::isValid() const
{
bool isValidLevel = (level == Any) ||
(level == UML1 && !Settings::optionState().generalState.uml2) ||
(level == UML2 && Settings::optionState().generalState.uml2);
if (language == All)
return isValidLevel;
else if (language == Java && UMLApp::app()->activeLanguage() == Uml::ProgrammingLanguage::Java)
return isValidLevel;
else
return false;
}
| 36,111
|
C++
|
.cpp
| 533
| 60.103189
| 144
| 0.618242
|
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,251
|
main.cpp
|
KDE_umbrello/umbrello/main.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// app includes
#define DBG_SRC QStringLiteral("main")
#include "debug_utils.h"
#include "uml.h"
#include "version.h"
#include "umldoc.h"
#include "cmdlineexportallviewsevent.h"
#include "umlviewimageexportermodel.h"
#include "umbrellosettings.h"
// kde includes
#include <KAboutData>
#include <QApplication>
#include <QCommandLineParser>
#include <KConfig>
#include <KLocalizedString>
#include <kcrash.h>
#include <QUrl>
#include <stdio.h>
DEBUG_REGISTER(main)
void getFiles(QStringList& files, const QString& path, QStringList& filters);
/**
* Determines if the application GUI should be shown based on command line arguments.
* @todo Add options to use the documentation generators from command line.
*
* @param args The command line arguments given.
* @return True if the GUI should be shown, false otherwise.
*/
bool showGUI(const QCommandLineParser *args)
{
if (args->values(QStringLiteral("export")).size() > 0 || args->isSet(QStringLiteral("export-formats"))) {
return false;
}
return true;
}
/**
* Creates a QUrl from a string.
* @return QUrl::fromLocalFile(input) if input does not contain a URI prefix.
*/
static QUrl makeURL(const QString& input)
{
if (input.indexOf(QStringLiteral("://")) < 0)
return QUrl::fromLocalFile(input);
return QUrl(input);
}
/**
* Initializes the document used by the application.
* If a file was specified in command line arguments, opens that file. Else, it
* opens the last opened file, or a new file if there isn't any "last file used"
* in the configuration.
*
* @param args The command line arguments given.
* @param progLang The programming language to set if no existing file was opened.
*/
void initDocument(const QStringList& args, Uml::ProgrammingLanguage::Enum progLang)
{
if (args.count()) {
UMLApp::app()->openDocumentFile(makeURL(args.first()));
} else {
bool last = UmbrelloSettings::loadlast();
QString file = UmbrelloSettings::lastFile();
if(last && !file.isEmpty()) {
UMLApp::app()->openDocumentFile(makeURL(file));
} else {
UMLApp::app()->newDocument();
if (progLang != Uml::ProgrammingLanguage::Reserved)
UMLApp::app()->setActiveLanguage(progLang);
}
}
}
/**
* Export all the views in the document using the command line args set by the user.
* Errors that occurred while exporting, if any, are shown using uError().
*
* @param args The command line arguments given.
* @param exportOpt A list containing all the "export" arguments given.
*/
void exportAllViews(const QString &extension, QUrl directory, bool useFolders)
{
// export to the specified directory, or the directory where the file is saved
// if no directory was specified
if (!directory.isValid()) {
QFileInfo fi(UMLApp::app()->document()->url().toLocalFile());
logInfo1("exportAllViews : No directory provided, using %1", fi.absolutePath());
directory = QUrl::fromLocalFile(fi.absolutePath());
}
logDebug2("exportAllViews extension: %1, directory: %2", extension, directory.path());
// the event is posted so when the Qt loop begins it's processed. UMLApp process this event executing
// the method it provides for exporting the views. Once all the views were exported, a quit event
// is sent and the app finishes without user interaction
qApp->postEvent(UMLApp::app(), new CmdLineExportAllViewsEvent(extension, directory, useFolders));
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
KCrash::initialize();
KLocalizedString::setApplicationDomain("umbrello");
Q_INIT_RESOURCE(ui);
KAboutData aboutData(QStringLiteral("umbrello"), // componentName
i18n("Umbrello UML Modeller"), // displayName
QLatin1String(umbrelloVersion().data()), // version
i18n("Umbrello – Visual development environment for software, "
"based on the industry standard Unified Modelling Language (UML).<br/>"
"See also <a href=\"http://www.omg.org/spec/\">http://www.omg.org/spec/</a>."),
KAboutLicense::GPL, // licenseType
i18n("Copyright © 2001 Paul Hensgen,\nCopyright © 2002-2022 Umbrello UML Modeller Authors"),
QString(), // otherText
QStringLiteral("https://apps.kde.org/umbrello")); // homePageAddress
aboutData.addAuthor(QStringLiteral("Paul Hensgen"), i18n("Author of initial version."), QStringLiteral("phensgen@users.sourceforge.net"));
aboutData.addAuthor(i18n("Umbrello UML Modeller Authors"), QString(), QStringLiteral("umbrello-devel@kde.org"));
// authors with more than 200 commits: git shortlog -seu | sort -g
aboutData.addCredit(QStringLiteral("Oliver Kellogg"),
i18n("Bug fixing, porting work, code cleanup, new features."),
QStringLiteral("okellogg@users.sourceforge.net"));
aboutData.addCredit(QStringLiteral("Ralf Habacker"),
i18n("Bug fixing, porting work, code cleanup, new features."),
QStringLiteral("ralf.habacker@freenet.de"));
aboutData.addCredit(QStringLiteral("Andi Fischer"),
i18n("Porting work, code cleanup, new features."),
QStringLiteral("andi.fischer@hispeed.ch"));
aboutData.addCredit(QStringLiteral("Jonathan Riddell"),
i18n("Current maintainer."),
QStringLiteral("jr@jriddell.org"));
aboutData.addCredit(QStringLiteral("Brian Thomas"),
i18n("A lot of work for C++ and Java code generation. Codeeditor."),
QStringLiteral("thomas@mail630.gsfc.nasa.gov"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
//PORTING SCRIPT: adapt aboutdata variable if necessary
aboutData.setupCommandLine(&parser);
parser.addPositionalArgument(QStringLiteral("file"), i18n("File to open"));
QCommandLineOption exportDiagrams(QStringLiteral("export"), i18n("export diagrams to extension and exit"), QStringLiteral("extension"));
parser.addOption(exportDiagrams);
QCommandLineOption listExportFormats(QStringLiteral("export-formats"), i18n("list available export extensions"));
parser.addOption(listExportFormats);
QCommandLineOption dirForExport(QStringLiteral("directory"), i18n("the local directory to save the exported diagrams in"), QStringLiteral("url"));
parser.addOption(dirForExport);
QCommandLineOption importFiles(QStringLiteral("import-files"), i18n("import files"));
parser.addOption(importFiles);
QCommandLineOption listProgLangs(QStringLiteral("languages"), i18n("list supported languages"));
parser.addOption(listProgLangs);
QCommandLineOption useFolders(QStringLiteral("use-folders"), i18n("keep the tree structure used to store the views in the document in the target directory"));
parser.addOption(useFolders);
QCommandLineOption importDir(QStringLiteral("import-directory"), i18n("import files from directory <dir>"), QStringLiteral("dir"));
parser.addOption(importDir);
QCommandLineOption setProgLang(QStringLiteral("set-language"), i18n("set language"), QStringLiteral("proglang"));
parser.addOption(setProgLang);
parser.process(app);
aboutData.processCommandLine(&parser);
Q_INIT_RESOURCE(icons);
app.setLayoutDirection(UmbrelloSettings::rightToLeftUI() ? Qt::RightToLeft : Qt::LeftToRight);
QPointer<UMLApp> uml;
if (app.isSessionRestored()) {
kRestoreMainWindows< UMLApp >();
} else {
const QCommandLineParser *parsedArgs = &parser;
if (parsedArgs->isSet(QStringLiteral("export-formats"))) {
for(const QString& type : UMLViewImageExporterModel::supportedImageTypes())
fprintf(stdout, "%s\n", qPrintable(type));
return 0;
} else if (parsedArgs->isSet(QStringLiteral("languages"))) {
for (int i = 0; i <= Uml::ProgrammingLanguage::Reserved; i++) {
Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromInt(i);
fprintf(stdout, "%s\n", qPrintable(Uml::ProgrammingLanguage::toString(pl)));
}
return 0;
}
uml = new UMLApp();
uml->setup();
app.processEvents();
if (showGUI(parsedArgs)) {
uml->show();
}
Uml::ProgrammingLanguage::Enum lang = Uml::ProgrammingLanguage::Reserved;
if (parsedArgs->isSet(QStringLiteral("set-language"))) {
QString value;
value = parsedArgs->value(QStringLiteral("set-language"));
// special cases: C++, C#
if (value == QStringLiteral("C++")) {
lang = Uml::ProgrammingLanguage::Cpp;
} else if (value == QStringLiteral("C#")) {
lang = Uml::ProgrammingLanguage::CSharp;
} else {
value = value.toLower();
for(int i = 0; i < Uml::ProgrammingLanguage::Reserved; i++) {
Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromInt(i);
QString langString = Uml::ProgrammingLanguage::toString(pl);
if (value == langString.toLower()) {
lang = Uml::ProgrammingLanguage::fromInt(i);
}
}
}
}
QStringList args;
args = parsedArgs->positionalArguments();
if (parsedArgs->isSet(QStringLiteral("import-files")) && args.count() > 0) {
uml->newDocument();
if (lang != Uml::ProgrammingLanguage::Reserved)
uml->setActiveLanguage(lang);
uml->importFiles(args);
}
else if (parsedArgs->isSet(QStringLiteral("import-directory"))) {
uml->newDocument();
if (lang != Uml::ProgrammingLanguage::Reserved)
uml->setActiveLanguage(lang);
QStringList filter = Uml::ProgrammingLanguage::toExtensions(uml->activeLanguage());
QString dir;
dir = parsedArgs->value(QStringLiteral("import-directory"));
QStringList listFile;
getFiles(listFile, dir, filter);
uml->importFiles(listFile, dir);
}
else {
initDocument(args, lang);
}
// Handle diagram export related options
if (parsedArgs->isSet(QStringLiteral("export"))) {
QString extension;
QUrl directory;
extension = parsedArgs->value(QStringLiteral("export"));
if (parsedArgs->isSet(QStringLiteral("directory"))) {
QString dirValue = parsedArgs->value(QStringLiteral("directory"));
directory = QUrl::fromUserInput(dirValue, QDir::currentPath());
}
bool useFolders = parsedArgs->isSet(QStringLiteral("use-folders"));
exportAllViews(extension, directory, useFolders);
}
}
int result = app.exec();
return result;
}
| 11,529
|
C++
|
.cpp
| 234
| 40.598291
| 162
| 0.646422
|
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,252
|
toolbarstateassociation.cpp
|
KDE_umbrello/umbrello/toolbarstateassociation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstateassociation.h"
// app includes
#include "assocrules.h"
#include "association.h"
#include "associationline.h"
#include "associationwidget.h"
#include "classifier.h"
#include "classifierwidget.h"
#include "cmds/widget/cmdcreatewidget.h"
#include "floatingtextwidget.h"
#include "debug_utils.h"
#include "folder.h"
#include "model_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
DEBUG_REGISTER(ToolBarStateAssociation)
/**
* Creates a new ToolBarStateAssociation.
*
* @param umlScene The UMLScene to use.
*/
ToolBarStateAssociation::ToolBarStateAssociation(UMLScene *umlScene)
: ToolBarStatePool(umlScene),
m_firstWidget(nullptr),
m_associationLine(nullptr)
{
}
/**
* Destroys this ToolBarStateAssociation.
* Deletes the association line.
*/
ToolBarStateAssociation::~ToolBarStateAssociation()
{
cleanAssociation();
}
/**
* Goes back to the initial state.
*/
void ToolBarStateAssociation::init()
{
ToolBarStatePool::init();
cleanAssociation();
}
/**
* Called when the current tool is changed to use another tool.
* Executes base method and cleans the association.
*/
void ToolBarStateAssociation::cleanBeforeChange()
{
ToolBarStatePool::cleanBeforeChange();
cleanAssociation();
}
/**
* Called when a mouse event happened.
* It executes the base method and then updates the position of the
* association line, if any.
*/
void ToolBarStateAssociation::mouseMove(QGraphicsSceneMouseEvent* ome)
{
ToolBarStatePool::mouseMove(ome);
if (m_associationLine) {
QPointF sp = m_associationLine->line().p1();
m_associationLine->setLine(sp.x(), sp.y(), m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y());
}
}
/**
* A widget was removed from the UMLScene.
* If the widget removed was the current widget, the current widget is set
* to 0.
* Also, if it was the first widget, the association is cleaned.
*/
void ToolBarStateAssociation::slotWidgetRemoved(UMLWidget* widget)
{
ToolBarState::slotWidgetRemoved(widget);
if (widget == m_firstWidget) {
cleanAssociation();
}
}
/**
* Called when the release event happened on an association.
* If the button pressed isn't left button, the association being created is
* cleaned. If it is left button, and the first widget is set and is a
* classifier widget, it creates an association class. Otherwise, the
* association being created is cleaned.
*/
void ToolBarStateAssociation::mouseReleaseAssociation()
{
if (m_pMouseEvent->button() != Qt::LeftButton ||
!m_firstWidget || !m_firstWidget->isClassWidget()) {
cleanAssociation();
return;
}
ClassifierWidget *classifier = dynamic_cast<ClassifierWidget*>(m_firstWidget);
if (classifier) {
currentAssociation()->createAssocClassLine(classifier,
currentAssociation()->associationLine().closestSegmentIndex(m_pMouseEvent->scenePos()));
m_firstWidget->addAssoc(currentAssociation());
} else {
logError0("ToolBarStateAssociation::mouseReleaseAssociation: dynamic_cast to ClassifierWidget* failed");
}
cleanAssociation();
}
/**
* Called when the release event happened on a widget.
* If the button pressed isn't left button, the association is cleaned. If
* it is left button, sets the first widget or the second, depending on
* whether the first widget is already set or not.
*/
void ToolBarStateAssociation::mouseReleaseWidget()
{
if (m_pMouseEvent->button() != Qt::LeftButton) {
cleanAssociation();
return;
}
// TODO In old code in ToolBarState there was a TODO that said: Should not
//be called by a Sequence message Association. Here's the check for that,
//although I don't know why it is needed, but it seems that it's not needed,
//as the old code worked fine without it...
if (getAssociationType() == Uml::AssociationType::Seq_Message) {
return;
}
if (!m_firstWidget) {
setFirstWidget();
} else {
setSecondWidget();
}
}
/**
* Called when the release event happened on an empty space.
* Cleans the association.
*/
void ToolBarStateAssociation::mouseReleaseEmpty()
{
cleanAssociation();
}
/**
* Sets the first widget in the association using the current widget.
* If the widget can't be associated using the current type of association,
* an error is shown and the widget isn't set.
* Otherwise, the temporary visual association is created and the mouse
* tracking is enabled, so move events will be delivered.
*/
void ToolBarStateAssociation::setFirstWidget()
{
UMLWidget* widget = currentWidget();
Uml::AssociationType::Enum type = getAssociationType();
if (!AssocRules::allowAssociation(type, widget)) {
//TODO improve error feedback: tell the user what are the valid type of associations for
//that widget
KMessageBox::error(nullptr, i18n("Incorrect use of associations."), i18n("Association Error"));
return;
}
//set up position
QPoint pos;
pos.setX(widget->scenePos().x() + (widget->width() / 2));
pos.setY(widget->scenePos().y() + (widget->height() / 2));
//TODO why is this needed?
m_pUMLScene->setPos(pos);
cleanAssociation();
m_firstWidget = widget;
// preliminary line
m_associationLine = new QGraphicsLineItem();
m_pUMLScene->addItem(m_associationLine);
m_associationLine->setLine(pos.x(), pos.y(), pos.x(), pos.y());
m_associationLine->setPen(QPen(m_pUMLScene->lineColor(), m_pUMLScene->lineWidth(), Qt::DashLine));
m_associationLine->setVisible(true);
m_pUMLScene->activeView()->viewport()->setMouseTracking(true);
}
/**
* Sets the second widget in the association using the current widget and
* creates the association.
* If the association between the two widgets using the current type of
* association is illegitimate, an error is shown and the association cancelled.
* Otherwise, the association is created and added to the scene, and the tool
* is changed to the default tool.
*
* @todo Why change to the default tool? Shouldn't it better to stay on
* association and let the user change with a right click? The tool to
* create widgets doesn't change to default after creating a widget
*/
void ToolBarStateAssociation::setSecondWidget()
{
Uml::AssociationType::Enum type = getAssociationType();
UMLWidget* widgetA = m_firstWidget;
UMLWidget* widgetB = currentWidget();
WidgetBase::WidgetType at = widgetA->baseType();
bool valid = true;
if (type == Uml::AssociationType::Generalization) {
type = AssocRules::isGeneralisationOrRealisation(widgetA, widgetB);
}
if (widgetA == widgetB) {
valid = AssocRules::allowSelf(type, at);
if (valid && type == Uml::AssociationType::Association) {
type = Uml::AssociationType::Association_Self;
}
} else {
valid = AssocRules::allowAssociation(type, widgetA, widgetB);
}
if (valid) {
if (widgetA->changesShape())
widgetA->updateGeometry();
if (widgetB->changesShape())
widgetB->updateGeometry();
if (widgetA->isClassWidget() && widgetB->isClassWidget()) {
if (type == Uml::AssociationType::Composition) {
UMLClassifier *c = widgetA->umlObject()->asUMLClassifier();
UMLAttribute *attr = new UMLAttribute(c, c->uniqChildName(UMLObject::ot_Attribute));
attr->setType(widgetB->umlObject());
c->addAttribute(attr);
cleanAssociation();
Q_EMIT finished();
return;
}
/* Activating this code will produce a DataType named as the Role B type
with a suffixed "*" to indicate it is a pointer type.
However, this is a non standard, C++ specific notation.
Further, if this code is activated then no Aggregation association to the
role B type will be shown. Instead, if the "B*" pointer type is dragged
to the diagram then a Composition to that type will be shown.
else if (type == Uml::AssociationType::Aggregation) {
UMLClassifier *c = widgetA->umlObject()->asUMLClassifier();
UMLAttribute *attr = new UMLAttribute(c, c->uniqChildName(UMLObject::ot_Attribute));
attr->setTypeName(QString(QStringLiteral("%1*")).arg(widgetB->umlObject()->name()));
c->addAttribute(attr);
cleanAssociation();
Q_EMIT finished();
return;
} */
}
AssociationWidget *temp = AssociationWidget::create(m_pUMLScene, widgetA, type, widgetB);
if (widgetA->baseType() == UMLWidget::wt_Port) {
QPointF lineStart = widgetA->getPos();
logDebug2("ToolBarStateAssociation::setSecondWidget : lineStart = (%1,%2)",
lineStart.x(), lineStart.y());
temp->associationLine().setPoint(0, lineStart);
}
FloatingTextWidget *wt = temp->textWidgetByRole(Uml::TextRole::Coll_Message);
if (wt)
wt->showOperationDialog();
UMLApp::app()->executeCommand(new Uml::CmdCreateWidget(temp));
} else {
//TODO improve error feedback: tell the user what are the valid type of associations for
//the second widget using the first widget
KMessageBox::error(nullptr, i18n("Incorrect use of associations."), i18n("Association Error"));
}
cleanAssociation();
Q_EMIT finished();
}
/**
* Returns the association type of this tool.
*
* @return The association type of this tool.
*/
Uml::AssociationType::Enum ToolBarStateAssociation::getAssociationType()
{
Uml::AssociationType::Enum at;
switch(getButton()) {
case WorkToolBar::tbb_Anchor: at = Uml::AssociationType::Anchor; break;
case WorkToolBar::tbb_Association: at = Uml::AssociationType::Association; break;
case WorkToolBar::tbb_UniAssociation: at = Uml::AssociationType::UniAssociation; break;
case WorkToolBar::tbb_Generalization: at = Uml::AssociationType::Generalization; break;
case WorkToolBar::tbb_Composition: at = Uml::AssociationType::Composition; break;
case WorkToolBar::tbb_Aggregation: at = Uml::AssociationType::Aggregation; break;
case WorkToolBar::tbb_Relationship: at = Uml::AssociationType::Relationship; break;
case WorkToolBar::tbb_Dependency: at = Uml::AssociationType::Dependency; break;
case WorkToolBar::tbb_Containment: at = Uml::AssociationType::Containment; break;
case WorkToolBar::tbb_Seq_Message_Creation:
case WorkToolBar::tbb_Seq_Message_Destroy:
case WorkToolBar::tbb_Seq_Message_Synchronous:
case WorkToolBar::tbb_Seq_Combined_Fragment:
case WorkToolBar::tbb_Seq_Precondition:
case WorkToolBar::tbb_Seq_Message_Asynchronous: at = Uml::AssociationType::Seq_Message; break;
case WorkToolBar::tbb_Coll_Mesg_Sync: at = Uml::AssociationType::Coll_Mesg_Sync; break;
case WorkToolBar::tbb_Coll_Mesg_Async: at = Uml::AssociationType::Coll_Mesg_Async; break;
case WorkToolBar::tbb_State_Transition: at = Uml::AssociationType::State; break;
case WorkToolBar::tbb_Activity_Transition: at = Uml::AssociationType::Activity; break;
case WorkToolBar::tbb_Exception: at = Uml::AssociationType::Exception; break;
case WorkToolBar::tbb_Category2Parent: at = Uml::AssociationType::Category2Parent; break;
case WorkToolBar::tbb_Child2Category: at = Uml::AssociationType::Child2Category; break;
default: at = Uml::AssociationType::Unknown; break;
}
return at;
}
/**
* Adds an AssociationWidget to the association list and creates the
* corresponding UMLAssociation in the current UMLDoc.
* If the association can't be added, is deleted.
*
* @param assoc The AssociationWidget to add.
* @return True on success
*/
bool ToolBarStateAssociation::addAssociationInViewAndDoc(AssociationWidget* assoc)
{
// append in view
if (m_pUMLScene->addAssociation(assoc, false)) {
// if view went ok, then append in document
UMLAssociation *umla = assoc->association();
if (umla) {
// association with model representation in UMLDoc
Uml::ModelType::Enum m = Model_Utils::convert_DT_MT(m_pUMLScene->type());
UMLDoc *umldoc = UMLApp::app()->document();
umla->setUMLPackage(umldoc->rootFolder(m));
umldoc->addAssociation(umla);
}
return true;
} else {
logError0("ToolBarStateAssociation: cannot addAssocInViewAndDoc(), deleting");
delete assoc;
return false;
}
}
/**
* Cleans the first widget and the temporary association line, if any.
* Both are set to null, and the association line is also deleted.
*/
void ToolBarStateAssociation::cleanAssociation()
{
m_firstWidget = nullptr;
delete m_associationLine;
m_associationLine = nullptr;
}
| 13,724
|
C++
|
.cpp
| 333
| 35.711712
| 113
| 0.676299
|
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,253
|
optionstate.cpp
|
KDE_umbrello/umbrello/optionstate.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "optionstate.h"
#include "umbrellosettings.h"
namespace Settings {
void GeneralState::load()
{
undo = UmbrelloSettings::undo();
tabdiagrams = UmbrelloSettings::tabdiagrams();
#ifdef ENABLE_NEW_CODE_GENERATORS
newcodegen = UmbrelloSettings::newcodegen();
#endif
layoutType = UmbrelloSettings::layoutType();
footerPrinting = UmbrelloSettings::footerPrinting();
uml2 = UmbrelloSettings::uml2();
autosave = UmbrelloSettings::autosave();
time = UmbrelloSettings::time(); //old autosavetime value kept for compatibility
autosavetime = UmbrelloSettings::autosavetime();
//if we don't have a "new" autosavetime value, convert the old one
if (autosavetime == 0) {
switch (time) {
case 0: autosavetime = 5; break;
case 1: autosavetime = 10; break;
case 2: autosavetime = 15; break;
case 3: autosavetime = 20; break;
case 4: autosavetime = 25; break;
default: autosavetime = 5; break;
}
}
autosavesuffix = UmbrelloSettings::autosavesuffix();
loadlast = UmbrelloSettings::loadlast();
diagram = UmbrelloSettings::diagram();
defaultLanguage = UmbrelloSettings::defaultLanguage();
}
void GeneralState::save()
{
UmbrelloSettings::setUndo(undo);
UmbrelloSettings::setTabdiagrams(tabdiagrams);
UmbrelloSettings::setNewcodegen(newcodegen);
UmbrelloSettings::setFooterPrinting(footerPrinting);
UmbrelloSettings::setAutosave(autosave);
UmbrelloSettings::setTime(time);
UmbrelloSettings::setAutosavetime(autosavetime);
UmbrelloSettings::setAutosavesuffix(autosavesuffix);
UmbrelloSettings::setLoadlast(loadlast);
UmbrelloSettings::setUml2(uml2);
UmbrelloSettings::setDiagram(diagram);
UmbrelloSettings::setDefaultLanguage(defaultLanguage);
}
void ClassState::load()
{
showVisibility = UmbrelloSettings::showVisibility();
showAtts = UmbrelloSettings::showAtts();
showOps = UmbrelloSettings::showOps();
showStereoType = UmbrelloSettings::showStereoType();
showAttSig = UmbrelloSettings::showAttSig();
showOpSig = UmbrelloSettings::showOpSig();
showPackage = UmbrelloSettings::showPackage();
showAttribAssocs = UmbrelloSettings::showAttribAssocs();
showPublicOnly = UmbrelloSettings::showPublicOnly();
defaultAttributeScope = UmbrelloSettings::defaultAttributeScope();
defaultOperationScope = UmbrelloSettings::defaultOperationScope();
}
void ClassState::save()
{
UmbrelloSettings::setShowVisibility(showVisibility);
UmbrelloSettings::setShowAtts(showAtts);
UmbrelloSettings::setShowOps(showOps);
UmbrelloSettings::setShowStereoType(showStereoType);
UmbrelloSettings::setShowAttSig(showAttSig);
UmbrelloSettings::setShowOpSig(showOpSig);
UmbrelloSettings::setShowPackage(showPackage);
UmbrelloSettings::setShowAttribAssocs(showAttribAssocs);
UmbrelloSettings::setShowPublicOnly(showPublicOnly);
UmbrelloSettings::setDefaultAttributeScope(defaultAttributeScope);
UmbrelloSettings::setDefaultOperationScope(defaultOperationScope);
}
/**
* Save instance to XMI.
* @param writer The QXmlStreamWriter to save to.
*/
void ClassState::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeAttribute(QStringLiteral("showattribassocs"), QString::number(showAttribAssocs));
writer.writeAttribute(QStringLiteral("showatts"), QString::number(showAtts));
writer.writeAttribute(QStringLiteral("showattsig"), QString::number(showAttSig));
writer.writeAttribute(QStringLiteral("showops"), QString::number(showOps));
writer.writeAttribute(QStringLiteral("showopsig"), QString::number(showOpSig));
writer.writeAttribute(QStringLiteral("showpackage"), QString::number(showPackage));
writer.writeAttribute(QStringLiteral("showpubliconly"), QString::number(showPublicOnly));
writer.writeAttribute(QStringLiteral("showscope"), QString::number(showVisibility));
#ifdef ENABLE_WIDGET_SHOW_DOC
writer.writeAttribute(QStringLiteral("showdocumentation"),QString::number(showDocumentation));
#endif
writer.writeAttribute(QStringLiteral("showstereotype"), QString::number(showStereoType));
}
/**
* Load instance from a QDomElement.
* @param element A QDomElement representing xml element data.
* @return true on success
* @return false on error
*/
bool ClassState::loadFromXMI(QDomElement &element)
{
QString temp = element.attribute(QStringLiteral("showattribassocs"), QStringLiteral("0"));
showAttribAssocs = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showatts"), QStringLiteral("0"));
showAtts = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showattsig"), QStringLiteral("0"));
showAttSig = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showops"), QStringLiteral("0"));
showOps = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showopsig"), QStringLiteral("0"));
showOpSig = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showpackage"), QStringLiteral("0"));
showPackage = (bool)temp.toInt();
#ifdef ENABLE_WIDGET_SHOW_DOC
temp = element.attribute(QStringLiteral("showdocumentation"), QStringLiteral("0"));
showDocumentation = (bool)temp.toInt();
#endif
temp = element.attribute(QStringLiteral("showpubliconly"), QStringLiteral("0"));
showPublicOnly = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showscope"), QStringLiteral("0"));
showVisibility = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("showstereotype"), QStringLiteral("0"));
showStereoType = (Uml::ShowStereoType::Enum)temp.toInt();
return true;
}
void UIState::load()
{
useFillColor = UmbrelloSettings::useFillColor();
fillColor = UmbrelloSettings::fillColor();
lineColor = UmbrelloSettings::lineColor();
lineWidth = UmbrelloSettings::lineWidth();
textColor = UmbrelloSettings::textColor();
font = UmbrelloSettings::uiFont();
backgroundColor = UmbrelloSettings::backgroundColor();
gridDotColor = UmbrelloSettings::gridDotColor();
}
void UIState::save()
{
UmbrelloSettings::setUseFillColor(useFillColor);
UmbrelloSettings::setFillColor(fillColor);
UmbrelloSettings::setLineColor(lineColor);
UmbrelloSettings::setLineWidth(lineWidth);
UmbrelloSettings::setTextColor(textColor);
UmbrelloSettings::setUiFont(font);
UmbrelloSettings::setBackgroundColor(backgroundColor);
UmbrelloSettings::setGridDotColor(gridDotColor);
}
/**
* Save instance to XMI.
* @param writer The QXmlStreamWriter to save to.
*/
void UIState::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeAttribute(QStringLiteral("backgroundcolor"), backgroundColor.name());
writer.writeAttribute(QStringLiteral("fillcolor"), fillColor.name());
writer.writeAttribute(QStringLiteral("font"), font.toString());
writer.writeAttribute(QStringLiteral("griddotcolor"), gridDotColor.name());
writer.writeAttribute(QStringLiteral("linecolor"), lineColor.name());
writer.writeAttribute(QStringLiteral("linewidth"), QString::number(lineWidth));
writer.writeAttribute(QStringLiteral("textcolor"), textColor.name());
writer.writeAttribute(QStringLiteral("usefillcolor"), QString::number(useFillColor));
}
/**
* Load instance from a QDomElement.
* @param element A QDomElement representing xml element data.
* @return true on success
* @return false on error
*/
bool UIState::loadFromXMI(QDomElement &element)
{
QString backgroundColor = element.attribute(QStringLiteral("backgroundcolor"));
if (!backgroundColor.isEmpty())
this->backgroundColor = QColor(backgroundColor);
QString fillcolor = element.attribute(QStringLiteral("fillcolor"));
if (!fillcolor.isEmpty())
this->fillColor = QColor(fillcolor);
QString font = element.attribute(QStringLiteral("font"));
if (!font.isEmpty()) {
this->font.fromString(font);
this->font.setUnderline(false);
}
QString gridDotColor = element.attribute(QStringLiteral("griddotcolor"));
if (!gridDotColor.isEmpty())
this->gridDotColor = QColor(gridDotColor);
QString linecolor = element.attribute(QStringLiteral("linecolor"));
if (!linecolor.isEmpty())
this->lineColor = QColor(linecolor);
QString linewidth = element.attribute(QStringLiteral("linewidth"));
if (!linewidth.isEmpty())
this->lineWidth = linewidth.toInt();
QString textColor = element.attribute(QStringLiteral("textcolor"));
if (!textColor.isEmpty())
this->textColor = QColor(textColor);
QString usefillcolor = element.attribute(QStringLiteral("usefillcolor"), QStringLiteral("0"));
this->useFillColor = (bool)usefillcolor.toInt();
return true;
}
void CodeImportState::load()
{
// code importer options
createArtifacts = UmbrelloSettings::createArtifacts();
resolveDependencies = UmbrelloSettings::resolveDependencies();
supportCPP11 = UmbrelloSettings::supportCPP11();
}
void CodeImportState::save()
{
UmbrelloSettings::setCreateArtifacts(createArtifacts);
UmbrelloSettings::setResolveDependencies(resolveDependencies);
UmbrelloSettings::setSupportCPP11(supportCPP11);
}
/**
* Save instance to XMI.
* @param writer The QXmlStreamWriter to save to.
*/
void CodeImportState::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeAttribute(QStringLiteral("createartifacts"), QString::number(createArtifacts));
writer.writeAttribute(QStringLiteral("resolvedependencies"), QString::number(resolveDependencies));
writer.writeAttribute(QStringLiteral("supportcpp11"), QString::number(supportCPP11));
}
/**
* Load instance from a QDomElement.
* @param element A QDomElement representing xml element data.
* @return true on success
* @return false on error
*/
bool CodeImportState::loadFromXMI(QDomElement &element)
{
QString temp = element.attribute(QStringLiteral("createartifacts"), QStringLiteral("0"));
createArtifacts = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("resolvedependencies"), QStringLiteral("0"));
resolveDependencies = (bool)temp.toInt();
temp = element.attribute(QStringLiteral("supportcpp11"), QStringLiteral("0"));
supportCPP11 = (bool)temp.toInt();
return true;
}
void CodeGenerationState::load()
{
// CPP code generation options
cppCodeGenerationState.autoGenAccessors = UmbrelloSettings::autoGenAccessors();
cppCodeGenerationState.inlineAccessors = UmbrelloSettings::inlineAccessors();
cppCodeGenerationState.publicAccessors = UmbrelloSettings::publicAccessors();
cppCodeGenerationState.inlineOps = UmbrelloSettings::inlineOps();
cppCodeGenerationState.virtualDestructors = UmbrelloSettings::virtualDestructors();
cppCodeGenerationState.packageIsNamespace = UmbrelloSettings::packageIsNamespace();
cppCodeGenerationState.stringClassName = UmbrelloSettings::stringClassName();
cppCodeGenerationState.stringClassNameInclude = UmbrelloSettings::stringClassNameInclude();
cppCodeGenerationState.stringIncludeIsGlobal = UmbrelloSettings::stringIncludeIsGlobal();
cppCodeGenerationState.vectorClassName = UmbrelloSettings::vectorClassName();
cppCodeGenerationState.vectorClassNameInclude = UmbrelloSettings::vectorClassNameInclude();
cppCodeGenerationState.vectorIncludeIsGlobal = UmbrelloSettings::vectorIncludeIsGlobal();
cppCodeGenerationState.docToolTag = UmbrelloSettings::docToolTag();
// Java code generation options
javaCodeGenerationState.autoGenerateAttributeAccessors = UmbrelloSettings::autoGenerateAttributeAccessorsJava();
javaCodeGenerationState.autoGenerateAssocAccessors = UmbrelloSettings::autoGenerateAssocAccessorsJava();
// D code generation options
dCodeGenerationState.autoGenerateAttributeAccessors = UmbrelloSettings::autoGenerateAttributeAccessorsD();
dCodeGenerationState.autoGenerateAssocAccessors = UmbrelloSettings::autoGenerateAssocAccessorsD();
// Ruby code generation options
rubyCodeGenerationState.autoGenerateAttributeAccessors = UmbrelloSettings::autoGenerateAttributeAccessorsRuby();
rubyCodeGenerationState.autoGenerateAssocAccessors = UmbrelloSettings::autoGenerateAssocAccessorsRuby();
}
void CodeGenerationState::save()
{
// write config for CPP code generation options
UmbrelloSettings::setAutoGenAccessors(cppCodeGenerationState.autoGenAccessors);
UmbrelloSettings::setInlineAccessors(cppCodeGenerationState.inlineAccessors);
UmbrelloSettings::setPublicAccessors(cppCodeGenerationState.publicAccessors);
UmbrelloSettings::setInlineOps(cppCodeGenerationState.inlineOps);
UmbrelloSettings::setVirtualDestructors(cppCodeGenerationState.virtualDestructors);
UmbrelloSettings::setGetterWithGetPrefix(cppCodeGenerationState.getterWithGetPrefix);
UmbrelloSettings::setRemovePrefixFromAccessorMethods(cppCodeGenerationState.removePrefixFromAccessorMethods);
UmbrelloSettings::setAccessorMethodsStartWithUpperCase(cppCodeGenerationState.accessorMethodsStartWithUpperCase);
UmbrelloSettings::setPackageIsNamespace(cppCodeGenerationState.packageIsNamespace);
UmbrelloSettings::setStringClassName(cppCodeGenerationState.stringClassName);
UmbrelloSettings::setStringClassNameInclude(cppCodeGenerationState.stringClassNameInclude);
UmbrelloSettings::setStringIncludeIsGlobal(cppCodeGenerationState.stringIncludeIsGlobal);
UmbrelloSettings::setVectorClassName(cppCodeGenerationState.vectorClassName);
UmbrelloSettings::setVectorClassNameInclude(cppCodeGenerationState.vectorClassNameInclude);
UmbrelloSettings::setVectorIncludeIsGlobal(cppCodeGenerationState.vectorIncludeIsGlobal);
UmbrelloSettings::setDocToolTag(cppCodeGenerationState.docToolTag);
UmbrelloSettings::setClassMemberPrefix(cppCodeGenerationState.classMemberPrefix);
// write config for Java code generation options
UmbrelloSettings::setAutoGenerateAttributeAccessorsJava(javaCodeGenerationState.autoGenerateAttributeAccessors);
UmbrelloSettings::setAutoGenerateAssocAccessorsJava(javaCodeGenerationState.autoGenerateAssocAccessors);
// CodeGenerator *codegen = getGenerator();
// JavaCodeGenerator *javacodegen = dynamic_cast<JavaCodeGenerator*>(codegen);
// if (javacodegen)
// UmbrelloSettings::setBuildANTDocumentJava(javacodegen->getCreateANTBuildFile());
// write config for D code generation options
UmbrelloSettings::setAutoGenerateAttributeAccessorsD(dCodeGenerationState.autoGenerateAttributeAccessors);
UmbrelloSettings::setAutoGenerateAssocAccessorsD(dCodeGenerationState.autoGenerateAssocAccessors);
// write config for Ruby code generation options
UmbrelloSettings::setAutoGenerateAttributeAccessorsRuby(rubyCodeGenerationState.autoGenerateAttributeAccessors);
UmbrelloSettings::setAutoGenerateAssocAccessorsRuby(rubyCodeGenerationState.autoGenerateAssocAccessors);
}
void AutoLayoutState::load()
{
autoDotPath = UmbrelloSettings::autoDotPath();
dotPath = UmbrelloSettings::dotPath();
showExportLayout = UmbrelloSettings::showExportLayout();
}
void AutoLayoutState::save()
{
UmbrelloSettings::setAutoDotPath(autoDotPath);
UmbrelloSettings::setDotPath(dotPath);
UmbrelloSettings::setShowExportLayout(showExportLayout);
}
OptionState& optionState()
{
return OptionState::instance();
}
void setOptionState(const OptionState& optstate)
{
OptionState::instance() = optstate;
}
OptionState::OptionState()
{
}
void OptionState::load()
{
generalState.load();
uiState.load();
classState.load();
codeViewerState.load();
codeGenerationState.load();
codeImportState.load();
autoLayoutState.load();
}
void OptionState::save()
{
generalState.save();
uiState.save();
classState.save();
codeViewerState.save();
codeGenerationState.save();
codeImportState.save();
autoLayoutState.save();
}
/**
* Save instance to a QXmlStreamWriter.
* @param writer The QXmlStreamWriter to save to.
*/
void OptionState::saveToXMI(QXmlStreamWriter& writer)
{
uiState.saveToXMI(writer);
classState.saveToXMI(writer);
}
/**
* Load instance from a QDomElement.
* @param element A QDomElement representing xml element data.
* @return true on success
* @return false on error
*/
bool OptionState::loadFromXMI(QDomElement& element)
{
uiState.loadFromXMI(element);
classState.loadFromXMI(element);
return true;
}
OptionState &OptionState::instance()
{
/*
* Impt: This ensures creation of OptionState object after
* QApplication thereby avoiding nasty font rendering issues
* which occurs due to creation of QFont objects before
* QApplication object is created.
*
* QScopedPointer usage covers object destroy on application
* exit to avoid a memory leak.
*/
static QScopedPointer<OptionState> optionState(new OptionState);
return *optionState;
}
} // namespace Settings
| 18,671
|
C++
|
.cpp
| 380
| 41.373684
| 121
| 0.71665
|
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,254
|
dotgenerator.cpp
|
KDE_umbrello/umbrello/dotgenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// self includes
#include "dotgenerator.h"
// app includes
#include "activitywidget.h"
#include "associationwidget.h"
#include "classifierwidget.h"
#include "signalwidget.h"
#include "statewidget.h"
#define DBG_SRC QStringLiteral("DotGenerator")
#include "debug_utils.h"
#include "uml.h" // only needed for log{Warn,Error}
// kde includes
#include <KConfigGroup>
#include <KDesktopFile>
// qt includes
#include <QFile>
#include <QPaintEngine>
#include <QProcess>
#include <QRectF>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QString>
#include <QTemporaryFile>
#include <QTextStream>
DEBUG_REGISTER(DotGenerator)
QString dotType(WidgetBase *widget)
{
const QString rawType = widget->baseTypeStr();
return rawType.toLower().remove(QStringLiteral("wt_"));
}
/**
* dot specific paint engine
*/
class DotPaintEngine : public QPaintEngine
{
public:
DotPaintEngine(PaintEngineFeatures caps = QPaintEngine::PrimitiveTransform) { Q_UNUSED(caps) }
virtual ~DotPaintEngine() {}
virtual bool begin (QPaintDevice * pdev)
{
Q_UNUSED(pdev)
return true;
}
virtual void drawEllipse(const QRectF & rect) { Q_UNUSED(rect) }
virtual void drawEllipse(const QRect & rect) { Q_UNUSED(rect) }
virtual void drawImage(const QRectF & rectangle, const QImage & image, const QRectF & sr, Qt::ImageConversionFlags flags = Qt::AutoColor) { Q_UNUSED(rectangle) Q_UNUSED(image) Q_UNUSED(sr) Q_UNUSED(flags) }
virtual void drawLines(const QLineF * lines, int lineCount) { Q_UNUSED(lines) Q_UNUSED(lineCount) }
virtual void drawLines(const QLine * lines, int lineCount) { Q_UNUSED(lines) Q_UNUSED(lineCount) }
virtual void drawPath(const QPainterPath & path) { Q_UNUSED(path) }
virtual void drawPixmap(const QRectF & r, const QPixmap & pm, const QRectF & sr) { Q_UNUSED(r) Q_UNUSED(pm) Q_UNUSED(sr) }
virtual void drawPoints(const QPointF * points, int pointCount) { Q_UNUSED(points) Q_UNUSED(pointCount) }
virtual void drawPoints(const QPoint * points, int pointCount) { Q_UNUSED(points) Q_UNUSED(pointCount) }
virtual void drawPolygon(const QPointF * points, int pointCount, PolygonDrawMode mode) { Q_UNUSED(points) Q_UNUSED(pointCount) Q_UNUSED(mode) }
virtual void drawPolygon(const QPoint * points, int pointCount, PolygonDrawMode mode) { Q_UNUSED(points) Q_UNUSED(pointCount) Q_UNUSED(mode) }
virtual void drawRects(const QRectF * rects, int rectCount) { Q_UNUSED(rects) Q_UNUSED(rectCount) }
virtual void drawRects(const QRect * rects, int rectCount) { Q_UNUSED(rects) Q_UNUSED(rectCount) }
virtual void drawTextItem(const QPointF & p, const QTextItem & textItem)
{
Q_UNUSED(p)
m_data << textItem.text();
}
virtual void drawTiledPixmap(const QRectF & rect, const QPixmap & pixmap, const QPointF & p) { Q_UNUSED(rect) Q_UNUSED(pixmap) Q_UNUSED(p) }
virtual bool end()
{
return true;
}
virtual Type type() const
{
return QPaintEngine::User;
}
virtual void updateState(const QPaintEngineState & state) { Q_UNUSED(state) }
QStringList m_data;
};
/**
* dot specific paint device
*/
class DotPaintDevice : public QPaintDevice
{
public:
DotPaintDevice() : m_engine(new DotPaintEngine)
{
}
~DotPaintDevice()
{
delete m_engine;
}
virtual QPaintEngine* paintEngine() const
{
return m_engine;
}
QStringList &data()
{
return m_engine->m_data;
}
protected:
virtual int metric(PaintDeviceMetric metric) const
{
switch(metric) {
case QPaintDevice::PdmDpiX: return 1;
case QPaintDevice::PdmDpiY: return 1;
case QPaintDevice::PdmWidth: return 100;
case QPaintDevice::PdmHeight: return 100;
default: return 0;
}
return 0;
}
DotPaintEngine *m_engine;
};
#define DOTGENERATOR_DEBUG
/**
* constructor
*/
DotGenerator::DotGenerator()
: m_scale(72),
m_generator(QStringLiteral("dot")),
m_usePosition(false),
m_useFullNodeLabels(true)
{
Settings::OptionState& optionState = Settings::optionState();
if (optionState.autoLayoutState.autoDotPath) {
m_dotPath = currentDotPath();
}
else if (!optionState.autoLayoutState.dotPath.isEmpty()) {
m_dotPath = optionState.autoLayoutState.dotPath;
}
}
/**
* Return the path where dot is installed.
*
* @return string with dot path
*/
QString DotGenerator::currentDotPath()
{
QString executable = QStandardPaths::findExecutable(QStringLiteral("dot"));
if (!executable.isEmpty()) {
QFileInfo fi(executable);
return fi.absolutePath();
}
#ifdef Q_OS_WIN
// search for dot installation
QString appDir(QLatin1String(qgetenv("ProgramFiles").constData()));
QDir dir(appDir);
dir.setFilter(QDir::Dirs);
dir.setNameFilters(QStringList() << QStringLiteral("Graphviz*"));
dir.setSorting(QDir::Reversed);
QFileInfoList list = dir.entryInfoList();
if (list.size() > 0) {
QString dotPath = list.at(0).absoluteFilePath();
QString exePath = QFile::exists(dotPath + QStringLiteral("\\bin")) ? dotPath + QStringLiteral("\\bin") : dotPath;
return QFile::exists(exePath + QStringLiteral("\\dot.exe")) ? exePath : QString();
}
#endif
return QString();
}
void DotGenerator::setGeneratorName(const QString &name)
{
m_generator = name;
m_version = generatorVersion();
logDebug3("DotGenerator::setGeneratorName(%1) found graphviz generator at %2 with version %3",
name, generatorFullPath(), m_version);
}
QString DotGenerator::generatorFullPath() const
{
return m_dotPath + QLatin1Char('/') + m_generator;
}
/**
* return usage of position attribute
*
* @return true if position are used
*/
bool DotGenerator::usePosition() const
{
return m_usePosition;
}
/**
* set usage of position attribute in dot file
*
* @param state The new state
*/
void DotGenerator::setUsePosition(bool state)
{
m_usePosition = state;
}
/**
* return usage of full node labels
*
* @return true if position are used
*/
bool DotGenerator::useFullNodeLabels() const
{
return m_useFullNodeLabels;
}
/**
* Set usage of full node labels.
* When set to true labels are extracted from the
* text output generated by the widget's paint method.
*
* @param state The new state
*/
void DotGenerator::setUseFullNodeLabels(bool state)
{
m_useFullNodeLabels = state;
}
/**
* Return a list of available templates for a given scene type
*
* @param scene The diagram
* @param configFiles will contain the collected list of config files
* @return true if collecting succeeds
*/
bool DotGenerator::availableConfigFiles(UMLScene *scene, QHash<QString, QString> &configFiles)
{
QString diagramType = Uml::DiagramType::toString(scene->type()).toLower();
QStringList fileNames = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString::fromLatin1("umbrello5/layouts/%1*.desktop").arg(diagramType));
for(const QString &fileName : fileNames) {
QFileInfo fi(fileName);
QString baseName;
if (fi.baseName().contains(QStringLiteral("-")))
baseName = fi.baseName().remove(diagramType + QLatin1Char('-'));
else if (fi.baseName() == diagramType)
baseName = fi.baseName();
else
baseName = QStringLiteral("default");
KDesktopFile desktopFile(fileName);
configFiles[baseName] = desktopFile.readName();
}
return true;
}
/**
* Read a layout config file
*
* @param diagramType String identifying the diagram
* @param variant String identifying the variant
* @return true on success
*/
bool DotGenerator::readConfigFile(QString diagramType, const QString &variant)
{
QStringList fileNames;
if (!variant.isEmpty())
fileNames << QString::fromLatin1("%1-%2.desktop").arg(diagramType).arg(variant);
fileNames << QString::fromLatin1("%1-default.desktop").arg(diagramType);
fileNames << QStringLiteral("default.desktop");
QString configFileName;
for(const QString &fileName : fileNames) {
configFileName = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QString::fromLatin1("umbrello5/layouts/%1").arg(fileName));
if (!configFileName.isEmpty())
break;
}
if (configFileName.isEmpty()) {
if (variant.isEmpty()) {
logError1("DotGenerator::readConfigFile could not find layout config file name "
"for diagram type %1 and empty variant", diagramType);
} else {
logError2("DotGenerator::readConfigFile could not find layout config file name "
"for diagram type %1 and variant %2", diagramType, variant);
}
return false;
}
logDebug1("DotGenerator::readConfigFile reading config file %1", configFileName);
m_configFileName = configFileName;
KDesktopFile desktopFile(configFileName);
KConfigGroup edgesAttributes(&desktopFile,QStringLiteral("X-UMBRELLO-Dot-Edges"));
KConfigGroup nodesAttributes(&desktopFile,QStringLiteral("X-UMBRELLO-Dot-Nodes"));
KConfigGroup attributes(&desktopFile,QStringLiteral("X-UMBRELLO-Dot-Attributes"));
QString layoutType = Uml::LayoutType::toString(Settings::optionState().generalState.layoutType);
KConfigGroup layoutAttributes(&desktopFile,QString(QStringLiteral("X-UMBRELLO-Dot-Attributes-%1")).arg(layoutType));
// settings are not needed by dotgenerator
KConfigGroup settings(&desktopFile,QStringLiteral("X-UMBRELLO-Dot-Settings"));
m_edgeParameters.clear();
m_nodeParameters.clear();
m_dotParameters.clear();
for(const QString &key : attributes.keyList()) {
QString value = attributes.readEntry(key);
if (!value.isEmpty())
m_dotParameters[key] = value;
}
for(const QString &key : layoutAttributes.keyList()) {
QString value = layoutAttributes.readEntry(key);
if (!value.isEmpty()) {
if (!m_dotParameters.contains(key))
m_dotParameters[key] = value;
else
m_dotParameters[key].append(QStringLiteral(",") + value);
}
}
for(const QString &key : nodesAttributes.keyList()) {
QString value = nodesAttributes.readEntry(key);
m_nodeParameters[key] = value;
}
for(const QString &key : edgesAttributes.keyList()) {
QString value = edgesAttributes.readEntry(key);
if (m_edgeParameters.contains(key)) {
m_edgeParameters[key] += QLatin1Char(',') + value;
} else {
m_edgeParameters[key] = value;
}
}
QString value = settings.readEntry(QStringLiteral("origin"));
QStringList a = value.split(QLatin1Char(','));
if (a.size() == 2)
m_origin = QPointF(a[0].toDouble(), a[1].toDouble());
else
logError1("DotGenerator::readConfigFile illegal format of entry 'origin' value %1",
value);
setGeneratorName(settings.readEntry("generator", "dot"));
#ifdef LAYOUTGENERATOR_DATA_DEBUG
DEBUG() << m_edgeParameters;
DEBUG() << m_nodeParameters;
DEBUG() << m_dotParameters;
#endif
return true;
}
/**
* Create dot file using displayed widgets
* and associations of the provided scene
* @note This method could also be used as a base to export diagrams as dot file
*
* @param scene The diagram from which the widget information is fetched
* @param fileName Filename where to create the dot file
* @param variant Variant string passed to readConfigFile()
*
* @return true if generating finished successfully
*/
bool DotGenerator::createDotFile(UMLScene *scene, const QString &fileName, const QString &variant)
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QString diagramType = Uml::DiagramType::toString(scene->type()).toLower();
if (!readConfigFile(diagramType, variant))
return false;
QString data;
QTextStream out(&data);
for(UMLWidget *widget : scene->widgetList()) {
QStringList params;
if (m_nodeParameters.contains(QStringLiteral("all")))
params << m_nodeParameters[QStringLiteral("all")].split(QLatin1Char(','));
if (usePosition())
params << QString::fromLatin1("pos=\"%1, %2\"").arg(widget->x()+widget->width()/2).arg(widget->y()+widget->height()/2);
QString type = dotType(widget);
if (type == QStringLiteral("state")) {
StateWidget *w = static_cast<StateWidget *>(widget);
type = w->stateTypeStr().toLower();
}
else if (type == QStringLiteral("activity")) {
ActivityWidget *w = static_cast<ActivityWidget *>(widget);
type = w->activityTypeStr().toLower();
}
else if (type == QStringLiteral("signal")) {
SignalWidget *w = static_cast<SignalWidget *>(widget);
type = w->signalTypeStr().toLower();
}
QString key = QStringLiteral("type::") + type;
QString label;
if (!useFullNodeLabels())
label = widget->name() + QStringLiteral("\\n") + type;
else {
DotPaintDevice d;
QPainter p(&d);
QStyleOptionGraphicsItem options;
widget->paint(&p, &options);
label = d.data().join(QStringLiteral("\\n"));
}
if (label.contains(QStringLiteral("\""))) {
label = label.replace(QLatin1Char('"'), QStringLiteral("\\\""));
logDebug2("DotGenerator::createDotFile(%1) replaced \" in %2", fileName, label);
}
if (m_nodeParameters.contains(key))
params << m_nodeParameters[key].split(QLatin1Char(','));
else if (m_nodeParameters.contains(QStringLiteral("type::default")))
params << m_nodeParameters[QStringLiteral("type::default")].split(QLatin1Char(','));
if (!findItem(params, QStringLiteral("label=")))
params << QString::fromLatin1("label=\"%1\"").arg(label);
if (!findItem(params, QStringLiteral("width=")))
params << QString::fromLatin1("width=\"%1\"").arg(widget->width()/m_scale);
if (!findItem(params, QStringLiteral("height=")))
params << QString::fromLatin1("height=\"%1\"").arg(widget->height()/m_scale);
#ifdef DOTGENERATOR_DATA_DEBUG
DEBUG() << type << params;
#endif
QString id = fixID(Uml::ID::toString(widget->localID()));
if (!widget->isTextWidget())
out << "\"" << id << "\""
<< " [" << params.join(QStringLiteral(",")) << "];\n";
// add associations for child items
for(QGraphicsItem *item : widget->childItems()) {
UMLWidget *w2 = dynamic_cast<UMLWidget *>(item);
if (!w2) {
logWarn1("DotGenerator::createDotFile: child item of widget %1 is null", key);
continue;
}
QString type2 = dotType(w2);
QString id2 = fixID(Uml::ID::toString(w2->localID()));
QStringList params2;
QString vkey = QString(QStringLiteral("visual::type::%1::%2")).arg(type).arg(type2);
if (m_edgeParameters.contains(vkey)) {
params2 << m_edgeParameters[vkey];
} else {
logDebug2("DotGenerator::createDotFile(%1) key %2 not found; skipping association",
fileName, vkey);
continue;
}
vkey = QString(QStringLiteral("ranking::type::%1::%2")).arg(type).arg(type2);
if (m_edgeParameters.contains(vkey)) {
params2 << m_edgeParameters[vkey];
} else {
logDebug2("DotGenerator::createDotFile(%1) key %2 not found", fileName, vkey);
}
out << "\"" << id << "\" -> \"" << id2 << "\""
<< " [" << params2.join(QStringLiteral(",")) << "];\n";
}
}
for(AssociationWidget *assoc : scene->associationList()) {
QString type = Uml::AssociationType::toString(assoc->associationType()).toLower();
QString key = QStringLiteral("type::") + type;
bool swapId = false;
if (m_edgeParameters.contains(QStringLiteral("id::") + key))
swapId = m_edgeParameters[QStringLiteral("id::") + key] == QStringLiteral("swap");
else if (m_edgeParameters.contains(QStringLiteral("id::type::default")))
swapId = m_edgeParameters[QStringLiteral("id::type::default")] == QStringLiteral("swap");
QString label;
if (!useFullNodeLabels())
label = assoc->name() + QStringLiteral("\\n") + type;
else
label = assoc->name();
QString headLabel = assoc->roleName(swapId ? Uml::RoleType::B : Uml::RoleType::A);
QString tailLabel = assoc->roleName(swapId ? Uml::RoleType::A : Uml::RoleType::B);
if (!headLabel.isEmpty())
headLabel.prepend(QStringLiteral("+"));
if (!tailLabel.isEmpty())
tailLabel.prepend(QStringLiteral("+"));
headLabel += QLatin1String(" ") + assoc->multiplicity(swapId ? Uml::RoleType::B : Uml::RoleType::A);
tailLabel += QLatin1String(" ") + assoc->multiplicity(swapId ? Uml::RoleType::A : Uml::RoleType::B);
QString edgeParameters;
QStringList params;
QString rkey = QLatin1String("ranking::") + key;
if (m_edgeParameters.contains(rkey))
edgeParameters = m_edgeParameters[rkey];
else if (m_edgeParameters.contains(QStringLiteral("ranking::type::default"))) {
edgeParameters = m_edgeParameters[QStringLiteral("ranking::type::default")];
}
params << edgeParameters.split(QLatin1Char(','));
QString vkey = QLatin1String("visual::") + key;
if (m_edgeParameters.contains(vkey))
edgeParameters = m_edgeParameters[vkey];
else if (m_edgeParameters.contains(QStringLiteral("visual::type::default"))) {
edgeParameters = m_edgeParameters[QStringLiteral("visual::type::default")];
}
params << edgeParameters.split(QLatin1Char(','));
if (!findItem(params, QStringLiteral("label=")))
params << QString::fromLatin1("label=\"%1\"").arg(label);
if (!findItem(params, QStringLiteral("headlabel=")))
params << QString::fromLatin1("headlabel=\"%1\"").arg(headLabel);
if (!findItem(params, QStringLiteral("taillabel=")))
params << QString::fromLatin1("taillabel=\"%1\"").arg(tailLabel);
#ifdef DOTGENERATOR_DATA_DEBUG
DEBUG() << type << params;
#endif
QString aID = fixID(Uml::ID::toString(assoc->widgetLocalIDForRole(swapId ? Uml::RoleType::A : Uml::RoleType::B)));
QString bID = fixID(Uml::ID::toString(assoc->widgetLocalIDForRole(swapId ? Uml::RoleType::B : Uml::RoleType::A)));
out << "\"" << aID << "\" -> \"" << bID << "\"" << " [" << params.join(QStringLiteral(",")) << "];\n";
}
QTextStream o(&file);
o << "# generated from " << m_configFileName << "\n";
o << "digraph G {\n";
for(const QString &key : m_dotParameters.keys()) {
o << "\t" << key << " [" << m_dotParameters[key] << "];\n";
}
o << data << "\n";
o << "}\n";
return true;
}
/**
* Find string starting with the search string in string list
* @param params string list to search in
* @param search string
* @return true when search string has been found
*/
bool DotGenerator::findItem(QStringList ¶ms, const QString &search)
{
for(const QString &s : params) {
if (s.startsWith(search))
return true;
}
return false;
}
/**
* There are id wrapped with '"', remove it.
*/
QString DotGenerator::fixID(const QString &_id)
{
// FIXME: some widget's ids returned from the list are wrapped with "\"", find and fix them
QString id(_id);
id.remove(QLatin1Char('"'));
return id;
}
/**
* get generator version
* @return version for example 20130928
*/
int DotGenerator::generatorVersion() const
{
QProcess p;
QStringList args;
args << QStringLiteral("-V");
p.start(generatorFullPath(), args);
p.waitForFinished();
QString out(QLatin1String(p.readAllStandardError()));
QRegularExpression rx(QStringLiteral("\\((.*)\\."));
QRegularExpressionMatch rm = rx.match(out);
QString version = out.indexOf(rx) != -1 ? rm.captured(1) : QString();
return version.toInt(nullptr);
}
#if 0
static QDebug operator<<(QDebug out, LayoutGenerator &c)
{
out << "DotGenerator:"
<< "m_boundingRect:" << c.m_boundingRect
<< "m_nodes:" << c.m_nodes
<< "m_edges:" << c.m_edges
<< "m_scale:" << c.m_scale
return out;
}
#endif
| 20,977
|
C++
|
.cpp
| 528
| 33.469697
| 210
| 0.652238
|
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,255
|
umlviewimageexporterall.cpp
|
KDE_umbrello/umbrello/umlviewimageexporterall.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlviewimageexporterall.h"
// application specific includes
#include "diagramprintpage.h"
#include "exportallviewsdialog.h"
#include "umlviewimageexportermodel.h"
#include "uml.h"
#include "umldoc.h"
// kde include files
#include <KComboBox>
#include <KLocalizedString>
#include <kurlrequester.h>
#include <KMessageBox>
// Qt include files
#include <QString>
#include <QStringList>
#include <QUrl>
/**
* Constructor for UMLViewImageExporterAll
*/
UMLViewImageExporterAll::UMLViewImageExporterAll()
{
m_dialog = new ExportAllViewsDialog(nullptr, "exportAllViewsDialog");
}
/**
* Destructor for UMLViewImageExporterAll
*/
UMLViewImageExporterAll::~UMLViewImageExporterAll()
{
delete m_dialog;
}
/**
* Export views selected by the DiagramPrintPage instance.
*
* See @ref exportViews(const UMLViewList &views) for more details.
*
* @param selectPage instance of DiagramPrintPage
*/
void UMLViewImageExporterAll::exportViews(DiagramPrintPage *selectPage)
{
UMLViewList views;
int count = selectPage->printUmlCount();
for (int i = 0; i < count; ++i) {
QString sID = selectPage->printUmlDiagram(i);
Uml::ID::Type id = Uml::ID::fromString(sID);
UMLView *v = UMLApp::app()->document()->findView(id);
if (v)
views.append(v);
}
exportViews(views);
}
/**
* Shows a dialog to the user to get the needed parameters and then exports
* the views.
* The dialog remembers values between calls (in the same application instance,
* although it's not persistent between Umbrello executions).
*
* Once the export begins, it can't be stopped until it ends itself. The status
* bar shows an information message until the export finishes.
*
* If something went wrong while exporting, an error dialog is shown to the
* user with the error messages explaining the problems occurred.
*/
void UMLViewImageExporterAll::exportViews(const UMLViewList &views)
{
UMLApp* app = UMLApp::app();
UMLDoc* umlDoc = app->document();
// default url can't be set when creating the action because the
// document wasn't loaded
if (m_dialog->m_kURL->url().isEmpty()) {
QUrl directory(umlDoc->url());
m_dialog->m_kURL->setUrl(directory.adjusted(QUrl::RemoveFilename));
}
if (m_dialog->exec() == QDialog::Rejected) {
return;
}
app->setImageMimeType(m_dialog->m_imageType->currentType());
float resolution = m_dialog->m_imageResolution->currentResolution();
// export all views
umlDoc->writeToStatusBar(i18n("Exporting all views..."));
QStringList errors = UMLViewImageExporterModel(resolution).exportViews(views,
UMLViewImageExporterModel::mimeTypeToImageType(m_dialog->m_imageType->currentType()),
QUrl(m_dialog->m_kURL->url()),
m_dialog->m_useFolders->isChecked());
if (!errors.empty()) {
KMessageBox::errorList(app, i18n("Some errors happened when exporting the images:"), errors);
}
umlDoc->writeToStatusBar(i18nc("reset status bar", "Ready."));
}
| 3,270
|
C++
|
.cpp
| 93
| 30.892473
| 117
| 0.710044
|
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,256
|
petalnode.cpp
|
KDE_umbrello/umbrello/petalnode.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "petalnode.h"
#include "debug_utils.h"
// todo avoid '"' on QString output
QString a;
class Indenter : public QDebug
{
public:
Indenter(QDebug &out, const char *className)
: QDebug(out)
{
level++;
*this << className
<< "(\n"
<< QString().fill(QLatin1Char('.'), level).toLatin1().constData()
;
}
~Indenter()
{
--level;
*this << "\n"
<< QString().fill(QLatin1Char(','), level).toLatin1().constData()
<< ")";
;
}
static int level;
};
int Indenter::level = 0;
QDebug operator<<(QDebug _out, const PetalNode::StringOrNode &p)
{
Indenter out(_out.nospace(), "PetalNode::StringOrNode");
if (!p.string.isEmpty())
out << "string: " << p.string;
if (p.node)
out << "node: " << *p.node;
return out;
}
QDebug operator<<(QDebug _out, const PetalNode::NameValue &p)
{
Indenter out(_out.nospace(), "PetalNode::NameValue");
out << "name: " << p.first
<< "value: " << p.second;
return out;
}
QDebug operator<<(QDebug _out, const PetalNode::NameValueList &p)
{
Indenter out(_out.nospace(), "PetalNode::NameValueList");
for (int i = 0; i < p.count(); ++i) {
out << i << ": " << p[i];
}
return out;
}
PetalNode::PetalNode(NodeType nt)
{
m_type = nt;
}
PetalNode::~PetalNode()
{
}
PetalNode::NodeType PetalNode::type() const
{
return m_type;
}
QStringList PetalNode::initialArgs() const
{
return m_initialArgs;
}
QString PetalNode::name() const
{
if (m_initialArgs.count() == 0)
return QString();
return m_initialArgs.first();
}
QString PetalNode::viewTag() const
{
if (m_initialArgs.count() == 0)
return QString();
return m_initialArgs.last();
}
/**
* Return the documentation from a petal node with carriage
* return handling and removed surrounding quotation marks
* if present.
*/
QString PetalNode::documentation() const
{
QString s = findAttribute(QStringLiteral("documentation")).string.trimmed();
if (s.isEmpty())
return s;
s.replace(QStringLiteral("\\n"), QStringLiteral("\n"));
if (s.startsWith(QLatin1Char('\"')) && s.endsWith(QLatin1Char('\"')))
return s.mid(1 ,s.length()-2);
else
return s;
}
PetalNode::NameValueList PetalNode::attributes() const
{
return m_attributes;
}
/*
void PetalNode::setType(PetalNode::NodeType t)
{
m_type = t;
}
*/
void PetalNode::setInitialArgs(const QStringList& args)
{
m_initialArgs = args;
}
void PetalNode::setAttributes(PetalNode::NameValueList vl)
{
m_attributes = vl;
}
/**
* Find an attribute by name.
* @return The value of the attribute. StringOrNode::isEmpty() returns true
* if the name could not be found.
*/
PetalNode::StringOrNode PetalNode::findAttribute(const QString& name) const
{
for (int i = 0; i < m_attributes.count(); i++) {
if (m_attributes[i].first == name)
return m_attributes[i].second;
}
return StringOrNode();
}
QDebug operator<<(QDebug _out, const PetalNode &p)
{
Indenter out(_out.nospace(), "PetalNode");
out << "type: " << p.type()
<< "name: " << p.name()
<< "attributes: " << p.attributes();
return out;
}
| 3,464
|
C++
|
.cpp
| 138
| 20.971014
| 92
| 0.626287
|
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,257
|
diagramswindow.cpp
|
KDE_umbrello/umbrello/diagramswindow.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "diagramswindow.h"
// app includes
#include "models/diagramsmodel.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QHeaderView>
#include <QTableView>
#include <QSortFilterProxyModel>
#include <QtDebug>
DiagramsWindow::DiagramsWindow(const QString &title, QWidget *parent)
: QDockWidget(title, parent)
{
setObjectName(QStringLiteral("DiagramsWindow"));
QSortFilterProxyModel *proxy = new QSortFilterProxyModel;
proxy->setSourceModel(UMLApp::app()->document()->diagramsModel());
proxy->setSortCaseSensitivity(Qt::CaseInsensitive);
m_diagramsTree = new QTableView;
m_diagramsTree->setModel(proxy);
m_diagramsTree->setSortingEnabled(true);
m_diagramsTree->verticalHeader()->setDefaultSectionSize(20);
m_diagramsTree->verticalHeader()->setVisible(false);
m_diagramsTree->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setWidget(m_diagramsTree);
connect(m_diagramsTree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotDiagramsDoubleClicked(QModelIndex)));
connect(m_diagramsTree, SIGNAL(clicked(QModelIndex)), this, SLOT(slotDiagramsClicked(QModelIndex)));
}
DiagramsWindow::~DiagramsWindow()
{
QAbstractItemModel *proxy = m_diagramsTree->model();
delete m_diagramsTree;
delete proxy;
}
void DiagramsWindow::modified()
{
UMLView *v = dynamic_cast<UMLView*>(QObject::sender());
if (!v)
return;
UMLApp::app()->document()->diagramsModel()->emitDataChanged(v);
}
void DiagramsWindow::slotDiagramsDoubleClicked(QModelIndex index)
{
QVariant v = m_diagramsTree->model()->data(index, Qt::UserRole);
if (v.canConvert<UMLView*>()) {
UMLView *view = v.value<UMLView*>();
view->showPropertiesDialog(this);
}
}
void DiagramsWindow::slotDiagramsClicked(QModelIndex index)
{
QVariant v = m_diagramsTree->model()->data(index, Qt::UserRole);
if (v.canConvert<UMLView*>()) {
UMLView *view = v.value<UMLView*>();
UMLApp::app()->setCurrentView(view, true);
}
}
| 2,244
|
C++
|
.cpp
| 63
| 32.063492
| 116
| 0.739631
|
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,258
|
diagram_utils.cpp
|
KDE_umbrello/umbrello/diagram_utils.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2017-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "diagram_utils.h"
// app includes
#include "associationwidget.h"
#include "association.h"
#define DBG_SRC QStringLiteral("Diagram_Utils")
#include "debug_utils.h"
#include "import_utils.h"
#include "messagewidget.h"
#include "object_factory.h"
#include "objectwidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
#include "umlobject.h"
#include "umlscene.h"
#include "widget_factory.h"
//// qt includes
#include <QListWidget>
#include <QMap>
#include <QMimeData>
#include <QRegularExpression>
// Currently this file is not using debug statements. Activate this line when inserting them:
DEBUG_REGISTER_DISABLED(Diagram_Utils)
namespace Diagram_Utils {
/**
* Detect sequence line format
* @param lines
* @return
*/
SequenceLineFormat detectSequenceLineFormat(const QStringList &lines)
{
QStringList l = lines;
while(l.size() > 0) {
QStringList cols = l.takeFirst().split(QRegularExpression(QStringLiteral("\\s+")),Qt::SkipEmptyParts);
if (cols.size() < 1)
continue;
if (cols[0] == QStringLiteral("#")) {
continue;
}
/*
* #0 0x000000000050d0b0 in Import_Utils::importStackTrace(QString const&, UMLScene*) (fileName=..., scene=scene@entry=0x12bd0f0)
*/
if (cols.size() > 2 && cols[0].startsWith(QStringLiteral("#")))
return GDB;
/*
* 6 Driver::ParseHelper::ParseHelper driver.cpp 299 0x634c44
*/
else if (cols[cols.size()-1].startsWith(QStringLiteral("0x")))
return QtCreatorGDB;
/*
* FloatingTextWidget::setPreText
*/
else if (cols[cols.size()-1].contains(QStringLiteral("::")))
return Simple;
else
return Invalid;
}
return Invalid;
}
/**
* Helper function to parse sequence line. The supported formats are:
*
* @param s string to parse
* @param sequence return of sequence number
* @param package return of package
* @param method return of method
* @param error return of error string if error happened
* @return true line could be parsed and return variable has been filled
* @return false line could not be parsed, no return variable has been filled
*/
bool parseSequenceLine(const QString &s, QString &sequence, QString &package, QString &method, QString &error)
{
QString identifier;
QString module;
QStringList cols = s.split(QRegularExpression(QStringLiteral("\\s+")),Qt::SkipEmptyParts);
if (cols.size() < 1) {
error = QStringLiteral("could not parse");
return false;
}
// skip comments
if (cols[0] == QStringLiteral("#")) {
return false;
}
/* gdb
* #0 0x000000000050d0b0 in Import_Utils::importStackTrace(QString const&, UMLScene*) (fileName=..., scene=scene@entry=0x12bd0f0)
* #25 0x00007fffefe1670c in g_main_context_iteration () from /usr/lib64/libglib-2.0.so.0
* #0 Import_Utils::importStackTrace (fileName=..., scene=scene@entry=0x137c000) at /home/ralf.habacker/src/umbrello-3/umbrello/codeimport/import_utils.cpp:715
*/
if (cols.size() > 2 && cols[0].startsWith(QStringLiteral("#"))) {
QString file;
sequence = cols.takeFirst();
if (cols[cols.size()-2] == QStringLiteral("at")) {
file = cols.takeLast();
cols.takeLast();
}
else if (cols[cols.size()-2] == QStringLiteral("from")) {
module = cols.takeLast();
cols.takeLast();
}
if (cols[1] == QStringLiteral("in")) {
cols.takeFirst(); // remove address
cols.takeFirst(); // in
}
identifier = cols.join(QStringLiteral(" "));
if (identifier.contains(QStringLiteral("::"))) {
QStringList b = identifier.split( QStringLiteral("::"));
// TODO handle multiple '::'
package = b.takeFirst();
method = b.join(QStringLiteral("::"));
}
else {
method = identifier;
package = module;
}
return true;
}
/**
* Qtcreator/gdb
* @verbatim
* 6 Driver::ParseHelper::ParseHelper driver.cpp 299 0x634c44
* 31 g_main_context_dispatch /usr/lib64/libglib-2.0.so.0 0x7fffefe16316
* ignoring
* ... <more> 0x7ffff41152d9
* 13 ?? 0x7ffff41152d9
* @endverbatim
*/
else if (cols[cols.size()-1].startsWith(QStringLiteral("0x"))) {
if (cols[0] == QStringLiteral("...") || cols[1] == QStringLiteral("??"))
return false;
sequence = cols.takeFirst();
cols.takeLast(); // remove address
QString line, file;
if (cols.size() == 2) {
module = cols.takeLast();
identifier = cols.join(QStringLiteral(" "));
} else if (cols.size() > 2) {
line = cols.takeLast();
file = cols.takeLast();
identifier = cols.join(QStringLiteral(" "));
}
if (identifier.contains(QStringLiteral("::"))) {
QStringList b = identifier.split( QStringLiteral("::"));
method = b.takeLast();
package = b.join(QStringLiteral("::"));
}
else {
method = identifier;
package = module;
}
if (package.isEmpty() && !file.isEmpty())
package = file;
if (!method.endsWith(QStringLiteral(")")))
method.append(QStringLiteral("()"));
return true;
} else if (cols[cols.size()-1].contains(QStringLiteral("::"))) {
QStringList b = s.split( QStringLiteral("::"));
method = b.takeLast();
package = b.join(QStringLiteral("::"));
return true;
}
error = QStringLiteral("unsupported line format");
return false;
}
/**
* Import sequence diagram entries from a string list.
*
* @param lines String list with sequences
* @param scene The diagram to import the sequences into.
* @param sourceHint The source the sequences are imported from
* @return true Import was successful.
* @return false Import failed.
*/
bool importSequences(const QStringList &lines, UMLScene *scene, const QString &sourceHint)
{
// object widget cache map
QMap<QString, ObjectWidget*> objectsMap;
// create "client widget"
UMLDoc *umldoc = UMLApp::app()->document();
QString name(QStringLiteral("client"));
UMLObject *left = umldoc->findUMLObject(name, UMLObject::ot_Class);
if (!left ) {
left = new UMLObject(nullptr, name);
left->setBaseType(UMLObject::ot_Class);
}
ObjectWidget *leftWidget = (ObjectWidget *)Widget_Factory::createWidget(scene, left);
leftWidget->activate();
// required to be savable
scene->addWidgetCmd(leftWidget);
objectsMap[name] = leftWidget;
ObjectWidget *rightWidget = nullptr;
ObjectWidget *mostRightWidget = leftWidget;
MessageWidget *messageWidget = nullptr;
// for further processing
MessageWidgetList messages;
QStringList l;
SequenceLineFormat format = detectSequenceLineFormat(lines);
if (format == GDB || format == QtCreatorGDB)
for(const QString &s : lines)
l.push_front(s);
else
l = lines;
// for each line
int index = 1;
for(const QString &line : l) {
QString stackframe, package, method, error;
if (!parseSequenceLine(line, stackframe, package, method, error)) {
if (!error.isEmpty()) {
QString item = QString::fromLatin1("%1:%2:%3: %4: %5")
.arg(sourceHint).arg(index)
.arg(1).arg(line).arg(error);
UMLApp::app()->log(item);
}
continue;
}
bool createObject = false;
if (package.contains(method))
createObject = true;
if (package.isEmpty())
package = QStringLiteral("unknown");
// get or create right object widget
if (objectsMap.contains(package)) {
rightWidget = objectsMap[package];
} else {
UMLFolder *logicalView = UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical);
UMLObject *right = Import_Utils::createUMLObjectHierarchy(UMLObject::ot_Class, package, logicalView);
rightWidget = (ObjectWidget *)Widget_Factory::createWidget(scene, right);
rightWidget->setX(mostRightWidget->x() + mostRightWidget->width() + 10);
rightWidget->activate();
objectsMap[package] = rightWidget;
scene->addWidgetCmd(rightWidget);
mostRightWidget = rightWidget;
}
// create message
int y = 10 + (messageWidget ? messageWidget->y() + messageWidget->height() : 20);
messageWidget = new MessageWidget(scene, leftWidget, rightWidget, y,
createObject ? Uml::SequenceMessage::Creation : Uml::SequenceMessage::Synchronous);
messageWidget->setCustomOpText(method);
messageWidget->setSequenceNumber(QString::number(index++));
messageWidget->calculateWidget();
messageWidget->activate();
messageWidget->setY(y);
// to make it savable
scene->addWidgetCmd(messageWidget);
messages.insert(0, messageWidget);
leftWidget = rightWidget;
}
if (messages.isEmpty())
return false;
// adjust vertical position
for(MessageWidget *w : messages) {
w->setY(w->y() + 20);
}
// adjust heights starting from the last message
MessageWidget *previous = messages.takeFirst();
for(MessageWidget *w : messages) {
w->setSize(w->width(), previous->y() - w->y() + previous->height() + 5);
// adjust vertical line length of object widgets
w->objectWidget(Uml::RoleType::A)->slotMessageMoved();
w->objectWidget(Uml::RoleType::B)->slotMessageMoved();
previous = w;
}
return true;
}
bool importClassGraph(const QStringList &lines, UMLScene *scene, const QString &sourceHint)
{
UMLDoc *umldoc = UMLApp::app()->document();
UMLWidget *lastWidget = nullptr;
UMLClassifier *c = nullptr;
QString methodIdentifier(QStringLiteral("()"));
QMap<QString, QPointer<UMLWidget>> widgetList;
int lineNumber = 0;
// for each line
for(const QString &line: lines) {
lineNumber++;
if (line.trimmed().isEmpty() || line.startsWith(QLatin1Char('#')) || line.startsWith(QStringLiteral("//")))
continue;
QStringList l = line.split(QStringLiteral(" "));
if (l.size() == 1) {
UMLObject *o = umldoc->findUMLObject(l[0], UMLObject::ot_Class);
if (!o)
o = Object_Factory::createUMLObject(UMLObject::ot_Class, l[0]);
c = o->asUMLClassifier();
// TODO: avoid multiple inserts
UMLWidget *w = Widget_Factory::createWidget(scene, o);
if (lastWidget)
w->setX(lastWidget->x() + lastWidget->width() + 10);
scene->setupNewWidget(w, false);
scene->createAutoAssociations(w);
scene->createAutoAttributeAssociations2(w);
widgetList[l[0]] = w;
lastWidget = w;
} else if (l.size() == 3 && l[1].startsWith(QLatin1Char('-'))) { // associations
UMLObject *o1 = umldoc->findUMLObject(l[0], UMLObject::ot_Class);
if (!o1)
o1 = Object_Factory::createUMLObject(UMLObject::ot_Class, l[0]);
UMLObject *o2 = umldoc->findUMLObject(l[2], UMLObject::ot_Class);
if (!o2)
o2 = Object_Factory::createUMLObject(UMLObject::ot_Class, l[2]);
bool swapObjects = false;
Uml::AssociationType::Enum type = Uml::AssociationType::Unknown;
UMLAssociation *assoc = nullptr;
bool newAssoc = false;
if (l[1] == QStringLiteral("---")) {
type = Uml::AssociationType::Association;
} else if (l[1] == QStringLiteral("-->")) {
type = Uml::AssociationType::UniAssociation;
} else if (l[1] == QStringLiteral("-<>")) {
type = Uml::AssociationType::Aggregation;
swapObjects = true;
} else if (l[1] == QStringLiteral("--*")) {
type = Uml::AssociationType::Composition;
swapObjects = true;
} else if (l[1] == QStringLiteral("-|>")) {
type = Uml::AssociationType::Generalization;
}
QPointer<UMLWidget> w1 = nullptr;
QPointer<UMLWidget> w2 = nullptr;
bool error = false;
if (swapObjects) {
w1 = widgetList[l[2]];
w2 = widgetList[l[0]];
if (w1 && w2) {
if (!assoc) {
assoc = umldoc->findAssociation(type, o1, o2);
if (!assoc) {
assoc = new UMLAssociation(type, o1, o2);
newAssoc = true;
}
}
}
else
error = true;
} else {
w1 = widgetList[l[0]];
w2 = widgetList[l[2]];
if (w1 && w2) {
if (!assoc) {
assoc = umldoc->findAssociation(type, o2, o1);
if (!assoc) {
assoc = new UMLAssociation(type, o2, o1);
newAssoc = true;
}
}
}
else
error = true;
}
if (!error) {
if (newAssoc) {
assoc->setUMLPackage(umldoc->rootFolder(Uml::ModelType::Logical));
umldoc->addAssociation(assoc);
}
AssociationWidget* aw = AssociationWidget::create(scene, w1, type, w2, assoc);
scene->addAssociation(aw);
} else {
// in case of error, assoc remains nullptr
QString item = QString::fromLatin1("%1:%2:%3: %4: %5")
.arg(sourceHint).arg(lineNumber)
.arg(1).arg(line).arg(QStringLiteral("error:could not add association"));
UMLApp::app()->log(item);
}
} else if (l[0].isEmpty() && c && l.size() == 2) {
QString name = l.last();
if (name.contains(methodIdentifier)) {
name.remove(methodIdentifier);
UMLOperation *m = Import_Utils::makeOperation(c, name);
Import_Utils::insertMethod(c, m, Uml::Visibility::Public, QStringLiteral("void"), false, false);
} else {
Import_Utils::insertAttribute(c, Uml::Visibility::Public, name, QStringLiteral("int"));
}
} else if (l[0].isEmpty() && c && l.size() >= 3) {
QString name = l.takeLast();
l.takeFirst();
QString v = l.first().toLower();
Uml::Visibility::Enum visibility = Uml::Visibility::fromString(v, true);
if (visibility == Uml::Visibility::Unknown)
visibility = Uml::Visibility::Public;
else
l.takeFirst();
QString type = l.join(QStringLiteral(" "));
if (name.contains(methodIdentifier)) {
name.remove(methodIdentifier);
UMLOperation *m = Import_Utils::makeOperation(c, name);
Import_Utils::insertMethod(c, m, visibility, type, false, false);
} else {
Import_Utils::insertAttribute(c, visibility, name, type);
}
} else {
QString item = QString::fromLatin1("%1:%2:%3: %4: %5")
.arg(sourceHint).arg(lineNumber)
.arg(1).arg(line).arg(QStringLiteral("syntax error"));
UMLApp::app()->log(item);
}
}
return true;
}
/**
* Import sequence diagram entries from a string list.
*
* @param lines String list with sequences
* @param scene The diagram to import the sequences into.
* @param sourceHint Source hint for use in error message in case of error.
* @return true Import was successful.
* @return false Import failed.
*/
bool importGraph(const QStringList &lines, UMLScene *scene, const QString &sourceHint)
{
bool result = false;
if (scene->isSequenceDiagram())
result = importSequences(lines, scene, sourceHint);
else if (scene->isClassDiagram())
result = importClassGraph(lines, scene, sourceHint);
if (result)
scene->updateSceneRect();
return result;
}
/**
* Import graph entries from clipboard
*
* @param mimeData instance of mime data to import from
* @param scene The diagram to import the graph into.
* @return true Import successful.
* @return false Import failed.
*/
bool importGraph(const QMimeData* mimeData, UMLScene *scene)
{
QString requestedFormat = QStringLiteral("text/plain");
if (!mimeData->hasFormat(requestedFormat))
return false;
QByteArray payload = mimeData->data(requestedFormat);
if (!payload.size()) {
return false;
}
QString data = QString::fromUtf8(payload);
QStringList lines = data.split(QStringLiteral("\n"));
UMLDoc *doc = UMLApp::app()->document();
doc->beginPaste();
bool result = importGraph(lines, scene, QLatin1String("from clipboard"));
doc->endPaste();
return result;
}
/**
* Import graph entries from file
*
* @param fileName filename to import the graph from.
* @param scene The diagram to import the graph into.
* @return true Import successful.
* @return false Import failed.
*/
bool importGraph(const QString &fileName, UMLScene *scene)
{
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly))
return false;
QStringList lines;
QTextStream in(&file);
in.setCodec("UTF-8");
while (!in.atEnd()) {
lines.append(in.readLine());
}
bool result = importGraph(lines, scene, fileName);
return result;
}
/**
* Check if name for a diagram is unique
*
* @param type type of diagram to check (set to undefined if to check against all diagrams)
* @param name name of diagram to check
* @return true - name is unique
* @return false - name is not unique
*/
bool isUniqueDiagramName(Uml::DiagramType::Enum type, QString &name)
{
bool found = false;
for(UMLView *view : UMLApp::app()->document()->viewIterator()) {
if (type == Uml::DiagramType::Undefined || view->umlScene()->type() == type) {
if (view->umlScene()->name() == name)
found = true;
}
}
return !found;
}
} // end namespace Diagram_Utils
| 19,090
|
C++
|
.cpp
| 488
| 30.319672
| 164
| 0.587788
|
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,259
|
icon_utils.cpp
|
KDE_umbrello/umbrello/icon_utils.cpp
|
/*
SPDX-FileCopyrightText: 2008 Andreas Fischer <andi.fischer@hispeed.ch>
SPDX-FileCopyrightText: 2009-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 "icon_utils.h"
#include "basictypes.h"
#define DBG_SRC QStringLiteral("Icon_Utils")
#include "debug_utils.h"
#include "optionstate.h"
#include "uml.h" // Only needed for logDebug
#include <kiconloader.h>
// qt includes
#include <QIcon>
#include <QFile>
DEBUG_REGISTER(Icon_Utils)
namespace Icon_Utils {
#define ICON_PREFIX QStringLiteral(":/pics/")
/**
* Returns the pixmap for the given type as small icon.
* @param type the identification of the icon
* @return the wanted pixmap
*/
QPixmap SmallIcon(IconType type)
{
QString icon = toString(type);
if (QFile::exists(ICON_PREFIX + icon + QStringLiteral(".png")))
return QPixmap(ICON_PREFIX + icon);
else
return DesktopIcon(type);
}
/**
* Returns the pixmap for the given type as bar icon.
* @param type the identification of the icon
* @return the wanted pixmap
*/
QPixmap BarIcon(IconType type)
{
QString icon = toString(type);
if (QFile::exists(ICON_PREFIX + icon + QStringLiteral(".png")))
return QPixmap(ICON_PREFIX + icon);
else
return DesktopIcon(type);
}
/**
* Returns the pixmap for the given type as main bar icon.
* @param type the identification of the icon
* @return the wanted pixmap
*/
QPixmap MainBarIcon(IconType type)
{
QString icon = toString(type);
if (QFile::exists(ICON_PREFIX + icon + QStringLiteral(".png")))
return QPixmap(ICON_PREFIX + icon);
else
return DesktopIcon(type);
}
/**
* Returns the pixmap for the given type as user icon.
* @param type the identification of the icon
* @return the wanted pixmap
*/
QPixmap UserIcon(IconType type)
{
QString icon = toString(type);
if (QFile::exists(ICON_PREFIX + icon + QStringLiteral(".png")))
return QPixmap(ICON_PREFIX + icon);
else
return DesktopIcon(type);
}
/**
* Returns the pixmap for the given type as desktop icon.
* @param type the identification of the icon
* @return the wanted icon
*/
QPixmap DesktopIcon(IconType type)
{
QString icon = toString(type);
if (KIconLoader().hasIcon(icon))
return KIconLoader().loadIcon(icon, KIconLoader::Group::Desktop);
else
return QPixmap(QSize(22,22));
}
/**
* Returns the pixmap for the given type as user icon.
* This is used in worktoolbar to create cursors.
* @param type the identification of the icon
* @return the wanted cursor
*/
QCursor Cursor(IconType type)
{
// TODO: generate from a 32x32 cursor template and place requested icon into
QString icon = QStringLiteral("cursor-") + toString(type);
if (QFile::exists(ICON_PREFIX + icon + QStringLiteral(".png")))
return QCursor(QPixmap(ICON_PREFIX + icon), 9, 9);
else
return QCursor(UserIcon(type), 9, 9);
}
/**
* Return the icon corresponding to the given Diagram_Type.
* @param dt the diagram type
* @return the wanted icon
*/
QPixmap iconSet(Uml::DiagramType::Enum dt)
{
switch (dt) {
case Uml::DiagramType::UseCase:
return DesktopIcon(it_Diagram_Usecase);
case Uml::DiagramType::Collaboration:
return DesktopIcon(it_Diagram_Collaboration);
case Uml::DiagramType::Class:
return DesktopIcon(it_Diagram_Class);
case Uml::DiagramType::Object:
return DesktopIcon(it_Diagram_Object);
case Uml::DiagramType::Sequence:
return DesktopIcon(it_Diagram_Sequence);
case Uml::DiagramType::State:
return DesktopIcon(it_Diagram_State);
case Uml::DiagramType::Activity:
return DesktopIcon(it_Diagram_Activity);
case Uml::DiagramType::Component:
return DesktopIcon(it_Diagram_Component);
case Uml::DiagramType::Deployment:
return DesktopIcon(it_Diagram_Deployment);
case Uml::DiagramType::EntityRelationship:
return DesktopIcon(it_Diagram_EntityRelationship);
default:
logDebug1("Icon_Utils::iconSet: unknown diagram type %1",
Uml::DiagramType::toString(dt));
return QPixmap();
}
}
/**
* Return the icon corresponding to the given Diagram_Type.
* @param dt the diagram type
* @return the wanted icon
*/
QPixmap smallIcon(Uml::DiagramType::Enum dt)
{
switch (dt) {
case Uml::DiagramType::UseCase:
return SmallIcon(it_Diagram_Usecase);
case Uml::DiagramType::Collaboration:
return SmallIcon(it_Diagram_Collaboration);
case Uml::DiagramType::Class:
return SmallIcon(it_Diagram_Class);
case Uml::DiagramType::Object:
return SmallIcon(it_Diagram_Object);
case Uml::DiagramType::Sequence:
return SmallIcon(it_Diagram_Sequence);
case Uml::DiagramType::State:
return SmallIcon(it_Diagram_State);
case Uml::DiagramType::Activity:
return SmallIcon(it_Diagram_Activity);
case Uml::DiagramType::Component:
return SmallIcon(it_Diagram_Component);
case Uml::DiagramType::Deployment:
return SmallIcon(it_Diagram_Deployment);
case Uml::DiagramType::EntityRelationship:
return SmallIcon(it_Diagram_EntityRelationship);
default:
logDebug1("Icon_Utils::smallIcon: unknown diagram type %1",
Uml::DiagramType::toString(dt));
return QPixmap();
}
}
/**
* Conversion from icon type to its string name.
* @param type the identification of the icon
* @return the string representation of the type
*/
QString toString(IconType type)
{
switch (type) {
case it_Accept_Signal: return QStringLiteral("accept_signal");
case it_Accept_TimeEvent: return QStringLiteral("accept_time_event");
case it_Activity: return QStringLiteral("activity");
case it_Activity_End: return QStringLiteral("end_state");
case it_Activity_Final: return QStringLiteral("final_activity");
case it_Activity_Initial: return QStringLiteral("initial_state");
case it_Activity_Transition: return QStringLiteral("uniassociation");
case it_Actor: return QStringLiteral("actor");
case it_Add_Point: return QStringLiteral("format-add-node");
case it_Aggregation: return QStringLiteral("aggregation");
case it_Align_Bottom: return QStringLiteral("align-vertical-bottom");
case it_Align_HorizontalDistribute: return QStringLiteral("distribute-horizontal");
case it_Align_HorizontalMiddle: return QStringLiteral("align-horizontal-center");
case it_Align_Left: return QStringLiteral("align-horizontal-left");
case it_Align_Right: return QStringLiteral("align-horizontal-right");
case it_Align_Top: return QStringLiteral("align-vertical-top");
case it_Align_VerticalDistribute: return QStringLiteral("distribute-vertical");
case it_Align_VerticalMiddle: return QStringLiteral("align-vertical-center");
case it_Anchor: return QStringLiteral("anchor");
case it_And_Line: return QStringLiteral("andline");
case it_Arrow: return QStringLiteral("arrow");
case it_Arrow_Down: return QStringLiteral("arrow-down");
case it_Arrow_Up: return QStringLiteral("arrow-up");
case it_Artifact: return QStringLiteral("artifact");
case it_Association: return QStringLiteral("association");
case it_Attribute_New: return QStringLiteral("CVpublic_var");
case it_Box: return QStringLiteral("box");
case it_Branch: return QStringLiteral("branch");
case it_Category: return QStringLiteral("category");
case it_Category_Child: return QStringLiteral("child2category");
case it_Category_Parent: return QStringLiteral("category2parent");
case it_Change_Font: return QStringLiteral("preferences-desktop-font");
case it_Check_Constraint: return QStringLiteral("check_constraint");
case it_Choice_Rhomb: return QStringLiteral("choice-rhomb");
case it_Choice_Round: return QStringLiteral("choice-round");
case it_Class: return QStringLiteral("class");
case it_ClassOrPackage: return QStringLiteral("class-or-package");
case it_Clear: return QStringLiteral("edit-clear");
case it_Code_Gen_Wizard: return QStringLiteral("umbrello");
case it_Color_Fill: return QStringLiteral("fill-color");
case it_Color_Line: return QStringLiteral("draw-brush");
case it_Combined_Fragment: return QStringLiteral("combined_fragment");
case it_Component: return Settings::optionState().generalState.uml2 ? QStringLiteral("component") : QStringLiteral("component1");
case it_Composition: return QStringLiteral("composition");
case it_Condition_PrePost: return QStringLiteral("PrePostCondition");
case it_Constraint_Check: return QStringLiteral("check_constraint");
case it_Constraint_ForeignKey: return QStringLiteral("foreignkey_constraint");
case it_Constraint_PrimaryKey: return QStringLiteral("primarykey_constraint");
case it_Constraint_Unique: return QStringLiteral("unique_constraint");
case it_Containment: return QStringLiteral("containment");
case it_Copy: return QStringLiteral("edit-copy");
case it_Cut: return QStringLiteral("edit-cut");
case it_Datatype: return QStringLiteral("datatype");
case it_Delete: return QStringLiteral("edit-delete");
case it_Delete_Point: return QStringLiteral("format-remove-node");
case it_Dependency: return QStringLiteral("dependency");
case it_Diagram: return QStringLiteral("CVnamespace");
case it_Diagram_Activity: return QStringLiteral("umbrello_diagram_activity");
case it_Diagram_Class: return QStringLiteral("umbrello_diagram_class");
case it_Diagram_Collaboration: return QStringLiteral("umbrello_diagram_collaboration");
case it_Diagram_Component: return QStringLiteral("umbrello_diagram_component");
case it_Diagram_Deployment: return QStringLiteral("umbrello_diagram_deployment");
case it_Diagram_EntityRelationship: return QStringLiteral("umbrello_diagram_deployment");
case it_Diagram_Object: return QStringLiteral("umbrello_diagram_object");
case it_Diagram_Sequence: return QStringLiteral("umbrello_diagram_sequence");
case it_Diagram_State: return QStringLiteral("umbrello_diagram_state");
case it_Diagram_Usecase: return QStringLiteral("umbrello_diagram_usecase");
case it_Directional_Association: return QStringLiteral("uniassociation");
case it_Document_Edit: return QStringLiteral("document-edit");
case it_Duplicate: return QStringLiteral("duplicate");
case it_EndState: return QStringLiteral("end_state");
case it_Entity: return QStringLiteral("entity");
case it_Entity_Attribute: return QStringLiteral("text-x-generic");
case it_Entity_Attribute_New: return QStringLiteral("text-x-generic");
case it_Enum: return QStringLiteral("enum");
case it_Enum_Literal: return QStringLiteral("text-x-generic");
case it_Exception: return QStringLiteral("exception");
case it_Export_Files: return QStringLiteral("document-export");
case it_Export_Picture: return QStringLiteral("image-x-generic");
case it_File_Open: return QStringLiteral("document-open");
case it_Folder: return QStringLiteral("folder-new");
case it_Folder_Cyan: return QStringLiteral("folder");
case it_Folder_Cyan_Open: return QStringLiteral("folder-open");
case it_Folder_Green: return QStringLiteral("folder-green");
case it_Folder_Green_Open: return QStringLiteral("folder-green"); //FIXME was folder_green_open
case it_Folder_Grey: return QStringLiteral("folder-grey");
case it_Folder_Grey_Open: return QStringLiteral("folder-grey"); //FIXME was folder_grey_open
case it_Folder_Orange: return QStringLiteral("folder-orange");
case it_Folder_Orange_Open: return QStringLiteral("folder-orange"); //FIXME was folder_orange_open
case it_Folder_Red: return QStringLiteral("folder-red");
case it_Folder_Red_Open: return QStringLiteral("folder-red"); //FIXME was folder_red_open
case it_Folder_Violet: return QStringLiteral("folder-violet");
case it_Folder_Violet_Open: return QStringLiteral("folder-violet"); //FIXME was folder_violet_open
case it_ForeignKey_Constraint: return QStringLiteral("foreignkey_constraint");
case it_Fork_Join: return QStringLiteral("activity-fork");
case it_Fork_State: return QStringLiteral("state-fork");
case it_Generalisation: return QStringLiteral("generalisation");
case it_Go_Next: return QStringLiteral("go-next");
case it_Go_Previous: return QStringLiteral("go-previous");
case it_History_Deep: return QStringLiteral("deep-history");
case it_History_Shallow: return QStringLiteral("shallow-history");
case it_Home: return QStringLiteral("user-home");
case it_Implementation_Attribute: return QStringLiteral("CVimplementation_var");
case it_Implementation_Method: return QStringLiteral("CVimplementation_meth");
case it_Implements: return QStringLiteral("generalisation");
case it_Import_File: return QStringLiteral("document-import");
case it_Import_Files: return QStringLiteral("document-import");
case it_Import_Project: return QStringLiteral("document-import");
case it_InitialState: return QStringLiteral("initial_state");
case it_Instance: return QStringLiteral("instance");
case it_Interface: return QStringLiteral("interface");
case it_Interface_Requirement: return QStringLiteral("interface-requirement");
case it_Interface_Provider: return QStringLiteral("interface-provider");
case it_Join: return QStringLiteral("join");
case it_Junction: return QStringLiteral("junction");
case it_Literal_New: return QStringLiteral("text-x-generic");
case it_Message_Async: return QStringLiteral("umbr-message-asynchronous");
case it_Message_Asynchronous: return QStringLiteral("umbr-coll-message-asynchronous");
case it_Message_Creation: return QStringLiteral("umbr-message-creation");
case it_Message_Destroy: return QStringLiteral("umbr-message-destroy");
case it_Message_Found: return QStringLiteral("umbr-message-found");
case it_Message_Lost: return QStringLiteral("umbr-message-lost");
case it_Message_Sync: return QStringLiteral("umbr-message-synchronous");
case it_Message_Synchronous: return QStringLiteral("umbr-coll-message-synchronous");
case it_New: return QStringLiteral("document-new");
case it_Node: return QStringLiteral("node");
case it_Note: return QStringLiteral("note");
case it_Object: return QStringLiteral("object");
case it_Object_Node: return QStringLiteral("object_node");
case it_Operation_New: return QStringLiteral("document-new");
case it_Operation_Public_New: return QStringLiteral("CVpublic_meth");
case it_Package: return QStringLiteral("package");
case it_Parameter_New: return QStringLiteral("text-x-generic");
case it_Paste: return QStringLiteral("edit-paste");
case it_Pin: return QStringLiteral("pin");
case it_Port: return QStringLiteral("port");
case it_Precondition: return QStringLiteral("precondition");
case it_PrimaryKey_Constraint: return QStringLiteral("primarykey_constraint");
case it_Private_Attribute: return QStringLiteral("CVprivate_var");
case it_Private_Method: return QStringLiteral("CVprivate_meth");
case it_Properties: return QStringLiteral("preferences-system");
case it_Properties_Activities: return QStringLiteral("text-x-generic");
case it_Properties_Associations: return QStringLiteral("preferences-other");
case it_Properties_Attributes: return QStringLiteral("preferences-other");
case it_Properties_AutoLayout: return QStringLiteral("code-class");
case it_Properties_Class: return QStringLiteral("document-properties");
case it_Properties_CodeGeneration: return QStringLiteral("document-export");
case it_Properties_CodeImport: return QStringLiteral("document-import");
case it_Properties_CodeViewer: return QStringLiteral("package_graphics_viewer");
case it_Properties_Color: return QStringLiteral("preferences-desktop-color");
case it_Properties_Columns: return QStringLiteral("preferences-other");
case it_Properties_Contents: return QStringLiteral("preferences-other");
case it_Properties_Display: return QStringLiteral("preferences-desktop-theme");
case it_Properties_EntityAttributes: return QStringLiteral("preferences-other");
case it_Properties_EntityConstraints: return QStringLiteral("preferences-other");
case it_Properties_EnumLiterals: return QStringLiteral("preferences-other");
case it_Properties_Font: return QStringLiteral("preferences-desktop-font");
case it_Properties_General: return QStringLiteral("preferences-other");
case it_Properties_Operations: return QStringLiteral("preferences-other");
case it_Properties_Roles: return QStringLiteral("preferences-other");
case it_Properties_Templates: return QStringLiteral("preferences-other");
case it_Properties_UserInterface: return QStringLiteral("preferences-desktop-theme");
case it_Protected_Attribute: return QStringLiteral("CVprotected_var");
case it_Protected_Method: return QStringLiteral("CVprotected_meth");
case it_Public_Attribute: return QStringLiteral("CVpublic_var");
case it_Public_Method: return QStringLiteral("CVpublic_meth");
case it_Redo: return QStringLiteral("edit-redo");
case it_Refactor: return QStringLiteral("refactor");
case it_Region: return QStringLiteral("region");
case it_Relationship: return QStringLiteral("relationship");
case it_Remove: return QStringLiteral("remove");
case it_Rename: return QStringLiteral("edit-rename");
case it_Send_Signal: return QStringLiteral("send_signal");
case it_Show: return QStringLiteral("document-preview");
case it_State: return QStringLiteral("state");
case it_State_Activity: return QStringLiteral("text-x-generic");
case it_State_Transition: return QStringLiteral("uniassociation");
case it_Subsystem: return QStringLiteral("subsystem");
case it_Tab_Close: return QStringLiteral("tab-close");
case it_Tab_New: return QStringLiteral("tab-new");
case it_Template: return QStringLiteral("template");
case it_Template_Class: return QStringLiteral("format-justify-fill");
case it_Template_Interface: return QStringLiteral("text-x-generic-template");
case it_Template_New: return QStringLiteral("text-x-generic-template");
case it_Text: return QStringLiteral("text");
case it_Undo: return QStringLiteral("edit-undo");
case it_UndoView: return QStringLiteral("document-save");
case it_Uniassociation: return QStringLiteral("uniassociation");
case it_Unique_Constraint: return QStringLiteral("unique_constraint");
case it_UseCase: return QStringLiteral("usecase");
case it_View_Code: return QStringLiteral("text-x-generic");
case it_Zoom_100: return QStringLiteral("zoom-original");
case it_Zoom_Slider: return QStringLiteral("zoom-original");
default: return QString();
}
}
} // namespace
| 22,220
|
C++
|
.cpp
| 371
| 54.725067
| 133
| 0.639199
|
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,260
|
file_utils.cpp
|
KDE_umbrello/umbrello/file_utils.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2020-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "file_utils.h"
// app includes
#define DBG_SRC QStringLiteral("File_Utils")
#include "debug_utils.h"
#include "uml.h" // Only needed for logDebug
// qt includes
#include <QFileInfo>
#include <QCoreApplication>
DEBUG_REGISTER(File_Utils)
namespace File_Utils {
/**
* returns path to xml catalog
* @return string with file path
*/
QString xmlCatalogFilePath()
{
#ifdef Q_OS_WIN
QString dataRoot = QCoreApplication::applicationDirPath() + QStringLiteral("/../");
#else
QString dataRoot = QStringLiteral("/");
#endif
QFileInfo fi(dataRoot + QStringLiteral("etc/xml/catalog"));
logDebug1("File_Utils::xmlCatalogFilePath: %1", fi.canonicalFilePath());
return fi.canonicalFilePath();
}
} // namespace File_Utils
| 890
|
C++
|
.cpp
| 30
| 27.4
| 92
| 0.747948
|
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,261
|
umlviewimageexporter.cpp
|
KDE_umbrello/umbrello/umlviewimageexporter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlviewimageexporter.h"
// application specific includes
#define DBG_SRC QStringLiteral("UMLViewImageExporter")
#include "debug_utils.h"
#include "dotgenerator.h"
#include "umlfiledialog.h"
#include "umlviewimageexportermodel.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
//kde include files
#include <KIO/Job>
#include <KJobWidgets>
#include <KLocalizedString>
#include <KMessageBox>
// Qt include files
#include <QFileDialog>
#include <QPointer>
#include <QString>
#include <QStringList>
#include <kio/statjob.h>
DEBUG_REGISTER_DISABLED(UMLViewImageExporter)
/**
* Constructor for UMLViewImageExporter.
*/
UMLViewImageExporter::UMLViewImageExporter(UMLScene* scene)
{
m_scene = scene;
m_imageMimeType = UMLApp::app()->imageMimeType();
}
/**
* Destructor for UMLViewImageExporter
*/
UMLViewImageExporter::~UMLViewImageExporter()
{
}
/**
* Shows a save dialog to the user to get the needed parameters and then exports
* the view.
* If the selected file already exists, an overwrite confirmation
* dialog is shown. If the user doesn't want to overwrite the file,
* the save dialog is shown again.
* The dialog remembers values between calls (in the same application instance,
* although it's not persistent between Umbrello executions).
*
* The status bar shows an information message until the export finishes.
*
* If something went wrong while exporting, an error dialog is shown to the
* user with the error message explaining the problem that happened.
*/
void UMLViewImageExporter::exportView()
{
if (!prepareExport()) {
return;
}
UMLApp* app = UMLApp::app();
// export the view
app->document()->writeToStatusBar(i18n("Exporting view..."));
UMLViewImageExporterModel theExporter;
QString error = theExporter.exportView(m_scene,
UMLViewImageExporterModel::mimeTypeToImageType(m_imageMimeType), m_imageURL);
if (!error.isNull()) {
KMessageBox::error(app, i18n("An error happened when exporting the image:\n") + error);
}
app->document()->writeToStatusBar(i18nc("reset status bar", "Ready."));
}
/**
* Shows a save file dialog to the user to get the parameters used
* to export the scene.
* If the selected file already exists, an overwrite confirmation
* dialog is shown. If the user doesn't want to overwrite the file,
* the save dialog is shown again.
*
* @return True if the user wants to save the image,
* false if the operation is cancelled.
*/
bool UMLViewImageExporter::prepareExport()
{
bool exportPrepared = false;
do {
if (!getParametersFromUser()) {
return false;
}
// check if the file exists
KIO::StatJob *job = KIO::stat(m_imageURL, KIO::StatJob::SourceSide, KIO::StatDetails(0));
KJobWidgets::setWindow(job, UMLApp::app());
job->exec();
bool result = !job->error();
if (result) {
int wantSave = KMessageBox::warningContinueCancel(nullptr,
i18n("The selected file %1 exists.\nDo you want to overwrite it?", m_imageURL.url(QUrl::PreferLocalFile)),
i18n("File Already Exists"), KGuiItem(i18n("&Overwrite")));
if (wantSave == KMessageBox::Continue) {
exportPrepared = true;
}
} else {
exportPrepared = true;
}
} while (!exportPrepared);
return true;
}
/**
* Shows a save file dialog to the user to get the parameters used
* to export the view and updates the attributes with the parameters got.
*
* @return True if the user wants to save the image,
* false if the operation is cancelled.
*/
bool UMLViewImageExporter::getParametersFromUser()
{
bool success = true;
// configure & show the file dialog
QUrl url;
QPointer<UMLFileDialog> dialog = new UMLFileDialog(url, QString(), UMLApp::app());
prepareFileDialog(dialog);
dialog->exec();
if (dialog->selectedUrl().isEmpty()) {
success = false;
}
else {
m_scene->clearSelected(); // Thanks to Peter Soetens for the idea
// update image url and mime type
m_imageURL = dialog->selectedUrl();
QFileInfo f(m_imageURL.toLocalFile());
m_imageMimeType = UMLViewImageExporterModel::imageTypeToMimeType(f.suffix());
UMLApp::app()->setImageMimeType(m_imageMimeType);
logDebug2("UMLViewImageExporter::getParametersFromUser: image mime type=%1"
" / URL=%2", m_imageMimeType, m_imageURL.path());
}
delete dialog;
return success;
}
/**
* Prepares the save file dialog.
* Sets the mime type filter, sensible default values...
*
* @param fileDialog The dialog to prepare.
*/
void UMLViewImageExporter::prepareFileDialog(UMLFileDialog *fileDialog)
{
// get all supported mime types
QStringList mimeTypes = UMLViewImageExporterModel::supportedMimeTypes();
QHash<QString, QString> configFiles;
if (!DotGenerator::availableConfigFiles(m_scene, configFiles) || configFiles.size() == 0)
mimeTypes.removeOne(QStringLiteral("image/x-dot"));
fileDialog->setCaption(i18n("Save As"));
fileDialog->setAcceptMode(QFileDialog::AcceptSave);
fileDialog->setMimeTypeFilters(mimeTypes);
// set a sensible default filename
if (m_imageURL.isEmpty()) {
QUrl docURL = UMLApp::app()->document()->url();
docURL.setUrl(docURL.toString(QUrl::RemoveFilename)
+ m_scene->name() + QLatin1Char('.')
+ UMLViewImageExporterModel::mimeTypeToImageType(m_imageMimeType));
fileDialog->selectUrl(docURL);
fileDialog->setSelection(m_scene->name() + QLatin1Char('.') + UMLViewImageExporterModel::mimeTypeToImageType(m_imageMimeType));
} else {
fileDialog->setUrl(m_imageURL);
fileDialog->setSelection(m_imageURL.fileName());
}
}
| 6,099
|
C++
|
.cpp
| 166
| 31.710843
| 138
| 0.693284
|
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,262
|
docwindow.cpp
|
KDE_umbrello/umbrello/docwindow.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "docwindow.h"
// local includes
#include "associationwidget.h"
#include "debug_utils.h"
#include "folder.h"
#include "icon_utils.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include "umldoc.h"
#include "umlobject.h"
#include "umlscene.h"
#include "umlwidget.h"
// kde includes
#include <QTextEdit>
#include <KLocalizedString>
// qt includes
#include <QCheckBox>
#include <QLabel>
#include <QGridLayout>
#include <QVBoxLayout>
/**
* Displays the 'modified' state of class DocWindow documentation.
*
* Also provides left mouse click handler to apply documentation back
* to the related object/widget.
*/
class ModifiedWidget : public QLabel
{
public:
ModifiedWidget(DocWindow *_parent)
: QLabel(_parent),
parent(_parent)
{
setAlignment(Qt::AlignCenter);
setToolTip(i18n("Flag whether documentation was modified. Press left mouse button to apply modified content."));
}
void setModified(bool state)
{
if (state)
setPixmap(Icon_Utils::SmallIcon(Icon_Utils::it_Document_Edit));
else
setPixmap(QPixmap());
}
virtual void mousePressEvent(QMouseEvent *ev)
{
QLabel::mousePressEvent(ev);
parent->updateDocumentation();
setPixmap(QPixmap());
}
DocWindow *parent;
};
/**
* Constructor.
*/
DocWindow::DocWindow(UMLDoc * doc, QWidget *parent)
: QWidget(parent),
m_pUMLObject(nullptr),
m_pUMLScene(nullptr),
m_pUMLDoc(doc),
m_pUMLWidget(nullptr),
m_pAssocWidget(nullptr),
m_Showing(st_Project),
m_focusEnabled(false)
{
//setup visual display
QGridLayout* statusLayout = new QGridLayout();
m_typeLabel = createPixmapLabel();
m_typeLabel->setToolTip(i18n("Documentation type"));
statusLayout->addWidget(m_typeLabel, 0, 0, 1, 1);
m_nameLabel = new QLabel(this);
m_nameLabel->setFrameStyle(QFrame::Panel | QFrame::Raised);
m_nameLabel->setAlignment(Qt::AlignHCenter);
statusLayout->addWidget(m_nameLabel, 0, 1, 1, 4);
QCheckBox *box = new QCheckBox();
box->setToolTip(i18n("Activate documentation edit after focus change."));
connect(box, SIGNAL(stateChanged(int)), this, SLOT(slotFocusEnabledChanged(int)));
statusLayout->addWidget(box, 0, 5, 1, 1);
m_modifiedWidget = new ModifiedWidget(this);
statusLayout->addWidget(m_modifiedWidget, 0, 6, 1, 1);
m_docTE = new QTextEdit(this);
m_docTE->setText(QString());
setFocusProxy(m_docTE);
//m_docTE->setWordWrapMode(QTextEdit::WidgetWidth);
QVBoxLayout* docLayout = new QVBoxLayout(this);
docLayout->addLayout(statusLayout);
docLayout->addWidget(m_docTE);
docLayout->setContentsMargins({});
connect(m_docTE, SIGNAL(textChanged()), this, SLOT(slotTextChanged()));
}
/**
* Destructor.
*/
DocWindow::~DocWindow()
{
}
/**
* Called when a widget wishes to display its documentation in the
* doc window. If there was already documentation there, that will
* be updated before being removed from the view.
*
* Also call this function if you update the documentation in another
* place, such as a properties dialog. Just set overwrite to true.
*
* Overwrite is used when you believe that the documentation window
* is already displaying documentation for the widget you wish to
* display.
* Overwrite just determines whose version is more up to date.
*/
void DocWindow::showDocumentation(UMLObject * object, bool overwrite)
{
if (!object) {
reset();
return;
}
if (m_Showing == st_UMLObject && object == m_pUMLObject) {
if (!overwrite) {
return;
}
}
else if (m_Showing == st_UMLWidget && object == m_pUMLWidget->umlObject()) {
if (!overwrite) {
updateDocumentation();
}
}
else {
updateDocumentation(true);
}
m_Showing = st_UMLObject;
m_pUMLObject = object;
m_docTE->setText(m_pUMLObject->doc());
if (m_pUMLObject->baseType() == UMLObject::ot_Folder) {
const UMLFolder *folder = m_pUMLObject->asUMLFolder();
updateLabel(folder->localName());
}
else
updateLabel(m_pUMLObject->name());
toForeground();
}
/**
* This method is the same as the one for UMLObjects except it
* displays documentation for a diagram.
*/
void DocWindow::showDocumentation(UMLScene * scene, bool overwrite)
{
if (!scene) {
reset();
return;
}
if (m_Showing == st_UMLScene && scene == m_pUMLScene) {
if (!overwrite) {
return;
}
}
else if (m_Showing == st_UMLWidget && scene == m_pUMLWidget->umlScene()) {
if (!overwrite) {
updateDocumentation();
}
}
else {
updateDocumentation(true);
}
m_Showing = st_UMLScene;
m_pUMLScene = scene;
m_docTE->setText(m_pUMLScene->documentation());
updateLabel(m_pUMLScene->name());
toForeground();
}
/**
* This method is the same as the one for UMLObjects except it
* displays documentation for an object instance (StateWidget/
* ObjectWidget).
*/
void DocWindow::showDocumentation(UMLWidget * widget, bool overwrite)
{
if (!widget) {
reset();
return;
}
if (m_Showing == st_UMLWidget && widget == m_pUMLWidget) {
if (!overwrite) {
return;
}
}
else if (m_Showing == st_UMLObject && widget->umlObject() == m_pUMLObject)
{
if (!overwrite) {
updateDocumentation();
}
}
else if (m_Showing == st_UMLScene && widget->umlScene() == m_pUMLScene)
{
if (!overwrite) {
updateDocumentation();
}
}
else {
updateDocumentation(true);
}
m_Showing = st_UMLWidget;
m_pUMLWidget = widget;
m_docTE->setText(m_pUMLWidget->documentation());
updateLabel(m_pUMLWidget->name());
toForeground();
}
/**
* This method is the same as the one for UMLObjects except it
* displays documentation for an association instance
* (AssociationWidget).
*/
void DocWindow::showDocumentation(AssociationWidget * widget, bool overwrite)
{
if (!widget) {
reset();
return;
}
if (widget == m_pAssocWidget) {
if (!overwrite) {
return;
}
}
else {
updateDocumentation(true);
}
m_Showing = st_Association;
m_pAssocWidget = widget;
m_docTE->setText(m_pAssocWidget->documentation());
updateLabel(m_pAssocWidget->name());
toForeground();
}
/**
* Call when you wish move changes in the doc window back into the
* members documentation.
*
* If clear is true the doc window will display the documentation
* for the current project instead of the widget documentation.
*
* This is usually called before displaying a properties dialog.
*
* @param clear If true, show the documentation of current project
* @param startup If true, no setModified(true) calls will be done and nothing is pushed to the undo stack
*/
void DocWindow::updateDocumentation(bool clear, bool startup)
{
// the file is marked modified, if the documentation differs
// we don't do this on startup/load of a xmi file, because every time
// modified is set, we get another undo/redo backup point
if (isModified()) {
if (m_Showing == st_UMLObject && m_pUMLObject) {
m_pUMLObject->setDoc(m_docTE->toPlainText());
} else if(m_Showing == st_UMLScene && m_pUMLScene) {
m_pUMLScene->setDocumentation(m_docTE->toPlainText());
} else if (m_Showing == st_UMLWidget && m_pUMLWidget) {
m_pUMLWidget->setDocumentation(m_docTE->toPlainText());
m_pUMLWidget->updateGeometry();
} else if (m_Showing == st_Association && m_pAssocWidget) {
m_pAssocWidget->setDocumentation(m_docTE->toPlainText());
} else if (m_Showing == st_Project) {
m_pUMLDoc->setDocumentation(m_docTE->toPlainText());
} else {
logError1("DocWindow: Could not update doc due to unknown type and object combination "
"(m_Showing=%1)", m_Showing);
}
// now do the setModified call
if (startup == false) {
m_pUMLDoc->setModified(true);
}
}
// we should show the documentation of the whole project
if (clear) {
reset();
}
}
/**
* Re-initializes the class for a new document.
*/
void DocWindow::reset()
{
m_pUMLScene = nullptr;
m_pUMLObject = nullptr;
m_pUMLWidget = nullptr;
m_pAssocWidget = nullptr;
m_Showing = st_Project;
m_docTE->setText(m_pUMLDoc->documentation());
updateLabel(m_pUMLDoc->name());
}
/**
* Checks if the user is typing in the documentation edit window.
*/
bool DocWindow::isTyping() const
{
if (m_docTE->hasFocus())
return true;
else
return false;
}
void DocWindow::setFocus()
{
parentWidget()->setVisible(true);
m_docTE->setFocus();
}
/**
* Checks if the user is typing in the documentation edit window.
*/
bool DocWindow::isModified() const
{
bool modified = false;
const QString currentText = m_docTE->toPlainText();
QString originalText;
switch (m_Showing) {
case st_UMLObject:
if (m_pUMLObject) {
originalText = m_pUMLObject->doc();
}
break;
case st_UMLScene:
if (m_pUMLScene) {
originalText = m_pUMLScene->documentation();
}
break;
case st_UMLWidget:
if (m_pUMLWidget) {
originalText = m_pUMLWidget->documentation();
}
break;
case st_Association:
if (m_pAssocWidget) {
originalText = m_pAssocWidget->documentation();
}
break;
case st_Project:
if (m_pUMLDoc) {
originalText = m_pUMLDoc->documentation();
}
break;
default:
break;
}
if (QString::compare(originalText, currentText) != 0) {
modified = true;
}
return modified;
}
/**
* An association was removed from the UMLScene.
* If the association removed was the association whose documentation is
* being shown, m_pAssocWidget is set to 0.
*/
void DocWindow::slotAssociationRemoved(AssociationWidget* association)
{
if (association == m_pAssocWidget || association->umlObject() == m_pUMLObject) {
// In old code, the below line crashed (bugs.kde.org/89860)
// A hotfix was made and detailed analysis was To Be Done:
// reset()
// However, it seems to have been fixed and the below line seems to work fine
updateDocumentation(true);
}
}
/**
* A widget was removed from the UMLScene.
* If the association removed was the association which documentation is
* being shown, m_pUMLWidget is set to 0.
*/
void DocWindow::slotWidgetRemoved(UMLWidget* widget)
{
if (widget == m_pUMLWidget || widget->umlObject() == m_pUMLObject) {
updateDocumentation(true);
}
}
/**
* text from the edit field has been changed
*/
void DocWindow::slotTextChanged()
{
updateLabel();
}
/**
* Set state of focus enabled support.
*/
void DocWindow::slotFocusEnabledChanged(int status)
{
m_focusEnabled = status == Qt::Checked;
}
/**
* Updates the info label with the current state.
* If the given name is empty only the modified icon is set.
*/
void DocWindow::updateLabel(const QString& name)
{
Icon_Utils::IconType icon = Icon_Utils::it_Home;
switch (m_Showing) {
case st_Project:
icon = Icon_Utils::it_Code_Gen_Wizard;
break;
case st_UMLScene:
icon = Icon_Utils::it_Diagram_Class;
break;
case st_UMLObject:
icon = UMLObject::toIcon(m_pUMLObject->baseType());
break;
case st_UMLWidget:
icon = WidgetBase::toIcon(m_pUMLWidget->baseType());
break;
case st_Association:
icon = Icon_Utils::it_Association;
break;
}
m_typeLabel->setPixmap(Icon_Utils::SmallIcon(icon));
m_nameLabel->setText(name);
m_modifiedWidget->setModified(isModified());
}
/**
* Creates a QLabel used with a pixmap.
* @return the just created QLabel
*/
QLabel* DocWindow::createPixmapLabel()
{
QLabel* label = new QLabel(this);
label->setAlignment(Qt::AlignCenter);
return label;
}
/**
* Bring doc window to foreground if it is tabbed with other dock widgets.
*/
void DocWindow::toForeground()
{
for(QTabBar *tab : UMLApp::app()->findChildren<QTabBar *>()) {
for(int i = 0; i < tab->count(); i++) {
if (tab->tabText(i) == parentWidget()->windowTitle())
tab->setCurrentIndex(i);
}
}
if (m_focusEnabled)
m_docTE->setFocus();
}
| 12,868
|
C++
|
.cpp
| 438
| 24.356164
| 120
| 0.654135
|
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,263
|
umllistview.cpp
|
KDE_umbrello/umbrello/umllistview.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umllistview.h"
// app includes
#include "actor.h"
#include "classifier.h"
#include "cmds.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "package.h"
#include "folder.h"
#include "component.h"
#include "node.h"
#include "artifact.h"
#include "enum.h"
#include "enumliteral.h"
#include "entity.h"
#include "category.h"
#include "datatype.h"
#include "docwindow.h"
#include "layoutgenerator.h"
#include "umllistviewpopupmenu.h"
#include "template.h"
#include "operation.h"
#include "attribute.h"
#include "entityattribute.h"
#include "instance.h"
#include "instanceattribute.h"
#include "uniqueconstraint.h"
#include "foreignkeyconstraint.h"
#include "checkconstraint.h"
#include "uml.h"
#include "umlclipboard.h"
#include "umldoc.h"
#include "umllistviewitemlist.h"
#include "umllistviewitem.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlviewimageexporter.h"
#include "usecase.h"
#include "model_utils.h"
#include "models/diagramsmodel.h"
#include "optionstate.h"
#include "uniqueid.h"
#include "idchangelog.h"
#include "umldragdata.h"
#include "classpropertiesdialog.h"
#include "umlattributedialog.h"
#include "umlentityattributedialog.h"
#include "umloperationdialog.h"
#include "umltemplatedialog.h"
#include "umluniqueconstraintdialog.h"
#include "umlforeignkeyconstraintdialog.h"
#include "umlcheckconstraintdialog.h"
#include "object_factory.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QApplication>
#include <QDrag>
#include <QDropEvent>
#include <QEvent>
#include <QFileDialog>
#include <QFocusEvent>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QPointer>
#include <QRegularExpression>
#include <QPoint>
#include <QRect>
#include <QToolTip>
#include <QXmlStreamWriter>
DEBUG_REGISTER(UMLListView)
/**
* Constructs the tree view.
*
* @param parent The parent to this.
*/
UMLListView::UMLListView(QWidget *parent)
: QTreeWidget(parent),
m_rv(nullptr),
m_datatypeFolder(nullptr),
m_settingsFolder(nullptr),
m_doc(UMLApp::app()->document()),
m_bStartedCut(false),
m_bStartedCopy(false),
m_bCreatingChildObject(false),
m_dragStartPosition(QPoint()),
m_dragCopyData(nullptr)
{
// setup list view
setAcceptDrops(true);
//setDropVisualizer(false);
//setItemsMovable(true);
//setItemsRenameable(true);
setSelectionMode(ExtendedSelection);
setFocusPolicy(Qt::StrongFocus);
setDragEnabled(true);
//setColumnWidthMode(0, Manual);
//setDefaultRenameAction(Accept);
//setResizeMode(LastColumn);
//header()->setClickEnabled(true);
//add columns and initial items
//addColumn(m_doc->name());
setSortingEnabled(true);
sortByColumn(0, Qt::AscendingOrder);
setEditTriggers(QAbstractItemView::EditKeyPressed);
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_lv[i] = nullptr;
}
//setup slots/signals
connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(slotCollapsed(QTreeWidgetItem*)));
connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(slotExpanded(QTreeWidgetItem*)));
connect(UMLApp::app(), SIGNAL(sigCutSuccessful()), this, SLOT(slotCutSuccessful()));
connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(slotItemSelectionChanged()));
}
/**
* Standard destructor.
*/
UMLListView::~UMLListView()
{
clean(); // m_lv
delete m_datatypeFolder;
delete m_settingsFolder;
delete m_rv;
}
/**
* Sets the title.
* @param column column in which to write
* @param text the text to write
*/
void UMLListView::setTitle(int column, const QString &text)
{
headerItem()->setText(column, text);
}
/**
* Handler for item selection changed signals.
*/
void UMLListView::slotItemSelectionChanged()
{
UMLListViewItem* currItem = static_cast<UMLListViewItem*>(currentItem());
if (currItem && currItem->isSelected()) {
logDebug1("UMLListView selection changed to %1", currItem->text(0));
// Update current view to selected object's view
if (Model_Utils::typeIsDiagram(currItem->type())) {
// If the user navigates to a diagram, load the diagram just like what
// would happen when clicking on it (includes saving/showing the documentation)
m_doc->changeCurrentView(currItem->ID());
} else {
// If the user navigates to any other item, save the current object's
// documentation and show selected object's documentation
UMLApp::app()->docWindow()->showDocumentation(currItem->umlObject(), true);
}
}
}
/**
* Event handler for the tool tip event.
* Works only for operations to show the signature.
*/
bool UMLListView::event(QEvent *e)
{
if (e->type() == QEvent::ToolTip) {
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);
UMLListViewItem * item = static_cast<UMLListViewItem*>(itemAt(helpEvent->pos()));
if (item) {
QToolTip::showText(helpEvent->globalPos(), item->toolTip());
} else {
QToolTip::hideText();
e->ignore();
}
return true;
}
return QTreeWidget::event(e);
}
/**
* Handler for mouse press events.
* @param me the mouse event
*/
void UMLListView::mousePressEvent(QMouseEvent *me)
{
UMLView *currentView = UMLApp::app()->currentView();
if (!currentView) {
logWarn0("UMLListView::mousePressEvent: ignoring because currentView is not set");
return;
}
UMLScene *scene = currentView->umlScene();
Q_ASSERT(scene);
scene->clearSelected();
if (me->modifiers() != Qt::ShiftModifier)
clearSelection();
// Get the UMLListViewItem at the point where the mouse pointer was pressed
UMLListViewItem * item = static_cast<UMLListViewItem*>(itemAt(me->pos()));
if (item) {
logDebug1("UMLListView::mousePressEvent on %1", UMLListViewItem::toString(item->type()));
}
else {
logDebug0("UMLListView::mousePressEvent on empty space");
}
const Qt::MouseButton button = me->button();
if (!item || (button != Qt::RightButton && button != Qt::LeftButton)) {
UMLApp::app()->docWindow()->updateDocumentation(true);
return;
}
if (button == Qt::LeftButton) {
UMLObject *o = item->umlObject();
if (o)
UMLApp::app()->docWindow()->showDocumentation(o, false);
else
UMLApp::app()->docWindow()->updateDocumentation(true);
m_dragStartPosition = me->pos();
}
QTreeWidget::mousePressEvent(me);
}
/**
* Handler for mouse move events.
* @param me the mouse event
*/
void UMLListView::mouseMoveEvent(QMouseEvent* me)
{
if (!(me->buttons() & Qt::LeftButton)) {
logDebug0("UMLListView::mouseMoveEvent not LeftButton (no action)");
return;
}
if ((me->pos() - m_dragStartPosition).manhattanLength()
< QApplication::startDragDistance()) {
logDebug0("UMLListView::mouseMoveEvent pos change since dragStart is below "
"startDragDistance threshold (no action)");
return;
}
logDebug0("UMLListView::mouseMoveEvent initiating drag");
// Store a copy of selected list items in case the user
// will ctrl-drag (basically just copy/paste) an item
//
// The QDrag mime data is used for moving items onto the diagram
// or internally in the tree view
UMLClipboard clipboard;
if ((m_dragCopyData = clipboard.copy(false)) == nullptr) {
// This should never happen, this is just like using ctrl+c on the list view item
logError0("UMLListView::mouseMoveEvent: Unable to obtain mime data for copy-drag operation");
}
QDrag* drag = new QDrag(this);
drag->setMimeData(getDragData());
drag->exec(Qt::MoveAction | Qt::CopyAction, Qt::MoveAction);
}
/**
* Handler for mouse release event.
* @param me the mouse event
*/
void UMLListView::mouseReleaseEvent(QMouseEvent *me)
{
if (me->button() != Qt::LeftButton) {
QTreeWidget::mouseReleaseEvent(me);
return;
}
UMLListViewItem *item = static_cast<UMLListViewItem*>(itemAt(me->pos()));
if (item == nullptr || !Model_Utils::typeIsDiagram(item->type())) {
QTreeWidget::mouseReleaseEvent(me);
return;
}
// Switch to diagram on mouse release - not on mouse press
// because the user might intend a drag-to-note.
m_doc->changeCurrentView(item->ID());
UMLView *view = m_doc->findView(item->ID());
if (view && view->umlScene())
UMLApp::app()->docWindow()->showDocumentation(view->umlScene(), false);
QTreeWidget::mouseReleaseEvent(me);
}
/**
* Handler for key press events.
* @param ke the key event
*/
void UMLListView::keyPressEvent(QKeyEvent *ke)
{
QTreeWidget::keyPressEvent(ke); // let parent handle it
const int k = ke->key();
if (k == Qt::Key_Delete || k == Qt::Key_Backspace) {
slotDeleteSelectedItems();
} else if (k == Qt::Key_F3) {
// preliminary support for layout generator
LayoutGenerator r;
if (!r.generate(UMLApp::app()->currentView()->umlScene()))
return;
r.apply(UMLApp::app()->currentView()->umlScene());
}
}
/**
* Called when a right mouse button menu has an item selected.
* @param action the selected action
* @param position the position of the menu on the diagram (only used for multi selection "Show")
*/
void UMLListView::slotMenuSelection(QAction* action, const QPoint &position)
{
UMLListViewItem * currItem = static_cast<UMLListViewItem*>(currentItem());
if (!currItem) {
logDebug0("UMLListView::slotMenuSelection Invoked without currently selectedItem!");
return;
}
UMLListViewItem::ListViewType lvt = currItem->type();
ListPopupMenu::MenuType menuType = ListPopupMenu::typeFromAction(action);
switch (menuType) {
case ListPopupMenu::mt_Activity_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_Activity_Diagram);
break;
case ListPopupMenu::mt_Class_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_Class_Diagram);
break;
case ListPopupMenu::mt_Collaboration_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_Collaboration_Diagram);
break;
case ListPopupMenu::mt_Component_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_Component_Diagram);
break;
case ListPopupMenu::mt_Deployment_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_Deployment_Diagram);
break;
case ListPopupMenu::mt_EntityRelationship_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_EntityRelationship_Diagram);
break;
case ListPopupMenu::mt_Sequence_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_Sequence_Diagram);
break;
case ListPopupMenu::mt_State_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_State_Diagram);
break;
case ListPopupMenu::mt_UseCase_Diagram:
addNewItem(currItem, UMLListViewItem::lvt_UseCase_Diagram);
break;
case ListPopupMenu::mt_Class:
addNewItem(currItem, UMLListViewItem::lvt_Class);
break;
case ListPopupMenu::mt_Package:
addNewItem(currItem, UMLListViewItem::lvt_Package);
break;
case ListPopupMenu::mt_Subsystem:
addNewItem(currItem, UMLListViewItem::lvt_Subsystem);
break;
case ListPopupMenu::mt_Component:
addNewItem(currItem, UMLListViewItem::lvt_Component);
break;
case ListPopupMenu::mt_Port:
if (Settings::optionState().generalState.uml2)
addNewItem(currItem, UMLListViewItem::lvt_Port);
break;
case ListPopupMenu::mt_Node:
addNewItem(currItem, UMLListViewItem::lvt_Node);
break;
case ListPopupMenu::mt_Artifact:
addNewItem(currItem, UMLListViewItem::lvt_Artifact);
break;
case ListPopupMenu::mt_Interface:
addNewItem(currItem, UMLListViewItem::lvt_Interface);
break;
case ListPopupMenu::mt_Enum:
addNewItem(currItem, UMLListViewItem::lvt_Enum);
break;
case ListPopupMenu::mt_EnumLiteral:
addNewItem(currItem, UMLListViewItem::lvt_EnumLiteral);
break;
case ListPopupMenu::mt_Template:
addNewItem(currItem, UMLListViewItem::lvt_Template);
break;
case ListPopupMenu::mt_Entity:
addNewItem(currItem, UMLListViewItem::lvt_Entity);
break;
case ListPopupMenu::mt_Instance:
addNewItem(currItem, UMLListViewItem::lvt_Instance);
break;
case ListPopupMenu::mt_Category:
addNewItem(currItem, UMLListViewItem::lvt_Category);
break;
case ListPopupMenu::mt_DisjointSpecialisation:
{
UMLCategory* catObj = currItem->umlObject()->asUMLCategory();
catObj->setType(UMLCategory::ct_Disjoint_Specialisation);
}
break;
case ListPopupMenu::mt_OverlappingSpecialisation:
{
UMLCategory* catObj = currItem->umlObject()->asUMLCategory();
catObj->setType(UMLCategory::ct_Overlapping_Specialisation);
}
break;
case ListPopupMenu::mt_Union:
{
UMLCategory* catObj = currItem->umlObject()->asUMLCategory();
catObj->setType(UMLCategory::ct_Union);
}
break;
case ListPopupMenu::mt_Datatype:
addNewItem(currItem, UMLListViewItem::lvt_Datatype);
break;
case ListPopupMenu::mt_Actor:
addNewItem(currItem, UMLListViewItem::lvt_Actor);
break;
case ListPopupMenu::mt_UseCase:
addNewItem(currItem, UMLListViewItem::lvt_UseCase);
break;
case ListPopupMenu::mt_Attribute:
addNewItem(currItem, UMLListViewItem::lvt_Attribute);
break;
case ListPopupMenu::mt_EntityAttribute:
addNewItem(currItem, UMLListViewItem::lvt_EntityAttribute);
break;
case ListPopupMenu::mt_InstanceAttribute:
addNewItem(currItem, UMLListViewItem::lvt_InstanceAttribute);
break;
case ListPopupMenu::mt_Operation:
addNewItem(currItem, UMLListViewItem::lvt_Operation);
break;
case ListPopupMenu::mt_UniqueConstraint:
addNewItem(currItem, UMLListViewItem::lvt_UniqueConstraint);
break;
case ListPopupMenu::mt_PrimaryKeyConstraint:
addNewItem(currItem, UMLListViewItem::lvt_PrimaryKeyConstraint);
break;
case ListPopupMenu::mt_ForeignKeyConstraint:
addNewItem(currItem, UMLListViewItem::lvt_ForeignKeyConstraint);
break;
case ListPopupMenu::mt_CheckConstraint:
addNewItem(currItem, UMLListViewItem::lvt_CheckConstraint);
break;
case ListPopupMenu::mt_Import_Class:
UMLApp::app()->slotImportClass();
break;
case ListPopupMenu::mt_Import_Project:
UMLApp::app()->slotImportProject();
break;
case ListPopupMenu::mt_Expand_All:
expandAll(currItem);
break;
case ListPopupMenu::mt_Collapse_All:
collapseAll(currItem);
break;
case ListPopupMenu::mt_Export_Image:
{
const Uml::ID::Type id = currItem->ID();
UMLView *view = m_doc->findView(id);
if (view) {
if (view->umlScene())
view->umlScene()->getImageExporter()->exportView();
else
logError1("ListPopupMenu::mt_Export_Image: view %1 umlScene() is NULL", Uml::ID::toString(id));
} else {
logError1("ListPopupMenu::mt_Export_Image: m_doc->findView(%1) returns NULL", Uml::ID::toString(id));
}
}
break;
case ListPopupMenu::mt_Externalize_Folder:
{
UMLListViewItem *current = static_cast<UMLListViewItem*>(currentItem());
UMLFolder *modelFolder = current->umlObject()->asUMLFolder();
if (modelFolder == nullptr) {
logError0("ListPopupMenu::slotMenuSelection(mt_Externalize_Folder): modelFolder is null");
return;
}
// configure & show the file dialog
const QString rootDir(m_doc->url().adjusted(QUrl::RemoveFilename).path());
QPointer<QFileDialog> fileDialog = new QFileDialog(this, i18n("Externalize Folder"), rootDir, QStringLiteral("*.xml"));
// set a sensible default filename
QString defaultFilename = current->text(0).toLower();
defaultFilename.replace(QRegularExpression(QStringLiteral("\\W+")), QStringLiteral("_"));
defaultFilename.append(QStringLiteral(".xml")); // default extension
fileDialog->selectFile(defaultFilename);
QList<QUrl> selURL;
if (fileDialog->exec() == QDialog::Accepted) {
selURL = fileDialog->selectedUrls();
}
delete fileDialog;
if (selURL.isEmpty())
return;
QString path = selURL[0].toLocalFile();
QString fileName = path;
if (fileName.startsWith(rootDir)) {
fileName.remove(rootDir);
} else {
KMessageBox::error(
nullptr,
i18n("Folder %1 must be relative to the main model directory, %2.", path, rootDir),
i18n("Path Error"));
return;
}
QFile file(path);
// Warn if file exists.
if (file.exists()) {
KMessageBox::error(
nullptr,
i18n("File %1 already exists!\nThe existing file will be overwritten.", fileName),
i18n("File Exists"));
}
// Test if file is writable.
if (file.open(QIODevice::WriteOnly)) {
file.close();
} else {
KMessageBox::error(
nullptr,
i18n("There was a problem saving file: %1", fileName),
i18n("Save Error"));
return;
}
modelFolder->setFolderFile(fileName);
// Recompute text of the folder
QString folderText = current->text(0);
folderText.remove(QRegularExpression(QStringLiteral("\\s*\\(.*$")));
folderText.append(QStringLiteral(" (") + fileName + QLatin1Char(')'));
current->setText(folderText);
break;
}
case ListPopupMenu::mt_Internalize_Folder:
{
UMLListViewItem *current = static_cast<UMLListViewItem*>(currentItem());
UMLFolder *modelFolder = current->umlObject()->asUMLFolder();
if (modelFolder == nullptr) {
logError0("ListPopupMenu::slotMenuSelection(mt_Internalize_Folder): modelFolder is null");
return;
}
modelFolder->setFolderFile(QString());
// Recompute text of the folder
QString folderText = current->text(0);
folderText.remove(QRegularExpression(QStringLiteral("\\s*\\(.*$")));
current->setText(folderText);
break;
}
case ListPopupMenu::mt_Model:
{
QString name = m_doc->name();
bool ok = Dialog_Utils::askName(i18n("Enter Model Name"),
i18n("Enter the new name of the model:"),
name);
if (ok) {
setTitle(0, name);
m_doc->setName(name);
}
break;
}
case ListPopupMenu::mt_Open_File: {
UMLListViewItem *current = static_cast<UMLListViewItem*>(currentItem());
const UMLArtifact *artifact = current->umlObject()->asUMLArtifact();
if (artifact == nullptr) {
logError0("ListPopupMenu::slotMenuSelection(mt_Internalize_Folder): artifact is null");
return;
}
QUrl file = QUrl::fromLocalFile(artifact->fullPath());
UMLApp::app()->slotOpenFileInEditor(file);
break;
}
case ListPopupMenu::mt_Rename:
edit(currentIndex());
break;
case ListPopupMenu::mt_Delete:
deleteItem(currItem);
break;
case ListPopupMenu::mt_Show:
// first check if we are on a diagram
if (!Model_Utils::typeIsDiagram(lvt)) {
UMLObject * object = currItem->umlObject();
if (!object) {
logError0("ListPopupMenu::slotMenuSelection(mt_Show): umlObject is null");
return;
}
QList<UMLWidget*> findResults;
if (Model_Utils::typeIsCanvasWidget(lvt)) {
UMLViewList views = m_doc->viewIterator();
for (UMLView *view : views) {
for (UMLWidget *widget : view->umlScene()->widgetList()) {
if (object == widget->umlObject()) {
findResults.append(widget);
}
}
}
}
if (findResults.size() == 0) {
break;
}
UMLWidget *selectedResult = nullptr;
if (findResults.size() > 1) {
QMenu menu(this);
int i = 0;
for(UMLWidget *w : findResults) {
QAction *action = menu.addAction(w->umlScene()->name() + QLatin1Char(':') + w->name());
action->setData(i++);
}
QAction *action = menu.exec(position);
if (action) {
selectedResult = findResults.at(action->data().toInt());
}
} else {
selectedResult = findResults.first();
}
if (!selectedResult) {
break;
}
UMLView *view = selectedResult->umlScene()->activeView();
selectedResult->umlScene()->setIsOpen(true);
view->setZoom(100);
if (UMLApp::app()->currentView() != view) {
UMLApp::app()->setCurrentView(view, false);
}
view->centerOn(selectedResult->scenePos());
selectedResult->setSelected(true);
}
break;
case ListPopupMenu::mt_Properties:
if (Model_Utils::typeIsProperties(lvt)) {
UMLApp::app()->slotPrefs(Model_Utils::convert_LVT_PT(lvt));
return;
}
else if (Model_Utils::typeIsDiagram(lvt)) {
UMLView * pView = m_doc->findView(currItem->ID());
if (pView) {
UMLApp::app()->docWindow()->updateDocumentation(false);
pView->showPropertiesDialog();
UMLApp::app()->docWindow()->showDocumentation(pView->umlScene(), true);
}
return;
}
{ // ok, we are on another object, so find out on which one
UMLObject * object = currItem->umlObject();
if (!object) {
logError0("ListPopupMenu::slotMenuSelection(mt_Properties): umlObject is null");
return;
}
object->showPropertiesDialog();
}
break;
case ListPopupMenu::mt_Logical_Folder:
addNewItem(currItem, UMLListViewItem::lvt_Logical_Folder);
break;
case ListPopupMenu::mt_UseCase_Folder:
addNewItem(currItem, UMLListViewItem::lvt_UseCase_Folder);
break;
case ListPopupMenu::mt_Component_Folder:
addNewItem(currItem, UMLListViewItem::lvt_Component_Folder);
break;
case ListPopupMenu::mt_Deployment_Folder:
addNewItem(currItem, UMLListViewItem::lvt_Deployment_Folder);
break;
case ListPopupMenu::mt_EntityRelationship_Folder:
addNewItem(currItem, UMLListViewItem::lvt_EntityRelationship_Folder);
break;
case ListPopupMenu::mt_Cut:
m_bStartedCut = true;
m_bStartedCopy = false;
UMLApp::app()->slotEditCut();
break;
case ListPopupMenu::mt_Copy:
m_bStartedCut = false;
m_bStartedCopy = true;
UMLApp::app()->slotEditCopy();
break;
case ListPopupMenu::mt_Paste:
UMLApp::app()->slotEditPaste();
break;
case ListPopupMenu::mt_Clone:
UMLApp::app()->slotEditCopy();
UMLApp::app()->slotEditPaste();
break;
case ListPopupMenu::mt_ChangeToClass:
{
UMLClassifier* o = currItem->umlObject()->asUMLClassifier();
o->setStereotypeCmd(QString());
currItem->updateObject();
}
break;
case ListPopupMenu::mt_ChangeToPackage:
{
UMLClassifier* o = currItem->umlObject()->asUMLClassifier();
o->setStereotypeCmd(QString());
o->setBaseType(UMLObject::ot_Package);
currItem->updateObject();
}
break;
case ListPopupMenu::mt_Undefined:
// We got signalled for a menu action, but that menu action was not
// defined in ListPopupMenu. This is the case for "create diagram"
// actions which are defined and handled in UMLApp. This is fine,
// ignore them without warning.
break;
default:
logError1("ListPopupMenu::slotMenuSelection: unknown type %1", menuType);
break;
}//end switch
}
/**
* Find the parent folder for a diagram.
* If the currently selected item in the list view is a folder
* then that folder is returned as the parent.
*
* @param dt The Diagram_Type of the diagram.
* The type will only be used if there is no currently
* selected item, or if the current item is not a folder.
* In that case the root folder which is suitable for the
* Diagram_Type is returned.
* @return Pointer to the parent UMLListViewItem for the diagram.
*/
UMLListViewItem *UMLListView::findFolderForDiagram(Uml::DiagramType::Enum dt) const
{
UMLListViewItem *p = static_cast<UMLListViewItem*>(currentItem());
if (p && Model_Utils::typeIsFolder(p->type())
&& !Model_Utils::typeIsRootView(p->type())) {
return p;
}
switch (dt) {
case Uml::DiagramType::UseCase:
p = m_lv[Uml::ModelType::UseCase];
break;
case Uml::DiagramType::Component:
p = m_lv[Uml::ModelType::Component];
break;
case Uml::DiagramType::Deployment:
p = m_lv[Uml::ModelType::Deployment];
break;
case Uml::DiagramType::EntityRelationship:
p = m_lv[Uml::ModelType::EntityRelationship];
break;
default:
p = m_lv[Uml::ModelType::Logical];
break;
}
return p;
}
/**
* Creates a new item to represent a new diagram.
* @param id the id of the new diagram
*/
void UMLListView::slotDiagramCreated(Uml::ID::Type id)
{
if (findItem(id)) {
logDebug1("UMLListView::slotDiagramCreated: list view item %1 already exists",
Uml::ID::toString(id));
return;
}
UMLView *v = m_doc->findView(id);
if (v) {
UMLScene *scene = v->umlScene();
if (scene) {
const Uml::DiagramType::Enum dt = scene->type();
UMLListViewItem* p = findUMLObject(scene->folder());
UMLListViewItem* item = new UMLListViewItem(p, scene->name(), Model_Utils::convert_DT_LVT(dt), id);
item->setSelected(true);
UMLApp::app()->docWindow()->showDocumentation(scene, false);
}
} else {
logWarn1("umlDoc::findView(%1) returns NULL", Uml::ID::toString(id));
}
}
/**
* Determine the parent ListViewItem given a UMLObject.
*
* @param object Pointer to the UMLObject for which to look up the parent.
* @return Pointer to the parent UMLListViewItem chosen.
* Returns NULL on error (no parent could be determined.)
*/
UMLListViewItem* UMLListView::determineParentItem(UMLObject* object) const
{
if (object == nullptr)
return nullptr;
UMLListViewItem *parentItem = nullptr;
UMLPackage *pkg = nullptr;
UMLListViewItem* current = (UMLListViewItem*) currentItem();
UMLListViewItem::ListViewType lvt = UMLListViewItem::lvt_Unknown;
if (current)
lvt = current->type();
UMLObject::ObjectType t = object->baseType();
switch (t) {
case UMLObject::ot_Attribute:
case UMLObject::ot_Operation:
case UMLObject::ot_Template:
case UMLObject::ot_EnumLiteral:
case UMLObject::ot_EntityAttribute:
case UMLObject::ot_InstanceAttribute:
case UMLObject::ot_UniqueConstraint:
case UMLObject::ot_ForeignKeyConstraint:
case UMLObject::ot_CheckConstraint:
//this will be handled by childObjectAdded
return nullptr;
break;
case UMLObject::ot_Association:
case UMLObject::ot_Role:
case UMLObject::ot_Stereotype:
return nullptr; // currently no representation in list view
break;
default:
pkg = object->umlPackage();
if (pkg) {
UMLListViewItem* pkgItem = findUMLObject(pkg);
if (pkgItem == nullptr)
logError2("UMLListView::determineParentItem(%1): could not find parent package %2",
object->name(), pkg->name());
else
parentItem = pkgItem;
} else if ((lvt == UMLListViewItem::lvt_UseCase_Folder &&
(t == UMLObject::ot_Actor || t == UMLObject::ot_UseCase))
|| (lvt == UMLListViewItem::lvt_Component_Folder && t == UMLObject::ot_Component)
|| (lvt == UMLListViewItem::lvt_Deployment_Folder && t == UMLObject::ot_Node)
|| (lvt == UMLListViewItem::lvt_EntityRelationship_Folder && t == UMLObject::ot_Entity)) {
parentItem = current;
} else if (t == UMLObject::ot_Datatype) {
parentItem = m_datatypeFolder;
} else {
Uml::ModelType::Enum guess = Model_Utils::guessContainer(object);
if (guess != Uml::ModelType::N_MODELTYPES)
parentItem = m_lv[guess];
else
logWarn1("UMLListView::determineParentItem(%1): cannot guess container", object->name());
}
break;
}
return parentItem;
}
/**
* Return true if the given ObjectType permits child items.
* A "child item" is anything that qualifies as a UMLClassifierListItem,
* e.g. operations and attributes of classifiers.
*/
bool UMLListView::mayHaveChildItems(UMLObject::ObjectType type)
{
bool retval = false;
switch (type) {
case UMLObject::ot_Class:
case UMLObject::ot_Interface:
// case UMLObject::ot_Instance:
// Must be handled separately because UMLInstanceAttribute is not a
// UMLClassifierListItem.
case UMLObject::ot_Enum:
case UMLObject::ot_Entity: // CHECK: more?
retval = true;
break;
default:
break;
}
return retval;
}
/**
* Creates a new list view item and connects the appropriate signals/slots.
* @param object the newly created object
*/
void UMLListView::slotObjectCreated(UMLObject* object)
{
if (m_bCreatingChildObject) {
// @todo eliminate futile signal traffic
// e.g. we get here thru various indirections from
// ClassifierListPage::slot{Up, Down}Clicked()
return;
}
if (object->baseType() == UMLObject::ot_Association)
return;
UMLListViewItem* newItem = findUMLObject(object);
logDebug1("UMLListView::slotObjectCreated: object=%1", object->name());
if (newItem) {
logDebug3("UMLListView::slotObjectCreated %1, type=%2, id=%3: item already exists",
object->name(), newItem->type(), Uml::ID::toString(object->id()));
Icon_Utils::IconType icon = Model_Utils::convert_LVT_IT(newItem->type());
newItem->setIcon(icon);
return;
}
UMLListViewItem *parentItem = nullptr;
UMLPackage *p = object->umlPackage();
if (p) {
parentItem = findUMLObject(p);
if (parentItem == nullptr)
parentItem = determineParentItem(object);
} else {
logWarn1("UMLListView::slotObjectCreated(%1) : umlPackage not set on object", object->name());
parentItem = determineParentItem(object);
}
if (parentItem == nullptr)
return;
UMLObject::ObjectType type = object->baseType();
if (type == UMLObject::ot_Datatype) {
const UMLDatatype *dt = object->asUMLDatatype();
if (!dt->isActive()) {
logDebug1("UMLListView::slotObjectCreated: %1 is not active. "
"Refusing to create UMLListViewItem", object->name());
return;
}
}
connectNewObjectsSlots(object);
const UMLListViewItem::ListViewType lvt = Model_Utils::convert_OT_LVT(object);
QString name = object->name();
if (type == UMLObject::ot_Folder) {
const UMLFolder *f = object->asUMLFolder();
QString folderFile = f->folderFile();
if (!folderFile.isEmpty())
name.append(QStringLiteral(" (") + folderFile + QLatin1Char(')'));
}
newItem = new UMLListViewItem(parentItem, name, lvt, object);
parentItem->addChildItem(object, newItem); // for updating the ChildObjectMap
if (mayHaveChildItems(type)) {
UMLClassifier *c = object->asUMLClassifier();
UMLClassifierListItemList cListItems = c->getFilteredList(UMLObject::ot_UMLObject);
for(UMLClassifierListItem *cli : cListItems)
childObjectAdded(cli, c);
}
if (m_doc->loading())
return;
scrollToItem(newItem);
newItem->setOpen(true);
clearSelection();
newItem->setSelected(true);
UMLApp::app()->docWindow()->showDocumentation(object, false);
}
/**
* Connect some signals into slots in the list view for newly created UMLObjects.
*/
void UMLListView::connectNewObjectsSlots(UMLObject* object)
{
UMLObject::ObjectType type = object->baseType();
switch (type) {
case UMLObject::ot_Class:
case UMLObject::ot_Interface:
{
UMLClassifier *c = object->asUMLClassifier();
connect(c, SIGNAL(attributeAdded(UMLClassifierListItem*)),
this, SLOT(childObjectAdded(UMLClassifierListItem*)));
connect(c, SIGNAL(attributeRemoved(UMLClassifierListItem*)),
this, SLOT(childObjectRemoved(UMLClassifierListItem*)));
connect(c, SIGNAL(operationAdded(UMLClassifierListItem*)),
this, SLOT(childObjectAdded(UMLClassifierListItem*)));
connect(c, SIGNAL(operationRemoved(UMLClassifierListItem*)),
this, SLOT(childObjectRemoved(UMLClassifierListItem*)));
connect(c, SIGNAL(templateAdded(UMLClassifierListItem*)),
this, SLOT(childObjectAdded(UMLClassifierListItem*)));
connect(c, SIGNAL(templateRemoved(UMLClassifierListItem*)),
this, SLOT(childObjectRemoved(UMLClassifierListItem*)));
connect(object, SIGNAL(modified()), this, SLOT(slotObjectChanged()));
}
break;
case UMLObject::ot_Instance:
{
connect(object, SIGNAL(modified()), this, SLOT(slotObjectChanged()));
}
break;
case UMLObject::ot_Enum:
{
UMLEnum *e = object->asUMLEnum();
connect(e, SIGNAL(enumLiteralAdded(UMLClassifierListItem*)),
this, SLOT(childObjectAdded(UMLClassifierListItem*)));
connect(e, SIGNAL(enumLiteralRemoved(UMLClassifierListItem*)),
this, SLOT(childObjectRemoved(UMLClassifierListItem*)));
}
connect(object, SIGNAL(modified()), this, SLOT(slotObjectChanged()));
break;
case UMLObject::ot_Entity:
{
UMLEntity *ent = object->asUMLEntity();
connect(ent, SIGNAL(entityAttributeAdded(UMLClassifierListItem*)),
this, SLOT(childObjectAdded(UMLClassifierListItem*)));
connect(ent, SIGNAL(entityAttributeRemoved(UMLClassifierListItem*)),
this, SLOT(childObjectRemoved(UMLClassifierListItem*)));
connect(ent, SIGNAL(entityConstraintAdded(UMLClassifierListItem*)),
this, SLOT(childObjectAdded(UMLClassifierListItem*)));
connect(ent, SIGNAL(entityConstraintRemoved(UMLClassifierListItem*)),
this, SLOT(childObjectRemoved(UMLClassifierListItem*)));
}
connect(object, SIGNAL(modified()), this, SLOT(slotObjectChanged()));
break;
case UMLObject::ot_Datatype:
case UMLObject::ot_Attribute:
case UMLObject::ot_Operation:
case UMLObject::ot_Template:
case UMLObject::ot_EnumLiteral:
case UMLObject::ot_EntityAttribute:
case UMLObject::ot_InstanceAttribute:
case UMLObject::ot_UniqueConstraint:
case UMLObject::ot_ForeignKeyConstraint:
case UMLObject::ot_CheckConstraint:
case UMLObject::ot_Package:
case UMLObject::ot_Actor:
case UMLObject::ot_UseCase:
case UMLObject::ot_Component:
case UMLObject::ot_Port:
case UMLObject::ot_Artifact:
case UMLObject::ot_Node:
case UMLObject::ot_Folder:
case UMLObject::ot_Category:
connect(object, SIGNAL(modified()), this, SLOT(slotObjectChanged()));
break;
case UMLObject::ot_UMLObject:
case UMLObject::ot_Association:
case UMLObject::ot_Stereotype:
break;
default:
logWarn2("UMLListView::connectNewObjectsSlots(%1) : unknown type %2",
object->name(), type);
break;
}
}
/**
* Calls updateObject() on the item representing the sending object
* no parameters, uses sender() to work out which object called the slot.
*/
void UMLListView::slotObjectChanged()
{
if (m_doc->loading()) { //needed for class wizard
return;
}
UMLObject* obj = const_cast<UMLObject*>(dynamic_cast<const UMLObject*>(sender()));
UMLListViewItem* item = findUMLObject(obj);
if (item) {
item->updateObject();
}
}
/**
* Adds a new operation, attribute or template item to a classifier.
* @param obj the child object
*/
void UMLListView::childObjectAdded(UMLClassifierListItem* obj)
{
UMLClassifier *parent = const_cast<UMLClassifier*>(dynamic_cast<const UMLClassifier*>(sender()));
childObjectAdded(obj, parent);
}
/**
* Adds a new operation, attribute or template item to a classifier, identical to
* childObjectAdded(obj) but with an explicit parent.
* @param child the child object
* @param parent the parent object
*/
void UMLListView::childObjectAdded(UMLClassifierListItem* child, UMLClassifier* parent)
{
if (m_bCreatingChildObject)
return;
const QString text = child->toString(Uml::SignatureType::SigNoVis);
UMLListViewItem *childItem = nullptr;
UMLListViewItem *parentItem = findUMLObject(parent);
if (parentItem == nullptr) {
logDebug2("UMLListView::childObjectAdded %1: parent %2 does not yet exist, creating it now.",
child->name(), parent->name());
const UMLListViewItem::ListViewType lvt = Model_Utils::convert_OT_LVT(parent);
parentItem = new UMLListViewItem(m_lv[Uml::ModelType::Logical], parent->name(), lvt, parent);
} else {
childItem = parentItem->findChildObject(child);
}
if (childItem) {
childItem->setText(text);
} else {
const UMLListViewItem::ListViewType lvt = Model_Utils::convert_OT_LVT(child);
childItem = new UMLListViewItem(parentItem, text, lvt, child);
parentItem->addChildItem(child, childItem); // for updating the ChildObjectMap
if (! m_doc->loading()) {
scrollToItem(childItem);
clearSelection();
childItem->setSelected(true);
}
connectNewObjectsSlots(child);
}
}
/**
* Deletes the list view item.
* @param obj the object to remove
*/
void UMLListView::childObjectRemoved(UMLClassifierListItem* obj)
{
UMLClassifier *parent = const_cast<UMLClassifier*>(dynamic_cast<const UMLClassifier*>(sender()));
UMLListViewItem *parentItem = findUMLObject(parent);
if (parentItem == nullptr) {
logError1("UMLListView::childObjectRemoved(%1): cannot find parent UMLListViewItem", obj->name());
return;
}
parentItem->deleteChildItem(obj);
}
/**
* Renames a diagram in the list view
* @param id the id of the renamed diagram
*/
void UMLListView::slotDiagramRenamed(Uml::ID::Type id)
{
UMLListViewItem* item;
UMLView* v = m_doc->findView(id);
if ((item = findView(v)) == nullptr) {
logError1("UMLDoc::findView(%1) returns null", Uml::ID::toString(id));
return;
}
item->setText(v->umlScene()->name());
}
/**
* Sets the document this is associated with. This is important as
* this is required as to set up the callbacks.
*
* @param doc The document to associate with this class.
*/
void UMLListView::setDocument(UMLDoc *doc)
{
if (m_doc && m_doc != doc) {
//disconnect signals from old doc and reset view
}
m_doc = doc;
connect(m_doc, SIGNAL(sigDiagramCreated(Uml::ID::Type)), this, SLOT(slotDiagramCreated(Uml::ID::Type)));
connect(m_doc, SIGNAL(sigDiagramRemoved(Uml::ID::Type)), this, SLOT(slotDiagramRemoved(Uml::ID::Type)));
connect(m_doc, SIGNAL(sigDiagramRenamed(Uml::ID::Type)), this, SLOT(slotDiagramRenamed(Uml::ID::Type)));
connect(m_doc, SIGNAL(sigObjectCreated(UMLObject*)), this, SLOT(slotObjectCreated(UMLObject*)));
connect(m_doc, SIGNAL(sigObjectRemoved(UMLObject*)), this, SLOT(slotObjectRemoved(UMLObject*)));
}
/**
* Disconnects signals and removes the list view item.
* @param object the object about to be removed
*/
void UMLListView::slotObjectRemoved(UMLObject* object)
{
if (m_doc->loading() && !m_doc->importing()) { //needed for class wizard but not when importing
return;
}
disconnect(object, SIGNAL(modified()), this, SLOT(slotObjectChanged()));
UMLListViewItem* item = findItem(object->id());
UMLListViewItem::deleteItem(item);
UMLApp::app()->docWindow()->updateDocumentation(true);
}
/**
* Removes the item representing a diagram.
* @param id the id of the diagram
*/
void UMLListView::slotDiagramRemoved(Uml::ID::Type id)
{
UMLListViewItem* item = findItem(id);
delete item;
UMLApp::app()->docWindow()->updateDocumentation(true);
}
/**
*
*/
UMLDragData* UMLListView::getDragData()
{
UMLListViewItemList itemsSelected = selectedItems();
UMLListViewItemList list;
for(UMLListViewItem *item : itemsSelected) {
UMLListViewItem::ListViewType type = item->type();
if (!Model_Utils::typeIsCanvasWidget(type) && !Model_Utils::typeIsDiagram(type)
&& !Model_Utils::typeIsClassifierList(type)) {
return nullptr;
}
list.append(item);
}
UMLDragData *t = new UMLDragData(list, this);
return t;
}
/**
* This method looks for an object in a folder an its subfolders recursively.
* @param folder The folder entry of the list view.
* @param obj The object to be found in the folder.
* @return The object if found else a NULL pointer.
*/
UMLListViewItem * UMLListView::findUMLObjectInFolder(UMLListViewItem* folder, UMLObject* obj)
{
for (int i=0; i < folder->childCount(); ++i) {
UMLListViewItem *item = folder->childItem(i);
switch (item->type()) {
case UMLListViewItem::lvt_Actor :
case UMLListViewItem::lvt_UseCase :
case UMLListViewItem::lvt_Class :
case UMLListViewItem::lvt_Package :
case UMLListViewItem::lvt_Subsystem :
case UMLListViewItem::lvt_Component :
case UMLListViewItem::lvt_Port :
case UMLListViewItem::lvt_Node :
case UMLListViewItem::lvt_Artifact :
case UMLListViewItem::lvt_Interface :
case UMLListViewItem::lvt_Datatype :
case UMLListViewItem::lvt_Enum :
case UMLListViewItem::lvt_Entity :
case UMLListViewItem::lvt_Category:
if (item->umlObject() == obj)
return item;
break;
case UMLListViewItem::lvt_Logical_Folder :
case UMLListViewItem::lvt_UseCase_Folder :
case UMLListViewItem::lvt_Component_Folder :
case UMLListViewItem::lvt_Deployment_Folder :
case UMLListViewItem::lvt_EntityRelationship_Folder :
case UMLListViewItem::lvt_Datatype_Folder : {
UMLListViewItem *temp = findUMLObjectInFolder(item, obj);
if (temp)
return temp;
}
default:
break;
}
}
return nullptr;
}
/**
* Find a UMLObject in the listview.
*
* @param p Pointer to the object to find in the list view.
* @return Pointer to the UMLObject found or NULL if not found.
*/
UMLListViewItem * UMLListView::findUMLObject(const UMLObject *p) const
{
UMLListViewItem *item = m_rv;
UMLListViewItem *testItem = item->findUMLObject(p);
if (testItem)
return testItem;
return nullptr;
}
/**
* Changes the icon for the given UMLObject to the given icon.
*/
void UMLListView::changeIconOf(UMLObject *o, Icon_Utils::IconType to)
{
UMLListViewItem *item = findUMLObject(o);
if (item)
item->setIcon(to);
}
/**
* Searches through the tree for the item which represents the diagram given.
* @param v the diagram to search for
* @return the item which represents the diagram
*/
UMLListViewItem* UMLListView::findView(UMLView* v)
{
if (!v) {
logWarn0("UMLListView::findView returning null - param is null.");
return nullptr;
}
UMLListViewItem* item;
Uml::DiagramType::Enum dType = v->umlScene()->type();
UMLListViewItem::ListViewType type = Model_Utils::convert_DT_LVT(dType);
Uml::ID::Type id = v->umlScene()->ID();
if (dType == Uml::DiagramType::UseCase) {
item = m_lv[Uml::ModelType::UseCase];
} else if (dType == Uml::DiagramType::Component) {
item = m_lv[Uml::ModelType::Component];
} else if (dType == Uml::DiagramType::Deployment) {
item = m_lv[Uml::ModelType::Deployment];
} else if (dType == Uml::DiagramType::EntityRelationship) {
item = m_lv[Uml::ModelType::EntityRelationship];
} else {
item = m_lv[Uml::ModelType::Logical];
}
for (int i=0; i < item->childCount(); i++) {
UMLListViewItem* foundItem = recursiveSearchForView(item->childItem(i), type, id);
if (foundItem) {
return foundItem;
}
}
if (m_doc->loading()) {
logDebug2("UMLListView::findView could not find %1 in %2", v->umlScene()->name(), item->text(0));
} else {
logWarn2("UMLListView::findView could not find %1 in %2", v->umlScene()->name(), item->text(0));
}
return nullptr;
}
/**
* Searches the tree for a diagram (view).
* Warning: these method may return in some cases the wrong diagram
* Used by findView().
*/
UMLListViewItem* UMLListView::recursiveSearchForView(UMLListViewItem* listViewItem,
UMLListViewItem::ListViewType type, Uml::ID::Type id)
{
if (!listViewItem)
return nullptr;
if (Model_Utils::typeIsFolder(listViewItem->type())) {
for (int i=0; i < listViewItem->childCount(); i++) {
UMLListViewItem* child = listViewItem->childItem(i);
UMLListViewItem* resultListViewItem = recursiveSearchForView(child, type, id);
if (resultListViewItem)
return resultListViewItem;
}
} else {
if (listViewItem->type() == type && listViewItem->ID() == id)
return listViewItem;
}
return nullptr;
}
/**
* Searches through the tree for the item with the given ID.
*
* @param id The ID to search for.
* @return The item with the given ID or 0 if not found.
*/
UMLListViewItem* UMLListView::findItem(Uml::ID::Type id)
{
UMLListViewItem *topLevel = m_rv;
UMLListViewItem *item = topLevel->findItem(id);
if (item)
return item;
return nullptr;
}
/**
* Carries out initalisation of attributes in class.
* This method is called more than once during an instance's lifetime (by UMLDoc)!
* So we must not allocate any memory before freeing the previously allocated one
* or do connect()s.
*/
void UMLListView::init()
{
if (m_rv == nullptr) {
m_rv = new UMLListViewItem(this, i18n("Views"), UMLListViewItem::lvt_View);
m_rv->setID("Views");
//m_rv->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator);
}
clean();
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
Uml::ModelType::Enum mt = Uml::ModelType::fromInt(i);
UMLFolder *sysFolder = m_doc->rootFolder(mt);
UMLListViewItem::ListViewType lvt = Model_Utils::convert_MT_LVT(mt);
m_lv[i] = new UMLListViewItem(m_rv, sysFolder->localName(), lvt, sysFolder);
m_rv->addChildItem(sysFolder, m_lv[i]); // for updating the ChildObjectMap
}
UMLFolder *datatypeFolder = m_doc->datatypeFolder();
m_datatypeFolder = new UMLListViewItem(m_lv[Uml::ModelType::Logical], datatypeFolder->localName(),
UMLListViewItem::lvt_Datatype_Folder, datatypeFolder);
// update the ChildObjectMap
m_lv[Uml::ModelType::Logical]->addChildItem(datatypeFolder, m_datatypeFolder);
if (m_settingsFolder == nullptr) {
m_settingsFolder = new UMLListViewItem(this, i18n("Settings"), UMLListViewItem::lvt_Properties);
Icon_Utils::IconType icon = Model_Utils::convert_LVT_IT(m_settingsFolder->type());
m_settingsFolder->setIcon(icon);
m_settingsFolder->setID("Settings");
new UMLListViewItem(m_settingsFolder, i18n("Auto Layout"), UMLListViewItem::lvt_Properties_AutoLayout);
new UMLListViewItem(m_settingsFolder, i18n("Class"), UMLListViewItem::lvt_Properties_Class);
new UMLListViewItem(m_settingsFolder, i18n("Code Importer"), UMLListViewItem::lvt_Properties_CodeImport);
new UMLListViewItem(m_settingsFolder, i18n("Code Generation"), UMLListViewItem::lvt_Properties_CodeGeneration);
new UMLListViewItem(m_settingsFolder, i18n("Code Viewer"), UMLListViewItem::lvt_Properties_CodeViewer);
new UMLListViewItem(m_settingsFolder, i18n("Font"), UMLListViewItem::lvt_Properties_Font);
new UMLListViewItem(m_settingsFolder, i18n("General"), UMLListViewItem::lvt_Properties_General);
new UMLListViewItem(m_settingsFolder, i18n("User Interface"), UMLListViewItem::lvt_Properties_UserInterface);
}
m_rv->setOpen(true);
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_lv[i]->setOpen(true);
}
m_datatypeFolder->setOpen(false);
//setup misc.
m_bStartedCut = m_bStartedCopy = false;
m_bCreatingChildObject = false;
headerItem()->setHidden(true);
}
/**
* Remove all items and subfolders of the main folders.
*/
void UMLListView::clean()
{
m_datatypeFolder = nullptr;
for (int i = 0; i < Uml::ModelType::N_MODELTYPES; ++i) {
m_lv[i] = nullptr;
}
deleteChildrenOf(m_rv);
}
/**
* Set the current view to the given view.
*
* @param view The current view.
*/
void UMLListView::setView(UMLView * view)
{
if (!view)
return;
UMLListViewItem * temp = findView(view);
if (temp)
temp->setSelected(true);
}
/**
* Event handler for mouse double click.
*/
void UMLListView::mouseDoubleClickEvent(QMouseEvent * me)
{
UMLListViewItem * item = static_cast<UMLListViewItem *>(currentItem());
if (!item || me->button() != Qt::LeftButton)
return;
UMLListViewItem::ListViewType lvType = item->type();
if (Model_Utils::typeIsProperties(lvType)) {
UMLApp::app()->docWindow()->updateDocumentation(false);
UMLApp::app()->slotPrefs(Model_Utils::convert_LVT_PT(lvType));
return;
}
else if (Model_Utils::typeIsDiagram(lvType)) {
UMLView * pView = m_doc->findView(item->ID());
if (pView) {
UMLApp::app()->docWindow()->updateDocumentation(false);
pView->showPropertiesDialog();
UMLApp::app()->docWindow()->showDocumentation(pView->umlScene(), true);
}
return;
}
//else see if an object
UMLObject * object = item->umlObject();
//continue only if we are on a UMLObject
if (!object) {
return;
}
object->showPropertiesDialog(this);
}
/**
* Event handler for accepting drag request.
* @param event the drop event
* @return success state
*/
bool UMLListView::acceptDrag(QDropEvent* event) const
{
UMLListViewItem* target = (UMLListViewItem*)itemAt(event->pos());
if (!target) {
logDebug0("UMLListView::acceptDrag: itemAt(mouse position) returns 0");
return false;
}
if (m_doc->loading()) {
logWarn0("UMLListView::acceptDrag: cut/copy is not safe while loading");
return false;
}
bool accept = false;
UMLListViewItem::ListViewType srcType = UMLListViewItem::lvt_Unknown;
UMLListViewItem::ListViewType dstType = UMLListViewItem::lvt_Unknown;
// Handle different drop actions
switch (event->proposedAction()) {
case Qt::CopyAction: {
// Instead of relying on the current item being the drag source,
// we should use the mime data to obtain the dragged type (or types
// if we implement multiple item selections in tree view)
srcType = static_cast<UMLListViewItem*>(currentItem())->type();
dstType = target->type();
// Copy of diagrams is not supported
if (Model_Utils::typeIsDiagram(srcType)) {
accept = false;
} else {
accept = Model_Utils::typeIsAllowedInType(srcType, dstType);
}
break;
}
case Qt::MoveAction: {
UMLDragData::LvTypeAndID_List list;
if (!UMLDragData::getClip3TypeAndID(event->mimeData(), list)) {
logError0("UMLListView::acceptDrag(Move): UMLDragData::getClip3TypeAndID returns false");
return false;
}
UMLDragData::LvTypeAndID_It it(list);
UMLDragData::LvTypeAndID *data = nullptr;
dstType = target->type();
while (it.hasNext()) {
data = it.next();
srcType = data->type;
accept = Model_Utils::typeIsAllowedInType(srcType, dstType);
// disallow drop if any child element is not allowed
if (!accept)
break;
}
break;
}
default: {
logError0("UMLListView::acceptDrag: Unsupported drop-action");
return false;
}
}
if (!accept) {
logDebug2("UMLListView::acceptDrag: Disallowing drop because source type %1 "
"is not allowed in target type %2",
UMLListViewItem::toString(srcType), UMLListViewItem::toString(dstType));
}
return accept;
}
/**
* Auxiliary method for moveObject(): Adds the model object at the proper
* new container (package if nested, UMLDoc if at global level), and
* updates the containment relationships in the model.
*/
void UMLListView::addAtContainer(UMLListViewItem *item, UMLListViewItem *parent)
{
UMLCanvasObject *o = item->umlObject()->asUMLCanvasObject();
if (o == nullptr) {
logDebug1("UMLListView::addAtContainer %1: item's UMLObject is null", item->text(0));
} else if (Model_Utils::typeIsContainer(parent->type())) {
/**** TBC: Do this here?
If yes then remove that logic at the callers
and rename this method to moveAtContainer()
UMLPackage *oldPkg = o->getUMLPackage();
if (oldPkg)
oldPkg->removeObject(o);
*********/
UMLPackage *pkg = parent->umlObject()->asUMLPackage();
o->setUMLPackage(pkg);
pkg->addObject(o);
} else {
logError2("UMLListView::addAtContainer(%1): parent type is %2", item->text(0), parent->type());
}
UMLView *currentView = UMLApp::app()->currentView();
if (currentView)
currentView->umlScene()->updateContainment(o);
}
/**
* Moves an object given its unique ID and listview type to an
* other listview parent item.
* Also takes care of the corresponding move in the model.
*/
UMLListViewItem * UMLListView::moveObject(Uml::ID::Type srcId, UMLListViewItem::ListViewType srcType,
UMLListViewItem *newParent)
{
if (newParent == nullptr)
return nullptr;
UMLListViewItem * move = findItem(srcId);
if (move == nullptr)
return nullptr;
UMLObject *newParentObj = nullptr;
// Remove the source object at the old parent package.
UMLObject *srcObj = m_doc->findObjectById(srcId);
if (srcObj) {
newParentObj = newParent->umlObject();
if (srcObj == newParentObj) {
logError1("UMLListView::moveObject(%1): Cannot move onto self", srcObj->name());
return nullptr;
}
UMLPackage *srcPkg = srcObj->umlPackage();
if (srcPkg) {
if (srcPkg == newParentObj) {
logError1("UMLListView::moveObject(%1): Object is already in target package", srcObj->name());
return nullptr;
}
srcPkg->removeObject(srcObj);
}
}
else if (Model_Utils::typeIsDiagram(srcType)) {
UMLView *v = m_doc->findView(srcId);
UMLFolder *newParentObj = newParent->umlObject()->asUMLFolder();
if (v) {
UMLFolder *srcPkg = v->umlScene()->folder();
if (srcPkg) {
if (srcPkg == newParentObj) {
logError1("UMLListView::moveObject(%1): Object is already in target package",
v->umlScene()->name());
return nullptr;
}
srcPkg->removeView(v);
newParentObj->addView(v);
v->umlScene()->setFolder(newParentObj);
UMLApp::app()->document()->diagramsModel()->emitDataChanged(v);
}
}
}
UMLListViewItem::ListViewType newParentType = newParent->type();
logDebug1("UMLListView::moveObject: newParentType is %1",
UMLListViewItem::toString(newParentType));
UMLListViewItem *newItem = nullptr;
//make sure trying to place in correct location
switch (srcType) {
case UMLListViewItem::lvt_UseCase_Folder:
case UMLListViewItem::lvt_Actor:
case UMLListViewItem::lvt_UseCase:
case UMLListViewItem::lvt_UseCase_Diagram:
if (newParentType == UMLListViewItem::lvt_UseCase_Folder ||
newParentType == UMLListViewItem::lvt_UseCase_View) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Component_Folder:
case UMLListViewItem::lvt_Artifact:
case UMLListViewItem::lvt_Component_Diagram:
if (newParentType == UMLListViewItem::lvt_Component_Folder ||
newParentType == UMLListViewItem::lvt_Component_View) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Subsystem:
if (newParentType == UMLListViewItem::lvt_Component_Folder ||
newParentType == UMLListViewItem::lvt_Component_View ||
newParentType == UMLListViewItem::lvt_Subsystem) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Component:
if (newParentType == UMLListViewItem::lvt_Component_Folder ||
newParentType == UMLListViewItem::lvt_Component_View ||
newParentType == UMLListViewItem::lvt_Component ||
newParentType == UMLListViewItem::lvt_Subsystem) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Port:
if (newParentType == UMLListViewItem::lvt_Component) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Deployment_Folder:
case UMLListViewItem::lvt_Node:
case UMLListViewItem::lvt_Deployment_Diagram:
if (newParentType == UMLListViewItem::lvt_Deployment_Folder ||
newParentType == UMLListViewItem::lvt_Deployment_View) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_EntityRelationship_Folder:
case UMLListViewItem::lvt_Entity:
case UMLListViewItem::lvt_Category:
case UMLListViewItem::lvt_EntityRelationship_Diagram:
if (newParentType == UMLListViewItem::lvt_EntityRelationship_Folder ||
newParentType == UMLListViewItem::lvt_EntityRelationship_Model) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Collaboration_Diagram:
case UMLListViewItem::lvt_Class_Diagram:
case UMLListViewItem::lvt_State_Diagram:
case UMLListViewItem::lvt_Activity_Diagram:
case UMLListViewItem::lvt_Sequence_Diagram:
case UMLListViewItem::lvt_Logical_Folder:
case UMLListViewItem::lvt_Object_Diagram:
if (newParentType == UMLListViewItem::lvt_Package ||
newParentType == UMLListViewItem::lvt_Logical_Folder ||
newParentType == UMLListViewItem::lvt_Logical_View) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
addAtContainer(newItem, newParent);
}
break;
case UMLListViewItem::lvt_Class:
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Interface:
case UMLListViewItem::lvt_Enum:
case UMLListViewItem::lvt_Datatype:
case UMLListViewItem::lvt_Instance:
if (newParentType == UMLListViewItem::lvt_Logical_Folder ||
newParentType == UMLListViewItem::lvt_Datatype_Folder ||
newParentType == UMLListViewItem::lvt_Logical_View ||
newParentType == UMLListViewItem::lvt_Class ||
newParentType == UMLListViewItem::lvt_Interface ||
newParentType == UMLListViewItem::lvt_Package) {
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
newParent->addChildItem(newItem->umlObject(), newItem);
UMLCanvasObject *o = newItem->umlObject()->asUMLCanvasObject();
if (o == nullptr) {
logDebug0("UMLListView::moveObject: newItem's UMLObject is null");
} else if (newParentObj == nullptr) {
logError1("UMLListView::moveObject(%1): newParentObj is null", o->name());
} else {
UMLPackage *pkg = newParentObj->asUMLPackage();
o->setUMLPackage(pkg);
pkg->addObject(o);
}
UMLView *currentView = UMLApp::app()->currentView();
if (currentView)
currentView->umlScene()->updateContainment(o);
}
break;
case UMLListViewItem::lvt_Attribute:
case UMLListViewItem::lvt_Operation:
if (newParentType == UMLListViewItem::lvt_Class ||
newParentType == UMLListViewItem::lvt_Interface) {
// update list view
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
// update model objects
m_bCreatingChildObject = true;
if (!srcObj) {
logError0("UMLListView::moveObject: srcObj is NULL");
break;
}
//UMLClassifier *oldParentClassifier = srcObj->umlParent()->asUMLClassifier();
UMLClassifier *newParentClassifier = newParentObj->asUMLClassifier();
if (srcType == UMLListViewItem::lvt_Attribute) {
UMLAttribute *att = srcObj->asUMLAttribute();
// We can't use the existing 'att' directly
// because its parent is fixed to the old classifier
// and we have no way of changing that:
// QObject does not permit changing the parent().
if (att == nullptr) {
logError1("UMLListView::moveObject internal error: srcObj %1 is not a UMLAttribute",
srcObj->name());
// } else if (oldParentClassifier->takeItem(att) == -1) {
// logError1("UMLListView::moveObject: oldParentClassifier->takeItem(attr %1) returns error",
// att->name());
} else {
const QString& nm = att->name();
UMLAttribute *newAtt = newParentClassifier->createAttribute(nm,
att->getType(),
att->visibility(),
att->getInitialValue());
newItem->setUMLObject(newAtt);
newParent->addChildItem(newAtt, newItem);
connectNewObjectsSlots(newAtt);
// Let's not forget to update the DocWindow::m_pObject
// because the old one is about to be physically deleted !
UMLApp::app()->docWindow()->showDocumentation(newAtt, true);
delete att;
}
} else {
UMLOperation *op = srcObj->asUMLOperation();
// We can't use the existing 'op' directly
// because its parent is fixed to the old classifier
// and we have no way of changing that:
// QObject does not permit changing the parent().
if (op == nullptr) {
logError1("UMLListView::moveObject internal error: srcObj %1 is not a UMLOperation",
srcObj->name());
// } else if (oldParentClassifier->takeItem(op) == -1) {
// logError1("UMLListView::moveObject: oldParentClassifier->takeItem(op %1) returns error",
// op->name());
} else {
bool isExistingOp;
Model_Utils::NameAndType_List ntDummyList;
// We need to provide a dummy NameAndType_List
// else UMLClassifier::createOperation will
// bring up an operation dialog.
UMLOperation *newOp = newParentClassifier->createOperation(
op->name(), &isExistingOp, &ntDummyList);
newOp->setType(op->getType());
newOp->setVisibility(op->visibility());
UMLAttributeList parmList = op->getParmList();
for(UMLAttribute *parm : parmList) {
UMLAttribute *newParm = new UMLAttribute(newParentClassifier,
parm->name(),
Uml::ID::None,
parm->visibility(),
parm->getType(),
parm->getInitialValue());
newParm->setParmKind(parm->getParmKind());
newOp->addParm(newParm);
}
newItem->setUMLObject(newOp);
newParent->addChildItem(newOp, newItem);
connectNewObjectsSlots(newOp);
// Let's not forget to update the DocWindow::m_pObject
// because the old one is about to be physically deleted !
UMLApp::app()->docWindow()->showDocumentation(newOp, true);
delete op;
}
}
m_bCreatingChildObject = false;
}
break;
case UMLListViewItem::lvt_EnumLiteral:
if (newParentType == UMLListViewItem::lvt_Enum) {
// update list view
newItem = move->deepCopy(newParent);
UMLListViewItem::deleteItem(move);
// update model objects
m_bCreatingChildObject = true;
if (!srcObj) {
logError0("UMLListView::moveObject: srcObj is NULL");
break;
}
//UMLEnum *oldParentEnum = srcObj->umlParent()->asUMLEnum();
UMLEnum *newParentEnum = newParentObj->asUMLEnum();
UMLEnumLiteral *srcLit = srcObj->asUMLEnumLiteral();
// We can't use the existing 'srcLit' directly
// because its parent is fixed to the old Enum
// and we have no way of changing that:
// QObject does not permit changing the parent().
if (srcLit == nullptr) {
logError1("UMLListView::moveObject internal error: srcObj %1 is not a UMLEnumLiteral",
srcObj->name());
} else {
const QString& nm = srcLit->name();
UMLObject *literal = newParentEnum->createEnumLiteral(nm);
newItem->setUMLObject(literal);
newParent->addChildItem(literal, newItem);
connectNewObjectsSlots(literal);
// Let's not forget to update the DocWindow::m_pObject
// because the old one is about to be physically deleted !
UMLApp::app()->docWindow()->showDocumentation(literal, true);
delete srcLit;
}
m_bCreatingChildObject = false;
}
break;
default:
break;
}
return newItem;
}
/**
* Something has been dragged and dropped onto the list view.
*/
void UMLListView::slotDropped(QDropEvent* de, UMLListViewItem* target)
{
logDebug1("UMLListView::slotDropped: Dropping on target %1", target->text(0));
// Copy or move tree items
if (de->dropAction() == Qt::CopyAction) {
UMLClipboard clipboard;
// Todo: refactor UMLClipboard to support pasting to a non-current item
setCurrentItem(target);
// Paste the data (not always clip3)
if (!clipboard.paste(m_dragCopyData)) {
logError0("UMLListView::slotDropped: Unable to copy selected item into the target item");
}
} else {
UMLDragData::LvTypeAndID_List srcList;
if (! UMLDragData::getClip3TypeAndID(de->mimeData(), srcList)) {
logError0("UMLListView::slotDropped: Unexpected mime data in drop event");
return;
}
UMLDragData::LvTypeAndID_It it(srcList);
UMLDragData::LvTypeAndID *src = nullptr;
while (it.hasNext()) {
src = it.next();
moveObject(src->id, src->type, target);
}
}
}
/**
* Get selected items.
* @return the list of selected items
*/
UMLListViewItemList UMLListView::selectedItems() const
{
UMLListViewItemList itemList;
// There is no QTreeWidgetItemConstIterator, hence we const_cast :/
UMLListViewItemIterator it(const_cast<UMLListView*>(this));
// iterate through all items of the list view
for (; *it; ++it) {
if ((*it)->isSelected()) {
UMLListViewItem *item = (UMLListViewItem*)*it;
itemList.append(item);
}
}
// logDebug1("UMLListView::selectedItems count=%1", itemList.count());
return itemList;
}
/**
* Get selected items, but only root elements selected (without children).
* @return the list of selected root items
*/
UMLListViewItemList UMLListView::selectedItemsRoot() const
{
UMLListViewItemList itemList;
// There is no QTreeWidgetItemConstIterator, hence we const_cast :/
UMLListViewItemIterator it(const_cast<UMLListView*>(this));
// iterate through all items of the list view
for (; *it; ++it) {
if ((*it)->isSelected()) {
UMLListViewItem *item = (UMLListViewItem*)*it;
// this is the trick, we select only the item with a parent unselected
// since we can't select a child and its grandfather without its parent
// we would be able to delete each item individually, without an invalid iterator
if (item && item->parent() && item->parent()->isSelected() == false) {
itemList.append(item);
}
}
}
return itemList;
}
/**
* Create a listview item for an existing diagram.
*
* @param view The existing diagram.
*/
UMLListViewItem* UMLListView::createDiagramItem(UMLView *view)
{
if (!view) {
return nullptr;
}
UMLListViewItem::ListViewType lvt = Model_Utils::convert_DT_LVT(view->umlScene()->type());
UMLListViewItem *parent = nullptr;
UMLFolder *f = view->umlScene()->folder();
if (f) {
parent = findUMLObject(f);
if (parent == nullptr)
logError2("UMLListView::createDiagramItem in scene %1 : findUMLObject(%2) returns null",
view->umlScene()->name(), f->name());
} else {
logDebug1("UMLListView::createDiagramItem %1: no parent folder set, using predefined folder",
view->umlScene()->name());
}
if (parent == nullptr) {
parent = determineParentItem(lvt);
lvt = Model_Utils::convert_DT_LVT(view->umlScene()->type());
}
UMLListViewItem *item = new UMLListViewItem(parent, view->umlScene()->name(), lvt, view->umlScene()->ID());
return item;
}
/**
* Determine the parent ListViewItem given a ListViewType.
* This parent is used for creating new UMLListViewItems.
*
* @param lvt The ListViewType for which to lookup the parent.
* @return Pointer to the parent UMLListViewItem chosen.
*/
UMLListViewItem* UMLListView::determineParentItem(UMLListViewItem::ListViewType lvt) const
{
UMLListViewItem *parent = nullptr;
switch (lvt) {
case UMLListViewItem::lvt_Datatype:
parent = m_datatypeFolder;
break;
case UMLListViewItem::lvt_Actor:
case UMLListViewItem::lvt_UseCase:
case UMLListViewItem::lvt_UseCase_Folder:
case UMLListViewItem::lvt_UseCase_Diagram:
parent = m_lv[Uml::ModelType::UseCase];
break;
case UMLListViewItem::lvt_Component_Diagram:
case UMLListViewItem::lvt_Component:
case UMLListViewItem::lvt_Port:
case UMLListViewItem::lvt_Artifact:
parent = m_lv[Uml::ModelType::Component];
break;
case UMLListViewItem::lvt_Deployment_Diagram:
case UMLListViewItem::lvt_Node:
parent = m_lv[Uml::ModelType::Deployment];
break;
case UMLListViewItem::lvt_EntityRelationship_Diagram:
case UMLListViewItem::lvt_Entity:
case UMLListViewItem::lvt_Category:
parent = m_lv[Uml::ModelType::EntityRelationship];
break;
default:
if (Model_Utils::typeIsDiagram(lvt) || !Model_Utils::typeIsClassifierList(lvt))
parent = m_lv[Uml::ModelType::Logical];
break;
}
return parent;
}
/**
* Return the amount of items selected.
*/
int UMLListView::selectedItemsCount() const
{
UMLListViewItemList items = selectedItems();
return items.count();
}
/**
* Returns the document pointer. Called by the UMLListViewItem class.
*/
UMLDoc * UMLListView::document() const
{
return m_doc;
}
/**
* Event handler for lost focus.
* @param fe the focus event
*/
void UMLListView::focusOutEvent(QFocusEvent * fe)
{
Qt::FocusReason reason = fe->reason();
if (reason != Qt::PopupFocusReason && reason != Qt::MouseFocusReason) {
clearSelection();
//triggerUpdate();
}
//repaint();
QTreeWidget::focusOutEvent(fe);
}
void UMLListView::contextMenuEvent(QContextMenuEvent *event)
{
// Get the UMLListViewItem at the point where the mouse pointer was pressed
UMLListViewItem * item = static_cast<UMLListViewItem*>(itemAt(event->pos()));
if (item) {
UMLListViewPopupMenu popup(this, item);
QAction *triggered = popup.exec(event->globalPos());
slotMenuSelection(triggered, event->globalPos());
event->accept();
}
QTreeWidget::contextMenuEvent(event);
}
/**
* Determines the root listview type of the given UMLListViewItem.
* Starts at the given item, compares it against each of the
* predefined root views (Root, Logical, UseCase, Component,
* Deployment, EntityRelationship.) Returns the ListViewType
* of the matching root view; if no match then continues the
* search using the item's parent, then grandparent, and so forth.
* Returns UMLListViewItem::lvt_Unknown if no match at all is found.
*/
UMLListViewItem::ListViewType UMLListView::rootViewType(UMLListViewItem *item)
{
if (item == m_rv)
return UMLListViewItem::lvt_View;
if (item == m_lv[Uml::ModelType::Logical])
return UMLListViewItem::lvt_Logical_View;
if (item == m_lv[Uml::ModelType::UseCase])
return UMLListViewItem::lvt_UseCase_View;
if (item == m_lv[Uml::ModelType::Component])
return UMLListViewItem::lvt_Component_View;
if (item == m_lv[Uml::ModelType::Deployment])
return UMLListViewItem::lvt_Deployment_View;
if (item == m_lv[Uml::ModelType::EntityRelationship])
return UMLListViewItem::lvt_EntityRelationship_Model;
UMLListViewItem *parent = dynamic_cast<UMLListViewItem*>(item->parent());
if (parent)
return rootViewType(parent);
return UMLListViewItem::lvt_Unknown;
}
/**
* Return true if the given list view type can be expanded/collapsed.
*/
bool UMLListView::isExpandable(UMLListViewItem::ListViewType lvt)
{
if (Model_Utils::typeIsRootView(lvt) || Model_Utils::typeIsFolder(lvt))
return true;
switch (lvt) {
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Component:
case UMLListViewItem::lvt_Subsystem:
return true;
break;
default:
break;
}
return false;
}
/**
* Calls updateFolder() on the item to update the icon to open.
*/
void UMLListView::slotExpanded(QTreeWidgetItem * item)
{
UMLListViewItem * myItem = dynamic_cast<UMLListViewItem*>(item);
if (!myItem)
return;
if (isExpandable(myItem->type())) {
myItem->updateFolder();
}
}
/**
* Calls updateFolder() on the item to update the icon to closed.
*/
void UMLListView::slotCollapsed(QTreeWidgetItem * item)
{
UMLListViewItem * myItem = dynamic_cast<UMLListViewItem*>(item);
if (!myItem)
return;
if (isExpandable(myItem->type())) {
myItem->updateFolder();
}
}
/**
* Connects to the signal that @ref UMLApp emits when a
* cut operation is successful.
*/
void UMLListView::slotCutSuccessful()
{
if (m_bStartedCut) {
UMLListViewItem* item = static_cast<UMLListViewItem*>(currentItem());
deleteItem(item);
m_bStartedCut = false;
}
}
/**
* Delete every selected item
*/
void UMLListView::slotDeleteSelectedItems()
{
UMLListViewItemList itemsSelected = selectedItemsRoot();
for(UMLListViewItem *item : itemsSelected) {
deleteItem(item);
}
}
/**
* Adds a new item to the tree of the given type under the given parent.
* Method will take care of signalling anyone needed on creation of new item.
* e.g. UMLDoc if a UMLObject is created.
*/
void UMLListView::addNewItem(UMLListViewItem *parentItem, UMLListViewItem::ListViewType type)
{
parentItem->setOpen(true);
// Determine the UMLObject belonging to the listview item we're using as parent
UMLObject* parent = parentItem->umlObject();
if (parent == nullptr) {
logError1("UMLListView::addNewItem(%1): parentPkg is null", UMLListViewItem::toString(type));
return;
}
if (Model_Utils::typeIsDiagram(type)) {
Uml::DiagramType::Enum diagramType = Model_Utils::convert_LVT_DT(type);
QString diagramName = m_doc->createDiagramName(diagramType);
if (diagramName.isEmpty()) {
// creation was cancelled by the user
return;
}
UMLFolder* parent = parentItem->umlObject()->asUMLFolder();
UMLApp::app()->executeCommand(new Uml::CmdCreateDiagram(m_doc, diagramType, diagramName, parent));
return;
}
// Determine the ObjectType of the new object
UMLObject::ObjectType objectType = Model_Utils::convert_LVT_OT(type);
if (objectType == UMLObject::ot_UMLObject) {
logError1("UMLListView::addNewItem: no UMLObject for type", UMLListViewItem::toString(type));
return;
}
if (Model_Utils::typeIsClassifierList(type)) {
UMLClassifier* classifier = parent->asUMLClassifier();
QString name = classifier->uniqChildName(objectType);
UMLObject* object = Object_Factory::createChildObject(classifier, objectType, name);
if (object == nullptr) {
// creation was cancelled by the user
return;
}
// Handle primary key constraints (mark the unique constraint as PK on
// the parent entity)
if (type == UMLListViewItem::lvt_PrimaryKeyConstraint) {
UMLUniqueConstraint* uuc = object->asUMLUniqueConstraint();
UMLEntity* ent = uuc ? uuc->umlParent()->asUMLEntity() : nullptr;
if (ent) {
ent->setAsPrimaryKey(uuc);
}
}
} else {
bool instanceOfClass = (type == UMLListViewItem::lvt_Instance && parent->isUMLClassifier());
UMLPackage* package = (instanceOfClass ? parent->umlPackage() : parent->asUMLPackage());
QString name = Model_Utils::uniqObjectName(objectType, package);
UMLObject* object = Object_Factory::createUMLObject(objectType, name, package);
if (object == nullptr) {
// creation was cancelled by the user
return;
}
if (type == UMLListViewItem::lvt_Subsystem) {
object->setStereotypeCmd(QStringLiteral("subsystem"));
} else if (Model_Utils::typeIsFolder(type)) {
object->setStereotypeCmd(QStringLiteral("folder"));
} else if (instanceOfClass) {
qApp->processEvents();
UMLInstance *inst = object->asUMLInstance();
inst->setClassifierCmd(parent->asUMLClassifier());
UMLListViewItem *instanceItem = findUMLObject(inst);
if (instanceItem == nullptr) {
logError1("UMLListView::addNewItem: listviewitem for %1 not found",
UMLListViewItem::toString(type));
return;
}
scrollToItem(instanceItem);
clearSelection();
instanceItem->setSelected(true);
UMLObjectList& values = inst->subordinates();
for(UMLObject *child : values) {
if (!child->isUMLInstanceAttribute())
continue;
connectNewObjectsSlots(child);
const QString text = child->asUMLInstanceAttribute()->toString();
UMLListViewItem *childItem =
new UMLListViewItem(instanceItem, text, UMLListViewItem::lvt_InstanceAttribute , child);
instanceItem->addChildItem(child, childItem); // for updating the ChildObjectMap
}
}
}
}
/**
* Returns if the given name is unique for the given items type.
*/
bool UMLListView::isUnique(UMLListViewItem * item, const QString &name) const
{
UMLListViewItem * parentItem = static_cast<UMLListViewItem *>(item->parent());
UMLListViewItem::ListViewType type = item->type();
switch (type) {
case UMLListViewItem::lvt_Class_Diagram:
return !m_doc->findView(Uml::DiagramType::Class, name);
break;
case UMLListViewItem::lvt_Sequence_Diagram:
return !m_doc->findView(Uml::DiagramType::Sequence, name);
break;
case UMLListViewItem::lvt_UseCase_Diagram:
return !m_doc->findView(Uml::DiagramType::UseCase, name);
break;
case UMLListViewItem::lvt_Collaboration_Diagram:
return !m_doc->findView(Uml::DiagramType::Collaboration, name);
break;
case UMLListViewItem::lvt_State_Diagram:
return !m_doc->findView(Uml::DiagramType::State, name);
break;
case UMLListViewItem::lvt_Activity_Diagram:
return !m_doc->findView(Uml::DiagramType::Activity, name);
break;
case UMLListViewItem::lvt_Component_Diagram:
return !m_doc->findView(Uml::DiagramType::Component, name);
break;
case UMLListViewItem::lvt_Deployment_Diagram:
return !m_doc->findView(Uml::DiagramType::Deployment, name);
break;
case UMLListViewItem::lvt_EntityRelationship_Diagram:
return !m_doc->findView(Uml::DiagramType::EntityRelationship, name);
break;
case UMLListViewItem::lvt_Object_Diagram:
return !m_doc->findView(Uml::DiagramType::Object, name);
break;
case UMLListViewItem::lvt_Actor:
case UMLListViewItem::lvt_UseCase:
case UMLListViewItem::lvt_Node:
case UMLListViewItem::lvt_Artifact:
case UMLListViewItem::lvt_Category:
case UMLListViewItem::lvt_Instance:
return !m_doc->findUMLObject(name, Model_Utils::convert_LVT_OT(type));
break;
case UMLListViewItem::lvt_Class:
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Interface:
case UMLListViewItem::lvt_Datatype:
case UMLListViewItem::lvt_Enum:
case UMLListViewItem::lvt_Entity:
case UMLListViewItem::lvt_Component:
case UMLListViewItem::lvt_Port:
case UMLListViewItem::lvt_Subsystem:
case UMLListViewItem::lvt_Logical_Folder:
case UMLListViewItem::lvt_UseCase_Folder:
case UMLListViewItem::lvt_Component_Folder:
case UMLListViewItem::lvt_Deployment_Folder:
case UMLListViewItem::lvt_EntityRelationship_Folder: {
UMLListViewItem::ListViewType lvt = parentItem->type();
if (!Model_Utils::typeIsContainer(lvt))
return (m_doc->findUMLObject(name) == nullptr);
const UMLPackage *pkg = parentItem->umlObject()->asUMLPackage();
if (pkg == nullptr) {
logError0("UMLListView::isUnique(internal): parent listviewitem is package but has no UMLObject");
return true;
}
return (pkg->findObject(name) == nullptr);
break;
}
case UMLListViewItem::lvt_Template:
case UMLListViewItem::lvt_Attribute:
case UMLListViewItem::lvt_EntityAttribute:
case UMLListViewItem::lvt_InstanceAttribute:
case UMLListViewItem::lvt_Operation:
case UMLListViewItem::lvt_EnumLiteral:
case UMLListViewItem::lvt_UniqueConstraint:
case UMLListViewItem::lvt_PrimaryKeyConstraint:
case UMLListViewItem::lvt_ForeignKeyConstraint:
case UMLListViewItem::lvt_CheckConstraint: {
const UMLClassifier *parent = parentItem->umlObject()->asUMLClassifier();
if (parent == nullptr) {
logError0("UMLListView::isUnique(internal): parent listviewitem is classifier but has no UMLObject");
return true;
}
return (parent->findChildObject(name) == nullptr);
break;
}
default:
break;
}
return false;
}
/**
*
*/
void UMLListView::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("listview"));
m_rv->saveToXMI(writer);
writer.writeEndElement();
}
/**
*
*/
bool UMLListView::loadFromXMI(QDomElement & element)
{
QDomNode node = element.firstChild();
QDomElement domElement = node.toElement();
m_doc->writeToStatusBar(i18n("Loading listview..."));
while (!domElement.isNull()) {
if (domElement.tagName() == QStringLiteral("listitem")) {
QString type = domElement.attribute(QStringLiteral("type"), QStringLiteral("-1"));
if (type == QStringLiteral("-1"))
return false;
UMLListViewItem::ListViewType lvType = (UMLListViewItem::ListViewType)type.toInt();
if (lvType == UMLListViewItem::lvt_View) {
if (!loadChildrenFromXMI(m_rv, domElement))
return false;
} else
return false;
}
node = node.nextSibling();
domElement = node.toElement();
}//end while
return true;
}
/**
*
*/
bool UMLListView::loadChildrenFromXMI(UMLListViewItem * parent, QDomElement & element)
{
QDomNode node = element.firstChild();
QDomElement domElement = node.toElement();
while (!domElement.isNull()) {
node = domElement.nextSibling();
if (domElement.tagName() != QStringLiteral("listitem")) {
domElement = node.toElement();
continue;
}
QString id = domElement.attribute(QStringLiteral("id"), QStringLiteral("-1"));
QString type = domElement.attribute(QStringLiteral("type"), QStringLiteral("-1"));
QString label = domElement.attribute(QStringLiteral("label"));
QString open = domElement.attribute(QStringLiteral("open"), QStringLiteral("1"));
if (type == QStringLiteral("-1"))
return false;
UMLListViewItem::ListViewType lvType = (UMLListViewItem::ListViewType)type.toInt();
bool bOpen = (bool)open.toInt();
Uml::ID::Type nID = Uml::ID::fromString(id);
UMLListViewItem *item = nullptr;
if (nID != Uml::ID::None) {
// The following is an ad hoc hack for the copy/paste code.
// The clip still contains the old children although new
// UMLCLassifierListItems have already been created.
// If the IDChangeLog finds new IDs this means we are in
// copy/paste and need to adjust the child listitems to the
// new UMLCLassifierListItems.
IDChangeLog *idchanges = m_doc->changeLog();
if (idchanges) {
Uml::ID::Type newID = idchanges->findNewID(nID);
if (newID != Uml::ID::None) {
logDebug2("UMLListView::loadChildrenFromXMI using id %1 instead of %2",
Uml::ID::toString(newID), Uml::ID::toString(nID));
nID = newID;
}
}
/************ End of hack for copy/paste code ************/
UMLObject *pObject = m_doc->findObjectById(nID);
if (pObject) {
if (label.isEmpty())
label = pObject->name();
} else if (Model_Utils::typeIsFolder(lvType)) {
// Synthesize the UMLFolder here
UMLObject *umlParent = parent->umlObject();
UMLPackage *parentPkg = umlParent->asUMLPackage();
if (parentPkg == nullptr) {
logError2("UMLListView::loadChildrenFromXMI(%1): umlParent %2 is not a UMLPackage",
UMLListViewItem::toString(lvType), umlParent->name());
domElement = node.toElement();
continue;
}
UMLFolder *f = new UMLFolder(label, nID);
f->setUMLPackage(parentPkg);
parentPkg->addObject(f);
pObject = f;
item = new UMLListViewItem(parent, label, lvType, pObject);
parent->addChildItem(pObject, item); // for updating the ChildObjectMap
// Moving all relevant UMLObjects to the new UMLFolder is done below,
// in the switch(lvType)
}
} else if (Model_Utils::typeIsRootView(lvType)) {
// Predefined folders did not have their ID set.
const Uml::ModelType::Enum mt = Model_Utils::convert_LVT_MT(lvType);
nID = m_doc->rootFolder(mt)->id();
} else if (Model_Utils::typeIsFolder(lvType)) {
// Pre-1.2 format: Folders did not have their ID set.
// Pull a new ID now.
nID = m_doc->rootFolder(Uml::ModelType::Logical)->id();
} else {
logError1("UMLListView::loadChildrenFromXMI: item of type %1 has no ID, skipping.",
UMLListViewItem::toString(lvType));
domElement = node.toElement();
continue;
}
switch (lvType) {
case UMLListViewItem::lvt_Actor:
case UMLListViewItem::lvt_UseCase:
case UMLListViewItem::lvt_Class:
case UMLListViewItem::lvt_Instance:
case UMLListViewItem::lvt_Interface:
case UMLListViewItem::lvt_Datatype:
case UMLListViewItem::lvt_Enum:
case UMLListViewItem::lvt_Entity:
case UMLListViewItem::lvt_Package:
case UMLListViewItem::lvt_Subsystem:
case UMLListViewItem::lvt_Component:
case UMLListViewItem::lvt_Port:
case UMLListViewItem::lvt_Node:
case UMLListViewItem::lvt_Artifact:
case UMLListViewItem::lvt_Logical_Folder:
case UMLListViewItem::lvt_UseCase_Folder:
case UMLListViewItem::lvt_Component_Folder:
case UMLListViewItem::lvt_Deployment_Folder:
case UMLListViewItem::lvt_EntityRelationship_Folder:
case UMLListViewItem::lvt_Category:
item = findItem(nID);
if (item == nullptr) {
logError2("UMLListView::loadChildrenFromXMI(%1) internal: findItem(id %2) returns null",
UMLListViewItem::toString(lvType), Uml::ID::toString(nID));
} else if (parent != item->parent()) {
// The existing item was created by the slot event triggered
// by the loading of the corresponding model object from the
// XMI file.
UMLListViewItem *itmParent = dynamic_cast<UMLListViewItem*>(item->parent());
logDebug3("UMLListView::loadChildrenFromXMI: Loaded <listview> entry does not match uml model "
"item %1 parent %2 != %3", item->text(0), parent->text(0),
(itmParent ? itmParent->text(0) : QStringLiteral("")));
}
break;
case UMLListViewItem::lvt_Attribute:
case UMLListViewItem::lvt_EntityAttribute:
case UMLListViewItem::lvt_InstanceAttribute:
case UMLListViewItem::lvt_Template:
case UMLListViewItem::lvt_Operation:
case UMLListViewItem::lvt_EnumLiteral:
case UMLListViewItem::lvt_UniqueConstraint:
case UMLListViewItem::lvt_PrimaryKeyConstraint:
case UMLListViewItem::lvt_ForeignKeyConstraint:
case UMLListViewItem::lvt_CheckConstraint:
item = findItem(nID);
if (item == nullptr) {
logDebug2("UMLListView::loadChildrenFromXMI: item %1 (of type %2) does not yet exist...",
Uml::ID::toString(nID), UMLListViewItem::toString(lvType));
UMLObject* umlObject = parent->umlObject();
if (!umlObject) {
logDebug0("- and also the parent->umlObject() does not exist");
return false;
}
if (nID == Uml::ID::None) {
logError1("UMLListView::loadChildrenFromXMI(%1) has id -1",
UMLListViewItem::toString(lvType));
} else if (lvType == UMLListViewItem::lvt_InstanceAttribute) {
UMLInstance *instance = umlObject->asUMLInstance();
if (instance) {
UMLObject *attrObj = instance->findChildObjectById(nID);
if (attrObj) {
UMLInstanceAttribute *instAttr = attrObj->asUMLInstanceAttribute();
connectNewObjectsSlots(instAttr);
label = instAttr->toString();
item = new UMLListViewItem(parent, label, lvType, instAttr);
parent->addChildItem(instAttr, item); // for updating the ChildObjectMap
} else {
logDebug2("UMLListView::loadChildrenFromXMI: %1 lvt_InstanceAttribute child "
" object %2 not found", umlObject->name(), Uml::ID::toString(nID));
}
} else {
logDebug0("UMLListView::loadChildrenFromXMI cast to instance object failed");
}
} else {
UMLClassifier *classifier = umlObject->asUMLClassifier();
if (classifier) {
umlObject = classifier->findChildObjectById(nID);
if (umlObject) {
connectNewObjectsSlots(umlObject);
label = umlObject->name();
item = new UMLListViewItem(parent, label, lvType, umlObject);
parent->addChildItem(umlObject, item); // for updating the ChildObjectMap
} else {
logDebug2("UMLListView::loadChildrenFromXMI lvtype %1 child object %2 not found",
UMLListViewItem::toString(lvType), Uml::ID::toString(nID));
}
} else {
logDebug0("UMLListView::loadChildrenFromXMI cast to classifier object failed");
}
}
}
break;
case UMLListViewItem::lvt_Logical_View:
item = m_lv[Uml::ModelType::Logical];
break;
case UMLListViewItem::lvt_Datatype_Folder:
item = m_datatypeFolder;
break;
case UMLListViewItem::lvt_UseCase_View:
item = m_lv[Uml::ModelType::UseCase];
break;
case UMLListViewItem::lvt_Component_View:
item = m_lv[Uml::ModelType::Component];
break;
case UMLListViewItem::lvt_Deployment_View:
item = m_lv[Uml::ModelType::Deployment];
break;
case UMLListViewItem::lvt_EntityRelationship_Model:
item = m_lv[Uml::ModelType::EntityRelationship];
break;
default:
if (Model_Utils::typeIsDiagram(lvType)) {
item = new UMLListViewItem(parent, label, lvType, nID);
} else {
logError2("UMLListView::loadChildrenFromXMI internal: unexpected listview type %1 (ID %2)",
UMLListViewItem::toString(lvType), Uml::ID::toString(nID));
}
break;
}//end switch
if (item) {
item->setOpen((bool)bOpen);
if (!loadChildrenFromXMI(item, domElement)) {
return false;
}
} else {
logWarn2("UMLListView::loadChildrenFromXMI: unused list view ID %1 of lvtype %2",
Uml::ID::toString(nID), UMLListViewItem::toString(lvType));
}
domElement = node.toElement();
}//end while
return true;
}
/**
* Open all items in the list view.
*/
void UMLListView::expandAll(UMLListViewItem *item)
{
if (!item) item = m_rv;
for (int i = 0; i < item->childCount(); i++) {
expandAll(item->childItem(i));
}
item->setExpanded(true);
}
/**
* Close all items in the list view.
*/
void UMLListView::collapseAll(UMLListViewItem *item)
{
if (!item) item = m_rv;
for (int i = 0; i < item->childCount(); i++) {
collapseAll(item->childItem(i));
}
item->setExpanded(false);
}
/**
* Set the variable m_bStartedCut
* to indicate that selection should be deleted
* in slotCutSuccessful().
*/
void UMLListView::setStartedCut(bool startedCut)
{
m_bStartedCut = startedCut;
}
/**
* Set the variable m_bStartedCopy.
* NB: While m_bStartedCut is reset as soon as the Cut operation is done,
* the variable m_bStartedCopy is reset much later - upon pasting.
*/
void UMLListView::setStartedCopy(bool startedCopy)
{
m_bStartedCopy = startedCopy;
}
/**
* Return the variable m_bStartedCopy.
*/
bool UMLListView::startedCopy() const
{
return m_bStartedCopy;
}
/**
* Returns the corresponding view if the listview type is one of the root views,
* Root/Logical/UseCase/Component/Deployment/EntityRelation View.
*/
UMLListViewItem *UMLListView::rootView(UMLListViewItem::ListViewType type)
{
UMLListViewItem *theView = nullptr;
switch (type) {
case UMLListViewItem::lvt_View:
theView = m_rv;
break;
case UMLListViewItem::lvt_Logical_View:
theView = m_lv[Uml::ModelType::Logical];
break;
case UMLListViewItem::lvt_UseCase_View:
theView = m_lv[Uml::ModelType::UseCase];
break;
case UMLListViewItem::lvt_Component_View:
theView = m_lv[Uml::ModelType::Component];
break;
case UMLListViewItem::lvt_Deployment_View:
theView = m_lv[Uml::ModelType::Deployment];
break;
case UMLListViewItem::lvt_EntityRelationship_Model:
theView = m_lv[Uml::ModelType::EntityRelationship];
break;
case UMLListViewItem::lvt_Datatype_Folder: // @todo fix asymmetric naming
theView = m_datatypeFolder;
break;
default:
break;
}
return theView;
}
/**
* Deletes all child-items of @p parent.
* Do it in reverse order, because of the index.
*/
void UMLListView::deleteChildrenOf(UMLListViewItem* parent)
{
if (!parent) {
return;
}
if (parent == m_lv[Uml::ModelType::Logical]) {
m_datatypeFolder = nullptr;
}
for (int i = parent->childCount() - 1; i >= 0; --i)
parent->removeChild(parent->child(i));
}
/**
*
*/
void UMLListView::closeDatatypesFolder()
{
m_datatypeFolder->setOpen(false);
}
/**
* Delete a listview item.
* @param temp a non-null UMLListViewItem, for example: (UMLListViewItem*)currentItem()
* @return true if correctly deleted
*/
bool UMLListView::deleteItem(UMLListViewItem *temp)
{
if (!temp)
return false;
UMLObject *object = temp->umlObject();
UMLListViewItem::ListViewType lvt = temp->type();
if (Model_Utils::typeIsDiagram(lvt)) {
m_doc->removeDiagram(temp->ID());
} else if (temp == m_datatypeFolder) {
// we can't delete the datatypeFolder because umbrello will crash without a special handling
return false;
} else if (Model_Utils::typeIsCanvasWidget(lvt) || Model_Utils::typeIsClassifierList(lvt)) {
UMLPackage *nmSpc = object->asUMLPackage();
if (nmSpc) {
UMLObjectList contained = nmSpc->containedObjects();
if (contained.count()) {
if (nmSpc->baseType() == UMLObject::ot_Class) {
KMessageBox::error(
nullptr,
i18n("The class must be emptied before it can be deleted."),
i18n("Class Not Empty"));
} else if (nmSpc->baseType() == UMLObject::ot_Package) {
KMessageBox::error(
nullptr,
i18n("The package must be emptied before it can be deleted."),
i18n("Package Not Empty"));
} else if (nmSpc->baseType() == UMLObject::ot_Folder) {
KMessageBox::error(
nullptr,
i18n("The folder must be emptied before it can be deleted."),
i18n("Folder Not Empty"));
}
return false;
}
}
UMLCanvasObject *canvasObj = object->asUMLCanvasObject();
if (canvasObj) {
// We cannot just delete canvasObj here: What if the object
// is still being used by others (for example, as a parameter
// or return type of an operation) ?
// Deletion should not have been permitted in the first place
// if the object still has users - but Umbrello is lacking
// that logic.
canvasObj->removeAllChildObjects();
}
if (object) {
UMLApp::app()->executeCommand(new Uml::CmdRemoveUMLObject(object));
// Physical deletion of `temp' will be done by Qt signal, see
// UMLDoc::removeUMLObject()
} else {
UMLListViewItem::deleteItem(temp);
}
} else {
logWarn1("UMLListView::deleteItem is called with unknown type %1",
UMLListViewItem::toString(lvt));
}
return true;
}
/**
* Always allow starting a drag
*/
void UMLListView::dragEnterEvent(QDragEnterEvent* event)
{
event->accept();
}
/**
* Check drag destination and update move/copy action
*/
void UMLListView::dragMoveEvent(QDragMoveEvent* event)
{
// Check if drag destination is compatible with source
if (acceptDrag(event)) {
event->acceptProposedAction();
} else {
event->ignore();
return;
}
}
/**
*
*/
void UMLListView::dropEvent(QDropEvent* event)
{
if (!acceptDrag(event)) {
event->ignore();
}
else {
UMLListViewItem* target = static_cast<UMLListViewItem*>(itemAt(event->pos()));
if (!target) {
logDebug0("UMLListView::dropEvent itemAt(mousePoint) returns 0");
event->ignore();
return;
}
slotDropped(event, target);
}
}
void UMLListView::commitData(QWidget *editor)
{
if (!editor)
return;
QModelIndex index = currentIndex();
if (!index.isValid())
return;
QAbstractItemDelegate *delegate = itemDelegate(index);
editor->removeEventFilter(delegate);
QByteArray n = editor->metaObject()->userProperty().name();
if (n.isEmpty()) {
logDebug0("UMLListView::commitData: no name property found in list view item editor");
return;
}
QString newText = editor->property(n.data()).toString();
UMLListViewItem *item = dynamic_cast<UMLListViewItem *>(currentItem());
if (!item) {
logDebug2("UMLListView::commitData: no item found after editing model index (row%1 col%2)",
index.row(), index.column());
return;
}
item->slotEditFinished(newText);
editor->installEventFilter(delegate);
}
/**
* Set the background color.
* @param color the new background color
*/
void UMLListView::setBackgroundColor(const QColor & color)
{
QPalette palette;
palette.setColor(backgroundRole(), color);
setPalette(palette);
}
/**
* Overloading operator for debugging output.
*/
QDebug operator<<(QDebug out, const UMLListView& view)
{
UMLListViewItem* header = static_cast<UMLListViewItem*>(view.headerItem());
if (header) {
out << *header;
for(int indx = 0; indx < header->childCount(); ++indx) {
UMLListViewItem* item = static_cast<UMLListViewItem*>(header->child(indx));
if (item) {
out << indx << " - " << *item << '\n';
}
else {
out << indx << " - " << "<null>" << '\n';
}
}
}
else {
out << "<null>";
}
return out.space();
}
| 107,976
|
C++
|
.cpp
| 2,735
| 31.117002
| 131
| 0.627977
|
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,264
|
toolbarstate.cpp
|
KDE_umbrello/umbrello/toolbarstate.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstate.h"
// app includes
#include "associationwidget.h"
#include "debug_utils.h"
#include "messagewidget.h"
#include "floatingdashlinewidget.h"
#include "objectwidget.h"
#include "uml.h"
#include "umlview.h"
#include "umlwidget.h"
#include "widget_utils.h"
// qt includes
#include <QScrollBar>
DEBUG_REGISTER(ToolBarState)
/**
* Destroys this ToolBarState.
* Frees m_pMouseEvent.
*/
ToolBarState::~ToolBarState()
{
delete m_pMouseEvent;
}
/**
* Goes back to the initial state.
* Subclasses can extend, but not override, this method as needed.
*/
void ToolBarState::init()
{
if (m_pUMLScene->activeView())
m_pUMLScene->activeView()->viewport()->setMouseTracking(false);
m_pMouseEvent = nullptr;
m_currentWidget = nullptr;
m_currentAssociation = nullptr;
connect(m_pUMLScene, SIGNAL(sigAssociationRemoved(AssociationWidget*)),
this, SLOT(slotAssociationRemoved(AssociationWidget*)));
connect(m_pUMLScene, SIGNAL(sigWidgetRemoved(UMLWidget*)),
this, SLOT(slotWidgetRemoved(UMLWidget*)));
}
/**
* Called when the current tool is changed to use another tool.
* Subclasses can extend, but not override, this method as needed.
* Default implementation does nothing.
*/
void ToolBarState::cleanBeforeChange()
{
disconnect(m_pUMLScene, SIGNAL(sigAssociationRemoved(AssociationWidget*)),
this, SLOT(slotAssociationRemoved(AssociationWidget*)));
disconnect(m_pUMLScene, SIGNAL(sigWidgetRemoved(UMLWidget*)),
this, SLOT(slotWidgetRemoved(UMLWidget*)));
}
/**
* Handler for mouse press events.
* Mouse tracking is enabled, any pop up menu removed, the position of the
* cursor set and paste state disabled.
* Then, the current association or widget are set (if any), and events are
* delivered to the specific methods, depending on where the cursor was
* pressed.
*
* @param ome The received event.
* @see setCurrentElement()
*/
void ToolBarState::mousePress(QGraphicsSceneMouseEvent* ome)
{
setMouseEvent(ome, QEvent::MouseButtonPress);
m_pUMLScene->activeView()->viewport()->setMouseTracking(true);
// TODO: Check who needs this.
m_pUMLScene->setPos(m_pMouseEvent->scenePos());
//TODO check why
m_pUMLScene->setPaste(false);
setCurrentElement();
if (currentWidget()) {
mousePressWidget();
} else if (currentAssociation()) {
mousePressAssociation();
} else {
mousePressEmpty();
}
}
/**
* Handler for mouse release events.
* Mouse tracking is disabled and the position of the cursor set.
* The events are delivered to the specific methods, depending on where the
* cursor was released, and the current association or widget cleaned.
* Finally, the current tool is changed if needed.
*
* @param ome The received event.
*/
void ToolBarState::mouseRelease(QGraphicsSceneMouseEvent* ome)
{
setMouseEvent(ome, QEvent::MouseButtonRelease);
// Set the position of the mouse
// TODO, should only be available in this state?
m_pUMLScene->setPos(m_pMouseEvent->scenePos());
m_pUMLScene->activeView()->viewport()->setMouseTracking(false);
if (currentWidget()) {
logDebug0("ToolBarState::mouseRelease calling mouseReleaseWidget");
mouseReleaseWidget();
setCurrentWidget(nullptr);
} else if (currentAssociation()) {
logDebug0("ToolBarState::mouseRelease calling mouseReleaseAssociation");
mouseReleaseAssociation();
setCurrentAssociation(nullptr);
} else {
logDebug0("ToolBarState::mouseRelease calling mouseReleaseEmpty");
mouseReleaseEmpty();
}
// Default, rightbutton changes the tool.
// The arrow tool overrides the changeTool() function.
changeTool();
}
/**
* Handler for mouse double click events.
* The current association or widget is set (if any), and events are
* delivered to the specific methods, depending on where the cursor was pressed.
* After delivering the events, the current association or widget is cleaned.
*
* @param ome The received event.
*/
void ToolBarState::mouseDoubleClick(QGraphicsSceneMouseEvent* ome)
{
setMouseEvent(ome, QEvent::MouseButtonDblClick);
UMLWidget* currentWidget = m_pUMLScene->widgetAt(m_pMouseEvent->scenePos());
AssociationWidget* currentAssociation = associationAt(m_pMouseEvent->scenePos());
if (currentWidget || currentAssociation) {
ome->accept();
}
if (currentWidget) {
setCurrentWidget(currentWidget);
mouseDoubleClickWidget();
setCurrentWidget(nullptr);
} else if (currentAssociation) {
setCurrentAssociation(currentAssociation);
mouseDoubleClickAssociation();
setCurrentAssociation(nullptr);
} else {
mouseDoubleClickEmpty();
}
}
/**
* Handler for mouse move events.
* Events are delivered to the specific methods, depending on where the cursor
* was pressed. It uses the current widget or association set in press event,
* if any.
* Then, the scene is scrolled if needed (if the cursor is moved in any of the
* 30 pixels width area from left, top, right or bottom sides, and there is
* more diagram currently not being shown in that direction).
* This method is only called when mouse tracking is enabled and the mouse
* is moved.
*
* @param ome The received event.
*/
void ToolBarState::mouseMove(QGraphicsSceneMouseEvent* ome)
{
setMouseEvent(ome, QEvent::MouseMove);
if (currentWidget()) {
mouseMoveWidget();
} else if (currentAssociation()) {
mouseMoveAssociation();
} else {
mouseMoveEmpty();
}
#if 0
// scrolls the view
static int mouseCount = 0;
int vx = ome->scenePos().x();
int vy = ome->scenePos().y();
UMLView* view = m_pUMLScene->activeView();
// QRectF maxArea = view->sceneRect();
QRectF visibleArea = view->mapToScene(view->rect()).boundingRect();
int dtr = visibleArea.x() + visibleArea.width() - vx; // delta right
int dtb = visibleArea.y() + visibleArea.height() - vy; // delta bottom
int dtt = vy - visibleArea.y(); // delta top
int dtl = vx - visibleArea.x(); // delta left
// uDebug() << "mouse [x, y] = [ " << vx << ", " << vy << "] / "
// << "visibleArea [x, y, w, h] = [ " << visibleArea.x() << ", " << visibleArea.y() << ", " << visibleArea.width() << ", " << visibleArea.height() << "] / "
// << "maxArea [x, y, w, h] = [ " << maxArea.x() << ", " << maxArea.y() << ", " << maxArea.width() << ", " << maxArea.height() << "] / "
// << "delta right=" << dtr << ", bottom=" << dtb << ", top=" << dtt << ", left=" << dtl;
if (dtr < 30) {
logDebug0("ToolBarState::mouseMove translate RIGHT");
view->ensureVisible(vx, vy, 0.1 /*30-dtr*/, 0, 2, 2);
}
if (dtb < 30) {
mouseCount++;
logDebug1("ToolBarState::mouseMove translate BOTTOM %1", mouseCount);
// view->ensureVisible(vx, vy, 0, 0.1 /*30-dtb*/, 2, 2);
if (mouseCount > 30) {
view->verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
mouseCount = 0;
}
}
if (dtl < 30) { uDebug() << "translate LEFT"; view->ensureVisible(vx, vy, -0.1 /*-(30-dtl)*/, 0, 2, 2); }
if (dtt < 30) { uDebug() << "translate TOP"; view->ensureVisible(vx, vy, 0, -0.1 /*-(30-dtt)*/, 2, 2); }
#endif
}
/**
* An association was removed from the UMLScene.
* If the association removed was the current association, the current
* association is set to 0.
* It can be extended in subclasses if needed.
*/
void ToolBarState::slotAssociationRemoved(AssociationWidget* association)
{
if (association == currentAssociation()) {
setCurrentAssociation(nullptr);
}
}
/**
* A widget was removed from the UMLScene.
* If the widget removed was the current widget, the current widget is set
* to nullptr.
* It can be extended in subclasses if needed.
*/
void ToolBarState::slotWidgetRemoved(UMLWidget* widget)
{
if (widget == currentWidget()) {
setCurrentWidget(nullptr);
}
}
/**
* Creates a new ToolBarState.
* UMLScene is set as parent of this QObject, and name is left empty.
* Protected to avoid classes other than derived to create objects of this
* class.
*
* @param umlScene The UMLScene to use.
*/
ToolBarState::ToolBarState(UMLScene *umlScene)
: QObject(umlScene),
m_pUMLScene(umlScene),
m_pMouseEvent(nullptr)
{
init();
}
/**
* Sets the current association or widget.
* It sets the current element when a press event happened. The element will
* be used until the next release event.
* Default implementation first checks for associations, then message widgets
* and then any other widgets.
* It can be overridden in subclasses if needed.
*/
void ToolBarState::setCurrentElement()
{
// Check associations.
AssociationWidget* association = associationAt(m_pMouseEvent->scenePos());
if (association) {
setCurrentAssociation(association);
return;
}
// Check messages.
//TODO check why message widgets are treated different
MessageWidget* message = messageAt(m_pMouseEvent->scenePos());
if (message) {
setCurrentWidget(message);
return;
}
//TODO check why message widgets are treated different
FloatingDashLineWidget* floatingline = floatingLineAt(m_pMouseEvent->scenePos());
if (floatingline) {
setCurrentWidget(floatingline);
return;
}
ObjectWidget* objectWidgetLine = m_pUMLScene->onWidgetDestructionBox(m_pMouseEvent->scenePos());
if (objectWidgetLine) {
setCurrentWidget(objectWidgetLine);
return;
}
objectWidgetLine = m_pUMLScene->onWidgetLine(m_pMouseEvent->scenePos());
if (objectWidgetLine) {
setCurrentWidget(objectWidgetLine);
return;
}
// Check widgets.
UMLWidget *widget = m_pUMLScene->widgetAt(m_pMouseEvent->scenePos());
if (widget) {
setCurrentWidget(widget);
return;
}
}
/**
* Called when the press event happened on an association.
* Default implementation does nothing.
*/
void ToolBarState::mousePressAssociation()
{
}
/**
* Called when the press event happened on a widget.
* Default implementation does nothing.
*/
void ToolBarState::mousePressWidget()
{
}
/**
* Called when the press event happened on an empty space.
* Default implementation cleans the selection.
*/
void ToolBarState::mousePressEmpty()
{
// TODO activate when QGraphicsScene selection handling is used
//m_pUMLScene->clearSelection();
m_pUMLScene->clearSelected();
}
/**
* Called when the release event happened on an association.
* Default implementation does nothing.
*/
void ToolBarState::mouseReleaseAssociation()
{
}
/**
* Called when the release event happened on a widget.
* Default implementation does nothing.
*/
void ToolBarState::mouseReleaseWidget()
{
}
/**
* Called when the release event happened on an empty space.
* Default implementation does nothing.
*/
void ToolBarState::mouseReleaseEmpty()
{
if (m_currentWidget) {
logDebug0("ToolBarState::mouseReleaseEmpty : m_currentWidget is set => ensureNestedVisible");
Widget_Utils::ensureNestedVisible(m_currentWidget, m_pUMLScene->widgetList());
}
}
/**
* Called when the double click event happened on an association.
* Default implementation does nothing.
*/
void ToolBarState::mouseDoubleClickAssociation()
{
}
/**
* Called when the double click event happened on a widget.
* Default implementation does nothing.
*/
void ToolBarState::mouseDoubleClickWidget()
{
}
/**
* Called when the double click event happened on an empty space.
* Default implementation cleans the selection.
*/
void ToolBarState::mouseDoubleClickEmpty()
{
// TODO activate when QGraphicsScene selection handling is used
//m_pUMLScene->clearSelection();
m_pUMLScene->clearSelected();
}
/**
* Called when the move event happened when an association is
* currently available.
* Default implementation does nothing.
*/
void ToolBarState::mouseMoveAssociation()
{
}
/**
* Called when the move event happened when a widget is
* currently available.
* Default implementation does nothing.
*/
void ToolBarState::mouseMoveWidget()
{
}
/**
* Called when the move event happened when no association nor
* widget are currently available.
* Default implementation does nothing.
*/
void ToolBarState::mouseMoveEmpty()
{
}
/**
* Changes the current tool to the default one if the right button was released.
* It can be overridden in subclasses if needed.
*/
void ToolBarState::changeTool()
{
if (m_pMouseEvent->buttons() == Qt::RightButton) {
UMLApp::app()->workToolBar()->setDefaultTool();
}
}
/**
* Returns the widget currently in use.
*
* @return The widget currently in use.
*/
UMLWidget* ToolBarState::currentWidget() const
{
return m_currentWidget;
}
/**
* Sets the widget currently in use.
* This method is called in main press events handler just before calling
* the press event for widgets handler.
* Default implementation is set the specified widget, although this
* behaviour can be overridden in subclasses if needed.
*
* @param widget The widget to be set.
*/
void ToolBarState::setCurrentWidget(UMLWidget* widget)
{
m_currentWidget = widget;
}
/**
* Returns the association currently in use.
*
* @return The association currently in use.
*/
AssociationWidget* ToolBarState::currentAssociation() const
{
return m_currentAssociation;
}
/**
* Sets the association currently in use.
* This method is called in main press events handler just before calling
* the press event for associations handler.
* Default implementation is set the specified association, although this
* behaviour can be overridden in subclasses if needed.
*
* @param association The association to be set.
*/
void ToolBarState::setCurrentAssociation(AssociationWidget* association)
{
m_currentAssociation = association;
}
/**
* Sets m_pMouseEvent as the equivalent of the received event after transforming it
* using the inverse world matrix in the UMLScene.
* This method is called at the beginning of the main event handler methods.
*
* @param ome The mouse event to transform.
* @param type The type of the event.
*/
void ToolBarState::setMouseEvent(QGraphicsSceneMouseEvent* ome, const QEvent::Type &type)
{
delete m_pMouseEvent;
//:TODO: uDebug() << "[PORT] Check if scenePos works like view->inverseWorldMatrix().map()";
// Using copy constructor here.
m_pMouseEvent = new QGraphicsSceneMouseEvent(type);
m_pMouseEvent->setPos(ome->pos());
m_pMouseEvent->setScenePos(ome->scenePos());
m_pMouseEvent->setScreenPos(ome->screenPos());
m_pMouseEvent->setLastPos(ome->lastPos());
m_pMouseEvent->setLastScenePos(ome->lastScenePos());
m_pMouseEvent->setLastScreenPos(ome->lastScreenPos());
m_pMouseEvent->setButtons(ome->buttons());
m_pMouseEvent->setButton(ome->button());
m_pMouseEvent->setModifiers(ome->modifiers());
}
/**
* Returns the MessageWidget at the specified position, or null if there is none.
* The message is only returned if it is visible.
* If there are more than one message at this point, it returns the first found.
*
* @param pos The position to get the message.
* @return The MessageWidget at the specified position, or null if there is none.
* @todo Better handling for messages at the same point
*/
MessageWidget* ToolBarState::messageAt(const QPointF& pos)
{
for(MessageWidget* message : m_pUMLScene->messageList()) {
if (message->isVisible() && message->onWidget(pos)) {
return message;
}
}
return nullptr;
}
/**
* Returns the AssociationWidget at the specified position, or null if there is none.
* If there are more than one association at this point, it returns the first found.
*
* @param pos The position to get the association.
* @return The AssociationWidget at the specified position, or null if there is none.
* @todo Better handling for associations at the same point
*/
AssociationWidget* ToolBarState::associationAt(const QPointF& pos)
{
for(AssociationWidget* association : m_pUMLScene->associationList()) {
if (association->onAssociation(pos)) {
return association;
}
}
return nullptr;
}
/**
* Returns the FloatingDashLineWidget at the specified position, or null if there is none.
* The floatingdashline is only returned if it is visible.
*
* @param pos The position to get the floatingLine.
* @return The MessageWidget at the specified position, or null if there is none.
*/
FloatingDashLineWidget* ToolBarState::floatingLineAt(const QPointF& pos)
{
FloatingDashLineWidget *floatingline = nullptr;
for(UMLWidget* widget : m_pUMLScene->widgetList()) {
uIgnoreZeroPointer(widget);
if (widget->isFloatingDashLineWidget()){
if (widget->asFloatingDashLineWidget()->onLine(pos)) {
floatingline = widget->asFloatingDashLineWidget();
}
}
}
return floatingline;
}
| 17,343
|
C++
|
.cpp
| 514
| 30.180934
| 168
| 0.712105
|
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,265
|
umlview.cpp
|
KDE_umbrello/umbrello/umlview.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlview.h"
// application specific includes
#include "debug_utils.h"
#include "docwindow.h"
#include "model_utils.h"
#include "notewidget.h"
#include "uml.h"
#include "umldoc.h"
#include "umldragdata.h"
#include "umlscene.h"
#include "umlviewdialog.h"
#include "umlwidget.h"
#include <QPointer>
#include <QScrollBar>
DEBUG_REGISTER(UMLView)
/**
* Constructor.
*/
UMLView::UMLView(UMLFolder *parentFolder)
: QGraphicsView(UMLApp::app()->mainViewWidget())
{
setAcceptDrops(true);
setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
setDragMode(NoDrag); //:TODO: RubberBandDrag);
setScene(new UMLScene(parentFolder, this));
setResizeAnchor(AnchorUnderMouse);
setTransformationAnchor(AnchorUnderMouse);
}
/**
* Destructor.
*/
UMLView::~UMLView()
{
delete umlScene();
}
/**
* Getter for the uml scene.
*/
UMLScene* UMLView::umlScene() const
{
return static_cast<UMLScene*>(scene());
}
/**
* Returns the zoom of the diagram.
*/
qreal UMLView::zoom() const
{
return transform().m11()*100.0;
}
/**
* Sets the zoom of the diagram.
*/
void UMLView::setZoom(qreal zoom)
{
if (zoom < 10) {
zoom = 10;
} else if (zoom > 500) {
zoom = 500;
}
logDebug1("UMLView::setZoom %1", zoom);
QTransform wm;
wm.scale(zoom / 100.0, zoom / 100.0);
setTransform(wm);
}
/**
* Shows the properties dialog for the view.
*/
bool UMLView::showPropertiesDialog(QWidget *parent)
{
QPointer<UMLViewDialog> dlg = new UMLViewDialog(parent, umlScene());
bool success = dlg->exec() == QDialog::Accepted;
delete dlg;
return success;
}
void UMLView::zoomIn()
{
QTransform wm = transform();
wm.scale(1.5, 1.5); // adjust zooming step here
setZoom(wm.m11()*100.0);
}
void UMLView::zoomOut()
{
QTransform wm = transform();
wm.scale(2.0 / 3.0, 2.0 / 3.0); //adjust zooming step here
setZoom(wm.m11()*100.0);
}
/**
* Overrides standard method from QWidget for possible additional actions.
* TBC can we remove this?
*/
void UMLView::show()
{
QWidget::show();
}
/**
* Zoom the view in and out.
*/
void UMLView::wheelEvent(QWheelEvent* event)
{
// get the position of the mouse before scaling, in scene coords
QPointF pointBeforeScale(mapToScene(event->position().toPoint()));
// scale the view ie. do the zoom
double scaleFactor = 1.15;
if (event->delta() > 0) {
// zoom in
if (zoom() < 500) {
setZoom(zoom() * scaleFactor);
} else {
return;
}
} else {
// zooming out
if (zoom() > 10) {
setZoom(zoom() / scaleFactor);
} else {
return;
}
}
// get the position after scaling, in scene coords
QPointF pointAfterScale(mapToScene(event->position().toPoint()));
// get the offset of how the screen moved
QPointF offset = pointBeforeScale - pointAfterScale;
// adjust to the new center for correct zooming
QPointF newCenter = mapToScene(viewport()->rect().center()) + offset;
centerOn(newCenter);
UMLApp::app()->setZoom(zoom(), false);
}
/**
* Overrides the standard operation.
*/
void UMLView::showEvent(QShowEvent* se)
{
UMLApp* theApp = UMLApp::app();
WorkToolBar* tb = theApp->workToolBar();
UMLScene *us = umlScene();
connect(tb, SIGNAL(sigButtonChanged(int)), us, SLOT(slotToolBarChanged(int)));
connect(us, SIGNAL(sigResetToolBar()), tb, SLOT(slotResetToolBar()));
umlScene()->showEvent(se);
us->resetToolbar();
}
/**
* Overrides the standard operation.
*/
void UMLView::hideEvent(QHideEvent* he)
{
UMLApp* theApp = UMLApp::app();
WorkToolBar* tb = theApp->workToolBar();
UMLScene *us = umlScene();
disconnect(tb, SIGNAL(sigButtonChanged(int)), us, SLOT(slotToolBarChanged(int)));
disconnect(us, SIGNAL(sigResetToolBar()), tb, SLOT(slotResetToolBar()));
us->hideEvent(he);
}
/**
* Override standard method.
*/
void UMLView::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::MidButton) {
setDragMode(QGraphicsView::ScrollHandDrag);
setInteractive(false);
QMouseEvent fake(event->type(), event->pos(), Qt::LeftButton, Qt::LeftButton, event->modifiers());
QGraphicsView::mousePressEvent(&fake);
} else
QGraphicsView::mousePressEvent(event);
}
/**
* Override standard method.
*/
void UMLView::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::MidButton) {
QMouseEvent fake(event->type(), event->pos(), Qt::LeftButton, Qt::LeftButton, event->modifiers());
QGraphicsView::mouseReleaseEvent(&fake);
setInteractive(true);
setDragMode(QGraphicsView::NoDrag);
} else
QGraphicsView::mouseReleaseEvent(event);
}
/**
* Override standard method.
*/
void UMLView::resizeEvent(QResizeEvent *event)
{
bool oldState1 = verticalScrollBar()->blockSignals(true);
bool oldState2 = horizontalScrollBar()->blockSignals(true);
QGraphicsView::resizeEvent(event);
verticalScrollBar()->blockSignals(oldState1);
horizontalScrollBar()->blockSignals(oldState2);
}
| 5,327
|
C++
|
.cpp
| 194
| 23.737113
| 106
| 0.680313
|
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,266
|
umlscene.cpp
|
KDE_umbrello/umbrello/umlscene.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlscene.h"
// application specific includes
#include "activitywidget.h"
#include "actorwidget.h"
#include "artifactwidget.h"
#include "association.h"
#include "associationwidget.h"
#include "assocrules.h"
#include "attribute.h"
#include "boxwidget.h"
#include "classifier.h"
#include "classifierwidget.h"
#include "classoptionspage.h"
#include "component.h"
#include "cmds.h"
#include "componentwidget.h"
#include "datatype.h"
#include "diagram_utils.h"
#include "pinportbase.h"
#include "datatypewidget.h"
#define DBG_SRC QStringLiteral("UMLScene")
#include "debug_utils.h" // we cannot use the predefined DBG_SRC due to class UMLScenePrivate
#include "dialog_utils.h"
#include "docwindow.h"
#include "entity.h"
#include "entitywidget.h"
#include "enumwidget.h"
#include "floatingtextwidget.h"
#include "folder.h"
#include "foreignkeyconstraint.h"
#include "forkjoinwidget.h"
#include "idchangelog.h"
#include "interfacewidget.h"
#include "import_utils.h"
#include "layoutgenerator.h"
#include "layoutgrid.h"
#include "messagewidget.h"
#include "model_utils.h"
#include "notewidget.h"
#include "object_factory.h"
#include "objectnodewidget.h"
#include "objectwidget.h"
#include "package.h"
#include "packagewidget.h"
#include "pinwidget.h"
#include "portwidget.h"
#include "seqlinewidget.h"
#include "signalwidget.h"
#include "statewidget.h"
#include "toolbarstate.h"
#include "toolbarstatefactory.h"
#include "uml.h"
#include "umldoc.h"
#include "umldragdata.h"
#include "umlfiledialog.h"
#include "umllistview.h"
#include "umllistviewitem.h"
#include "umlobject.h"
#include "umlobjectlist.h"
#include "umlrole.h"
#include "umlscenepopupmenu.h"
#include "umlview.h"
#include "umlviewimageexporter.h"
#include "umlwidget.h"
#include "uniqueid.h"
#include "widget_factory.h"
#include "widget_utils.h"
#include "widgetlist_utils.h"
//kde include files
#include <KMessageBox>
#include <kcursor.h>
#include <KLocalizedString>
// include files for Qt
#include <QColor>
#include <QLineF>
#include <QPainter>
#include <QPixmap>
#include <QPrinter>
#include <QString>
#include <QStringList>
#include <QXmlStreamWriter>
// system includes
#include <cmath> // for ceil
// static members
const qreal UMLScene::s_defaultCanvasWidth = 1100;
const qreal UMLScene::s_defaultCanvasHeight = 800;
const qreal UMLScene::s_maxCanvasSize = 100000.0;
const qreal UMLScene::s_sceneBorder = 5.0;
bool UMLScene::s_showDocumentationIndicator = false;
using namespace Uml;
DEBUG_REGISTER_DISABLED(UMLScene)
/**
* The class UMLScenePrivate is intended to hold private
* members/classes to reduce the size of the public class
* and to speed up recompiling.
* The migration to this class is not complete yet.
*/
class UMLScenePrivate {
public:
UMLScenePrivate(UMLScene *parent)
: p(parent)
, toolBarState(nullptr)
, inMouseMoveEvent(false)
{
toolBarStateFactory = new ToolBarStateFactory;
}
~UMLScenePrivate()
{
delete toolBarState;
delete toolBarStateFactory;
}
/**
* Check if there is a corresponding port widget
* for all UMLPort instances and add if not.
*/
void addMissingPorts()
{
UMLWidgetList ports;
UMLWidgetList components;
for(UMLWidget *w : p->widgetList()) {
if (w->isPortWidget())
ports.append(w);
else if (w->isComponentWidget())
components.append(w);
}
for(UMLWidget *cw : components) {
const UMLComponent *c = cw->umlObject()->asUMLComponent();
if (!c)
continue;
// iterate through related ports for this component widget
for(UMLObject *o : c->containedObjects()) {
UMLPort *up = o->asUMLPort();
if (!up)
continue;
Uml::ID::Type id = o->id();
bool found = false;
for(UMLWidget *p : ports) {
if (p->id() == id) {
found = true;
break;
}
}
if (!found)
new PortWidget(p, up, cw);
}
}
}
/**
* Check if port are located equally on the border of a component
* and fix position if not.
*/
void fixPortPositions()
{
for(UMLWidget *w : p->widgetList()) {
if (w->isPortWidget()) {
QGraphicsItem *g = w->parentItem();
ComponentWidget *c = dynamic_cast<ComponentWidget*>(g);
Q_ASSERT(c);
qreal w2 = w->width()/2;
qreal h2 = w->height()/2;
if (w->x() <= -w2 || w->y() <= -h2
|| w->x() >= c->width() - w2
|| w->y() >= c->height() - h2)
continue;
if (w->x() >= c->width() - 3 * w2) { // right
w->setX(c->width() - w2);
} else if (w->y() >= c->height() - 3 * h2) { // bottom
w->setY(c->height() - h2);
} else if (w->x() < 3 * w2) { // left
w->setX(-w2);
} else if (w->y() < 3 * h2) { // top
w->setY(-h2);
} else
logWarn1("UMLScenePrivate::fixPortPositions unhandled widget %1 position", w->name());
}
}
}
/**
* Check if duplicated floating text labels are in the scene and remove them
*/
void removeDuplicatedFloatingTextInstances()
{
UMLWidgetList labelsWithoutParents;
UMLWidgetList labelsWithParent;
const QString pName(p->name());
logDebug2("UMLScenePrivate::removeDuplicatedFloatingTextInstances checking diagram %1 id %2",
pName, Uml::ID::toString(p->ID()));
for(UMLWidget *w : p->widgetList()) {
if (!w->isTextWidget())
continue;
if (w->parentItem())
labelsWithParent.append(w);
else
labelsWithoutParents.append(w);
}
for(UMLWidget *w : labelsWithoutParents) {
for(UMLWidget *wp : labelsWithParent) {
if (w->id() == wp->id() &&
w->localID() == wp->localID() &&
w->name() == wp->name()) {
p->removeWidgetCmd(w);
logDebug2("UMLScenePrivate::removeDuplicatedFloatingTextInstances removed "
"duplicated text label %1 id %2", w->name(), Uml::ID::toString(w->id()));
break;
}
}
}
}
void setToolBarChanged(WorkToolBar::ToolBar_Buttons button)
{
if (toolBarState)
toolBarState->cleanBeforeChange();
toolBarState = toolBarStateFactory->getState(button, p);
toolBarState->init();
p->setPaste(false);
}
void triggerToolBarButton(WorkToolBar::ToolBar_Buttons button)
{
UMLApp::app()->workToolBar()->buttonChanged(button);
setToolBarChanged(button);
QGraphicsSceneMouseEvent event;
event.setScenePos(p->pos());
event.setButton(Qt::LeftButton);
toolBarState->mousePress(&event);
toolBarState->mouseRelease(&event);
p->connect(toolBarState, SIGNAL(finished()), UMLApp::app()->workToolBar(), SLOT(slotResetToolBar()));
}
UMLScene *p;
ToolBarStateFactory *toolBarStateFactory;
ToolBarState *toolBarState;
QPointer<WidgetBase> widgetLink;
bool inMouseMoveEvent;
};
/**
* Constructor.
*/
UMLScene::UMLScene(UMLFolder *parentFolder, UMLView *view)
: QGraphicsScene(0, 0, s_defaultCanvasWidth, s_defaultCanvasHeight),
m_nLocalID(Uml::ID::None),
m_nID(Uml::ID::None),
m_Type(Uml::DiagramType::Undefined),
m_Name(QString()),
m_Documentation(QString()),
m_Options(Settings::optionState()),
m_bUseSnapToGrid(false),
m_bUseSnapComponentSizeToGrid(false),
m_isOpen(true),
m_nCollaborationId(0),
m_bCreateObject(false),
m_bDrawSelectedOnly(false),
m_bPaste(false),
m_bStartedCut(false),
m_d(new UMLScenePrivate(this)),
m_view(view),
m_pFolder(parentFolder),
m_pIDChangesLog(nullptr),
m_isActivated(false),
m_bPopupShowing(false),
m_autoIncrementSequence(false),
m_minX(s_maxCanvasSize), m_minY(s_maxCanvasSize),
m_maxX(0.0), m_maxY(0.0),
m_fixX(0.0), m_fixY(0.0)
{
m_PastePoint = QPointF(0, 0);
m_pImageExporter = new UMLViewImageExporter(this);
// setup signals
connect(UMLApp::app(), SIGNAL(sigCutSuccessful()),
this, SLOT(slotCutSuccessful()));
m_d->setToolBarChanged(WorkToolBar::tbb_Arrow);
m_doc = UMLApp::app()->document();
// // settings for background
// setBackgroundBrush(QColor(195, 195, 195));
m_layoutGrid = new LayoutGrid(this);
// fix crash caused by Qt stale item issue see https://bugs.kde.org/show_bug.cgi?id=383592
setItemIndexMethod(NoIndex);
}
/**
* Destructor.
*/
UMLScene::~UMLScene()
{
delete m_pImageExporter;
m_pImageExporter = nullptr;
delete m_pIDChangesLog;
m_pIDChangesLog = nullptr;
// before we can delete the QCanvas, all widgets must be explicitly
// removed
// otherwise the implicit remove of the contained widgets will cause
// events which would demand a valid connected QCanvas
// ==> this causes umbrello to crash for some - larger?? - projects
// first avoid all events, which would cause some update actions
// on deletion of each removed widget
blockSignals(true);
removeAllWidgets();
delete m_layoutGrid;
delete m_d;
}
/**
* The size returned is large enough to account for possible bogus widget
* coordinate offsets as described in
* https://bugs.kde.org/show_bug.cgi?id=449622
* Coordinate values below -maxCanvasSize() or above maxCanvasSize() are
* deemed unrecoverable.
*
* @return the maximum possible canvas size
*/
qreal UMLScene::maxCanvasSize() {
return s_maxCanvasSize;
}
/**
* Return the UMLFolder in which this diagram lives.
*/
UMLFolder* UMLScene::folder() const
{
return m_pFolder;
}
/**
* Set the UMLFolder in which this diagram lives.
*/
void UMLScene::setFolder(UMLFolder *folder)
{
m_pFolder = folder;
}
/**
* Returns the active view associated with this scene.
*/
UMLView* UMLScene::activeView() const
{
return m_view;
}
/**
* Return the documentation of the diagram.
*/
QString UMLScene::documentation() const
{
return m_Documentation;
}
/**
* Set the documentation of the diagram.
*/
void UMLScene::setDocumentation(const QString &doc)
{
m_Documentation = doc;
}
/**
* Return the state of the auto increment sequence
*/
bool UMLScene::autoIncrementSequence() const
{
return m_autoIncrementSequence;
}
void UMLScene::setAutoIncrementSequence(bool state)
{
m_autoIncrementSequence = state;
}
/**
* Return the next auto increment sequence value
*/
QString UMLScene::autoIncrementSequenceValue()
{
int sequenceNumber = 0;
if (isSequenceDiagram()) {
for(MessageWidget* message : messageList()) {
bool ok;
int value = message->sequenceNumber().toInt(&ok);
if (ok && value > sequenceNumber)
sequenceNumber = value;
}
}
else if (isCollaborationDiagram()) {
for(AssociationWidget* assoc : associationList()) {
bool ok;
int value = assoc->sequenceNumber().toInt(&ok);
if (ok && value > sequenceNumber)
sequenceNumber = value;
}
}
return QString::number(sequenceNumber + 1);
}
/**
* Return the name of the diagram.
*/
QString UMLScene::name() const
{
return m_Name;
}
/**
* Set the name of the diagram.
*/
void UMLScene::setName(const QString &name)
{
m_Name = name;
}
/**
* Returns the type of the diagram.
*/
DiagramType::Enum UMLScene::type() const
{
return m_Type;
}
/**
* Set the type of diagram.
*/
void UMLScene::setType(DiagramType::Enum type)
{
m_Type = type;
}
/**
* Returns the ID of the diagram.
*/
Uml::ID::Type UMLScene::ID() const
{
return m_nID;
}
/**
* Sets the ID of the diagram.
*/
void UMLScene::setID(Uml::ID::Type id)
{
m_nID = id;
}
/**
* Returns the position of the diagram.
*/
QPointF UMLScene::pos() const
{
return m_pos;
}
/**
* Sets the position of the diagram.
*/
void UMLScene::setPos(const QPointF &pos)
{
m_pos = pos;
}
/**
* Returns the fill color to use.
*/
const QColor& UMLScene::fillColor() const
{
return m_Options.uiState.fillColor;
}
/**
* Set the background color.
*
* @param color The color to use.
*/
void UMLScene::setFillColor(const QColor &color)
{
m_Options.uiState.fillColor = color;
Q_EMIT sigFillColorChanged(ID());
}
/**
* Returns the line color to use.
*/
const QColor& UMLScene::lineColor() const
{
return m_Options.uiState.lineColor;
}
/**
* Sets the line color.
*
* @param color The color to use.
*/
void UMLScene::setLineColor(const QColor &color)
{
m_Options.uiState.lineColor = color;
Q_EMIT sigLineColorChanged(ID());
}
/**
* Returns the line width to use.
*/
uint UMLScene::lineWidth() const
{
return m_Options.uiState.lineWidth;
}
/**
* Sets the line width.
*
* @param width The width to use.
*/
void UMLScene::setLineWidth(uint width)
{
m_Options.uiState.lineWidth = width;
Q_EMIT sigLineWidthChanged(ID());
}
/**
* Returns the text color to use.
*/
const QColor& UMLScene::textColor() const
{
return m_Options.uiState.textColor;
}
/**
* Sets the text color.
*
* @param color The color to use.
*/
void UMLScene::setTextColor(const QColor& color)
{
m_Options.uiState.textColor = color;
Q_EMIT sigTextColorChanged(ID());
}
/**
* return grid dot color
*
* @return Color
*/
const QColor& UMLScene::gridDotColor() const
{
return m_layoutGrid->gridDotColor();
}
/**
* set grid dot color
*
* @param color grid dot color
*/
void UMLScene::setGridDotColor(const QColor& color)
{
m_Options.uiState.gridDotColor = color;
m_layoutGrid->setGridDotColor(color);
}
/**
* Returns the options being used.
*/
Settings::OptionState& UMLScene::optionState()
{
return m_Options;
}
/**
* Sets the options to be used.
*/
void UMLScene::setOptionState(const Settings::OptionState& options)
{
m_Options = options;
setBackgroundBrush(options.uiState.backgroundColor);
setGridDotColor(options.uiState.gridDotColor);
}
/**
* Returns the association list.
*/
AssociationWidgetList UMLScene::associationList() const
{
AssociationWidgetList result;
for(QGraphicsItem *item : items()) {
AssociationWidget *w = dynamic_cast<AssociationWidget*>(item);
if (w)
result.append(w);
}
return result;
}
/**
* Returns the widget list.
*/
UMLWidgetList UMLScene::widgetList() const
{
UMLWidgetList result;
for(QGraphicsItem *item : items()) {
UMLWidget *w = dynamic_cast<UMLWidget*>(item);
if (w && !w->isMessageWidget() && !w->isAssociationWidget())
result.append(w);
}
return result;
}
void UMLScene::addWidgetCmd(UMLWidget* widget)
{
Q_ASSERT(nullptr != widget);
logDebug5("UMLScene::addWidgetCmd(%1) : x=%2, y=%3, w=%4, h=%5",
widget->name(), widget->x(), widget->y(), widget->width(), widget->height());
addItem(widget);
}
void UMLScene::addWidgetCmd(AssociationWidget* widget)
{
Q_ASSERT(nullptr != widget);
addItem(widget);
}
/**
* Returns the message list.
*/
MessageWidgetList UMLScene::messageList() const
{
MessageWidgetList result;
for(QGraphicsItem *item : items()) {
MessageWidget *w = dynamic_cast<MessageWidget*>(item);
if (w)
result.append(w);
}
return result;
}
/**
* Used for creating unique name of collaboration messages.
*/
int UMLScene::generateCollaborationId()
{
return ++m_nCollaborationId;
}
/**
* Returns the open state.
* @return when true diagram is shown to the user
*/
bool UMLScene::isOpen() const
{
return m_isOpen;
}
/**
* Sets the flag 'isOpen'.
* @param isOpen flag indicating that the diagram is shown to the user
*/
void UMLScene::setIsOpen(bool isOpen)
{
m_isOpen = isOpen;
}
/**
* Contains the implementation for printing functionality.
*/
void UMLScene::print(QPrinter *pPrinter, QPainter & pPainter)
{
bool isFooter = optionState().generalState.footerPrinting;
// The printer will probably use a different font with different font metrics,
// force the widgets to update accordingly on paint
forceUpdateWidgetFontMetrics(&pPainter);
QRectF source = diagramRect();
QRect paper = pPrinter->paperRect(QPrinter::Millimeter).toRect();
QRect page = pPrinter->pageRect(QPrinter::Millimeter).toRect();
// use the painter font metrics, not the screen fm!
QFontMetrics fm = pPainter.fontMetrics();
int fontHeight = fm.lineSpacing();
if (paper == page) {
QSize margin = page.size() * 0.025;
page.adjust(margin.width(), margin.height(), -margin.width(), -margin.height());
}
if (isFooter) {
int margin = 3 + 3 * fontHeight;
page.adjust(0, 0, 0, -margin);
}
getDiagram(pPainter, QRectF(source), QRectF(page));
//draw foot note
if (isFooter) {
page.adjust(0, 0, 0, fontHeight);
QString string = i18n("Diagram: %2 Page %1", 1, name());
QColor textColor(50, 50, 50);
pPainter.setPen(textColor);
pPainter.drawLine(page.left(), page.bottom() , page.right(), page.bottom());
pPainter.drawText(page.left(), page.bottom() + 3, page.right(), 2*fontHeight, Qt::AlignLeft, string);
}
// next painting will most probably be to a different device (i.e. the screen)
forceUpdateWidgetFontMetrics(nullptr);
}
/**
* Initialize and announce a newly created widget.
* Auxiliary to contentsMouseReleaseEvent().
*/
void UMLScene::setupNewWidget(UMLWidget *w, bool setPosition)
{
if (setPosition &&
!w->isPinWidget() &&
!w->isPortWidget() &&
!w->isObjectWidget()) {
// ObjectWidget's position is handled by the widget
w->setX(m_pos.x());
w->setY(m_pos.y());
}
w->setVisible(true);
w->activate();
w->setFontCmd(font());
w->slotFillColorChanged(ID());
w->slotTextColorChanged(ID());
w->slotLineWidthChanged(ID());
m_doc->setModified();
if (m_doc->loading()) { // do not emit signals while loading
addWidgetCmd(w);
// w->activate(); // will be done by UMLDoc::activateAllViews() after loading
} else {
UMLApp::app()->executeCommand(new CmdCreateWidget(w));
}
}
/**
* Return whether we are currently creating an object.
*/
bool UMLScene::getCreateObject() const
{
return m_bCreateObject;
}
/**
* Set whether we are currently creating an object.
*/
void UMLScene::setCreateObject(bool bCreate)
{
m_bCreateObject = bCreate;
}
/**
* Overrides the standard operation.
*/
void UMLScene::showEvent(QShowEvent* /*se*/)
{
connect(m_doc, SIGNAL(sigObjectCreated(UMLObject*)),
this, SLOT(slotObjectCreated(UMLObject*)));
connect(this, SIGNAL(sigAssociationRemoved(AssociationWidget*)),
UMLApp::app()->docWindow(), SLOT(slotAssociationRemoved(AssociationWidget*)));
connect(this, SIGNAL(sigWidgetRemoved(UMLWidget*)),
UMLApp::app()->docWindow(), SLOT(slotWidgetRemoved(UMLWidget*)));
}
/**
* Overrides the standard operation.
*/
void UMLScene::hideEvent(QHideEvent* /*he*/)
{
disconnect(m_doc, SIGNAL(sigObjectCreated(UMLObject*)), this, SLOT(slotObjectCreated(UMLObject*)));
disconnect(this, SIGNAL(sigAssociationRemoved(AssociationWidget*)),
UMLApp::app()->docWindow(), SLOT(slotAssociationRemoved(AssociationWidget*)));
disconnect(this, SIGNAL(sigWidgetRemoved(UMLWidget*)),
UMLApp::app()->docWindow(), SLOT(slotWidgetRemoved(UMLWidget*)));
}
/**
* Changes the current tool to the selected tool.
* The current tool is cleaned and the selected tool initialized.
*/
void UMLScene::slotToolBarChanged(int c)
{
m_d->setToolBarChanged((WorkToolBar::ToolBar_Buttons)c);
}
/**
* Slot called when an object is created.
* @param o created UML object
*/
void UMLScene::slotObjectCreated(UMLObject* o)
{
logDebug2("UMLScene::slotObjectCreated: scene=%1 / object=%2", name(), o->name());
m_bPaste = false;
//check to see if we want the message
//may be wanted by someone else e.g. list view
if (!m_bCreateObject) {
return;
}
UMLWidget* newWidget = Widget_Factory::createWidget(this, o);
if (!newWidget) {
return;
}
setupNewWidget(newWidget);
m_bCreateObject = false;
if (Model_Utils::hasAssociations(o->baseType()))
{
createAutoAssociations(newWidget);
// We need to invoke createAutoAttributeAssociations()
// on all other widgets again because the newly created
// widget might saturate some latent attribute assocs.
createAutoAttributeAssociations2(newWidget);
}
UMLView* cv = activeView();
if (cv) {
// this should activate the bird view:
UMLApp::app()->setCurrentView(cv, false);
}
}
/**
* Slot called when an object is removed.
* @param o removed UML object
*/
void UMLScene::slotObjectRemoved(UMLObject * o)
{
m_bPaste = false;
Uml::ID::Type id = o->id();
for(UMLWidget* obj : widgetList()) {
if (obj->id() != id)
continue;
removeWidget(obj);
break;
}
}
/**
* Override standard method.
*/
void UMLScene::dragEnterEvent(QGraphicsSceneDragDropEvent *e)
{
UMLDragData::LvTypeAndID_List tidList;
if (!UMLDragData::getClip3TypeAndID(e->mimeData(), tidList)) {
logDebug0("UMLScene::dragEnterEvent: UMLDragData::getClip3TypeAndID returned false");
return;
}
const DiagramType::Enum diagramType = type();
bool bAccept = true;
for(UMLDragData::LvTypeAndID_List::const_iterator it = tidList.begin(); it != tidList.end(); it++) {
UMLListViewItem::ListViewType lvtype = (*it)->type;
Uml::ID::Type id = (*it)->id;
UMLObject *temp = nullptr;
//if dragging diagram - might be a drag-to-note
if (Model_Utils::typeIsDiagram(lvtype)) {
break;
}
//can't drag anything onto state/activity diagrams
if (diagramType == DiagramType::State || diagramType == DiagramType::Activity) {
bAccept = false;
break;
}
//make sure can find UMLObject
if (!(temp = m_doc->findObjectById(id))) {
logDebug1("UMLScene::dragEnterEvent: object %1 not found", Uml::ID::toString(id));
bAccept = false;
break;
}
if (!Model_Utils::typeIsAllowedInDiagram(temp, this)) {
logDebug2("UMLScene::dragEnterEvent: %1 is not allowed in diagram type %2", temp->name(), diagramType);
bAccept = false;
break;
}
}
if (bAccept) {
e->accept();
} else {
e->ignore();
}
}
/**
* Override standard method.
*/
void UMLScene::dragMoveEvent(QGraphicsSceneDragDropEvent* e)
{
e->accept();
}
/**
* Override standard method.
*/
void UMLScene::dropEvent(QGraphicsSceneDragDropEvent *e)
{
UMLDragData::LvTypeAndID_List tidList;
if (!UMLDragData::getClip3TypeAndID(e->mimeData(), tidList)) {
logDebug0("UMLScene::dropEvent: UMLDragData::getClip3TypeAndID returned error");
return;
}
m_pos = e->scenePos();
for(UMLDragData::LvTypeAndID_List::const_iterator it = tidList.begin(); it != tidList.end(); it++) {
UMLListViewItem::ListViewType lvtype = (*it)->type;
Uml::ID::Type id = (*it)->id;
if (Model_Utils::typeIsDiagram(lvtype)) {
bool breakFlag = false;
UMLWidget *w = nullptr;
for(UMLWidget *w: widgetList()) {
if (w->isNoteWidget() && w->onWidget(e->scenePos())) {
breakFlag = true;
break;
}
}
if (breakFlag) {
NoteWidget *note = static_cast<NoteWidget*>(w);
note->setDiagramLink(id);
}
continue;
}
UMLObject* o = m_doc->findObjectById(id);
if (!o) {
logDebug1("UMLScene::dropEvent: object id=%1 not found", Uml::ID::toString(id));
continue;
}
UMLWidget* newWidget = Widget_Factory::createWidget(this, o);
if (!newWidget) {
logWarn1("UMLScene::dropEvent could not create widget for uml object %1", o->name());
continue;
}
setupNewWidget(newWidget, true);
m_pos += QPointF(UMLWidget::DefaultMinimumSize.width(), UMLWidget::DefaultMinimumSize.height());
createAutoAssociations(newWidget);
createAutoAttributeAssociations2(newWidget);
}
}
/**
* Overrides the standard operation.
* Calls the same method in the current tool bar state.
*/
void UMLScene::mouseMoveEvent(QGraphicsSceneMouseEvent* ome)
{
if (m_d->inMouseMoveEvent)
return;
m_d->inMouseMoveEvent = true;
m_d->toolBarState->mouseMove(ome);
m_d->inMouseMoveEvent = false;
}
/**
* Override standard method.
* Calls the same method in the current tool bar state.
*/
void UMLScene::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if (event->button() != Qt::LeftButton) {
event->ignore();
return;
}
m_d->toolBarState->mousePress(event);
// setup document
if (selectedItems().count() == 0)
UMLApp::app()->docWindow()->showDocumentation(this);
event->accept();
}
/**
* Override standard method.
* Calls the same method in the current tool bar state.
*/
void UMLScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
if (!m_doc->loading())
m_d->toolBarState->mouseDoubleClick(event);
if (!event->isAccepted()) {
// show properties dialog of the scene
if (m_view->showPropertiesDialog() == true) {
m_doc->setModified();
}
event->accept();
}
}
/**
* Overrides the standard operation.
* Calls the same method in the current tool bar state.
*/
void UMLScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* ome)
{
m_d->toolBarState->mouseRelease(ome);
}
/**
* Determine whether on a sequence diagram we have clicked on a line
* of an Object.
*
* @return The widget owning the line which was clicked.
* Returns 0 if no line was clicked on.
*/
ObjectWidget * UMLScene::onWidgetLine(const QPointF &point) const
{
for(UMLWidget *obj : widgetList()) {
ObjectWidget *ow = obj->asObjectWidget();
if (ow == nullptr)
continue;
SeqLineWidget *pLine = ow->sequentialLine();
if (pLine == nullptr) {
logError2("UMLScene::onWidgetLine: SeqLineWidget of %1 (id %2) is null",
ow->name(), Uml::ID::toString(ow->localID()));
continue;
}
if (pLine->onWidget(point))
return ow;
}
return nullptr;
}
/**
* Determine whether on a sequence diagram we have clicked on
* the destruction box of an Object.
*
* @return The widget owning the destruction box which was clicked.
* Returns 0 if no destruction box was clicked on.
*/
ObjectWidget * UMLScene::onWidgetDestructionBox(const QPointF &point) const
{
for(UMLWidget *obj : widgetList()) {
ObjectWidget *ow = obj->asObjectWidget();
if (ow == nullptr)
continue;
SeqLineWidget *pLine = ow->sequentialLine();
if (pLine == nullptr) {
logError2("UMLScene::onWidgetDestructionBox: SeqLineWidget of %1 (id %2) is null",
ow->name(), Uml::ID::toString(ow->localID()));
continue;
}
if (pLine->onDestructionBox(point))
return ow;
}
return nullptr;
}
/**
* Return pointer to the first selected widget (for multi-selection)
*/
UMLWidget* UMLScene::getFirstMultiSelectedWidget() const
{
if (selectedWidgets().size() == 0)
return nullptr;
return selectedWidgets().first();
}
/**
* Checks the specified point against all widgets and returns the widget
* for which the point is within its bounding box.
* @param p Point in scene coordinates to search for
* @return Returns the first widget of type UMLWidget returned by QGraphicsScene::items() for multiple matches
* @return Returns NULL if the point is not inside any widget.
*/
UMLWidget* UMLScene::widgetAt(const QPointF& p)
{
for(QGraphicsItem *item : items(p)) {
UMLWidget *w = dynamic_cast<UMLWidget*>(item);
if (w)
return w;
}
return nullptr;
}
/**
* Tests the given point against all associations and returns the
* association widget for which the point is on the line.
* Returns NULL if the point is not inside any association.
* CHECK: This is the same method as in ToolBarState.
*/
AssociationWidget* UMLScene::associationAt(const QPointF& p)
{
for(AssociationWidget *association : associationList()) {
if (association->onAssociation(p)) {
return association;
}
}
return nullptr;
}
/**
* Tests the given point against all associations and returns the
* association widget for which the point is on the line.
* Returns NULL if the point is not inside any association.
*/
MessageWidget* UMLScene::messageAt(const QPointF& p)
{
for(MessageWidget *message : messageList()) {
if (message->onWidget(p)) {
return message;
}
}
return nullptr;
}
/**
* Sees if a message is relevant to the given widget. If it does delete it.
* @param w The widget to check messages against.
*/
void UMLScene::checkMessages(ObjectWidget * w)
{
if (type() != DiagramType::Sequence) {
return;
}
for(MessageWidget *obj : messageList()) {
if (obj->hasObjectWidget(w)) {
removeWidgetCmd(obj);
}
}
}
/**
* Returns whether a widget is already on the diagram.
*
* @param id The id of the widget to check for.
*
* @return Returns pointer to the widget if it is on the diagram, NULL if not.
*/
UMLWidget* UMLScene::widgetOnDiagram(Uml::ID::Type id)
{
for(UMLWidget *obj : widgetList()) {
if (!obj)
continue;
UMLWidget* w = obj->widgetWithID(id);
if (w)
return w;
}
for(UMLWidget *obj : messageList()) {
// CHECK: Should MessageWidget reimplement widgetWithID() ?
// If yes then we should use obj->widgetWithID(id) here too.
if (id == obj->id())
return obj;
}
return nullptr;
}
/**
* Returns whether a widget is already on the diagram.
*
* @param type The type of the widget to check for.
*
* @return Returns pointer to the widget if it is on the diagram, NULL if not.
*/
UMLWidget* UMLScene::widgetOnDiagram(WidgetBase::WidgetType type)
{
for(UMLWidget *widget : widgetList()) {
if (!widget)
continue;
if (widget->baseType() == type)
return widget;
}
return nullptr;
}
/**
* Finds a widget with the given ID.
* Search both our UMLWidget AND MessageWidget lists.
* @param id The ID of the widget to find.
*
* @return Returns the widget found, returns 0 if no widget found.
*/
UMLWidget * UMLScene::findWidget(Uml::ID::Type id)
{
for(UMLWidget *obj : widgetList()) {
if (!obj)
continue;
UMLWidget* w = obj->widgetWithID(id);
if (w) {
return w;
}
}
for(UMLWidget *obj : messageList()) {
// CHECK: Should MessageWidget reimplement widgetWithID() ?
// If yes then we should use obj->widgetWithID(id) here too.
if (obj->localID() == id ||
obj->id() == id)
return obj;
}
return nullptr;
}
/**
* Finds an association widget with the given ID.
*
* @param id The ID of the widget to find.
*
* @return Returns the widget found, returns 0 if no widget found.
*/
AssociationWidget * UMLScene::findAssocWidget(Uml::ID::Type id)
{
for(AssociationWidget *obj : associationList()) {
UMLAssociation* umlassoc = obj->association();
if (umlassoc && umlassoc->id() == id) {
return obj;
}
}
return nullptr;
}
/**
* Finds an association widget with the given widgets and the given role B name.
* Considers the following association types:
* at_Association, at_UniAssociation, at_Composition, at_Aggregation
* This is used for seeking an attribute association.
*
* @param pWidgetA Pointer to the UMLWidget of role A.
* @param pWidgetB Pointer to the UMLWidget of role B.
* @param roleNameB Name at the B side of the association (the attribute name)
*
* @return Returns the widget found, returns 0 if no widget found.
*/
AssociationWidget * UMLScene::findAssocWidget(UMLWidget *pWidgetA,
UMLWidget *pWidgetB, const QString& roleNameB)
{
for(AssociationWidget *assoc : associationList()) {
const Uml::AssociationType::Enum testType = assoc->associationType();
if (testType != Uml::AssociationType::Association &&
testType != Uml::AssociationType::UniAssociation &&
testType != Uml::AssociationType::Composition &&
testType != Uml::AssociationType::Aggregation &&
testType != Uml::AssociationType::Relationship) {
continue;
}
if (pWidgetA->id() == assoc->widgetIDForRole(Uml::RoleType::A) &&
pWidgetB->id() == assoc->widgetIDForRole(Uml::RoleType::B) &&
assoc->roleName(Uml::RoleType::B) == roleNameB) {
return assoc;
}
}
return nullptr;
}
/**
* Finds an association widget with the given type and widgets.
*
* @param at The AssociationType of the widget to find.
* @param pWidgetA Pointer to the UMLWidget of role A.
* @param pWidgetB Pointer to the UMLWidget of role B.
*
* @return Returns the widget found, returns 0 if no widget found.
*/
AssociationWidget * UMLScene::findAssocWidget(AssociationType::Enum at,
UMLWidget *pWidgetA, UMLWidget *pWidgetB)
{
for(AssociationWidget *assoc : associationList()) {
Uml::AssociationType::Enum testType = assoc->associationType();
if (testType != at) {
continue;
}
if (pWidgetA->id() == assoc->widgetIDForRole(Uml::RoleType::A) &&
pWidgetB->id() == assoc->widgetIDForRole(Uml::RoleType::B)) {
return assoc;
}
}
return nullptr;
}
/**
* Remove a widget from view (undo command)
*
* @param o The widget to remove.
*/
void UMLScene::removeWidget(UMLWidget * o)
{
UMLApp::app()->executeCommand(new CmdRemoveWidget(o));
}
/**
* Remove an associationwidget from view (undo command)
*
* @param w The associationwidget to remove.
*/
void UMLScene::removeWidget(AssociationWidget* w)
{
UMLApp::app()->executeCommand(new CmdRemoveWidget(w));
}
/**
* Remove a widget from view.
*
* @param o The widget to remove.
*/
void UMLScene::removeWidgetCmd(UMLWidget * o)
{
if (!o)
return;
Q_EMIT sigWidgetRemoved(o);
removeAssociations(o);
removeOwnedWidgets(o);
WidgetBase::WidgetType t = o->baseType();
if (type() == DiagramType::Sequence && t == WidgetBase::wt_Object) {
checkMessages(static_cast<ObjectWidget*>(o));
}
o->cleanup();
if (!UMLApp::app()->shuttingDown()) {
/* Manipulating the Selected flag during shutdown may crash:
UMLWidget::setSelectedFlag ->
WidgetBase::setSelected ->
QGraphicsObjectWrapper::setSelected ->
QGraphicsItem::setSelected ->
QGraphicsObjectWrapper::itemChange ->
UMLWidget::setSelected ->
UMLApp::slotCopyChanged ->
UMLListView::selectedItemsCount ->
UMLListView::selectedItems ->
Crash somewhere in qobject_cast
(listview already destructed?)
*/
o->setSelectedFlag(false);
}
disconnect(this, SIGNAL(sigFillColorChanged(Uml::ID::Type)), o, SLOT(slotFillColorChanged(Uml::ID::Type)));
disconnect(this, SIGNAL(sigLineColorChanged(Uml::ID::Type)), o, SLOT(slotLineColorChanged(Uml::ID::Type)));
disconnect(this, SIGNAL(sigTextColorChanged(Uml::ID::Type)), o, SLOT(slotTextColorChanged(Uml::ID::Type)));
removeItem(o);
m_doc->setModified(true);
update();
}
/**
* Remove all widgets that have given widget as owner.
*
* @param o The owner widget that will be removed.
*/
void UMLScene::removeOwnedWidgets(UMLWidget* o)
{
for(QGraphicsItem *item : o->childItems()) {
UMLWidget* widget = dynamic_cast<UMLWidget*>(item);
if ((widget != nullptr) &&
(widget->isPinWidget() ||
widget->isPortWidget())) {
removeWidgetCmd(widget);
}
}
}
/**
* Returns background color
*/
const QColor& UMLScene::backgroundColor() const
{
return backgroundBrush().color();
}
/**
* Returns whether to use the fill/background color
*/
bool UMLScene::useFillColor() const
{
return m_Options.uiState.useFillColor;
}
/**
* Sets whether to use the fill/background color
*/
void UMLScene::setUseFillColor(bool ufc)
{
m_Options.uiState.useFillColor = ufc;
}
/**
* Gets the smallest area to print.
*
* @return Returns the smallest area to print.
*/
QRectF UMLScene::diagramRect()
{
return itemsBoundingRect();
}
/**
* Returns a list of selected widgets
* @return list of selected widgets based on class UMLWidget
* @note This method returns widgets including message widgets, but no association widgets
*/
UMLWidgetList UMLScene::selectedWidgets() const
{
QList<QGraphicsItem *> items = selectedItems();
UMLWidgetList widgets;
for(QGraphicsItem *item : items) {
UMLWidget *w = dynamic_cast<UMLWidget*>(item);
if (w)
widgets.append(w);
}
return widgets;
}
/**
* Returns a list of selected association widgets
* @return list of selected widgets based on class AssociationWidget
*/
AssociationWidgetList UMLScene::selectedAssociationWidgets() const
{
QList<QGraphicsItem *> items = selectedItems();
AssociationWidgetList widgets;
for(QGraphicsItem *item : items) {
AssociationWidget *w = dynamic_cast<AssociationWidget*>(item);
if (w)
widgets.append(w);
}
return widgets;
}
/**
* Returns a list of selected message widgets
* @return list of selected widgets based on class MessageWidget
*/
UMLWidgetList UMLScene::selectedMessageWidgets() const
{
QList<QGraphicsItem *> items = selectedItems();
UMLWidgetList widgets;
for(QGraphicsItem *item : items) {
MessageWidget *w = dynamic_cast<MessageWidget*>(item);
if (w) {
widgets.append(w);
} else {
WidgetBase *wb = dynamic_cast<WidgetBase*>(item);
QString name = (wb ? wb->name() : QStringLiteral("(null)"));
logDebug1("UMLScene::selectedMessageWidgets: %1 is not a MessageWidget", name);
}
}
return widgets;
}
/**
* Clear the selected widgets list.
*/
void UMLScene::clearSelected()
{
QList<QGraphicsItem *> items = selectedItems();
for(QGraphicsItem *item : items) {
WidgetBase *wb = dynamic_cast<WidgetBase*>(item);
if (wb) {
wb->setSelected(false);
}
}
clearSelection();
//m_doc->enableCutCopy(false);
}
/**
* Move all the selected widgets by a relative X and Y offset.
* TODO: Only used in UMLApp::handleCursorKeyReleaseEvent
*
* @param dX The distance to move horizontally.
* @param dY The distance to move vertically.
*/
void UMLScene::moveSelectedBy(qreal dX, qreal dY)
{
// logDebug1("UMLScene::moveSelectedBy: m_selectedList count=%1", m_selectedList.count());
for(UMLWidget *w : selectedWidgets()) {
w->moveByLocal(dX, dY);
}
}
/**
* Set the useFillColor variable to all selected widgets
*
* @param useFC The state to set the widget to.
*/
void UMLScene::selectionUseFillColor(bool useFC)
{
if (useFC) {
UMLApp::app()->beginMacro(i18n("Use fill color"));
} else {
UMLApp::app()->beginMacro(i18n("No fill color"));
}
for(UMLWidget *widget : selectedWidgets()) {
widget->setUseFillColor(useFC);
}
UMLApp::app()->endMacro();
}
/**
* Set the font for all the currently selected items.
*/
void UMLScene::selectionSetFont(const QFont &font)
{
UMLApp::app()->beginMacro(i18n("Change font"));
for(UMLWidget *temp : selectedWidgets()) {
temp->setFont(font);
}
UMLApp::app()->endMacro();
}
/**
* Set the line color for all the currently selected items.
*/
void UMLScene::selectionSetLineColor(const QColor &color)
{
UMLApp::app()->beginMacro(i18n("Change line color"));
for(UMLWidget *temp : selectedWidgets()) {
temp->setLineColor(color);
}
AssociationWidgetList assoclist = selectedAssocs();
for(AssociationWidget *aw : assoclist) {
aw->setLineColor(color);
}
UMLApp::app()->endMacro();
}
/**
* Set the line width for all the currently selected items.
*/
void UMLScene::selectionSetLineWidth(uint width)
{
UMLApp::app()->beginMacro(i18n("Change line width"));
for(UMLWidget *temp : selectedWidgets()) {
temp->setLineWidth(width);
temp->setUsesDiagramLineWidth(false);
}
AssociationWidgetList assoclist = selectedAssocs();
for(AssociationWidget *aw : assoclist) {
aw->setLineWidth(width);
aw->setUsesDiagramLineWidth(false);
}
UMLApp::app()->endMacro();
}
/**
* Set the fill color for all the currently selected items.
*/
void UMLScene::selectionSetFillColor(const QColor &color)
{
UMLApp::app()->beginMacro(i18n("Change fill color"));
for(UMLWidget *widget : selectedWidgets()) {
widget->setFillColor(color);
widget->setUsesDiagramFillColor(false);
}
UMLApp::app()->endMacro();
}
/**
* Set or unset the visual property (show ..) setting of all selected items.
*/
void UMLScene::selectionSetVisualProperty(ClassifierWidget::VisualProperty property, bool value)
{
UMLApp::app()->beginMacro(i18n("Change visual property"));
for(UMLWidget *temp : selectedWidgets()) {
ClassifierWidget *cw = temp->asClassifierWidget();
cw->setVisualProperty(property, value);
}
UMLApp::app()->endMacro();
}
/**
* Unselect child widgets when their owner is already selected.
*/
void UMLScene::unselectChildrenOfSelectedWidgets()
{
for(UMLWidget *widget : selectedWidgets()) {
if (widget->isPinWidget() ||
widget->isPortWidget()) {
for(UMLWidget *potentialParentWidget : selectedWidgets()) {
if (widget->parentItem() == potentialParentWidget) {
widget->setSelectedFlag(false);
}
}
}
}
}
/**
* Delete the selected widgets list and the widgets in it.
*/
void UMLScene::deleteSelection()
{
AssociationWidgetList selectedAssociations = selectedAssociationWidgets();
int selectionCount = selectedWidgets().count() + selectedAssociations.count();
if (selectionCount == 0)
return;
// check related associations
bool hasAssociations = false;
for(UMLWidget *widget : selectedWidgets()) {
if (widget->isTextWidget() && widget->asFloatingTextWidget()->textRole() != Uml::TextRole::Floating) {
continue;
}
if (widget->isMessageWidget() || widget->associationWidgetList().size() > 0)
hasAssociations = true;
}
if (hasAssociations && !Dialog_Utils::askDeleteAssociation())
return;
UMLApp::app()->beginMacro(i18n("Delete widgets"));
unselectChildrenOfSelectedWidgets();
for(UMLWidget *widget : selectedWidgets()) {
// Don't delete text widget that are connect to associations as these will
// be cleaned up by the associations.
if (widget->isTextWidget() &&
widget->asFloatingTextWidget()->textRole() != Uml::TextRole::Floating) {
widget->setSelectedFlag(false);
widget->hide();
} else if (widget->isPortWidget()) {
UMLObject *o = widget->umlObject();
removeWidget(widget);
if (o)
UMLApp::app()->executeCommand(new CmdRemoveUMLObject(o));
// message widgets are handled later
} else if (!widget->isMessageWidget()){
removeWidget(widget);
}
}
// Delete any selected associations.
for(AssociationWidget *assocwidget : selectedAssociations) {
removeWidget(assocwidget);
}
// we also have to remove selected messages from sequence diagrams
for(UMLWidget *cur_msgWgt : selectedMessageWidgets()) {
removeWidget(cur_msgWgt);
}
//make sure list empty - it should be anyway, just a check.
clearSelected();
UMLApp::app()->endMacro();
}
/**
* resize selected widgets
*/
void UMLScene::resizeSelection()
{
int selectionCount = selectedWidgets().count();
if (selectionCount > 1) {
UMLApp::app()->beginMacro(i18n("Resize widgets"));
}
if (selectedCount() == 0)
return;
for(UMLWidget *w : selectedWidgets()) {
w->resize();
}
m_doc->setModified();
if (selectionCount > 1) {
UMLApp::app()->endMacro();
}
}
/**
* Selects all widgets
*/
void UMLScene::selectAll()
{
selectWidgets(sceneRect().left(), sceneRect().top(), sceneRect().right(), sceneRect().bottom());
}
/**
* Returns true if this diagram resides in an externalized folder.
* CHECK: It is probably cleaner to move this to the UMLListViewItem.
*/
bool UMLScene::isSavedInSeparateFile()
{
if (optionState().generalState.tabdiagrams) {
// Umbrello currently does not support external folders
// when tabbed diagrams are enabled.
return false;
}
const QString msgPrefix(QStringLiteral("UMLScene::isSavedInSeparateFile(") + name() + QStringLiteral("): "));
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem *lvItem = listView->findItem(m_nID);
if (lvItem == nullptr) {
logError2("UMLScene::isSavedInSeparateFile(%1) : listView->findItem(%2) returns false",
name(), Uml::ID::toString(m_nID));
return false;
}
UMLListViewItem *parentItem = dynamic_cast<UMLListViewItem*>(lvItem->parent());
if (parentItem == nullptr) {
logError1("UMLScene::isSavedInSeparateFile(%1) : parent item in listview is not a UMLListViewItem (?)",
name());
return false;
}
const UMLListViewItem::ListViewType lvt = parentItem->type();
if (! Model_Utils::typeIsFolder(lvt))
return false;
const UMLFolder *modelFolder = parentItem->umlObject()->asUMLFolder();
if (modelFolder == nullptr) {
logError1("UMLScene::isSavedInSeparateFile(%1) : parent model object is not a UMLFolder (?)",
name());
return false;
}
QString folderFile = modelFolder->folderFile();
return !folderFile.isEmpty();
}
UMLSceneItemList UMLScene::collisions(const QPointF &p, int delta)
{
QPointF a = p-QPointF(delta, delta);
QPointF b = p+QPointF(delta, delta);
QList<QGraphicsItem *> list = items(QRectF(a, b));
return list;
}
/**
* Calls setSelected on the given UMLWidget and enters
* it into the m_selectedList while making sure it is
* there only once.
*/
void UMLScene::makeSelected(UMLWidget* uw)
{
if (uw) {
uw->setSelected(true);
}
}
/**
* Selects all the widgets of the given association widget.
*/
void UMLScene::selectWidgetsOfAssoc(AssociationWidget * a)
{
if (a) {
a->setSelected(true);
//select the two widgets
makeSelected(a->widgetForRole(Uml::RoleType::A));
makeSelected(a->widgetForRole(Uml::RoleType::B));
//select all the text
makeSelected(a->multiplicityWidget(Uml::RoleType::A));
makeSelected(a->multiplicityWidget(Uml::RoleType::B));
makeSelected(a->roleWidget(Uml::RoleType::A));
makeSelected(a->roleWidget(Uml::RoleType::B));
makeSelected(a->changeabilityWidget(Uml::RoleType::A));
makeSelected(a->changeabilityWidget(Uml::RoleType::B));
}
}
/**
* Selects all the widgets within an internally kept rectangle.
*/
void UMLScene::selectWidgets(qreal px, qreal py, qreal qx, qreal qy)
{
clearSelected();
QRectF rect;
if (px <= qx) {
rect.setLeft(px);
rect.setRight(qx);
} else {
rect.setLeft(qx);
rect.setRight(px);
}
if (py <= qy) {
rect.setTop(py);
rect.setBottom(qy);
} else {
rect.setTop(qy);
rect.setBottom(py);
}
// Select UMLWidgets that fall within the selection rectangle
for(UMLWidget *temp : widgetList()) {
uIgnoreZeroPointer(temp);
selectWidget(temp, &rect);
}
// Select messages that fall within the selection rectangle
for(MessageWidget *temp : messageList()) {
selectWidget(temp->asUMLWidget(), &rect);
}
// Select associations of selected widgets
selectAssociations(true);
// Automatically select all messages if two object widgets are selected
for(MessageWidget *w : messageList()) {
if (w->objectWidget(Uml::RoleType::A) &&
w->objectWidget(Uml::RoleType::B) &&
w->objectWidget(Uml::RoleType::A)->isSelected() &&
w->objectWidget(Uml::RoleType::B)->isSelected()) {
makeSelected(w);
}
}
}
/**
* Select a single widget
*
* If QRectF* rect is provided, the selection is only made if the widget is
* visible within the rectangle.
*/
void UMLScene::selectWidget(UMLWidget* widget, QRectF* rect)
{
if (rect == nullptr) {
makeSelected(widget);
return;
}
int x = widget->x();
int y = widget->y();
int w = widget->width();
int h = widget->height();
QRectF rect2(x, y, w, h);
//see if any part of widget is in the rectangle
if (!rect->intersects(rect2)) {
return;
}
//if it is text that is part of an association then select the association
//and the objects that are connected to it.
if (widget->isTextWidget()) {
FloatingTextWidget *ft = widget->asFloatingTextWidget();
Uml::TextRole::Enum t = ft->textRole();
LinkWidget *lw = ft->link();
MessageWidget * mw = dynamic_cast<MessageWidget*>(lw);
if (mw) {
makeSelected(mw);
} else if (t != Uml::TextRole::Floating) {
AssociationWidget * a = dynamic_cast<AssociationWidget*>(lw);
if (a)
selectWidgetsOfAssoc(a);
}
} else if (widget->isMessageWidget()) {
MessageWidget *mw = widget->asMessageWidget();
makeSelected(mw);
}
if (widget->isVisible()) {
makeSelected(widget);
}
}
/**
* Selects all the widgets from a list.
*/
void UMLScene::selectWidgets(UMLWidgetList &widgets)
{
for(UMLWidget *widget : widgets)
makeSelected(widget);
}
/**
* Returns the PNG picture of the paste operation.
* @param diagram the class to store PNG picture of the paste operation.
* @param rect the area of the diagram to copy
*/
void UMLScene::getDiagram(QPixmap &diagram, const QRectF &rect)
{
logDebug4("UMLScene::getDiagram pixmap(w=%1 h=%2) / copyArea(w=%3 h=%4)",
diagram.rect().width(), diagram.rect().height(),
rect.width(), rect.height());
QPainter painter(&diagram);
painter.fillRect(0, 0, rect.width(), rect.height(), Qt::white);
getDiagram(painter, rect);
}
/**
* Paint diagram to the paint device
* @param painter the QPainter to which the diagram is painted
* @param source the area of the diagram to copy
* @param target the rect where to paint into
*/
void UMLScene::getDiagram(QPainter &painter, const QRectF &source, const QRectF &target)
{
DEBUG() << "UMLScene::getDiagram painter=" << painter.window() << ", source=" << source << ", target=" << target; //@todo logDebug
//TODO unselecting and selecting later doesn't work now as the selection is
//cleared in UMLSceneImageExporter. Check if the anything else than the
//following is needed and, if it works, remove the clearSelected in
//UMLSceneImageExporter and UMLSceneImageExporterModel
UMLWidgetList selected = selectedWidgets();
for(UMLWidget *widget : selected) {
widget->setSelected(false);
}
AssociationWidgetList selectedAssociationsList = selectedAssocs();
for(AssociationWidget *association : selectedAssociationsList) {
association->setSelected(false);
}
// we don't want to get the grid
bool showSnapGrid = isSnapGridVisible();
setSnapGridVisible(false);
const int sourceMargin = 1;
QRectF alignedSource(source);
alignedSource.adjust(-sourceMargin, -sourceMargin, sourceMargin, sourceMargin);
logDebug0("UMLScene::getDiagram TODO: Check if this render method is identical to canvas()->drawArea()");
// [PORT]
render(&painter, target, alignedSource, Qt::KeepAspectRatio);
setSnapGridVisible(showSnapGrid);
//select again
for(UMLWidget *widget : selected) {
widget->setSelected(true);
}
for(AssociationWidget *association : selectedAssociationsList) {
association->setSelected(true);
}
}
/**
* Returns the imageExporter used to export the view.
*
* @return The imageExporter used to export the view.
*/
UMLViewImageExporter* UMLScene::getImageExporter()
{
return m_pImageExporter;
}
/**
* makes this view the active view by asking the document to show us
*/
void UMLScene::slotActivate()
{
m_doc->changeCurrentView(ID());
}
/**
* Activate all the objects and associations after a load from the clipboard
*/
void UMLScene::activate()
{
//Activate Regular widgets then activate messages
for(UMLWidget *obj : widgetList()) {
uIgnoreZeroPointer(obj);
//If this UMLWidget is already activated or is a MessageWidget then skip it
if (obj->isActivated() || obj->isMessageWidget()) {
continue;
}
if (obj->activate()) {
obj->setVisible(true);
} else {
removeItem(obj);
delete obj;
}
}
//Activate Message widgets
for(UMLWidget *obj : messageList()) {
//If this MessageWidget is already activated then skip it
if (obj->isActivated())
continue;
obj->activate(m_doc->changeLog());
obj->setVisible(true);
}
// Activate all association widgets
for(AssociationWidget *aw : associationList()) {
if (aw->activate()) {
if (m_PastePoint.x() != 0) {
int x = m_PastePoint.x() - m_pos.x();
int y = m_PastePoint.y() - m_pos.y();
aw->moveEntireAssoc(x, y);
}
} else {
removeWidgetCmd(aw);
delete aw;
}
}
}
/**
* Return the amount of widgets selected.
*
* @param filterText When true, do NOT count floating text widgets that
* belong to other widgets (i.e. only count TextRole::Floating.)
* Default: Count all widgets.
* @return Number of widgets selected.
*/
int UMLScene::selectedCount(bool filterText) const
{
if (!filterText)
return selectedWidgets().count();
int counter = 0;
for(UMLWidget *temp : selectedWidgets()) {
if (temp->isTextWidget()) {
const FloatingTextWidget *ft = static_cast<const FloatingTextWidget*>(temp);
if (ft->textRole() == TextRole::Floating)
counter++;
} else {
counter++;
}
}
return counter;
}
/**
* Fills the List with all the selected widgets from the diagram
* The list can be filled with all the selected widgets, or be filtered to prevent
* text widgets other than tr_Floating to be append.
*
* @param filterText Don't append the text unless their role is TextRole::Floating
* @return The UMLWidgetList to fill.
*/
UMLWidgetList UMLScene::selectedWidgetsExt(bool filterText /*= true*/)
{
UMLWidgetList widgetList;
for(UMLWidget *widgt : selectedWidgets()) {
if (filterText && widgt->isTextWidget()) {
FloatingTextWidget *ft = widgt->asFloatingTextWidget();
if (ft->textRole() == Uml::TextRole::Floating)
widgetList.append(widgt);
} else {
widgetList.append(widgt);
}
}
return widgetList;
}
/**
* Returns a list with all the selected associations from the diagram
*/
AssociationWidgetList UMLScene::selectedAssocs()
{
AssociationWidgetList assocWidgetList;
for(AssociationWidget *assocwidget : associationList()) {
if (assocwidget->isSelected())
assocWidgetList.append(assocwidget);
}
return assocWidgetList;
}
/**
* Adds a floating text widget to the view
*/
void UMLScene::addFloatingTextWidget(FloatingTextWidget* pWidget)
{
/* We cannot do the range check like this:
pWidget's x() and y() can legitimately be negative.
The scene's origin point (0,0) is somewhere in the middle of the diagram
area. QGraphicsItems located left or up from the scene's origin have
negative coordinates.
sceneRect() returns non negative coordinates such as (0,0,5000,5000).
That does not fit with the negative widget coordinates. */
#if 0
int wX = pWidget->x();
int wY = pWidget->y();
bool xIsOutOfRange = (wX < sceneRect().left() || wX > sceneRect().right());
bool yIsOutOfRange = (wY < sceneRect().top() || wY > sceneRect().bottom());
if (xIsOutOfRange || yIsOutOfRange) {
QString name = pWidget->name();
if (name.isEmpty()) {
FloatingTextWidget *ft = pWidget->asFloatingTextWidget();
if (ft)
name = ft->displayText();
}
logDebug4("UMLScene::addFloatingTextWidget(%1) type=%2 : position (%3,%4) is out of range",
name, pWidget->baseTypeStr(), wX, wY);
if (xIsOutOfRange) {
pWidget->setX(0);
wX = 0;
}
if (yIsOutOfRange) {
pWidget->setY(0);
wY = 0;
}
}
#endif
addWidgetCmd(pWidget);
}
/**
* Adds an association to the view from the given data.
* Use this method when pasting.
*/
bool UMLScene::addAssociation(AssociationWidget* pAssoc, bool isPasteOperation)
{
if (!pAssoc) {
return false;
}
const Uml::AssociationType::Enum assocType = pAssoc->associationType();
if (isPasteOperation) {
IDChangeLog * log = m_doc->changeLog();
if (!log) {
return false;
}
Uml::ID::Type ida = Uml::ID::None, idb = Uml::ID::None;
if (type() == DiagramType::Collaboration || type() == DiagramType::Sequence) {
//check local log first
ida = m_pIDChangesLog->findNewID(pAssoc->widgetIDForRole(Uml::RoleType::A));
idb = m_pIDChangesLog->findNewID(pAssoc->widgetIDForRole(Uml::RoleType::B));
//if either is still not found and assoc type is anchor
//we are probably linking to a notewidet - else an error
if (ida == Uml::ID::None && assocType == Uml::AssociationType::Anchor)
ida = log->findNewID(pAssoc->widgetIDForRole(Uml::RoleType::A));
if (idb == Uml::ID::None && assocType == Uml::AssociationType::Anchor)
idb = log->findNewID(pAssoc->widgetIDForRole(Uml::RoleType::B));
} else {
Uml::ID::Type oldIdA = pAssoc->widgetIDForRole(Uml::RoleType::A);
Uml::ID::Type oldIdB = pAssoc->widgetIDForRole(Uml::RoleType::B);
ida = log->findNewID(oldIdA);
if (ida == Uml::ID::None) { // happens after a cut
if (oldIdA == Uml::ID::None) {
return false;
}
ida = oldIdA;
}
idb = log->findNewID(oldIdB);
if (idb == Uml::ID::None) { // happens after a cut
if (oldIdB == Uml::ID::None) {
return false;
}
idb = oldIdB;
}
}
if (ida == Uml::ID::None || idb == Uml::ID::None) {
return false;
}
// cant do this anymore.. may cause problem for pasting
// pAssoc->setWidgetID(ida, A);
// pAssoc->setWidgetID(idb, B);
pAssoc->setWidgetForRole(findWidget(ida), Uml::RoleType::A);
pAssoc->setWidgetForRole(findWidget(idb), Uml::RoleType::B);
}
UMLWidget * pWidgetA = findWidget(pAssoc->widgetIDForRole(Uml::RoleType::A));
UMLWidget * pWidgetB = findWidget(pAssoc->widgetIDForRole(Uml::RoleType::B));
//make sure valid widget ids
if (!pWidgetA || !pWidgetB) {
return false;
}
//make sure there isn't already the same assoc
for(AssociationWidget *assocwidget : associationList()) {
if (*pAssoc == *assocwidget)
// this is nuts. Paste operation wants to know if 'true'
// for duplicate, but loadFromXMI needs 'false' value
return (isPasteOperation ? true : false);
}
addWidgetCmd(pAssoc);
FloatingTextWidget *ft[5] = { pAssoc->nameWidget(),
pAssoc->roleWidget(Uml::RoleType::A),
pAssoc->roleWidget(Uml::RoleType::B),
pAssoc->multiplicityWidget(Uml::RoleType::A),
pAssoc->multiplicityWidget(Uml::RoleType::B)
};
for (int i = 0; i < 5; i++) {
FloatingTextWidget *flotxt = ft[i];
if (flotxt) {
flotxt->updateGeometry();
addFloatingTextWidget(flotxt);
}
}
return true;
}
/**
* Activate the view after a load a new file
*/
void UMLScene::activateAfterLoad(bool bUseLog)
{
if (m_isActivated) {
return;
}
if (bUseLog) {
beginPartialWidgetPaste();
}
//now activate them all
activate();
if (bUseLog) {
endPartialWidgetPaste();
}
m_view->centerOn(0, 0);
m_isActivated = true;
}
void UMLScene::beginPartialWidgetPaste()
{
delete m_pIDChangesLog;
m_pIDChangesLog = nullptr;
m_pIDChangesLog = new IDChangeLog();
m_bPaste = true;
}
void UMLScene::endPartialWidgetPaste()
{
delete m_pIDChangesLog;
m_pIDChangesLog = nullptr;
m_bPaste = false;
}
/**
* Removes an AssociationWidget from a diagram
* Physically deletes the AssociationWidget passed in.
*
* @param pAssoc Pointer to the AssociationWidget.
*/
void UMLScene::removeWidgetCmd(AssociationWidget* pAssoc)
{
if (!pAssoc)
return;
Q_EMIT sigAssociationRemoved(pAssoc);
pAssoc->cleanup();
removeItem(pAssoc);
pAssoc->deleteLater();
m_doc->setModified();
}
/**
* Removes an AssociationWidget from the association list
* and removes the corresponding UMLAssociation from the current UMLDoc.
*/
void UMLScene::removeAssocInViewAndDoc(AssociationWidget* a)
{
// For umbrello 1.2, UMLAssociations can only be removed in two ways:
// 1. Right click on the assocwidget in the view and select Delete
// 2. Go to the Class Properties page, select Associations, right click
// on the association and select Delete
if (!a)
return;
if (a->associationType() == Uml::AssociationType::Containment) {
UMLObject *objToBeMoved = a->widgetForRole(Uml::RoleType::B)->umlObject();
if (objToBeMoved != nullptr) {
UMLListView *lv = UMLApp::app()->listView();
lv->moveObject(objToBeMoved->id(),
Model_Utils::convert_OT_LVT(objToBeMoved),
lv->theLogicalView());
// UMLListView::moveObject() will delete the containment
// AssociationWidget via UMLScene::updateContainment().
} else {
logDebug0("UMLScene::removeAssocInViewAndDoc(containment): objB is NULL");
}
} else {
// Remove assoc in doc.
m_doc->removeAssociation(a->association());
// Remove assoc in view.
removeWidgetCmd(a);
}
}
/**
* Removes all the associations related to Widget.
*
* @param widget Pointer to the widget to remove.
*/
void UMLScene::removeAssociations(UMLWidget* widget)
{
for(AssociationWidget *assocwidget : associationList()) {
if (assocwidget->containsAsEndpoint(widget)) {
removeWidgetCmd(assocwidget);
}
}
}
/**
* Sets each association as selected if the widgets it associates are selected
*
* @param bSelect True to select, false for unselect
*/
void UMLScene::selectAssociations(bool bSelect)
{
for(AssociationWidget *assocwidget : associationList()) {
UMLWidget *widA = assocwidget->widgetForRole(Uml::RoleType::A);
UMLWidget *widB = assocwidget->widgetForRole(Uml::RoleType::B);
if (bSelect &&
widA && widA->isSelected() &&
widB && widB->isSelected()) {
assocwidget->setSelected(true);
} else {
assocwidget->setSelected(false);
}
}
}
/**
* Fills Associations with all the associations that includes a widget related to object
*/
void UMLScene::getWidgetAssocs(UMLObject* Obj, AssociationWidgetList & Associations)
{
if (! Obj)
return;
for(AssociationWidget *assocwidget : associationList()) {
if (assocwidget->widgetForRole(Uml::RoleType::A)->umlObject() == Obj ||
assocwidget->widgetForRole(Uml::RoleType::B)->umlObject() == Obj)
Associations.append(assocwidget);
}
}
/**
* Removes All the associations of the diagram
*/
void UMLScene::removeAllAssociations()
{
//Remove All association widgets
for(AssociationWidget *assocwidget : associationList()) {
removeWidgetCmd(assocwidget);
}
}
/**
* Removes All the widgets of the diagram
*/
void UMLScene::removeAllWidgets()
{
// Remove widgets.
for(UMLWidget *temp : widgetList()) {
uIgnoreZeroPointer(temp);
// I had to take this condition back in, else umbrello
// crashes on exit. Still to be analyzed. --okellogg
if (!(temp->isTextWidget() &&
temp->asFloatingTextWidget()->textRole() != TextRole::Floating)) {
removeWidgetCmd(temp);
}
}
}
/**
* Refreshes containment association, i.e. removes possible old
* containment and adds new containment association if applicable.
*
* @param self Pointer to the contained object for which
* the association to the containing object is
* recomputed.
*/
void UMLScene::updateContainment(UMLCanvasObject *self)
{
if (self == nullptr)
return;
// See if the object has a widget representation in this view.
// While we're at it, also see if the new parent has a widget here.
UMLWidget *selfWidget = nullptr, *newParentWidget = nullptr;
UMLPackage *newParent = self->umlPackage();
for(UMLWidget *w : widgetList()) {
UMLObject *o = w->umlObject();
if (o == self)
selfWidget = w;
else if (newParent != nullptr && o == newParent)
newParentWidget = w;
}
if (selfWidget == nullptr)
return;
// Remove possibly obsoleted containment association.
for(AssociationWidget *a : associationList()) {
if (a->associationType() != Uml::AssociationType::Containment)
continue;
// Container is at role A, containee at B.
// We only look at association for which we are B.
UMLWidget *wB = a->widgetForRole(Uml::RoleType::B);
UMLObject *roleBObj = wB->umlObject();
if (roleBObj != self)
continue;
UMLWidget *wA = a->widgetForRole(Uml::RoleType::A);
UMLObject *roleAObj = wA->umlObject();
if (roleAObj == newParent) {
// Wow, all done. Great!
return;
}
removeWidgetCmd(a);
// It's okay to break out because there can only be a single
// containing object.
break;
}
if (newParentWidget == nullptr)
return;
// Create the new containment association.
AssociationWidget *a = AssociationWidget::create
(this, newParentWidget,
Uml::AssociationType::Containment, selfWidget);
addWidgetCmd(a);
}
/**
* Creates automatically any Associations that the given @ref UMLWidget
* may have on any diagram. This method is used when you just add the UMLWidget
* to a diagram.
*/
void UMLScene::createAutoAssociations(UMLWidget * widget)
{
if (widget == nullptr ||
(m_Type != Uml::DiagramType::Class &&
m_Type != Uml::DiagramType::Object &&
m_Type != Uml::DiagramType::Component &&
m_Type != Uml::DiagramType::Deployment
&& m_Type != Uml::DiagramType::EntityRelationship))
return;
// Recipe:
// If this widget has an underlying UMLCanvasObject then
// for each of the UMLCanvasObject's UMLAssociations
// if umlassoc's "other" role has a widget representation on this view then
// if the AssocWidget does not already exist then
// if the assoc type is permitted in the current diagram type then
// create the AssocWidget
// end if
// end if
// end if
// end loop
// Do createAutoAttributeAssociations()
// if this object is capable of containing nested objects then
// for each of the object's containedObjects
// if the containedObject has a widget representation on this view then
// if the containedWidget is not physically located inside this widget
// create the containment AssocWidget
// end if
// end if
// end loop
// end if
// if the UMLCanvasObject has a parentPackage then
// if the parentPackage has a widget representation on this view then
// create the containment AssocWidget
// end if
// end if
// end if
UMLObject *tmpUmlObj = widget->umlObject();
if (tmpUmlObj == nullptr)
return;
const UMLCanvasObject *umlObj = tmpUmlObj->asUMLCanvasObject();
if (umlObj == nullptr)
return;
const UMLAssociationList& umlAssocs = umlObj->getAssociations();
Uml::ID::Type myID = umlObj->id();
for(UMLAssociation *assoc : umlAssocs) {
UMLCanvasObject *other = nullptr;
UMLObject *roleAObj = assoc->getObject(Uml::RoleType::A);
if (roleAObj == nullptr) {
logDebug1("UMLScene::createAutoAssociations: roleA object is NULL at UMLAssoc %1",
Uml::ID::toString(assoc->id()));
continue;
}
UMLObject *roleBObj = assoc->getObject(Uml::RoleType::B);
if (roleBObj == nullptr) {
logDebug1("UMLScene::createAutoAssociations: roleB object is NULL at UMLAssoc %1",
Uml::ID::toString(assoc->id()));
continue;
}
if (roleAObj->id() == myID) {
other = roleBObj->asUMLCanvasObject();
} else if (roleBObj->id() == myID) {
other = roleAObj->asUMLCanvasObject();
} else {
logDebug2("UMLScene::createAutoAssociations: Cannot find own object %1 in UMLAssoc %2",
Uml::ID::toString(myID), Uml::ID::toString(assoc->id()));
continue;
}
// Now that we have determined the "other" UMLObject, seek it in
// this view's UMLWidgets.
if (!other) {
continue;
}
Uml::ID::Type otherID = other->id();
bool breakFlag = false;
UMLWidget *pOtherWidget = nullptr;
for(UMLWidget *pOtherWidget: widgetList()) {
if (pOtherWidget->id() == otherID) {
breakFlag = true;
break;
}
}
if (!breakFlag)
continue;
// Both objects are represented in this view:
// Assign widget roles as indicated by the UMLAssociation.
UMLWidget *widgetA, *widgetB;
if (myID == roleAObj->id()) {
widgetA = widget;
widgetB = pOtherWidget;
} else {
widgetA = pOtherWidget;
widgetB = widget;
}
// Check that the assocwidget does not already exist.
Uml::AssociationType::Enum assocType = assoc->getAssocType();
AssociationWidget * assocwidget = findAssocWidget(assocType, widgetA, widgetB);
if (assocwidget) {
assocwidget->calculateEndingPoints(); // recompute assoc lines
continue;
}
// Check that the assoc is allowed.
if (!AssocRules::allowAssociation(assocType, widgetA, widgetB)) {
logDebug1("UMLScene::createAutoAssociations: not transferring assoc of type %1",
assocType);
continue;
}
// Create the AssociationWidget.
assocwidget = AssociationWidget::create(this);
assocwidget->setWidgetForRole(widgetA, Uml::RoleType::A);
assocwidget->setWidgetForRole(widgetB, Uml::RoleType::B);
assocwidget->setAssociationType(assocType);
assocwidget->setUMLObject(assoc);
// Call calculateEndingPoints() before setting the FloatingTexts
// because their positions are computed according to the
// assocwidget line positions.
assocwidget->calculateEndingPoints();
assocwidget->syncToModel();
assocwidget->setActivated(true);
if (! addAssociation(assocwidget))
delete assocwidget;
}
createAutoAttributeAssociations(widget);
if (m_Type == Uml::DiagramType::EntityRelationship) {
createAutoConstraintAssociations(widget);
}
// if this object is capable of containing nested objects then
UMLObject::ObjectType t = umlObj->baseType();
if (t == UMLObject::ot_Package || t == UMLObject::ot_Class ||
t == UMLObject::ot_Interface || t == UMLObject::ot_Component) {
// for each of the object's containedObjects
const UMLPackage *umlPkg = umlObj->asUMLPackage();
UMLObjectList lst = umlPkg->containedObjects();
for(UMLObject *obj : lst) {
uIgnoreZeroPointer(obj);
// if the containedObject has a widget representation on this view then
Uml::ID::Type id = obj->id();
for(UMLWidget *w : widgetList()) {
uIgnoreZeroPointer(w);
if (w->id() != id)
continue;
// if the containedWidget is not physically located inside this widget
if (w->isLocatedIn(widget))
continue;
// create the containment AssocWidget
AssociationWidget *a = AssociationWidget::create(this, widget,
Uml::AssociationType::Containment, w);
a->calculateEndingPoints();
a->setActivated(true);
if (! addAssociation(a))
delete a;
}
}
}
// if the UMLCanvasObject has a parentPackage then
UMLPackage *parent = umlObj->umlPackage();
if (parent == nullptr)
return;
// if the parentPackage has a widget representation on this view then
Uml::ID::Type pkgID = parent->id();
bool breakFlag = false;
UMLWidget *pWidget = nullptr;
for(UMLWidget *pWidget: widgetList()) {
uIgnoreZeroPointer(pWidget);
if (pWidget->id() == pkgID) {
breakFlag = true;
break;
}
}
if (!breakFlag || widget->isLocatedIn(pWidget))
return;
// create the containment AssocWidget
AssociationWidget *a = AssociationWidget::create(this, pWidget, Uml::AssociationType::Containment, widget);
if (! addAssociation(a))
delete a;
}
/**
* If the m_Type of the given widget is WidgetBase::wt_Class then
* iterate through the class' attributes and create an
* association to each attribute type widget that is present
* on the current diagram.
*/
void UMLScene::createAutoAttributeAssociations(UMLWidget *widget)
{
if (widget == nullptr || m_Type != Uml::DiagramType::Class || !m_Options.classState.showAttribAssocs)
return;
// Pseudocode:
// if the underlying model object is really a UMLClassifier then
// for each of the UMLClassifier's UMLAttributes
// if the attribute type has a widget representation on this view then
// if the AssocWidget does not already exist then
// if the current diagram type permits compositions then
// create a composition AssocWidget
// end if
// end if
// end if
// if the attribute type is a Datatype then
// if the Datatype is a reference (pointer) type then
// if the referenced type has a widget representation on this view then
// if the AssocWidget does not already exist then
// if the current diagram type permits aggregations then
// create an aggregation AssocWidget from the ClassifierWidget to the
// widget of the referenced type
// end if
// end if
// end if
// end if
// end if
// end loop
// end if
//
// Implementation:
UMLObject *tmpUmlObj = widget->umlObject();
if (tmpUmlObj == nullptr)
return;
// if the underlying model object is really a UMLClassifier then
if (tmpUmlObj->isUMLDatatype()) {
const UMLDatatype *dt = tmpUmlObj->asUMLDatatype();
while (dt && dt->originType() != nullptr) {
tmpUmlObj = dt->originType();
if (!tmpUmlObj->isUMLDatatype())
break;
dt = tmpUmlObj->asUMLDatatype();
}
}
if (tmpUmlObj->baseType() != UMLObject::ot_Class)
return;
const UMLClassifier * klass = tmpUmlObj->asUMLClassifier();
// for each of the UMLClassifier's UMLAttributes
UMLAttributeList attrList = klass->getAttributeList();
for(UMLAttribute *attr : attrList) {
createAutoAttributeAssociation(attr->getType(), attr, widget);
/*
* The following code from attachment 19935 of https://bugs.kde.org/140669
* creates Aggregation/Composition to the template parameters.
* The current solution uses Dependency instead, see handling of template
* instantiation at Import_Utils::createUMLObject().
UMLClassifierList templateList = attr->getTemplateParams();
for (UMLClassifierListIt it(templateList); it.current(); ++it) {
createAutoAttributeAssociation(it, attr, widget);
}
*/
}
}
/**
* Create an association with the attribute attr associated with the UMLWidget
* widget if the UMLClassifier type is present on the current diagram.
*/
void UMLScene::createAutoAttributeAssociation(UMLClassifier *type, UMLAttribute *attr,
UMLWidget *widget /*, UMLClassifier * klass*/)
{
if (type == nullptr) {
// logDebug2("UMLScene::createAutoAttributeAssociation(%1): type is NULL for attribute %2",
// klass->getName(), attr->getName());
return;
}
Uml::AssociationType::Enum assocType = Uml::AssociationType::Composition;
UMLWidget *w = findWidget(type->id());
// if the attribute type has a widget representation on this view
if (w) {
AssociationWidget *a = findAssocWidget(widget, w, attr->name());
if (a) {
a->setAssociationType(assocType);
} else if (AssocRules::allowAssociation(assocType, widget, w)) {
// Create a composition AssocWidget, or, if the attribute type is
// stereotyped <<CORBAInterface>>, create a UniAssociation widget.
if (type->stereotype() == QStringLiteral("CORBAInterface"))
assocType = Uml::AssociationType::UniAssociation;
a = AssociationWidget::create(this, widget, assocType, w, attr);
a->setVisibility(attr->visibility(), Uml::RoleType::B);
/*
if (assocType == Uml::AssociationType::Aggregation || assocType == Uml::AssociationType::UniAssociation)
a->setMulti("0..1", Uml::RoleType::B);
*/
a->setRoleName(attr->name(), Uml::RoleType::B);
a->setActivated(true);
if (! addAssociation(a))
delete a;
}
}
// if the attribute type is a Datatype then
if (type->isUMLDatatype()) {
const UMLDatatype *dt = type->asUMLDatatype();
// if the Datatype is a reference (pointer) type
if (dt && dt->isReference()) {
UMLClassifier *c = dt->originType();
UMLWidget *w = c ? findWidget(c->id()) : nullptr;
// if the referenced type has a widget representation on this view
if (w) {
Uml::AssociationType::Enum assocType = Uml::AssociationType::Aggregation;
AssociationWidget *a = findAssocWidget(widget, w, attr->name());
if (a) {
a->setAssociationType(assocType);
} else if (AssocRules::allowAssociation(assocType, widget, w)) {
// create an aggregation AssocWidget from the ClassifierWidget
// to the widget of the referenced type
a = AssociationWidget::create (this, widget, assocType, w, attr);
a->setVisibility(attr->visibility(), Uml::RoleType::B);
//a->setChangeability(true, Uml::RoleType::B);
a->setMultiplicity(QStringLiteral("0..1"), Uml::RoleType::B);
a->setRoleName(attr->name(), Uml::RoleType::B);
a->setActivated(true);
if (! addAssociation(a))
delete a;
}
}
}
}
}
void UMLScene::createAutoConstraintAssociations(UMLWidget *widget)
{
if (widget == nullptr || m_Type != Uml::DiagramType::EntityRelationship)
return;
// Pseudocode:
// if the underlying model object is really a UMLEntity then
// for each of the UMLEntity's UMLForeignKeyConstraint's
// if the attribute type has a widget representation on this view then
// if the AssocWidget does not already exist then
// if the current diagram type permits relationships then
// create a relationship AssocWidget
// end if
// end if
// end if
UMLObject *tmpUmlObj = widget->umlObject();
if (tmpUmlObj == nullptr)
return;
// check if the underlying model object is really a UMLEntity
const UMLCanvasObject *umlObj = tmpUmlObj->asUMLCanvasObject();
if (umlObj == nullptr)
return;
// finished checking whether this widget has a UMLCanvas Object
if (tmpUmlObj->baseType() != UMLObject::ot_Entity)
return;
const UMLEntity *entity = tmpUmlObj->asUMLEntity();
// for each of the UMLEntity's UMLForeignKeyConstraints
UMLClassifierListItemList constrList = entity->getFilteredList(UMLObject::ot_ForeignKeyConstraint);
for(UMLClassifierListItem *cli : constrList) {
UMLEntityConstraint *eConstr = cli->asUMLEntityConstraint();
UMLForeignKeyConstraint* fkc = eConstr->asUMLForeignKeyConstraint();
if (fkc == nullptr) {
return;
}
UMLEntity* refEntity = fkc->getReferencedEntity();
if (refEntity == nullptr) {
return;
}
createAutoConstraintAssociation(refEntity, fkc, widget);
}
}
void UMLScene::createAutoConstraintAssociation(UMLEntity* refEntity, UMLForeignKeyConstraint* fkConstraint, UMLWidget* widget)
{
if (refEntity == nullptr) {
return;
}
Uml::AssociationType::Enum assocType = Uml::AssociationType::Relationship;
UMLWidget *w = findWidget(refEntity->id());
AssociationWidget *aw = nullptr;
if (w) {
aw = findAssocWidget(assocType, w, widget);
if (aw) {
if (aw->roleWidget(Uml::RoleType::B))
aw->roleWidget(Uml::RoleType::B)->setName(fkConstraint->name());
else
logError0("UMLScene::createAutoConstraintAssociation could not find role widget B -> cannot rename constraint");
// if the current diagram type permits relationships
} else if (AssocRules::allowAssociation(assocType, w, widget)) {
// for foreign key constraint, we need to create the association type Uml::AssociationType::Relationship.
// The referenced entity is the "1" part (Role A) and the entity holding the relationship is the "many" part. (Role B)
AssociationWidget *a = AssociationWidget::create(this, w, assocType, widget);
a->setUMLObject(fkConstraint);
//a->setVisibility(attr->getVisibility(), Uml::RoleType::B);
a->setRoleName(fkConstraint->name(), Uml::RoleType::B);
a->setActivated(true);
if (! addAssociation(a))
delete a;
}
}
}
void UMLScene::createAutoAttributeAssociations2(UMLWidget *widget)
{
for(UMLWidget *w : widgetList()) {
uIgnoreZeroPointer(w);
if (w != widget) {
createAutoAttributeAssociations(w);
if (widget->umlObject() && widget->umlObject()->baseType() == UMLObject::ot_Entity)
createAutoConstraintAssociations(w);
}
}
}
/**
* Find the maximum bounding rectangle of FloatingTextWidget widgets.
* Auxiliary to copyAsImage().
*
* @param ft Pointer to the FloatingTextWidget widget to consider.
* @param px X coordinate of lower left corner. This value will be
* updated if the X coordinate of the lower left corner
* of ft is smaller than the px value passed in.
* @param py Y coordinate of lower left corner. This value will be
* updated if the Y coordinate of the lower left corner
* of ft is smaller than the py value passed in.
* @param qx X coordinate of upper right corner. This value will be
* updated if the X coordinate of the upper right corner
* of ft is larger than the qx value passed in.
* @param qy Y coordinate of upper right corner. This value will be
* updated if the Y coordinate of the upper right corner
* of ft is larger than the qy value passed in.
*/
void UMLScene::findMaxBoundingRectangle(const FloatingTextWidget* ft, qreal& px, qreal& py, qreal& qx, qreal& qy)
{
if (ft == nullptr || !ft->isVisible())
return;
qreal x = ft->x();
qreal y = ft->y();
qreal x1 = x + ft->width() - 1;
qreal y1 = y + ft->height() - 1;
if (px == -1 || x < px)
px = x;
if (py == -1 || y < py)
py = y;
if (qx == -1 || x1 > qx)
qx = x1;
if (qy == -1 || y1 > qy)
qy = y1;
}
/**
* Returns the PNG picture of the paste operation.
*/
void UMLScene::copyAsImage(QPixmap*& pix)
{
//get the smallest rect holding the diagram
QRectF rect = diagramRect();
QPixmap diagram(rect.width(), rect.height());
//only draw what is selected
m_bDrawSelectedOnly = true;
selectAssociations(true);
getDiagram(diagram, rect);
//now get the selection cut
qreal px = -1, py = -1, qx = -1, qy = -1;
//first get the smallest rect holding the widgets
for(UMLWidget *temp : selectedWidgets()) {
qreal x = temp->x();
qreal y = temp->y();
qreal x1 = x + temp->width() - 1;
qreal y1 = y + temp->height() - 1;
if (px == -1 || x < px) {
px = x;
}
if (py == -1 || y < py) {
py = y;
}
if (qx == -1 || x1 > qx) {
qx = x1;
}
if (qy == -1 || y1 > qy) {
qy = y1;
}
}
//also take into account any text lines in assocs or messages
//get each type of associations
//This needs to be reimplemented to increase the rectangle
//if a part of any association is not included
for(AssociationWidget *a : associationList()) {
if (! a->isSelected())
continue;
const FloatingTextWidget* multiA = a->multiplicityWidget(Uml::RoleType::A);
const FloatingTextWidget* multiB = a->multiplicityWidget(Uml::RoleType::B);
const FloatingTextWidget* roleA = a->roleWidget(Uml::RoleType::A);
const FloatingTextWidget* roleB = a->roleWidget(Uml::RoleType::B);
const FloatingTextWidget* changeA = a->changeabilityWidget(Uml::RoleType::A);
const FloatingTextWidget* changeB = a->changeabilityWidget(Uml::RoleType::B);
findMaxBoundingRectangle(multiA, px, py, qx, qy);
findMaxBoundingRectangle(multiB, px, py, qx, qy);
findMaxBoundingRectangle(roleA, px, py, qx, qy);
findMaxBoundingRectangle(roleB, px, py, qx, qy);
findMaxBoundingRectangle(changeA, px, py, qx, qy);
findMaxBoundingRectangle(changeB, px, py, qx, qy);
}
QRectF imageRect; //area with respect to diagramRect()
//i.e. all widgets on the scene. Was previously with
//respect to whole scene
imageRect.setLeft(px - rect.left());
imageRect.setTop(py - rect.top());
imageRect.setRight(qx - rect.left());
imageRect.setBottom(qy - rect.top());
pix = new QPixmap(imageRect.width(), imageRect.height());
QPainter output(pix);
output.drawPixmap(QPoint(0, 0), diagram, imageRect);
m_bDrawSelectedOnly = false;
}
/**
* Reset the toolbar.
*/
void UMLScene::resetToolbar()
{
Q_EMIT sigResetToolBar();
}
void UMLScene::triggerToolbarButton(WorkToolBar::ToolBar_Buttons button)
{
m_d->triggerToolBarButton(button);
}
/**
* Event handler for context menu events.
*/
void UMLScene::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
{
QGraphicsScene::contextMenuEvent(event);
if (!event->isAccepted()) {
setPos(event->scenePos());
UMLScenePopupMenu popup(m_view, this);
QAction *triggered = popup.exec(event->screenPos());
slotMenuSelection(triggered);
event->accept();
}
}
/**
* Returns the status on whether in a paste state.
*
* @return Returns the status on whether in a paste state.
*/
bool UMLScene::getPaste() const
{
return m_bPaste;
}
/**
* Sets the status on whether in a paste state.
*/
void UMLScene::setPaste(bool paste)
{
m_bPaste = paste;
}
/**
* When a menu selection has been made on the menu
* that this view created, this method gets called.
*/
void UMLScene::slotMenuSelection(QAction* action)
{
ListPopupMenu::MenuType sel = ListPopupMenu::typeFromAction(action);
switch (sel) {
case ListPopupMenu::mt_Undo:
UMLApp::app()->undo();
break;
case ListPopupMenu::mt_Redo:
UMLApp::app()->redo();
break;
case ListPopupMenu::mt_Clear:
clearDiagram();
break;
case ListPopupMenu::mt_Export_Image:
m_pImageExporter->exportView();
break;
case ListPopupMenu::mt_Apply_Layout:
case ListPopupMenu::mt_Apply_Layout1:
case ListPopupMenu::mt_Apply_Layout2:
case ListPopupMenu::mt_Apply_Layout3:
case ListPopupMenu::mt_Apply_Layout4:
case ListPopupMenu::mt_Apply_Layout5:
case ListPopupMenu::mt_Apply_Layout6:
case ListPopupMenu::mt_Apply_Layout7:
case ListPopupMenu::mt_Apply_Layout8:
case ListPopupMenu::mt_Apply_Layout9:
{
QVariant value = ListPopupMenu::dataFromAction(ListPopupMenu::dt_ApplyLayout, action);
applyLayout(value.toString());
}
break;
case ListPopupMenu::mt_FloatText:
{
FloatingTextWidget* ft = new FloatingTextWidget(this);
ft->showChangeTextDialog();
//if no text entered delete
if (!FloatingTextWidget::isTextValid(ft->text())) {
delete ft;
} else {
ft->setID(UniqueID::gen());
setupNewWidget(ft);
}
}
break;
case ListPopupMenu::mt_UseCase:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_UseCase);
break;
case ListPopupMenu::mt_Actor:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Actor);
break;
case ListPopupMenu::mt_Class:
case ListPopupMenu::mt_Object:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Class);
break;
case ListPopupMenu::mt_Package:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Package);
break;
case ListPopupMenu::mt_Subsystem:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_SubSystem);
break;
case ListPopupMenu::mt_Component:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Component);
break;
case ListPopupMenu::mt_Node:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Node);
break;
case ListPopupMenu::mt_Artifact:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Artifact);
break;
case ListPopupMenu::mt_Interface:
case ListPopupMenu::mt_InterfaceComponent:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Interface);
break;
case ListPopupMenu::mt_Enum:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Enum);
break;
case ListPopupMenu::mt_Entity:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Entity);
break;
case ListPopupMenu::mt_Category:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Category);
break;
case ListPopupMenu::mt_Datatype:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Datatype);
break;
case ListPopupMenu::mt_Instance:
m_bCreateObject = true;
Object_Factory::createUMLObject(UMLObject::ot_Instance);
break;
case ListPopupMenu::mt_Note: {
m_bCreateObject = true;
UMLWidget* widget = new NoteWidget(this);
addItem(widget);
widget->setPos(pos());
widget->setSize(100, 40);
widget->showPropertiesDialog();
QSizeF size = widget->minimumSize();
widget->setSize(size);
break;
}
case ListPopupMenu::mt_Cut:
//FIXME make this work for diagram's right click menu
if (selectedWidgets().count() &&
UMLApp::app()->editCutCopy(true)) {
deleteSelection();
m_doc->setModified(true);
}
break;
case ListPopupMenu::mt_Copy:
//FIXME make this work for diagram's right click menu
selectedWidgets().count() && UMLApp::app()->editCutCopy(true);
break;
case ListPopupMenu::mt_Paste:
m_PastePoint = m_pos;
m_pos.setX(2000);
m_pos.setY(2000);
UMLApp::app()->slotEditPaste();
m_PastePoint.setX(0);
m_PastePoint.setY(0);
break;
case ListPopupMenu::mt_Initial_State:
{
StateWidget* state = new StateWidget(this, StateWidget::Initial);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_End_State:
{
StateWidget* state = new StateWidget(this, StateWidget::End);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_Junction:
{
StateWidget* state = new StateWidget(this, StateWidget::Junction);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_DeepHistory:
{
StateWidget* state = new StateWidget(this, StateWidget::DeepHistory);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_ShallowHistory:
{
StateWidget* state = new StateWidget(this, StateWidget::ShallowHistory);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_Choice:
{
StateWidget* state = new StateWidget(this, StateWidget::Choice);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_StateFork:
{
StateWidget* state = new StateWidget(this, StateWidget::Fork);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_StateJoin:
{
StateWidget* state = new StateWidget(this, StateWidget::Join);
setupNewWidget(state);
}
break;
case ListPopupMenu::mt_State:
{
QString name = Widget_Utils::defaultWidgetName(WidgetBase::WidgetType::wt_State);
bool ok = Dialog_Utils::askNewName(WidgetBase::WidgetType::wt_State, name);
if (ok) {
StateWidget* state = new StateWidget(this);
state->setName(name);
setupNewWidget(state);
}
}
break;
case ListPopupMenu::mt_CombinedState:
{
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) {
StateWidget* state = new StateWidget(this);
state->setName(name);
setupNewWidget(state);
Uml::CmdCreateDiagram* d = new Uml::CmdCreateDiagram(m_doc, Uml::DiagramType::State, name);
UMLApp::app()->executeCommand(d);
state->setDiagramLink(d->view()->umlScene()->ID());
d->view()->umlScene()->setWidgetLink(state);
state->setStateType(StateWidget::Combined);
}
}
break;
case ListPopupMenu::mt_ReturnToClass:
case ListPopupMenu::mt_ReturnToCombinedState:
if (widgetLink()) {
UMLApp::app()->document()->changeCurrentView(widgetLink()->umlScene()->ID());
widgetLink()->update();
widgetLink()->umlScene()->update();
setWidgetLink(nullptr);
}
break;
case ListPopupMenu::mt_Initial_Activity:
{
ActivityWidget* activity = new ActivityWidget(this, ActivityWidget::Initial);
setupNewWidget(activity);
}
break;
case ListPopupMenu::mt_End_Activity:
{
ActivityWidget* activity = new ActivityWidget(this, ActivityWidget::End);
setupNewWidget(activity);
}
break;
case ListPopupMenu::mt_Branch:
{
ActivityWidget* activity = new ActivityWidget(this, ActivityWidget::Branch);
setupNewWidget(activity);
}
break;
case ListPopupMenu::mt_Activity:
{
QString name;
bool ok = Dialog_Utils::askDefaultNewName(WidgetBase::wt_Activity, name);
if (ok) {
ActivityWidget* activity = new ActivityWidget(this, ActivityWidget::Normal);
activity->setName(name);
setupNewWidget(activity);
}
}
break;
case ListPopupMenu::mt_SnapToGrid:
toggleSnapToGrid();
m_doc->setModified();
break;
case ListPopupMenu::mt_SnapComponentSizeToGrid:
toggleSnapComponentSizeToGrid();
m_doc->setModified();
break;
case ListPopupMenu::mt_ShowSnapGrid:
toggleShowGrid();
m_doc->setModified();
break;
case ListPopupMenu::mt_ShowDocumentationIndicator:
setShowDocumentationIndicator(!isShowDocumentationIndicator());
update();
break;
case ListPopupMenu::mt_Properties:
if (m_view->showPropertiesDialog() == true)
m_doc->setModified();
break;
case ListPopupMenu::mt_Delete:
m_doc->removeDiagram(ID());
break;
case ListPopupMenu::mt_Rename:
{
QString newName = name();
bool ok = Dialog_Utils::askName(i18n("Enter Diagram Name"),
i18n("Enter the new name of the diagram:"),
newName);
if (ok) {
setName(newName);
m_doc->signalDiagramRenamed(activeView());
}
}
break;
case ListPopupMenu::mt_Import_from_File:
{
QPointer<UMLFileDialog> dialog = new UMLFileDialog(QUrl(), QString(), UMLApp::app());
dialog->exec();
QUrl url = dialog->selectedUrl();
if (!url.isEmpty())
if (!Diagram_Utils::importGraph(url.toLocalFile(), this))
UMLApp::app()->slotStatusMsg(i18n("Failed to import from file."));
break;
}
case ListPopupMenu::mt_MessageCreation:
m_d->triggerToolBarButton(WorkToolBar::tbb_Seq_Message_Creation);
break;
case ListPopupMenu::mt_MessageDestroy:
m_d->triggerToolBarButton(WorkToolBar::tbb_Seq_Message_Destroy);
break;
case ListPopupMenu::mt_MessageSynchronous:
m_d->triggerToolBarButton(WorkToolBar::tbb_Seq_Message_Synchronous);
break;
case ListPopupMenu::mt_MessageAsynchronous:
m_d->triggerToolBarButton(WorkToolBar::tbb_Seq_Message_Asynchronous);
break;
case ListPopupMenu::mt_MessageFound:
m_d->triggerToolBarButton(WorkToolBar::tbb_Seq_Message_Found);
break;
case ListPopupMenu::mt_MessageLost:
m_d->triggerToolBarButton(WorkToolBar::tbb_Seq_Message_Lost);
break;
default:
logWarn1("UMLScene::slotMenuSelection: unknown ListPopupMenu::MenuType %1",
ListPopupMenu::toString(sel));
break;
}
}
/**
* Connects to the signal that @ref UMLApp emits when a cut operation
* is successful.
* If the view or a child started the operation the flag m_bStartedCut will
* be set and we can carry out any operation that is needed, like deleting the selected
* widgets for the cut operation.
*/
void UMLScene::slotCutSuccessful()
{
if (m_bStartedCut) {
deleteSelection();
m_bStartedCut = false;
}
}
/**
* Called by menu when to show the instance of the view.
*/
void UMLScene::slotShowView()
{
m_doc->changeCurrentView(ID());
}
/**
* Returns the offset point at which to place the paste from clipboard.
* Just add the amount to your co-ords.
* Only call this straight after the event, the value won't stay valid.
* Should only be called by Assoc widgets at the moment. no one else needs it.
*/
QPointF UMLScene::getPastePoint()
{
QPointF point = m_PastePoint;
point.setX(point.x() - m_pos.x());
point.setY(point.y() - m_pos.y());
return point;
}
/**
* Reset the paste point.
*/
void UMLScene::resetPastePoint()
{
m_PastePoint = m_pos;
}
/**
* Called by the view or any of its children when they start a cut
* operation.
*/
void UMLScene::setStartedCut()
{
m_bStartedCut = true;
}
/**
* Returns the font to use
*/
QFont UMLScene::font() const
{
return m_Options.uiState.font;
}
/**
* Sets the font for the view and optionally all the widgets on the view.
*/
void UMLScene::setFont(QFont font, bool changeAllWidgets /* = false */)
{
m_Options.uiState.font = font;
if (!changeAllWidgets)
return;
for(UMLWidget *w : widgetList()) {
uIgnoreZeroPointer(w);
w->setFont(font);
}
}
/**
* Sets some options for all the @ref ClassifierWidget on the view.
*/
void UMLScene::setClassWidgetOptions(ClassOptionsPage * page)
{
for(UMLWidget *pWidget : widgetList()) {
uIgnoreZeroPointer(pWidget);
WidgetBase::WidgetType wt = pWidget->baseType();
if (wt == WidgetBase::wt_Class) {
page->setWidget(pWidget->asClassifierWidget());
page->apply();
} else if (wt == WidgetBase::wt_Interface) {
page->setWidget(pWidget->asInterfaceWidget());
page->apply();
}
}
}
/**
* Returns the type of the selected widget or widgets.
*
* If multiple widgets of different types are selected then WidgetType
* wt_UMLWidget is returned.
*/
WidgetBase::WidgetType UMLScene::getUniqueSelectionType()
{
if (selectedWidgets().isEmpty()) {
return WidgetBase::wt_UMLWidget;
}
// Get the first item and its base type
UMLWidget * pTemp = (UMLWidget *) selectedWidgets().first();
WidgetBase::WidgetType tmpType = pTemp->baseType();
// Check all selected items, if they have the same BaseType
for(UMLWidget *pTemp: selectedWidgets()) {
if (pTemp->baseType() != tmpType) {
return WidgetBase::wt_UMLWidget;
}
}
return tmpType;
}
/**
* Asks for confirmation and clears everything on the diagram.
* Called from menus.
*/
void UMLScene::clearDiagram()
{
if (Dialog_Utils::askDeleteDiagram()) {
removeAllWidgets();
}
}
/**
* Apply an automatic layout.
*/
void UMLScene::applyLayout(const QString &variant)
{
logDebug1("UMLScene::applyLayout: %1", variant);
LayoutGenerator r;
r.generate(this, variant);
r.apply(this);
UMLApp::app()->slotZoomFit();
}
/**
* Changes snap to grid boolean.
* Called from menus.
*/
void UMLScene::toggleSnapToGrid()
{
setSnapToGrid(!snapToGrid());
}
/**
* Changes snap to grid for component size boolean.
* Called from menus.
*/
void UMLScene::toggleSnapComponentSizeToGrid()
{
setSnapComponentSizeToGrid(!snapComponentSizeToGrid());
}
/**
* Changes show grid boolean.
* Called from menus.
*/
void UMLScene::toggleShowGrid()
{
setSnapGridVisible(!isSnapGridVisible());
}
/**
* Return whether to use snap to grid.
*/
bool UMLScene::snapToGrid() const
{
return m_bUseSnapToGrid;
}
/**
* Sets whether to snap to grid.
*/
void UMLScene::setSnapToGrid(bool bSnap)
{
m_bUseSnapToGrid = bSnap;
Q_EMIT sigSnapToGridToggled(snapToGrid());
}
/**
* Return whether to use snap to grid for component size.
*/
bool UMLScene::snapComponentSizeToGrid() const
{
return m_bUseSnapComponentSizeToGrid;
}
/**
* Sets whether to snap to grid for component size.
*/
void UMLScene::setSnapComponentSizeToGrid(bool bSnap)
{
m_bUseSnapComponentSizeToGrid = bSnap;
updateComponentSizes();
Q_EMIT sigSnapComponentSizeToGridToggled(snapComponentSizeToGrid());
}
/**
* Returns the x grid size.
*/
int UMLScene::snapX() const
{
return m_layoutGrid->gridSpacingX();
}
/**
* Returns the y grid size.
*/
int UMLScene::snapY() const
{
return m_layoutGrid->gridSpacingY();
}
/**
* Sets the grid size in x and y.
*/
void UMLScene::setSnapSpacing(int x, int y)
{
m_layoutGrid->setGridSpacing(x, y);
}
/**
* Returns the input coordinate with possible grid-snap applied.
*/
qreal UMLScene::snappedX(qreal _x)
{
if (snapToGrid()) {
int x = (int)_x;
int gridX = snapX();
int modX = x % gridX;
x -= modX;
if (modX >= gridX / 2)
x += gridX;
return x;
}
else
return _x;
}
/**
* Returns the input coordinate with possible grid-snap applied.
*/
qreal UMLScene::snappedY(qreal _y)
{
if (snapToGrid()) {
int y = (int)_y;
int gridY = snapY();
int modY = y % gridY;
y -= modY;
if (modY >= gridY / 2)
y += gridY;
return y;
}
else
return _y;
}
/**
* Returns whether to show snap grid or not.
*/
bool UMLScene::isSnapGridVisible() const
{
return m_layoutGrid->isVisible();
}
/**
* Sets whether to show snap grid.
*/
void UMLScene::setSnapGridVisible(bool bShow)
{
m_layoutGrid->setVisible(bShow);
Q_EMIT sigShowGridToggled(bShow);
}
/**
* Returns whether to show documentation indicator.
*/
bool UMLScene::isShowDocumentationIndicator() const
{
return s_showDocumentationIndicator;
}
/**
* sets whether to show documentation indicator.
*/
void UMLScene::setShowDocumentationIndicator(bool bShow)
{
s_showDocumentationIndicator = bShow;
}
/**
* Returns whether to show operation signatures.
*/
bool UMLScene::showOpSig() const
{
return m_Options.classState.showOpSig;
}
/**
* Sets whether to show operation signatures.
*/
void UMLScene::setShowOpSig(bool bShowOpSig)
{
m_Options.classState.showOpSig = bShowOpSig;
}
/**
* Changes the zoom to the currently set level (now loaded from file)
* Called from UMLApp::slotUpdateViews()
*/
void UMLScene::fileLoaded()
{
m_view->setZoom(m_view->zoom());
}
/**
* Updates the size of all components in this view.
*/
void UMLScene::updateComponentSizes()
{
// update sizes of all components
for(UMLWidget *obj : widgetList()) {
uIgnoreZeroPointer(obj);
obj->updateGeometry();
}
}
/**
* Force the widget font metrics to be updated next time
* the widgets are drawn.
* This is necessary because the widget size might depend on the
* font metrics and the font metrics might change for different
* QPainter, i.e. font metrics for Display font and Printer font are
* usually different.
* Call this when you change the QPainter.
*/
void UMLScene::forceUpdateWidgetFontMetrics(QPainter * painter)
{
for(UMLWidget *obj : widgetList()) {
uIgnoreZeroPointer(obj);
obj->forceUpdateFontMetrics(painter);
}
}
/**
* Overrides standard method from QGraphicsScene drawing the background.
*/
void UMLScene::drawBackground(QPainter *painter, const QRectF &rect)
{
/* For some reason the incoming rect may contain invalid data.
Seen on loading the XMI file attached to bug 449393 :
(gdb) p rect
$2 = (const QRectF &) @0x7fffffffa3d0: {xp = -4160651296.6437497, yp = -18968990857.816666,
w = 4026436738.6874995, h = 33643115861.033333}
*/
const bool validX = (rect.x() >= -s_maxCanvasSize && rect.x() <= s_maxCanvasSize);
const bool validY = (rect.y() >= -s_maxCanvasSize && rect.y() <= s_maxCanvasSize);
const bool validW = (rect.width() >= 0.0 && rect.width() <= s_maxCanvasSize);
const bool validH = (rect.height() >= 0.0 && rect.height() <= s_maxCanvasSize);
if (!validX || !validY || !validW || !validH) {
logError4("UMLScene::drawBackground rejecting event due to invalid data: "
"validX=%1, validY=%2, validW=%3, validH=%4", validX, validY, validW, validH);
return;
}
QGraphicsScene::drawBackground(painter, rect);
m_layoutGrid->paint(painter, rect);
// debug info
if (Tracer::instance()->isEnabled(QLatin1String(metaObject()->className()))) {
painter->setPen(Qt::green);
painter->drawRect(sceneRect());
QVector<QLineF> origin;
origin << QLineF(QPointF(-5,0), QPointF(5,0))
<< QLineF(QPointF(0,-5), QPointF(0,5));
painter->drawLines(origin);
painter->setPen(Qt::blue);
painter->drawRect(itemsBoundingRect());
QVector<QLineF> lines;
lines << QLineF(m_pos + QPointF(-5,0), m_pos + QPointF(5,0))
<< QLineF(m_pos + QPointF(0,-5), m_pos + QPointF(0,5));
painter->setPen(Qt::gray);
painter->drawLines(lines);
}
}
/**
* Creates the "diagram" tag and fills it with the contents of the diagram.
*/
void UMLScene::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("diagram"));
writer.writeAttribute(QStringLiteral("xmi.id"), Uml::ID::toString(m_nID));
writer.writeAttribute(QStringLiteral("name"), name());
writer.writeAttribute(QStringLiteral("type"), QString::number(m_Type));
writer.writeAttribute(QStringLiteral("documentation"), m_Documentation);
//option state
m_Options.saveToXMI(writer);
//misc
writer.writeAttribute(QStringLiteral("localid"), Uml::ID::toString(m_nLocalID));
writer.writeAttribute(QStringLiteral("showgrid"), QString::number(m_layoutGrid->isVisible()));
writer.writeAttribute(QStringLiteral("snapgrid"), QString::number(m_bUseSnapToGrid));
writer.writeAttribute(QStringLiteral("snapcsgrid"), QString::number(m_bUseSnapComponentSizeToGrid));
writer.writeAttribute(QStringLiteral("snapx"), QString::number(m_layoutGrid->gridSpacingX()));
writer.writeAttribute(QStringLiteral("snapy"), QString::number(m_layoutGrid->gridSpacingY()));
// FIXME: move to UMLView
writer.writeAttribute(QStringLiteral("zoom"), QString::number(activeView()->zoom()));
writer.writeAttribute(QStringLiteral("canvasheight"), QString::number(height()));
writer.writeAttribute(QStringLiteral("canvaswidth"), QString::number(width()));
writer.writeAttribute(QStringLiteral("isopen"), QString::number(isOpen()));
if (isSequenceDiagram() || isCollaborationDiagram())
writer.writeAttribute(QStringLiteral("autoincrementsequence"), QString::number(autoIncrementSequence()));
//now save all the widgets
writer.writeStartElement(QStringLiteral("widgets"));
for(UMLWidget *widget : widgetList()) {
uIgnoreZeroPointer(widget);
// do not save floating text widgets having a parent widget; they are saved as part of the parent
if (widget->isTextWidget() && widget->parentItem())
continue;
// Having an exception is bad I know, but gotta work with
// system we are given.
// We DON'T want to record any text widgets which are belonging
// to associations as they are recorded later in the "associations"
// section when each owning association is dumped. -b.t.
if ((!widget->isTextWidget() &&
!widget->isFloatingDashLineWidget()) ||
(widget->asFloatingTextWidget() && widget->asFloatingTextWidget()->link() == nullptr))
widget->saveToXMI(writer);
}
writer.writeEndElement(); // widgets
//now save the message widgets
writer.writeStartElement(QStringLiteral("messages"));
for(UMLWidget* widget : messageList()) {
widget->saveToXMI(writer);
}
writer.writeEndElement(); // messages
//now save the associations
writer.writeStartElement(QStringLiteral("associations"));
if (associationList().count()) {
// We guard against (associationList().count() == 0) because
// this code could be reached as follows:
// ^ UMLScene::saveToXMI()
// ^ UMLDoc::saveToXMI()
// ^ UMLDoc::addToUndoStack()
// ^ UMLDoc::setModified()
// ^ UMLDoc::createDiagram()
// ^ UMLDoc::newDocument()
// ^ UMLApp::newDocument()
// ^ main()
//
AssociationWidget * assoc = nullptr;
for(AssociationWidget *assoc: associationList()) {
assoc->saveToXMI(writer);
}
}
writer.writeEndElement(); // associations
writer.writeEndElement(); // diagram
}
/**
* Loads the "diagram" tag.
*/
bool UMLScene::loadFromXMI(QDomElement & qElement)
{
QString id = qElement.attribute(QStringLiteral("xmi.id"), QStringLiteral("-1"));
m_nID = Uml::ID::fromString(id);
if (m_nID == Uml::ID::None)
return false;
setName(qElement.attribute(QStringLiteral("name")));
QString type = qElement.attribute(QStringLiteral("type"), QStringLiteral("0"));
m_Documentation = qElement.attribute(QStringLiteral("documentation"));
QString localid = qElement.attribute(QStringLiteral("localid"), QStringLiteral("0"));
// option state
m_Options.loadFromXMI(qElement);
setBackgroundBrush(m_Options.uiState.backgroundColor);
setGridDotColor(m_Options.uiState.gridDotColor);
//misc
QString showgrid = qElement.attribute(QStringLiteral("showgrid"), QStringLiteral("0"));
m_layoutGrid->setVisible((bool)showgrid.toInt());
QString snapgrid = qElement.attribute(QStringLiteral("snapgrid"), QStringLiteral("0"));
m_bUseSnapToGrid = (bool)snapgrid.toInt();
QString snapcsgrid = qElement.attribute(QStringLiteral("snapcsgrid"), QStringLiteral("0"));
m_bUseSnapComponentSizeToGrid = (bool)snapcsgrid.toInt();
QString snapx = qElement.attribute(QStringLiteral("snapx"), QStringLiteral("10"));
QString snapy = qElement.attribute(QStringLiteral("snapy"), QStringLiteral("10"));
m_layoutGrid->setGridSpacing(snapx.toInt(), snapy.toInt());
QString canvheight = qElement.attribute(QStringLiteral("canvasheight"), QString());
QString canvwidth = qElement.attribute(QStringLiteral("canvaswidth"), QString());
qreal canvasWidth = 0.0;
qreal canvasHeight = 0.0;
if (!canvwidth.isEmpty()) {
canvasWidth = toDoubleFromAnyLocale(canvwidth);
if (canvasWidth <= 0.0 || canvasWidth > s_maxCanvasSize) {
canvasWidth = 0.0;
}
}
if (!canvheight.isEmpty()) {
canvasHeight = toDoubleFromAnyLocale(canvheight);
if (canvasHeight <= 0.0 || canvasHeight > s_maxCanvasSize) {
canvasHeight = 0.0;
}
}
if (!qFuzzyIsNull(canvasWidth) && !qFuzzyIsNull(canvasHeight)) {
setSceneRect(0, 0, canvasWidth, canvasHeight);
}
QString zoom = qElement.attribute(QStringLiteral("zoom"), QStringLiteral("100"));
activeView()->setZoom(zoom.toInt());
QString isOpen = qElement.attribute(QStringLiteral("isopen"), QStringLiteral("1"));
m_isOpen = (bool)isOpen.toInt();
int nType = type.toInt();
if (nType == -1 || nType >= 400) {
// Pre 1.5.5 numeric values
// Values of "type" were changed in 1.5.5 to merge with Settings::Diagram
switch (nType) {
case 400:
m_Type = Uml::DiagramType::UseCase;
break;
case 401:
m_Type = Uml::DiagramType::Collaboration;
break;
case 402:
m_Type = Uml::DiagramType::Class;
break;
case 403:
m_Type = Uml::DiagramType::Sequence;
break;
case 404:
m_Type = Uml::DiagramType::State;
break;
case 405:
m_Type = Uml::DiagramType::Activity;
break;
case 406:
m_Type = Uml::DiagramType::Component;
break;
case 407:
m_Type = Uml::DiagramType::Deployment;
break;
case 408:
m_Type = Uml::DiagramType::EntityRelationship;
break;
case 409:
m_Type = Uml::DiagramType::Object;
break;
default:
m_Type = Uml::DiagramType::Undefined;
break;
}
} else {
m_Type = Uml::DiagramType::fromInt(nType);
}
m_nLocalID = Uml::ID::fromString(localid);
if (m_Type == Uml::DiagramType::Sequence ||
m_Type == Uml::DiagramType::Collaboration) {
QString autoIncrementSequence = qElement.attribute(QStringLiteral("autoincrementsequence"),
QStringLiteral("0"));
m_autoIncrementSequence = (bool)autoIncrementSequence.toInt();
}
QDomNode node = qElement.firstChild();
/*
https://bugs.kde.org/show_bug.cgi?id=449622
In order to compensate for QGraphicsScene offsets we make an extra loop in which
negative or positive X / Y offsets are determined.
The problem stems from the time when the QGraphicsScene coordinates were derived
from the coordinates of its widgets (function resizeSceneToItems prior to v2.34).
*/
m_fixX = m_fixY = 0.0;
qreal xNegOffset = 0.0;
qreal yNegOffset = 0.0;
qreal xPosOffset = 1.0e6;
qreal yPosOffset = 1.0e6;
// If an offset fix is applied then add a margin on the fix so that the leftmost
// or topmost widgets have some separation from the scene border.
const qreal marginIfFixIsApplied = 50.0;
// If all widgets have a positive X or Y offset exceeding this value
// then the fix will be applied.
const qreal xTriggerValueForPositiveFix = s_defaultCanvasWidth / 2.0;
const qreal yTriggerValueForPositiveFix = s_defaultCanvasHeight / 2.0;
while (!node.isNull()) {
QDomElement element = node.toElement();
if (element.isNull()) {
node = node.nextSibling();
continue;
}
if (element.tagName() == QStringLiteral("widgets")) {
QDomNode wNode = element.firstChild();
QDomElement widgetElement = wNode.toElement();
while (!widgetElement.isNull()) {
QString tag = widgetElement.tagName();
if ((tag.endsWith(QStringLiteral("widget")) && tag != QStringLiteral("pinwidget")
&& tag != QStringLiteral("portwidget"))
|| tag == QStringLiteral("floatingtext")) {
QString xStr = widgetElement.attribute(QStringLiteral("x"), QStringLiteral("0"));
qreal x = toDoubleFromAnyLocale(xStr);
if (x < -s_maxCanvasSize || x > s_maxCanvasSize) {
QString wName = widgetElement.attribute(QStringLiteral("name"), QString());
logWarn3("UMLScene::loadFromXMI(%1) ignoring widget %2 due to invalid X value %3",
name(), wName, xStr);
wNode = widgetElement.nextSibling();
widgetElement = wNode.toElement();
continue;
}
QString yStr = widgetElement.attribute(QStringLiteral("y"), QStringLiteral("0"));
qreal y = toDoubleFromAnyLocale(yStr);
if (y < -s_maxCanvasSize || y > s_maxCanvasSize) {
QString wName = widgetElement.attribute(QStringLiteral("name"), QString());
logWarn3("UMLScene::loadFromXMI(%1) ignoring widget %2 due to invalid Y value %3",
name(), wName, yStr);
wNode = widgetElement.nextSibling();
widgetElement = wNode.toElement();
continue;
}
if (x < 0.0) {
if (x < xNegOffset)
xNegOffset = x;
} else if (x < xPosOffset) {
xPosOffset = x;
}
if (y < 0.0) {
if (y < yNegOffset)
yNegOffset = y;
} else if (y < yPosOffset) {
yPosOffset = y;
}
// QString hStr = widgetElement.attribute(QStringLiteral("height"), QStringLiteral("0"));
// QString wStr = widgetElement.attribute(QStringLiteral("width"), QStringLiteral("0"));
}
wNode = widgetElement.nextSibling();
widgetElement = wNode.toElement();
}
}
node = node.nextSibling();
}
if (xNegOffset < 0.0)
m_fixX = -xNegOffset + marginIfFixIsApplied;
else if (xPosOffset > xTriggerValueForPositiveFix)
m_fixX = -xPosOffset + marginIfFixIsApplied;
if (yNegOffset < 0.0)
m_fixY = -yNegOffset + marginIfFixIsApplied;
else if (yPosOffset > yTriggerValueForPositiveFix)
m_fixY = -yPosOffset + marginIfFixIsApplied;
if (!qFuzzyIsNull(m_fixX) || !qFuzzyIsNull(m_fixY)) {
logDebug3("UMLScene::loadFromXMI(%1) : fixX = %2, fixY = %3", name(), m_fixX, m_fixY);
}
node = qElement.firstChild();
bool widgetsLoaded = false, messagesLoaded = false, associationsLoaded = false;
while (!node.isNull()) {
QDomElement element = node.toElement();
if (!element.isNull()) {
if (element.tagName() == QStringLiteral("widgets"))
widgetsLoaded = loadWidgetsFromXMI(element);
else if (element.tagName() == QStringLiteral("messages"))
messagesLoaded = loadMessagesFromXMI(element);
else if (element.tagName() == QStringLiteral("associations"))
associationsLoaded = loadAssociationsFromXMI(element);
}
node = node.nextSibling();
}
if (!widgetsLoaded) {
logWarn0("UMLScene::loadFromXMI failed on widgets");
return false;
}
if (!messagesLoaded) {
logWarn0("UMLScene::loadFromXMI failed on messages");
return false;
}
if (!associationsLoaded) {
logWarn0("UMLScene::loadFromXMI failed on associations");
return false;
}
if (this->isComponentDiagram()) {
m_d->addMissingPorts();
m_d->fixPortPositions();
}
m_d->removeDuplicatedFloatingTextInstances();
/*
During loadWidgetsFromXMI(), the required QGraphicsScene size was calculated
by finding the minimum (x, y) and maximum (x+width, y+height) values of the
widgets loaded.
These are stored in members m_minX, m_minY and m_maxX, m_maxY respectively.
This extra step in necessary because the XMI attributes "canvaswidth" and
"canvasheight" may contain invalid values. See updateCanvasSizeEstimate().
*/
if (m_maxX > canvasWidth || m_maxY > canvasHeight) {
if (m_minX < 0.0 || m_minY < 0.0) {
logWarn3("UMLScene::loadFromXMI(%1): Setting canvas size with strange values x=%2, y=%3",
name(), m_minX, m_minY);
setSceneRect(m_minX, m_minY, m_maxX, m_maxY);
} else {
logDebug5("UMLScene::loadFromXMI(%1) : Setting canvas size with w=%2, h=%3 (minX=%4, minY=%5)",
name(), m_maxX, m_maxY, m_minX, m_minY);
setSceneRect(0.0, 0.0, m_maxX, m_maxY);
}
}
return true;
}
bool UMLScene::loadWidgetsFromXMI(QDomElement & qElement)
{
UMLWidget *widget = nullptr;
QDomNode node = qElement.firstChild();
QDomElement widgetElement = node.toElement();
while (!widgetElement.isNull()) {
widget = loadWidgetFromXMI(widgetElement);
if (widget) {
addWidgetCmd(widget);
widget->clipSize();
// In the interest of best-effort loading, in case of a
// (widget == 0) we still go on.
// The individual widget's loadFromXMI method should
// already have generated an error message to tell the
// user that something went wrong.
}
node = widgetElement.nextSibling();
widgetElement = node.toElement();
}
return true;
}
/**
* Loads a "widget" element from XMI, used by loadFromXMI() and the clipboard.
*/
UMLWidget* UMLScene::loadWidgetFromXMI(QDomElement& widgetElement)
{
if (!m_doc) {
logWarn0("UMLScene::loadWidgetFromXMI: m_doc is NULL");
return (UMLWidget*)nullptr;
}
QString tag = widgetElement.tagName();
QString idstr = widgetElement.attribute(QStringLiteral("xmi.id"), QStringLiteral("-1"));
UMLWidget* widget = Widget_Factory::makeWidgetFromXMI(tag, idstr, this);
if (widget == nullptr)
return (UMLWidget*)nullptr;
if (!widget->loadFromXMI(widgetElement)) {
widget->cleanup();
delete widget;
return (UMLWidget*)nullptr;
}
return widget;
}
bool UMLScene::loadMessagesFromXMI(QDomElement & qElement)
{
MessageWidget *message = nullptr;
QDomNode node = qElement.firstChild();
QDomElement messageElement = node.toElement();
while (!messageElement.isNull()) {
QString tag = messageElement.tagName();
logDebug1("UMLScene::loadMessagesFromXMI: tag %1", tag);
if (tag == QStringLiteral("messagewidget") ||
tag == QStringLiteral("UML:MessageWidget")) { // for bkwd compatibility
message = new MessageWidget(this, SequenceMessage::Asynchronous,
Uml::ID::Reserved);
if (!message->loadFromXMI(messageElement)) {
delete message;
return false;
}
addWidgetCmd(message);
FloatingTextWidget *ft = message->floatingTextWidget();
if (!ft && message->sequenceMessageType() != SequenceMessage::Creation)
logDebug1("UMLScene::loadMessagesFromXMI: floating text is NULL for message %1",
Uml::ID::toString(message->id()));
}
node = messageElement.nextSibling();
messageElement = node.toElement();
}
return true;
}
bool UMLScene::loadAssociationsFromXMI(QDomElement & qElement)
{
QDomNode node = qElement.firstChild();
QDomElement assocElement = node.toElement();
int countr = 0;
while (!assocElement.isNull()) {
QString tag = assocElement.tagName();
if (tag == QStringLiteral("assocwidget") ||
tag == QStringLiteral("UML:AssocWidget")) { // for bkwd compatibility
countr++;
AssociationWidget *assoc = AssociationWidget::create(this);
if (!assoc->loadFromXMI(assocElement)) {
logError1("UMLScene::loadAssociationsFromXMI could not load association widget %1",
Uml::ID::toString(assoc->id()));
delete assoc;
/* return false;
Returning false here is a little harsh when the
rest of the diagram might load okay.
*/
} else {
assoc->clipSize();
if (!addAssociation(assoc, false)) {
logError1("UMLScene::loadAssociationsFromXMI could not addAssociation(%1) to scene",
Uml::ID::toString(assoc->id()));
delete assoc;
//return false; // soften error.. may not be that bad
}
}
}
node = assocElement.nextSibling();
assocElement = node.toElement();
}
return true;
}
/**
* Add an object to the application, and update the view.
*/
void UMLScene::addObject(UMLObject *object)
{
m_bCreateObject = true;
if (m_doc->addUMLObject(object))
m_doc->signalUMLObjectCreated(object); // m_bCreateObject is reset by slotObjectCreated()
else
m_bCreateObject = false;
}
bool UMLScene::loadUisDiagramPresentation(QDomElement & qElement)
{
for (QDomNode node = qElement.firstChild(); !node.isNull(); node = node.nextSibling()) {
QDomElement elem = node.toElement();
QString tag = elem.tagName();
if (! UMLDoc::tagEq(tag, QStringLiteral("Presentation"))) {
logError1("ignoring unknown UisDiagramPresentation tag %1", tag);
continue;
}
QDomNode n = elem.firstChild();
QDomElement e = n.toElement();
QString idStr;
int x = 0, y = 0, w = 0, h = 0;
while (!e.isNull()) {
tag = e.tagName();
logDebug1("UMLScene::loadUisDiagramPresentation: tag %1", tag);
if (UMLDoc::tagEq(tag, QStringLiteral("Presentation.geometry"))) {
QDomNode gnode = e.firstChild();
QDomElement gelem = gnode.toElement();
QString csv = gelem.text();
QStringList dim = csv.split(QLatin1Char(','));
x = dim[0].toInt();
y = dim[1].toInt();
w = dim[2].toInt();
h = dim[3].toInt();
} else if (UMLDoc::tagEq(tag, QStringLiteral("Presentation.style"))) {
// TBD
} else if (UMLDoc::tagEq(tag, QStringLiteral("Presentation.model"))) {
QDomNode mnode = e.firstChild();
QDomElement melem = mnode.toElement();
idStr = melem.attribute(QStringLiteral("xmi.idref"));
} else {
logDebug1("UMLScene::loadUisDiagramPresentation: ignoring tag %1", tag);
}
n = n.nextSibling();
e = n.toElement();
}
Uml::ID::Type id = Uml::ID::fromString(idStr);
UMLObject *o = m_doc->findObjectById(id);
if (o == nullptr) {
logError1("loadUisDiagramPresentation: Cannot find object for id %1", idStr);
} else {
UMLObject::ObjectType ot = o->baseType();
logDebug1("UMLScene::loadUisDiagramPresentation: Create widget for model object of type %1",
UMLObject::toString(ot));
UMLWidget *widget = nullptr;
switch (ot) {
case UMLObject::ot_Class:
widget = new ClassifierWidget(this, o->asUMLClassifier());
break;
case UMLObject::ot_Association: {
UMLAssociation *umla = o->asUMLAssociation();
Uml::AssociationType::Enum at = umla->getAssocType();
UMLObject* objA = umla->getObject(Uml::RoleType::A);
UMLObject* objB = umla->getObject(Uml::RoleType::B);
if (objA == nullptr || objB == nullptr) {
logError0("loadUisDiagramPresentation(association) intern err 1");
return false;
}
UMLWidget *wA = findWidget(objA->id());
UMLWidget *wB = findWidget(objB->id());
if (wA != nullptr && wB != nullptr) {
AssociationWidget *aw =
AssociationWidget::create(this, wA, at, wB, umla);
aw->syncToModel();
addWidgetCmd(aw);
} else {
const QString nullRole = (!wA && !wB ? QStringLiteral("both roles") :
!wA ? QStringLiteral("role A") : QStringLiteral("role B"));
logError1("loadUisDiagramPresentation cannot create assocwidget due to null widget at %1",
nullRole);
}
break;
}
case UMLObject::ot_Role: {
//UMLRole *robj = o->asUMLRole();
//UMLAssociation *umla = robj->getParentAssociation();
// @todo properly display role names.
// For now, in order to get the role names displayed
// simply delete the participating diagram objects
// and drag them from the list view to the diagram.
break;
}
default:
logError1("loadUisDiagramPresentation cannot create widget of type %1", ot);
}
if (widget) {
logDebug4("UMLScene::loadUisDiagramPresentation Widget: x=%1, y=%2, w=%3, h=%4", x, y, w, h);
widget->setX(x);
widget->setY(y);
widget->setSize(w, h);
addWidgetCmd(widget);
}
}
}
return true;
}
/**
* Loads the "UISDiagram" tag of Unisys.IntegratePlus.2 generated files.
*/
bool UMLScene::loadUISDiagram(QDomElement & qElement)
{
QString idStr = qElement.attribute(QStringLiteral("xmi.id"));
if (idStr.isEmpty())
return false;
m_nID = Uml::ID::fromString(idStr);
UMLListViewItem *ulvi = nullptr;
for (QDomNode node = qElement.firstChild(); !node.isNull(); node = node.nextSibling()) {
if (node.isComment())
continue;
QDomElement elem = node.toElement();
QString tag = elem.tagName();
if (tag == QStringLiteral("uisDiagramName")) {
setName(elem.text());
if (ulvi)
ulvi->setText(name());
} else if (tag == QStringLiteral("uisDiagramStyle")) {
QString diagramStyle = elem.text();
if (diagramStyle != QStringLiteral("ClassDiagram")) {
logError1("loadUISDiagram: style %1 is not yet implemented", diagramStyle);
continue;
}
m_doc->setMainViewID(m_nID);
m_Type = Uml::DiagramType::Class;
UMLListView *lv = UMLApp::app()->listView();
ulvi = new UMLListViewItem(lv->theLogicalView(), name(),
UMLListViewItem::lvt_Class_Diagram, m_nID);
} else if (tag == QStringLiteral("uisDiagramPresentation")) {
loadUisDiagramPresentation(elem);
} else if (tag != QStringLiteral("uisToolName")) {
logDebug1("UMLScene::loadUISDiagram ignoring tag %1", tag);
}
}
return true;
}
/**
* Left Alignment
*/
void UMLScene::alignLeft()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal smallestX = WidgetList_Utils::getSmallestX(widgetList);
for(UMLWidget *widget : widgetList) {
widget->setX(smallestX);
widget->adjustAssocs(widget->x(), widget->y());
}
//TODO: Push stored cmds to stack.
}
/**
* Right Alignment
*/
void UMLScene::alignRight()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal biggestX = WidgetList_Utils::getBiggestX(widgetList);
for(UMLWidget *widget : widgetList) {
widget->setX(biggestX - widget->width());
widget->adjustAssocs(widget->x(), widget->y());
}
//TODO: Push stored cmds to stack.
}
/**
* Top Alignment
*/
void UMLScene::alignTop()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal smallestY = WidgetList_Utils::getSmallestY(widgetList);
for(UMLWidget *widget : widgetList) {
widget->setY(smallestY);
widget->adjustAssocs(widget->x(), widget->y());
}
//TODO: Push stored cmds to stack.
}
/**
* Bottom Alignment
*/
void UMLScene::alignBottom()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal biggestY = WidgetList_Utils::getBiggestY(widgetList);
for(UMLWidget *widget : widgetList) {
widget->setY(biggestY - widget->height());
widget->adjustAssocs(widget->x(), widget->y());
}
//TODO: Push stored cmds to stack.
}
/**
* Vertical Middle Alignment
*/
void UMLScene::alignVerticalMiddle()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal smallestY = WidgetList_Utils::getSmallestY(widgetList);
qreal biggestY = WidgetList_Utils::getBiggestY(widgetList);
qreal middle = int((biggestY - smallestY) / 2) + smallestY;
for(UMLWidget *widget : widgetList) {
widget->setY(middle - widget->height() / 2);
widget->adjustAssocs(widget->x(), widget->y());
}
AssociationWidgetList assocList = selectedAssocs();
if (!assocList.isEmpty()) {
for(AssociationWidget *widget : assocList) {
widget->setYEntireAssoc(middle);
}
}
//TODO: Push stored cmds to stack.
}
/**
* Horizontal Middle Alignment
*/
void UMLScene::alignHorizontalMiddle()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal smallestX = WidgetList_Utils::getSmallestX(widgetList);
qreal biggestX = WidgetList_Utils::getBiggestX(widgetList);
qreal middle = int((biggestX - smallestX) / 2) + smallestX;
for(UMLWidget *widget : widgetList) {
widget->setX(middle - widget->width() / 2);
widget->adjustAssocs(widget->x(), widget->y());
}
AssociationWidgetList assocList = selectedAssocs();
if (!assocList.isEmpty()) {
for(AssociationWidget *widget : assocList) {
widget->setXEntireAssoc(middle);
}
}
//TODO: Push stored cmds to stack.
}
/**
* Vertical Distribute Alignment
*/
void UMLScene::alignVerticalDistribute()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal smallestY = WidgetList_Utils::getSmallestY(widgetList);
qreal biggestY = WidgetList_Utils::getBiggestY(widgetList);
qreal heightsSum = WidgetList_Utils::getHeightsSum(widgetList);
qreal distance = int(((biggestY - smallestY) - heightsSum) / (widgetList.count() - 1.0) + 0.5);
std::sort(widgetList.begin(), widgetList.end(), Widget_Utils::hasSmallerY);
int i = 1;
UMLWidget *widgetPrev = nullptr;
for(UMLWidget *widget : widgetList) {
if (i == 1) {
widgetPrev = widget;
} else {
widget->setY(widgetPrev->y() + widgetPrev->height() + distance);
widget->adjustAssocs(widget->x(), widget->y());
widgetPrev = widget;
}
i++;
}
//TODO: Push stored cmds to stack.
}
/**
* Horizontal Distribute Alignment
*/
void UMLScene::alignHorizontalDistribute()
{
UMLWidgetList widgetList = selectedWidgetsExt();
if (widgetList.isEmpty())
return;
qreal smallestX = WidgetList_Utils::getSmallestX(widgetList);
qreal biggestX = WidgetList_Utils::getBiggestX(widgetList);
qreal widthsSum = WidgetList_Utils::getWidthsSum(widgetList);
qreal distance = int(((biggestX - smallestX) - widthsSum) / (widgetList.count() - 1.0) + 0.5);
std::sort(widgetList.begin(), widgetList.end(), Widget_Utils::hasSmallerX);
int i = 1;
UMLWidget *widgetPrev = nullptr;
for(UMLWidget *widget : widgetList) {
if (i == 1) {
widgetPrev = widget;
} else {
widget->setX(widgetPrev->x() + widgetPrev->width() + distance);
widget->adjustAssocs(widget->x(), widget->y());
widgetPrev = widget;
}
i++;
}
//TODO: Push stored cmds to stack.
}
/**
* Overloading operator for debugging output.
*/
QDebug operator<<(QDebug dbg, UMLScene *item)
{
dbg.nospace() << "UMLScene: " << item->name()
<< " / type=" << DiagramType::toString(item->type())
<< " / id=" << Uml::ID::toString(item->ID())
<< " / isOpen=" << item->isOpen();
return dbg.space();
}
void UMLScene::setWidgetLink(WidgetBase *w)
{
m_d->widgetLink = w;
}
WidgetBase *UMLScene::widgetLink()
{
return m_d->widgetLink;
}
/**
* Unfortunately the XMI attributes "canvaswidth" and "canvasheight" cannot be
* relied on, in versions before 2.34 they sometimes contain bogus values.
* We work around this problem by gathering the minimum and maximum values
* of the widgets x, x+width, y, y+height into the variables m_minX, m_maxX,
* m_minY, m_maxY.
* These values are gathered, and the new scene rectangle is set if required,
* during loadFromXMI().
*
* @param x If value is less than m_minX then m_minX is set to this value.
* @param y If value is less than m_minY then m_minY is set to this value.
* @param w If @p x plus this value is greater than m_maxX then m_maxX is set to their sum.
* @param h If @p y plus this value is greater than m_maxY then m_maxY is set to their sum.
*/
void UMLScene::updateCanvasSizeEstimate(qreal x, qreal y, qreal w, qreal h)
{
if (x < m_minX)
m_minX = x;
else if (x + w > m_maxX)
m_maxX = x + w;
if (y < m_minY)
m_minY = y;
else if (y + h > m_maxY)
m_maxY = y + h;
}
/**
* Adjust scene rect to cover all contained items
*/
void UMLScene::updateSceneRect()
{
double b = s_sceneBorder;
setSceneRect(itemsBoundingRect().adjusted(-b, -b, b, b));
}
/**
* Compensate for QGraphicsScene offsets, https://bugs.kde.org/show_bug.cgi?id=449622
*/
qreal UMLScene::fixX() const
{
return m_fixX;
}
/**
* Compensate for QGraphicsScene offsets, https://bugs.kde.org/show_bug.cgi?id=449622
*/
qreal UMLScene::fixY() const
{
return m_fixY;
}
| 145,307
|
C++
|
.cpp
| 4,196
| 27.884652
| 134
| 0.629627
|
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,267
|
stereotypeswindow.cpp
|
KDE_umbrello/umbrello/stereotypeswindow.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2015-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "stereotypeswindow.h"
// app includes
#include "dialog_utils.h"
#include "debug_utils.h"
#include "stereotype.h"
#include "models/stereotypesmodel.h"
#include "dialogs/stereoattributedialog.h"
#include "uml.h"
#include "umldoc.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QHeaderView>
#include <QTableView>
#include <QSortFilterProxyModel>
#include <QContextMenuEvent>
#include <QtDebug>
DEBUG_REGISTER(StereotypesWindow)
StereotypesWindow::StereotypesWindow(const QString &title, QWidget *parent)
: QDockWidget(title, parent)
{
setObjectName(QStringLiteral("StereotypesWindow"));
QSortFilterProxyModel *proxy = new QSortFilterProxyModel;
proxy->setSourceModel(UMLApp::app()->document()->stereotypesModel());
proxy->setSortCaseSensitivity(Qt::CaseInsensitive);
m_stereotypesTree = new QTableView;
m_stereotypesTree->setModel(proxy);
m_stereotypesTree->setSortingEnabled(true);
m_stereotypesTree->verticalHeader()->setDefaultSectionSize(20);
m_stereotypesTree->verticalHeader()->setVisible(false);
m_stereotypesTree->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setWidget(m_stereotypesTree);
connect(m_stereotypesTree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotStereotypesDoubleClicked(QModelIndex)));
}
StereotypesWindow::~StereotypesWindow()
{
QAbstractItemModel *proxy = m_stereotypesTree->model();
delete m_stereotypesTree;
delete proxy;
}
void StereotypesWindow::modified()
{
UMLStereotype *o = dynamic_cast<UMLStereotype*>(QObject::sender());
if (!o)
return;
int index = UMLApp::app()->document()->stereotypes().indexOf(o);
UMLApp::app()->document()->stereotypesModel()->emitDataChanged(index);
}
void StereotypesWindow::slotStereotypesDoubleClicked(QModelIndex index)
{
QVariant v = m_stereotypesTree->model()->data(index, Qt::UserRole);
if (v.canConvert<UMLStereotype*>()) {
UMLStereotype *s = v.value<UMLStereotype*>();
s->showPropertiesDialog(this);
}
}
void StereotypesWindow::contextMenuEvent(QContextMenuEvent *event)
{
const QPoint& pos = event->pos();
int row = m_stereotypesTree->rowAt(pos.y() - 60);
// Apparently we need the "- 60" to subtract height of title lines "Stereotypes", "Name / Usage"
logDebug3("StereotypesWindow::contextMenuEvent: pos (%1, %2) row %3",
event->pos().x(), event->pos().y(), row);
if (row >= 0) {
QModelIndex index = m_stereotypesTree->model()->index(row, 0); // first column
// DEBUG() << "StereotypesWindow::contextMenuEvent: QModelIndex " << index;
QVariant v = m_stereotypesTree->model()->data(index, Qt::UserRole);
if (v.canConvert<UMLStereotype*>()) {
UMLStereotype *s = v.value<UMLStereotype*>();
StereoAttributeDialog *dialog = new StereoAttributeDialog(this, s);
dialog->exec();
delete dialog;
} else {
logDebug0("StereotypesWindow::contextMenuEvent: QVariant::canConvert returns false");
}
return;
}
QString name;
if (!Dialog_Utils::askDefaultNewName(UMLObject::ot_Stereotype, name))
return;
if (UMLApp::app()->document()->findStereotype(name))
return;
UMLStereotype *s = new UMLStereotype(name);
UMLApp::app()->document()->stereotypesModel()->addStereotype(s);
}
| 3,544
|
C++
|
.cpp
| 89
| 35.179775
| 122
| 0.714203
|
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,268
|
basictypes.cpp
|
KDE_umbrello/umbrello/basictypes.cpp
|
/*
SPDX-FileCopyrightText: 2011 Andi Fischer <andi.fischer@hispeed.ch>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "basictypes.h"
#include "debug_utils.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QFontDatabase>
namespace Uml
{
namespace ModelType
{
/**
* Convert ModelType item into QString representation.
* @param item item to convert
* @return QString representation of ModelType
*/
QString toString(Enum item)
{
switch (item) {
case UseCase:
return QString(QStringLiteral("UseCase"));
case Component:
return QString(QStringLiteral("Component"));
case Deployment:
return QString(QStringLiteral("Deployment"));
case EntityRelationship:
return QString(QStringLiteral("EntityRelationship"));
case Logical:
default:
return QString(QStringLiteral("Logical"));
}
}
/**
* Convert a string item into Model representation.
* @param item item to convert
* @return Model object
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("UseCase"))
return UseCase;
else if (item == QStringLiteral("Component"))
return Component;
else if (item == QStringLiteral("Deployment"))
return Deployment;
else if (item == QStringLiteral("EntityRelationship"))
return EntityRelationship;
else
return Logical;
}
/**
* Convert an integer item into ModelType representation.
* @param item integer value to convert
* @return ModelType enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace ModelType
//-----------------------------------------------------------------------------
namespace Visibility {
/**
* Convert Visibility item into QString representation.
* @param item item to convert
* @param mnemonic if true then return a single character:
* "+" for public, "-" for private,
* "#" for protected or "~" for implementation
* @return QString representation of Visibility
*/
QString toString(Enum item, bool mnemonic)
{
switch (item) {
case Protected:
return (mnemonic ? QStringLiteral("#") : QStringLiteral("protected"));
case Private:
return (mnemonic ? QStringLiteral("-") : QStringLiteral("private"));
case Implementation:
return (mnemonic ? QStringLiteral("~") : QStringLiteral("implementation"));
case Public:
default:
return (mnemonic ? QStringLiteral("+") : QStringLiteral("public"));
}
}
/**
* Convert a string item into Visibility representation.
* @param item item to convert
* @param checkUnknown If the visibility expression in @p item is not recognized
* and checkUnknown is true then the value Unknown is returned.
* @return Visibility enum
*/
Enum fromString(const QString& item, bool checkUnknown)
{
if (item == QStringLiteral("public") || item == QStringLiteral("+"))
return Public;
else if (item == QStringLiteral("protected") || item == QStringLiteral("#"))
return Protected;
else if (item == QStringLiteral("private") || item == QStringLiteral("-"))
return Private;
else if (item == QStringLiteral("~"))
return Implementation;
else if (item == QStringLiteral("signals"))
return Protected;
else if (item == QStringLiteral("class"))
return Private;
else if (checkUnknown)
return Unknown;
else
return Public;
}
/**
* Convert an integer item into Visibility representation.
* @param item integer value to convert
* @return Visibility enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace Visibility
//-----------------------------------------------------------------------------
namespace DiagramType {
/**
* Convert DiagramType item into QString representation.
* @param item item to convert
* @return QString representation of DiagramType
*/
QString toString(Enum item)
{
switch (item) {
case Undefined:
return QStringLiteral("Undefined");
case Class:
return QStringLiteral("Class");
case Object:
return QStringLiteral("Object");
case UseCase:
return QStringLiteral("UseCase");
case Sequence:
return QStringLiteral("Sequence");
case Collaboration:
return QStringLiteral("Collaboration");
case State:
return QStringLiteral("State");
case Activity:
return QStringLiteral("Activity");
case Component:
return QStringLiteral("Component");
case Deployment:
return QStringLiteral("Deployment");
case EntityRelationship:
return QStringLiteral("EntityRelationship");
case N_DIAGRAMTYPES: // must remain last
return QStringLiteral("N_DIAGRAMTYPES");
default:
return QStringLiteral("? DiagramType ?");
}
}
/**
* Return string corresponding to DiagramType
*/
QString toStringI18n(Enum item)
{
switch (item) {
case Class:
return i18n("Class Diagram");
case UseCase:
return i18n("Use Case Diagram");
case Sequence:
return i18n("Sequence Diagram");
case Collaboration:
return i18n("Collaboration Diagram");
case State:
return i18n("State Diagram");
case Activity:
return i18n("Activity Diagram");
case Component:
return i18n("Component Diagram");
case Deployment:
return i18n("Deployment Diagram");
case EntityRelationship:
return i18n("Entity Relationship Diagram");
case Object:
return i18n("Object Diagram");
default:
return i18n("No Diagram");
}
}
/**
* Convert a string item into DiagramType representation.
* @param item item to convert
* @return DiagramType object
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("Undefined"))
return Undefined;
else if (item == QStringLiteral("Class"))
return Class;
else if (item == QStringLiteral("UseCase"))
return UseCase;
else if (item == QStringLiteral("Sequence"))
return Sequence;
else if (item == QStringLiteral("Collaboration"))
return Collaboration;
else if (item == QStringLiteral("State"))
return State;
else if (item == QStringLiteral("Activity"))
return Activity;
else if (item == QStringLiteral("Component"))
return Component;
else if (item == QStringLiteral("Deployment"))
return Deployment;
else if (item == QStringLiteral("EntityRelationship"))
return EntityRelationship;
else
return Undefined;
}
/**
* Convert an integer item into DiagramType representation.
* @param item integer value to convert
* @return DiagramType enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace DiagramType
//-----------------------------------------------------------------------------
namespace AssociationType {
/**
* Convert AssociationType item into QString representation.
* @param item item to convert
* @return QString representation of AssociationType
*/
QString toString(Enum item)
{
switch (item) {
case Generalization:
return QStringLiteral("Generalization");
case Aggregation:
return QStringLiteral("Aggregation");
case Dependency:
return QStringLiteral("Dependency");
case Association:
return QStringLiteral("Association");
case Association_Self:
return QStringLiteral("Association_Self");
case Coll_Mesg_Async:
return QStringLiteral("Coll_Mesg_Async");
case Coll_Mesg_Sync:
return QStringLiteral("Coll_Mesg_Sync");
case Seq_Message:
return QStringLiteral("Seq_Message");
case Coll_Mesg_Self:
return QStringLiteral("Coll_Mesg_Self");
case Seq_Message_Self:
return QStringLiteral("Seq_Message_Self");
case Containment:
return QStringLiteral("Containment");
case Composition:
return QStringLiteral("Composition");
case Realization:
return QStringLiteral("Realization");
case UniAssociation:
return QStringLiteral("UniAssociation");
case Anchor:
return QStringLiteral("Anchor");
case State:
return QStringLiteral("State");
case Activity:
return QStringLiteral("Activity");
case Exception:
return QStringLiteral("Exception");
case Category2Parent:
return QStringLiteral("Category2Parent");
case Child2Category:
return QStringLiteral("Child2Category");
case Relationship:
return QStringLiteral("Relationship");
case Unknown:
return QStringLiteral("Unknown");
default:
return QStringLiteral("? AssociationType ?");
}
}
/**
* Converts an AssociationType to its string representation.
* @return the string representation of the AssociationType
*/
QString toStringI18n(Enum item)
{
switch (item) {
case Generalization:
return i18n("Generalization");
case Aggregation:
return i18n("Aggregation");
case Dependency:
return i18n("Dependency");
case Association:
return i18n("Association");
case Association_Self:
return i18n("Self Association");
case Coll_Mesg_Async:
return i18n("Collaboration Asynchronous Message");
case Coll_Mesg_Sync:
return i18n("Collaboration Synchronous Message");
case Seq_Message:
return i18n("Sequence Message");
case Coll_Mesg_Self:
return i18n("Collaboration Self Message");
case Seq_Message_Self:
return i18n("Sequence Self Message");
case Containment:
return i18n("Containment");
case Composition:
return i18n("Composition");
case Realization:
return i18n("Realization");
case UniAssociation:
return i18n("Uni Association");
case Anchor:
return i18n("Anchor");
case State:
return i18n("State Transition");
case Activity:
return i18n("Activity");
case Exception:
return i18n("Exception");
case Category2Parent:
return i18n("Category to Parent");
case Child2Category:
return i18n("Child to Category");
case Relationship:
return i18n("Relationship");
case Unknown:
return i18n("Unknown");
default:
return i18n("? AssociationType ?");
};
}
/**
* Convert a string item into AssociationType representation.
* @param item item to convert
* @return AssociationType object
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("Generalization"))
return Generalization;
else if (item == QStringLiteral("Aggregation"))
return Aggregation;
else if (item == QStringLiteral("Dependency"))
return Dependency;
else if (item == QStringLiteral("Association"))
return Association;
else if (item == QStringLiteral("Association_Self"))
return Association_Self;
else if (item == QStringLiteral("Coll_Mesg_Async"))
return Coll_Mesg_Async;
else if (item == QStringLiteral("Coll_Mesg_Sync"))
return Coll_Mesg_Sync;
else if (item == QStringLiteral("Seq_Message"))
return Seq_Message;
else if (item == QStringLiteral("Coll_Mesg_Self"))
return Coll_Mesg_Self;
else if (item == QStringLiteral("Seq_Message_Self"))
return Seq_Message_Self;
else if (item == QStringLiteral("Containment"))
return Containment;
else if (item == QStringLiteral("Composition"))
return Composition;
else if (item == QStringLiteral("Realization"))
return Realization;
else if (item == QStringLiteral("UniAssociation"))
return UniAssociation;
else if (item == QStringLiteral("Anchor"))
return Anchor;
else if (item == QStringLiteral("State"))
return State;
else if (item == QStringLiteral("Activity"))
return Activity;
else if (item == QStringLiteral("Exception"))
return Exception;
else if (item == QStringLiteral("Category2Parent"))
return Category2Parent;
else if (item == QStringLiteral("Child2Category"))
return Child2Category;
else if (item == QStringLiteral("Relationship"))
return Relationship;
else
return Unknown;
}
/**
* Convert an integer item into ProgrammingLanguage representation.
* @param item integer value to convert
* @return AssociationType enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
/**
* Returns true if the given AssociationType has a representation as a
* UMLAssociation.
* @param item the AssociationType enum value to check
* @return boolean value
*/
bool hasUMLRepresentation(Enum item)
{
return (item == Generalization ||
item == Realization ||
item == Association ||
item == Association_Self ||
item == UniAssociation ||
item == Aggregation ||
item == Relationship ||
item == Composition ||
item == Dependency ||
item == Category2Parent ||
item == Child2Category);
}
} // end namespace AssociationType
//-----------------------------------------------------------------------------
namespace LayoutType
{
/**
* Return string corresponding to the given LayoutType.
*/
QString toString(Enum item)
{
switch (item) {
case Direct:
return QStringLiteral("Direct");
case Orthogonal:
return QStringLiteral("Orthogonal");
case Polyline:
return QStringLiteral("Polyline");
case Spline:
return QStringLiteral("Spline");
default:
break;
}
return QString();
}
/**
* Return LayoutType corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("Direct"))
return Direct;
if (item == QStringLiteral("Orthogonal"))
return Orthogonal;
if (item == QStringLiteral("Polyline"))
return Polyline;
if (item == QStringLiteral("Spline"))
return Spline;
return Direct;
}
/**
* Convert an integer item into LayoutType representation.
* @param item integer value to convert
* @return LayoutType enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
}
//-----------------------------------------------------------------------------
namespace SignatureType {
/**
* Return string corresponding to the given SignatureType.
*/
QString toString(Enum item)
{
switch (item) {
case NoSig:
return QStringLiteral("NoSig");
case ShowSig:
return QStringLiteral("ShowSig");
case SigNoVis:
return QStringLiteral("SigNoVis");
case NoSigNoVis:
return QStringLiteral("NoSigNoVis");
default:
break;
}
return QString();
}
/**
* Return SignatureType corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("NoSig"))
return NoSig;
if (item == QStringLiteral("ShowSig"))
return ShowSig;
if (item == QStringLiteral("SigNoVis"))
return SigNoVis;
if (item == QStringLiteral("NoSigNoVis"))
return NoSigNoVis;
return NoSig;
}
/**
* Convert an integer item into SignatureType representation.
* @param item integer value to convert
* @return SignatureType enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace SignatureType
//-----------------------------------------------------------------------------
namespace TextRole {
/**
* Return string corresponding to the given TextRole.
*/
QString toString(Enum item)
{
switch (item) {
case Floating:
return QStringLiteral("Floating");
case MultiA:
return QStringLiteral("MultiA");
case MultiB:
return QStringLiteral("MultiB");
case Name:
return QStringLiteral("Name");
case Seq_Message:
return QStringLiteral("Seq_Message");
case Seq_Message_Self:
return QStringLiteral("Seq_Message_Self");
case Coll_Message:
return QStringLiteral("Coll_Message");
case Coll_Message_Self:
return QStringLiteral("Coll_Message_Self");
case State:
return QStringLiteral("State");
case RoleAName:
return QStringLiteral("RoleAName");
case RoleBName:
return QStringLiteral("RoleBName");
case ChangeA:
return QStringLiteral("ChangeA");
case ChangeB:
return QStringLiteral("ChangeB");
default:
break;
}
return QStringLiteral("? TextRole ?");
}
/**
* Return TextRole corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("Floating"))
return Floating;
if (item == QStringLiteral("MultiA"))
return MultiA;
if (item == QStringLiteral("MultiB"))
return MultiB;
if (item == QStringLiteral("Name"))
return Name;
if (item == QStringLiteral("Seq_Message"))
return Seq_Message;
if (item == QStringLiteral("Seq_Message_Self"))
return Seq_Message_Self;
if (item == QStringLiteral("Coll_Message"))
return Coll_Message;
if (item == QStringLiteral("Coll_Message_Self"))
return Coll_Message_Self;
if (item == QStringLiteral("State"))
return State;
if (item == QStringLiteral("RoleAName"))
return RoleAName;
if (item == QStringLiteral("RoleBName"))
return RoleBName;
if (item == QStringLiteral("ChangeA"))
return ChangeA;
if (item == QStringLiteral("ChangeB"))
return ChangeB;
return Floating;
}
/**
* Convert an integer item into TextRole representation.
* @param item integer value to convert
* @return TextRole enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace TextRole
//-----------------------------------------------------------------------------
namespace Changeability {
/**
* Convert Changeability::Enum value into QString representation.
* @param item The Changeability enum value to convert.
*/
QString toString(Enum item)
{
switch (item) {
case Changeability::Frozen:
return QStringLiteral("frozen");
case Changeability::AddOnly:
return QStringLiteral("addOnly");
case Changeability::Changeable:
return QStringLiteral("changeable");
default:
break;
}
return QStringLiteral("? Changeability ?");
}
/**
* Return Changeability::Enum corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("frozen"))
return Frozen;
if (item == QStringLiteral("addOnly"))
return AddOnly;
if (item == QStringLiteral("changeable"))
return Changeable;
return Changeable;
}
/**
* Convert an integer item into Changeability representation.
* @param item integer value to convert
* @return Changeability enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace Changeability
//-----------------------------------------------------------------------------
namespace SequenceMessage {
/**
* Return string corresponding to the given SequenceMessage.
*/
QString toString(Enum item)
{
switch (item) {
case Synchronous:
return QStringLiteral("Synchronous");
case Asynchronous:
return QStringLiteral("Asynchronous");
case Creation:
return QStringLiteral("Creation");
case Lost:
return QStringLiteral("Lost");
case Found:
return QStringLiteral("Found");
default:
break;
}
return QStringLiteral("? SequenceMessage ?");
}
/**
* Return SequenceMessage corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("Synchronous"))
return Synchronous;
if (item == QStringLiteral("Asynchronous"))
return Asynchronous;
if (item == QStringLiteral("Creation"))
return Creation;
if (item == QStringLiteral("Lost"))
return Lost;
if (item == QStringLiteral("Found"))
return Found;
return Synchronous;
}
/**
* Convert an integer item into SequenceMessage representation.
* @param item integer value to convert
* @return SequenceMessage enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace SequenceMessage
//-----------------------------------------------------------------------------
namespace RoleType {
/**
* Return string corresponding to the given RoleType.
*/
QString toString(Enum item)
{
switch (item) {
case A:
return QStringLiteral("A");
case B:
return QStringLiteral("B");
default:
break;
}
return QStringLiteral("? RoleType ?");
}
/**
* Return RoleType corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("A"))
return A;
if (item == QStringLiteral("B"))
return B;
return A;
}
/**
* Convert an integer item into RoleType representation.
* @param item integer value to convert
* @return RoleType enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace RoleType
//-----------------------------------------------------------------------------
namespace ParameterDirection {
/**
* Return string corresponding to the given ParameterDirection.
*/
QString toString(Enum item)
{
switch (item) {
case In:
return QStringLiteral("In");
case InOut:
return QStringLiteral("InOut");
case Out:
return QStringLiteral("Out");
default:
break;
}
return QStringLiteral("? ParameterDirection ?");
}
/**
* Return ParameterDirection corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("In"))
return In;
if (item == QStringLiteral("InOut"))
return InOut;
if (item == QStringLiteral("Out"))
return Out;
return In;
}
/**
* Convert an integer item into ParameterDirection representation.
* @param item integer value to convert
* @return ParameterDirection enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace ParameterDirection
//-----------------------------------------------------------------------------
namespace PrimitiveTypes {
const char *strings[] = {
"String",
"Boolean",
"UnlimitedNatural",
"Integer",
"Real",
"not_a_primitivetype"
};
QString toString(Enum item)
{
return QLatin1String(strings[item]);
}
QString toString(int item)
{
if (item < 0 || item >= n_types)
return QLatin1String(strings[Reserved]);
return QLatin1String(strings[item]);
}
/**
* Converts the string of an Enum to the Enum value.
* @param item The string to convert to Enum
* @param strict Controls the value returned if the given string does not
* represent an Enum value: If strict is true then the value
* Reserved is returned, otherwise the value String is
* returned.
*/
Enum fromString(const QString& item, bool strict /* = false */)
{
for (int i = 0; i < n_types; i++) {
if (item == toString(i))
return Enum(i);
}
return (strict ? Reserved : String);
}
Enum fromInt(int item)
{
if (item < 0 || item >= n_types)
return Reserved;
return Enum(item);
}
} // end namespace PrimitiveTypes
//-----------------------------------------------------------------------------
namespace ProgrammingLanguage {
/**
* Return string corresponding to the given ProgrammingLanguage.
*/
QString toString(Enum item)
{
switch (item) {
case ActionScript:
return QStringLiteral("ActionScript");
case Ada:
return QStringLiteral("Ada");
case Cpp:
return QStringLiteral("C++");
case CSharp:
return QStringLiteral("C#");
case D:
return QStringLiteral("D");
case IDL:
return QStringLiteral("IDL");
case Java:
return QStringLiteral("Java");
case JavaScript:
return QStringLiteral("JavaScript");
case MySQL:
return QStringLiteral("MySQL");
case Pascal:
return QStringLiteral("Pascal");
case Perl:
return QStringLiteral("Perl");
case PHP:
return QStringLiteral("PHP");
case PHP5:
return QStringLiteral("PHP5");
case PostgreSQL:
return QStringLiteral("PostgreSQL");
case Python:
return QStringLiteral("Python");
case Ruby:
return QStringLiteral("Ruby");
case SQL:
return QStringLiteral("SQL");
case Tcl:
return QStringLiteral("Tcl");
case Vala:
return QStringLiteral("Vala");
case XMLSchema:
return QStringLiteral("XMLSchema");
default:
break;
}
return QStringLiteral("none");
}
/**
* Return ProgrammingLanguage corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("ActionScript"))
return ActionScript;
if (item == QStringLiteral("Ada"))
return Ada;
if (item == QStringLiteral("C++") || item == QStringLiteral("Cpp")) // "Cpp" only for bkwd compatibility
return Cpp;
if (item == QStringLiteral("C#"))
return CSharp;
if (item == QStringLiteral("D"))
return D;
if (item == QStringLiteral("IDL"))
return IDL;
if (item == QStringLiteral("Java"))
return Java;
if (item == QStringLiteral("JavaScript"))
return JavaScript;
if (item == QStringLiteral("MySQL"))
return MySQL;
if (item == QStringLiteral("Pascal"))
return Pascal;
if (item == QStringLiteral("Perl"))
return Perl;
if (item == QStringLiteral("PHP"))
return PHP;
if (item == QStringLiteral("PHP5"))
return PHP5;
if (item == QStringLiteral("PostgreSQL"))
return PostgreSQL;
if (item == QStringLiteral("Python"))
return Python;
if (item == QStringLiteral("Ruby"))
return Ruby;
if (item == QStringLiteral("SQL"))
return SQL;
if (item == QStringLiteral("Tcl"))
return Tcl;
if (item == QStringLiteral("Vala"))
return Vala;
if (item == QStringLiteral("XMLSchema"))
return XMLSchema;
return Reserved;
}
/**
* Convert an integer item into ProgrammingLanguage representation.
* @param item integer value to convert
* @return ProgrammingLanguage enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
/**
* Return extensions associated with the requested language.
* @param item programming language index
* @return extensions list
*/
QStringList toExtensions(Enum item)
{
QStringList result;
switch (item) { //:TODO: More languages?
case ActionScript:
result << QStringLiteral("*.as");
break;
case Ada:
result << QStringLiteral("*.ads")
<< QStringLiteral("*.adb")
<< QStringLiteral("*.ada");
break;
case Cpp:
result << QStringLiteral("*.h")
<< QStringLiteral("*.hpp")
<< QStringLiteral("*.hh")
<< QStringLiteral("*.hxx")
<< QStringLiteral("*.H");
break;
case CSharp:
result << QStringLiteral("*.cs");
break;
case D:
result << QStringLiteral("*.d");
break;
case IDL:
result << QStringLiteral("*.idl");
break;
case Java:
result << QStringLiteral("*.java");
break;
case JavaScript:
result << QStringLiteral("*.js");
break;
case Pascal:
result << QStringLiteral("*.pas");
break;
case Perl:
result << QStringLiteral("*.pl");
break;
case PHP:
result << QStringLiteral("*.php") << QStringLiteral("*.inc");
break;
case PHP5:
result << QStringLiteral("*.php") << QStringLiteral("*.php5") << QStringLiteral("*.inc");
break;
case Python:
result << QStringLiteral("*.py") << QStringLiteral("*.pyw");
break;
case Ruby:
result << QStringLiteral("*.rb");
break;
case SQL:
case MySQL:
case PostgreSQL:
result << QStringLiteral("*.sql");
if (item == MySQL)
result << QStringLiteral("*.frm");
break;
case Tcl:
result << QStringLiteral("*.tcl");
break;
case Vala:
result << QStringLiteral("*.vala") << QStringLiteral("*.vapi");
break;
case XMLSchema:
result << QStringLiteral("*.xsd");
break;
default:
break;
}
return result;
}
/**
* Return clear text file extension description for the requested language.
* @param item programming language index
* @return extension
*/
QString toExtensionsDescription(Enum item)
{
QString result = QString::fromLatin1("Files");
switch (item) { //:TODO: More languages?
case Uml::ProgrammingLanguage::Ada:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::Cpp:
result = QStringLiteral("Header files");
break;
case Uml::ProgrammingLanguage::IDL:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::Java:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::Pascal:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::Python:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::CSharp:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::PHP:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::PHP5:
result = QStringLiteral("Source files");
break;
case Uml::ProgrammingLanguage::Vala:
result = QStringLiteral("Source files");
break;
default:
break;
}
return toString(item) + QStringLiteral(" ") + result;
}
bool isCaseSensitive(Enum item)
{
return (item != Uml::ProgrammingLanguage::Pascal &&
item != Uml::ProgrammingLanguage::Ada &&
item != Uml::ProgrammingLanguage::SQL &&
item != Uml::ProgrammingLanguage::MySQL &&
item != Uml::ProgrammingLanguage::PostgreSQL);
}
QString scopeSeparator(Enum item)
{
if (item == Uml::ProgrammingLanguage::Ada ||
item == Uml::ProgrammingLanguage::CSharp ||
item == Uml::ProgrammingLanguage::Vala ||
item == Uml::ProgrammingLanguage::Pascal ||
item == Uml::ProgrammingLanguage::Java ||
item == Uml::ProgrammingLanguage::JavaScript ||
item == Uml::ProgrammingLanguage::Vala ||
item == Uml::ProgrammingLanguage::Python) // CHECK: more?
return QStringLiteral(".");
return QStringLiteral("::");
}
} // end namespace ProgrammingLanguage
//-----------------------------------------------------------------------------
namespace Region {
/**
* Return string corresponding to the given Region.
*/
QString toString(Enum item)
{
switch (item) {
case Error:
return QStringLiteral("Error");
case West:
return QStringLiteral("West");
case North:
return QStringLiteral("North");
case East:
return QStringLiteral("East");
case South:
return QStringLiteral("South");
case NorthWest:
return QStringLiteral("NorthWest");
case NorthEast:
return QStringLiteral("NorthEast");
case SouthEast:
return QStringLiteral("SouthEast");
case SouthWest:
return QStringLiteral("SouthWest");
case Center:
return QStringLiteral("Center");
default:
break;
}
return QStringLiteral("? Region ?");
}
/**
* Return Region corresponding to the given string.
*/
Enum fromString(const QString& item)
{
if (item == QStringLiteral("Error"))
return Error;
if (item == QStringLiteral("West"))
return West;
if (item == QStringLiteral("North"))
return North;
if (item == QStringLiteral("East"))
return East;
if (item == QStringLiteral("South"))
return South;
if (item == QStringLiteral("NorthWest"))
return NorthWest;
if (item == QStringLiteral("NorthEast"))
return NorthEast;
if (item == QStringLiteral("SouthEast"))
return SouthEast;
if (item == QStringLiteral("SouthWest"))
return SouthWest;
if (item == QStringLiteral("Center"))
return Center;
return Error;
}
/**
* Convert an integer item into Region representation.
* @param item integer value to convert
* @return Region enum
*/
Enum fromInt(int item)
{
return Enum(item);
}
} // end namespace Region
//-----------------------------------------------------------------------------
//namespace Corner {
/**
* Return string corresponding to the given Corner.
*/
QString Corner::toString(Enum item)
{
switch (item) {
case TopLeft:
return QStringLiteral("TopLeft");
case TopRight:
return QStringLiteral("TopRight");
case BottomRight:
return QStringLiteral("BottomRight");
case BottomLeft:
return QStringLiteral("BottomLeft");
default:
break;
}
return QStringLiteral("? Corner ?");
}
/**
* Return Corner corresponding to the given string.
*/
Corner::Enum Corner::fromString(const QString& item)
{
if (item == QStringLiteral("TopLeft"))
return TopLeft;
if (item == QStringLiteral("TopRight"))
return TopRight;
if (item == QStringLiteral("BottomRight"))
return BottomRight;
if (item == QStringLiteral("BottomLeft"))
return BottomLeft;
return TopLeft;
}
/**
* Convert an integer item into Corner representation.
* @param item integer value to convert
* @return Corner enum
*/
Corner::Enum Corner::fromInt(int item)
{
return Enum(item);
}
//} // end namespace Corner
//-----------------------------------------------------------------------------
namespace ID {
QDebug operator<<(QDebug out, ID::Type &type)
{
out.nospace() << "ID::Type: " << Uml::ID::toString(type);
return out.space();
}
QString toString(const ID::Type &id)
{
return QLatin1String(id.c_str());
}
ID::Type fromString(const QString &id)
{
return qPrintable(id);
}
} // end namespace ID
/**
* Return general system font.
* @return font
*/
QFont systemFont()
{
return QFontDatabase::systemFont(QFontDatabase::GeneralFont);
}
} // end namespace Uml
/**
* Convert floating point number string with '.' or ',' as decimal point to qreal.
* @param s floating point number string
* @return floating point number
* @note See https://bugs.kde.org/show_bug.cgi?id=357373 for more informations.
*/
qreal toDoubleFromAnyLocale(const QString &s)
{
bool ok;
qreal value = s.toDouble(&ok);
if (!ok) {
static QLocale hungary(QLocale::Hungarian);
value = hungary.toDouble(s, &ok);
if (!ok) {
qCritical() << "could not read floating point number";
value = 0;
}
}
return value;
}
| 36,957
|
C++
|
.cpp
| 1,231
| 23.581641
| 109
| 0.604241
|
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,269
|
import_rose.cpp
|
KDE_umbrello/umbrello/import_rose.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "import_rose.h"
// app includes
#include "uml.h"
#include "umldoc.h"
#include "folder.h"
#define DBG_SRC QStringLiteral("Import_Rose")
#include "debug_utils.h"
#include "import_utils.h"
#include "petalnode.h"
#include "petaltree2uml.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QMessageBox>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
#include <QTextStream>
DEBUG_REGISTER(Import_Rose)
namespace Import_Rose {
/**
* Directory prefix of .mdl file is buffered for possibly finding .cat/.sub
* controlled units (if no path is given at their definition.)
*/
QString dirPrefix;
/**
* Set language if encountered in file.
* The last language encountered wins.
*/
Uml::ProgrammingLanguage::Enum progLang = Uml::ProgrammingLanguage::Reserved;
uint nClosures; // Multiple closing parentheses may appear on a single
// line. The parsing is done line-by-line and using
// recursive descent. This means that we can only handle
// _one_ closing parenthesis at a time, i.e. the closing
// of the currently parsed node. Since we may see more
// closing parentheses than we can handle, we need a
// counter indicating how many additional node closings
// have been seen.
uint linum; // line number
QString g_methodName;
void methodName(const QString& m)
{
g_methodName = m;
}
QString mdlPath()
{
return dirPrefix;
}
/**
* Auxiliary function for diagnostics: Return current location.
*/
QString loc()
{
return QStringLiteral("Import_Rose::") + g_methodName +
QStringLiteral(" line ") + QString::number(linum) + QStringLiteral(": ");
}
/**
* Split a line into lexemes.
*/
QStringList scan(const QString& lin)
{
QStringList result;
QString line = lin.trimmed();
if (line.isEmpty())
return result; // empty
QString lexeme;
const uint len = line.length();
bool inString = false;
for (uint i = 0; i < len; ++i) {
QChar c = line[i];
if (c == QLatin1Char('"')) {
lexeme += c;
if (inString) {
result.append(lexeme);
lexeme.clear();
}
inString = !inString;
} else if (inString ||
c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('@')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
result.append(lexeme);
lexeme.clear();
}
if (! c.isSpace()) {
result.append(QString(c));
}
}
}
if (!lexeme.isEmpty())
result.append(lexeme);
return result;
}
/**
* Emulate perl shift().
*/
QString shift(QStringList& l)
{
QString first = l.first();
l.pop_front();
return first;
}
/**
* Check for closing of one or more scopes.
*/
bool checkClosing(QStringList& tokens)
{
if (tokens.count() == 0)
return false;
if (tokens.last() == QStringLiteral(")")) {
// For a single closing parenthesis, we just return true.
// But if there are more closing parentheses, we need to increment
// nClosures for each scope.
tokens.pop_back();
while (tokens.count() && tokens.last() == QStringLiteral(")")) {
nClosures++;
tokens.pop_back();
}
return true;
}
return false;
}
/**
* Immediate values are numbers or quoted strings.
* @return True if the given text is a natural or negative number
* or a quoted string.
*/
bool isImmediateValue(QString s)
{
return s.contains(QRegularExpression(QStringLiteral("^[\\d\\-\"]")));
}
/**
* Extract immediate values out of `l'.
* Examples of immediate value lists:
* number list: (123, 456)
* string list: ("SomeText" 888)
* Any enclosing parentheses are removed.
* All extracted items are also removed from `l'.
* For the example given above the following is returned:
* "123 456"
* or
* "\"SomeText\" 888"
*/
QString extractImmediateValues(QStringList& l)
{
if (l.count() == 0)
return QString();
if (l.first() == QStringLiteral("("))
l.pop_front();
QString result;
bool start = true;
while (l.count() && isImmediateValue(l.first())) {
if (start)
start = false;
else
result += QLatin1Char(' ');
result += shift(l);
if (l.first() == QStringLiteral(","))
l.pop_front();
}
if (l.first() == QStringLiteral(")"))
l.pop_front();
while (l.count() && l.first() == QStringLiteral(")")) {
nClosures++;
l.pop_front();
}
return result;
}
QString collectVerbatimText(QTextStream& stream)
{
QString result;
QString line;
methodName(QStringLiteral("collectVerbatimText"));
while (!(line = stream.readLine()).isNull()) {
linum++;
line = line.trimmed();
if (line.isEmpty() || line.startsWith(QLatin1Char(')')))
break;
if (line[0] != QLatin1Char('|')) {
logError1("%1 expecting '|' at start of verbatim text", loc());
return QString();
} else {
result += line.mid(1) + QLatin1Char('\n');
}
}
if (line.isNull()) {
logError1("%1 premature EOF", loc());
return QString();
}
if (! line.isEmpty()) {
for (int i = 0; i < line.length(); ++i) {
const QChar& clParenth = line[i];
if (clParenth != QLatin1Char(')')) {
logError2("%1 expected ')', found: %2", loc(), clParenth);
return QString();
}
nClosures++;
}
}
return result;
}
/**
* Extract the stripped down value from a (value ...) element.
* Example: for the input
* (value Text "This is some text")
* the following is extracted:
* "This is some text"
* Extracted elements and syntactic sugar of the value element are
* removed from the input list.
* The stream is passed into this method because it may be necessary
* to read new lines - in the case of verbatim text.
* The format of verbatim text in petal files is as follows:
*
* (value Text
* |This is the first line of verbatim text.
* |This is another line of verbatim text.
* )
* (The '|' character is supposed to be in the first column of the line)
* In this case the two lines are extracted without the leading '|'.
* The line ending '\n' of each line is preserved.
*/
QString extractValue(QStringList& l, QTextStream& stream)
{
methodName(QStringLiteral("extractValue"));
if (l.count() == 0)
return QString();
if (l.first() == QStringLiteral("("))
l.pop_front();
if (l.first() != QStringLiteral("value"))
return QString();
l.pop_front(); // remove "value"
l.pop_front(); // remove the value type: could be e.g. "Text" or "cardinality"
QString result;
if (l.count() == 0) { // expect verbatim text to follow on subsequent lines
QString text = collectVerbatimText(stream);
nClosures--; // expect own closure
return text;
}
result = shift(l);
if (l.first() != QStringLiteral(")")) {
logError1("%1 expecting closing parenthesis", loc());
return result;
}
l.pop_front();
while (l.count() && l.first() == QStringLiteral(")")) {
nClosures++;
l.pop_front();
}
return result;
}
/**
* Read attributes of a node.
* @param initialArgs Tokens on the line of the opening "(" of the node
* but with leading whitespace and the opening "(" removed.
* @param stream The QTextStream from which to read following lines.
* @return Pointer to the created PetalNode or NULL on error.
*/
PetalNode *readAttributes(QStringList initialArgs, QTextStream& stream)
{
methodName(QStringLiteral("readAttributes"));
if (initialArgs.count() == 0) {
logError1("%1 initialArgs is empty", loc());
return nullptr;
}
PetalNode::NodeType nt;
QString type = shift(initialArgs);
if (type == QStringLiteral("object"))
nt = PetalNode::nt_object;
else if (type == QStringLiteral("list"))
nt = PetalNode::nt_list;
else {
logError2("%1 unknown node type %2", loc(), type);
return nullptr;
}
PetalNode *node = new PetalNode(nt);
bool seenClosing = checkClosing(initialArgs);
node->setInitialArgs(initialArgs);
if (seenClosing)
return node;
PetalNode::NameValueList attrs;
QString line;
while (!(line = stream.readLine()).isNull()) {
linum++;
line = line.trimmed();
if (line.isEmpty())
continue;
QStringList tokens = scan(line);
QString stringOrNodeOpener = shift(tokens);
QString name;
if (nt == PetalNode::nt_object && !stringOrNodeOpener.contains(QRegularExpression(QStringLiteral("^[A-Za-z]")))) {
logError2("%1 unexpected line %2", loc(), line);
delete node;
return nullptr;
}
PetalNode::StringOrNode value;
if (nt == PetalNode::nt_object) {
name = stringOrNodeOpener;
if (tokens.count() == 0) { // expect verbatim text to follow on subsequent lines
value.string = collectVerbatimText(stream);
PetalNode::NameValue attr(name, value);
attrs.append(attr);
if (nClosures) {
// Decrement nClosures exactly once, namely for the own scope.
// Each recursion of readAttributes() is only responsible for
// its own scope. I.e. each further scope closing is handled by
// an outer recursion in case of multiple closing parentheses.
nClosures--;
break;
}
continue;
}
stringOrNodeOpener = shift(tokens);
} else if (stringOrNodeOpener != QStringLiteral("(")) {
value.string = stringOrNodeOpener;
PetalNode::NameValue attr;
attr.second = value;
attrs.append(attr);
if (tokens.count() && tokens.first() != QStringLiteral(")")) {
logDebug1("%1 NYI - immediate list entry with more than one item", loc());
}
if (checkClosing(tokens))
break;
continue;
}
if (stringOrNodeOpener == QStringLiteral("(")) {
QString nxt = tokens.first();
if (isImmediateValue(nxt)) {
value.string = extractImmediateValues(tokens);
} else if (nxt == QStringLiteral("value") || nxt.startsWith(QLatin1Char('"'))) {
value.string = extractValue(tokens, stream);
} else {
value.node = readAttributes(tokens, stream);
if (value.node == nullptr) {
delete node;
return nullptr;
}
}
PetalNode::NameValue attr(name, value);
attrs.append(attr);
if (nClosures) {
// Decrement nClosures exactly once, namely for the own scope.
// Each recursion of readAttributes() is only responsible for
// its own scope. I.e. each further scope closing is handled by
// an outer recursion in case of multiple closing parentheses.
nClosures--;
break;
}
} else {
value.string = stringOrNodeOpener;
bool seenClosing = checkClosing(tokens);
PetalNode::NameValue attr(name, value);
attrs.append(attr);
if (name == QStringLiteral("language")) {
QString language(value.string);
language.remove(QLatin1Char('\"'));
if (language == QStringLiteral("Analysis"))
progLang = Uml::ProgrammingLanguage::Reserved;
else if (language == QStringLiteral("CORBA"))
progLang = Uml::ProgrammingLanguage::IDL;
else if (language == QStringLiteral("C++") || language == QStringLiteral("VC++"))
progLang = Uml::ProgrammingLanguage::Cpp;
else if (language == QStringLiteral("Java"))
progLang = Uml::ProgrammingLanguage::Java;
else if (language == QStringLiteral("Ada"))
progLang = Uml::ProgrammingLanguage::Ada;
}
if (seenClosing) {
break;
}
}
}
node->setAttributes(attrs);
return node;
}
#define SETCODEC(str) stream.setCodec(str); break
/**
* Parse a file into the PetalNode internal tree representation
* and then create Umbrello objects by traversing the tree.
*
* @return In case of error: NULL
* In case of success with non NULL parentPkg: pointer to UMLPackage created for controlled unit
* In case of success with NULL parentPkg: pointer to root folder of Logical View
*/
UMLPackage *loadFromMDL(QFile& file, UMLPackage *parentPkg /* = nullptr */)
{
methodName(QStringLiteral("loadFromMDL"));
if (parentPkg == nullptr) {
QString fName = file.fileName();
int lastSlash = fName.lastIndexOf(QLatin1Char('/'));
if (lastSlash > 0) {
dirPrefix = fName.left(lastSlash + 1);
}
}
QTextStream stream(&file);
stream.setCodec("ISO 8859-1");
QString line;
PetalNode *root = nullptr;
uint nClosures_sav = nClosures;
uint linum_sav = linum;
nClosures = 0;
linum = 0;
while (!(line = stream.readLine()).isNull()) {
linum++;
if (line.contains(QRegularExpression(QStringLiteral("^\\s*\\(object Petal")))) {
bool finish = false;
// Nested loop determines character set to use
while (!(line = stream.readLine()).isNull()) {
linum++; // CHECK: do we need petal version info?
if (line.contains(QLatin1Char(')'))) {
finish = true;
line = line.replace(QStringLiteral(")"), QString());
}
QStringList a = line.trimmed().split(QRegularExpression(QStringLiteral("\\s+")));
if (a.size() == 2 && a[0] == QStringLiteral("charSet")) {
const QString& charSet = a[1];
if (!charSet.contains(QRegularExpression(QStringLiteral("^\\d+$")))) {
logWarn2("%1 Unimplemented charSet %2", loc(), charSet);
if (finish)
break;
continue;
}
const int charSetNum = charSet.toInt();
switch (charSetNum) {
case 0: // ASCII
;
case 1: // Default
SETCODEC("System");
case 2: // Symbol
; // @todo SETCODEC("what");
case 77: // Mac
SETCODEC("macintosh");
case 128: // ShiftJIS (Japanese)
SETCODEC("Shift_JIS");
case 129: // Hangul (Korean)
SETCODEC("EUC-KR");
case 130: // Johab (Korean)
SETCODEC("EUC-KR");
case 134: // GB2312 (Chinese)
SETCODEC("GB18030"); // "Don't use GB2312 here" (Ralf H.)
case 136: // ChineseBig5
SETCODEC("Big5");
case 161: // Greek
SETCODEC("windows-1253");
case 162: // Turkish
SETCODEC("windows-1254");
case 163: // Vietnamese
SETCODEC("windows-1258");
case 177: // Hebrew
SETCODEC("windows-1255");
case 178: // Arabic
SETCODEC("windows-1256");
case 186: // Baltic
SETCODEC("windows-1257");
case 204: // Russian
SETCODEC("windows-1251");
case 222: // Thai
SETCODEC("TIS-620");
case 238: // EastEurope
SETCODEC("windows-1250");
case 255: // OEM (extended ASCII)
SETCODEC("windows-1252");
default:
logWarn2("%1 Unimplemented charSet number %2", loc(), charSetNum);
}
}
if (finish)
break;
}
if (line.isNull())
break;
} else {
QRegularExpression objectRx(QStringLiteral("^\\s*\\(object "));
if (line.contains(objectRx)) {
nClosures = 0;
QStringList initialArgs = scan(line);
initialArgs.pop_front(); // remove opening parenthesis
root = readAttributes(initialArgs, stream);
break;
}
}
}
file.close();
nClosures = nClosures_sav;
linum = linum_sav;
if (root == nullptr)
return nullptr;
if (progLang != UMLApp::app()->activeLanguage()) {
logDebug1("loadFromMDL: Setting active language to %1",
Uml::ProgrammingLanguage::toString(progLang));
UMLApp::app()->setGenerator(progLang);
}
if (parentPkg) {
UMLPackage *child = petalTree2Uml(root, parentPkg);
delete root;
return child;
}
if (root->name() != QStringLiteral("Design")) {
logError1("%1 expecting root name Design", loc());
delete root;
return nullptr;
}
Import_Utils::assignUniqueIdOnCreation(false);
UMLDoc *umldoc = UMLApp::app()->document();
//*************************** import Logical View *********************************
umldoc->setCurrentRoot(Uml::ModelType::Logical);
UMLPackage *logicalView = umldoc->rootFolder(Uml::ModelType::Logical);
importView(root, logicalView,
QStringLiteral("root_category"), QStringLiteral("logical_models"),
QStringLiteral("Class_Category"), QStringLiteral("logical_presentations"));
//*************************** import Use Case View ********************************
umldoc->setCurrentRoot(Uml::ModelType::UseCase);
UMLPackage *useCaseView = umldoc->rootFolder(Uml::ModelType::UseCase);
importView(root, useCaseView,
QStringLiteral("root_usecase_package"), QStringLiteral("logical_models"),
QStringLiteral("Class_Category"), QStringLiteral("logical_presentations"));
//*************************** import Component View *******************************
umldoc->setCurrentRoot(Uml::ModelType::Component);
UMLPackage *componentView = umldoc->rootFolder(Uml::ModelType::Component);
importView(root, componentView,
QStringLiteral("root_subsystem"), QStringLiteral("physical_models"),
QStringLiteral("SubSystem"), QStringLiteral("physical_presentations"));
//*************************** import Deployment View ******************************
umldoc->setCurrentRoot(Uml::ModelType::Deployment);
UMLPackage *deploymentView = umldoc->rootFolder(Uml::ModelType::Deployment);
importView(root, deploymentView, QStringLiteral("process_structure"),
QStringLiteral("ProcsNDevs"), QStringLiteral("Processes"));
//*************************** wrap up ********************************
delete root;
umldoc->setCurrentRoot(Uml::ModelType::Logical);
Import_Utils::assignUniqueIdOnCreation(true);
umldoc->resolveTypes();
return logicalView;
}
#undef SETCODEC
}
| 20,498
|
C++
|
.cpp
| 541
| 28.297597
| 122
| 0.552377
|
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,270
|
uniqueid.cpp
|
KDE_umbrello/umbrello/uniqueid.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "uniqueid.h"
#include <krandom.h>
namespace UniqueID {
/**
* Each model object gets assigned a unique ID.
*/
Uml::ID::Type m_uniqueID;
/**
* MAIN FUNCTION: Return a new unique ID.
*/
Uml::ID::Type gen()
{
m_uniqueID = 'u' + KRandom::randomString(12).toStdString();
return m_uniqueID;
}
/**
* Reinitialize the unique ID counter.
* Should not normally be required because the ID counter is
* initialized by default anyway.
*/
void init()
{
m_uniqueID = Uml::ID::Reserved;
}
/**
* Return the last generated unique ID without generating a new one.
*/
Uml::ID::Type get()
{
return m_uniqueID;
}
/**
* Explicitly set a new ID value.
*/
void set(Uml::ID::Type id)
{
m_uniqueID = id;
}
} // end namespace UniqueID
| 917
|
C++
|
.cpp
| 44
| 18.704545
| 92
| 0.701043
|
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,271
|
import_argo.cpp
|
KDE_umbrello/umbrello/import_argo.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "import_argo.h"
// app includes
#define DBG_SRC QStringLiteral("Import_Argo")
#include "debug_utils.h"
#include "uml.h"
#include "umldoc.h"
// kde includes
#include <KLocalizedString>
#include <KZip>
// qt includes
#include <QFile>
#include <QStringList>
#include <QTemporaryDir>
#include <QXmlStreamReader>
DEBUG_REGISTER(Import_Argo)
static void reportError(const QXmlStreamReader &xml, const KZip &zipFile, const QString &fileName)
{
logError3("Import_Argo %1 in file %2 : %3", xml.name().toString(), zipFile.fileName(), fileName);
}
bool Import_Argo::loadFromArgoFile(const KZip &zipFile, const QString &fileName)
{
const KArchiveFile *file = static_cast<const KArchiveFile*>(zipFile.directory()->entry(fileName));
if (!file)
return false;
QXmlStreamReader xml;
xml.addData(file->data());
bool result = true;
while (!xml.atEnd()) {
xml.readNext();
if (xml.name() == QStringLiteral("member")) {
QXmlStreamAttributes attributes = xml.attributes();
QString type = attributes.value(QStringLiteral("type")).toString();
QString name = attributes.value(QStringLiteral("name")).toString();
if (type == QStringLiteral("xmi") && !loadFromXMIFile(zipFile, name))
result = false;
else if (type == QStringLiteral("pgml") && !loadFromPGMLFile(zipFile, name))
result = false;
else if (type == QStringLiteral("todo") && loadFromTodoFile(zipFile, name))
result = false;
else {
logError3("loadFromArgoFile unknown file type %1 in file %2 : %3",
type, zipFile.fileName(), fileName);
result = false;
}
}
}
if (xml.hasError()) {
reportError(xml, zipFile, fileName);
result = false;
}
return result;
}
bool Import_Argo::loadFromPGMLFile(const KZip &zipFile, const QString &fileName)
{
const KArchiveFile *file = static_cast<const KArchiveFile*>(zipFile.directory()->entry(fileName));
if (!file)
return false;
QXmlStreamReader xml;
xml.addData(file->data());
while (!xml.atEnd()) {
xml.readNext();
logDebug3("Import_Argo::loadFromPGMLFile unhandled tag %1 in file %2:%3",
xml.name().toString(), zipFile.fileName(), fileName);
}
if (xml.hasError()) {
reportError(xml, zipFile, fileName);
return false;
}
return true;
}
bool Import_Argo::loadFromTodoFile(const KZip &zipFile, const QString &fileName)
{
const KArchiveFile *file = static_cast<const KArchiveFile*>(zipFile.directory()->entry(fileName));
if (!file)
return false;
QXmlStreamReader xml;
xml.addData(file->data());
while (!xml.atEnd()) {
xml.readNext();
logDebug3("Import_Argo::loadFromTodoFile unhandled tag %1 in file %2:%3",
xml.name().toString(), zipFile.fileName(), fileName);
}
if (xml.hasError()) {
reportError(xml, zipFile, fileName);
return false;
}
return true;
}
bool Import_Argo::loadFromXMIFile(const KZip &zipFile, const QString &fileName)
{
const KArchiveFile *file = static_cast<const KArchiveFile*>(zipFile.directory()->entry(fileName));
if (!file)
return false;
QTemporaryDir tmpDir;
tmpDir.setAutoRemove(true);
file->copyTo(tmpDir.path());
QFile xmiFile(tmpDir.path() + QLatin1Char('/') + file->name());
if(!xmiFile.open(QIODevice::ReadOnly)) {
return false;
}
return UMLApp::app()->document()->loadFromXMI(xmiFile, 0);
}
bool Import_Argo::loadFromZArgoFile(QIODevice &file, UMLPackage *parentPkg)
{
Q_UNUSED(parentPkg);
KZip zipFile(&file);
if (!zipFile.open(QIODevice::ReadOnly))
return false;
const KArchiveDirectory *directory = zipFile.directory();
bool result = true;
for(const QString &name : directory->entries()) {
const KArchiveEntry *entry = directory->entry(name);
if (entry->isFile()) {
const KArchiveFile *file = static_cast<const KArchiveFile*>(entry);
if (file == nullptr) {
logError1("loadFromZArgoFile: Could not read file from %1", name);
continue;
}
if (name.endsWith(QStringLiteral(".argo")))
result = loadFromArgoFile(zipFile, name);
}
}
return result;
}
| 4,621
|
C++
|
.cpp
| 129
| 29.20155
| 102
| 0.641691
|
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,272
|
worktoolbar.cpp
|
KDE_umbrello/umbrello/worktoolbar.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "worktoolbar.h"
// application specific includes
#include "debug_utils.h"
#include "icon_utils.h"
#include "optionstate.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
// kde include files
#include <KLocalizedString>
#include <KActionCollection>
// qt include files
#include <QToolButton>
/**
* Creates a work tool bar.
*
* @param parentWindow The parent of the toolbar.
*/
WorkToolBar::WorkToolBar(QMainWindow *parentWindow)
: KToolBar(QStringLiteral("worktoolbar"), parentWindow, Qt::TopToolBarArea, true, true, true)
{
m_CurrentButtonID = tbb_Undefined;
loadPixmaps();
m_Type = Uml::DiagramType::Class; // first time in just want it to load arrow,
// needs anything but Uml::DiagramType::Undefined
setOrientation(Qt::Vertical);
// setVerticalStretchable(true);
// initialize old tool map, everything starts with select tool (arrow)
m_map.insert(Uml::DiagramType::UseCase, tbb_Arrow);
m_map.insert(Uml::DiagramType::Collaboration, tbb_Arrow);
m_map.insert(Uml::DiagramType::Class, tbb_Arrow);
m_map.insert(Uml::DiagramType::Object, tbb_Arrow);
m_map.insert(Uml::DiagramType::Sequence, tbb_Arrow);
m_map.insert(Uml::DiagramType::State, tbb_Arrow);
m_map.insert(Uml::DiagramType::Activity, tbb_Arrow);
m_map.insert(Uml::DiagramType::EntityRelationship, tbb_Arrow);
m_map.insert(Uml::DiagramType::Undefined, tbb_Arrow);
slotCheckToolBar(Uml::DiagramType::Undefined);
}
/**
* Standard destructor.
*/
WorkToolBar::~WorkToolBar()
{
}
/**
* Inserts the button corresponding to the tbb value given
* and activates the toggle.
*/
QAction* WorkToolBar::insertHotBtn(ToolBar_Buttons tbb)
{
QAction *action = m_actions[tbb];
addAction(action);
action->setCheckable(true);
return action;
}
/**
* Inserts most associations, just reduces some string
* duplication (nice to translators)
*/
void WorkToolBar::insertBasicAssociations()
{
insertHotBtn(tbb_Association);
if (m_Type == Uml::DiagramType::Class || m_Type == Uml::DiagramType::UseCase ||
m_Type == Uml::DiagramType::Component || m_Type == Uml::DiagramType::Deployment) {
insertHotBtn(tbb_UniAssociation);
}
if (m_Type != Uml::DiagramType::Object) {
insertHotBtn(tbb_Dependency);
insertHotBtn(tbb_Generalization);
}
}
void WorkToolBar::slotCheckToolBar(Uml::DiagramType::Enum dt)
{
if (dt == m_Type)
return;
clear();
m_Type = dt;
if (m_Type == Uml::DiagramType::Undefined)
return;
// insert note, anchor and lines of text on all diagrams
QAction* action = insertHotBtn(tbb_Arrow);
action->setChecked(true);
m_CurrentButtonID = tbb_Arrow;
insertHotBtn(tbb_Note);
insertHotBtn(tbb_Anchor);
insertHotBtn(tbb_Text);
insertHotBtn(tbb_Box);
// insert diagram specific tools
switch (m_Type) {
case Uml::DiagramType::UseCase:
insertHotBtn(tbb_Actor);
insertHotBtn(tbb_UseCase);
insertBasicAssociations();
break;
case Uml::DiagramType::Class:
insertHotBtn(tbb_Class);
insertHotBtn(tbb_Interface);
insertHotBtn(tbb_Datatype);
insertHotBtn(tbb_Enum);
insertHotBtn(tbb_Package);
insertBasicAssociations();
insertHotBtn(tbb_Composition);
insertHotBtn(tbb_Aggregation);
insertHotBtn(tbb_Containment);
break;
case Uml::DiagramType::Object:
insertHotBtn(tbb_Instance);
insertHotBtn(tbb_Association);
break;
case Uml::DiagramType::Sequence:
insertHotBtn(tbb_Object);
insertHotBtn(tbb_Seq_Message_Creation);
insertHotBtn(tbb_Seq_Message_Destroy);
insertHotBtn(tbb_Seq_Message_Synchronous);
insertHotBtn(tbb_Seq_Message_Asynchronous);
insertHotBtn(tbb_Seq_Message_Found);
insertHotBtn(tbb_Seq_Message_Lost);
insertHotBtn(tbb_Seq_Combined_Fragment);
insertHotBtn(tbb_Seq_Precondition);
break;
case Uml::DiagramType::Collaboration:
insertHotBtn(tbb_Object);
insertHotBtn(tbb_Instance);
insertHotBtn(tbb_Coll_Mesg_Async);
insertHotBtn(tbb_Coll_Mesg_Sync);
break;
case Uml::DiagramType::State:
insertHotBtn(tbb_Initial_State);
insertHotBtn(tbb_State);
insertHotBtn(tbb_End_State);
insertHotBtn(tbb_State_Transition);
insertHotBtn(tbb_DeepHistory);
insertHotBtn(tbb_ShallowHistory);
insertHotBtn(tbb_StateJoin);
insertHotBtn(tbb_StateFork);
insertHotBtn(tbb_Junction);
insertHotBtn(tbb_Choice);
//insertHotBtn(tbb_Andline); //NotYetImplemented
break;
case Uml::DiagramType::Activity:
insertHotBtn(tbb_Initial_Activity);
insertHotBtn(tbb_Activity);
insertHotBtn(tbb_End_Activity);
insertHotBtn(tbb_Final_Activity);
insertHotBtn(tbb_Branch);
insertHotBtn(tbb_Fork);
insertHotBtn(tbb_Activity_Transition);
insertHotBtn(tbb_Exception);
insertHotBtn(tbb_PrePostCondition);
insertHotBtn(tbb_Send_Signal);
insertHotBtn(tbb_Accept_Signal);
insertHotBtn(tbb_Accept_Time_Event);
insertHotBtn(tbb_Region);
insertHotBtn(tbb_Pin);
insertHotBtn(tbb_Object_Node);
break;
case Uml::DiagramType::Component:
insertHotBtn(tbb_SubSystem);
if (Settings::optionState().generalState.uml2)
insertHotBtn(tbb_Interface_Requirement);
insertHotBtn(tbb_Component);
if (Settings::optionState().generalState.uml2)
insertHotBtn(tbb_Port);
insertHotBtn(tbb_Interface_Provider);
insertHotBtn(tbb_Artifact);
insertBasicAssociations();
break;
case Uml::DiagramType::Deployment:
insertHotBtn(tbb_Object);
insertHotBtn(tbb_Interface);
insertHotBtn(tbb_Component);
insertHotBtn(tbb_Node);
insertBasicAssociations();
break;
case Uml::DiagramType::EntityRelationship:
insertHotBtn(tbb_Entity);
insertHotBtn(tbb_Category);
insertHotBtn(tbb_Relationship);
insertHotBtn(tbb_Category2Parent);
insertHotBtn(tbb_Child2Category);
break;
default:
logWarn1("WorkToolBar::insertBasicAssociations on unknown diagram type: %1",
Uml::DiagramType::toString(m_Type));
break;
}
}
void WorkToolBar::buttonChanged(int b)
{
UMLView* view = UMLApp::app()->currentView();
// if trying to turn off arrow - stop it
ToolBar_Buttons tbb = (ToolBar_Buttons)b;
if (tbb == tbb_Arrow && m_CurrentButtonID == tbb_Arrow) {
m_actions[tbb_Arrow]->toggle();
// signal needed, in the case (when switching diagrams) that
// Arrow Button gets activated, but the toolBarState of the Views may be different
Q_EMIT sigButtonChanged(m_CurrentButtonID);
if (view)
view->setCursor(currentCursor());
return;
}
// if toggling off a button set to arrow
if (tbb == m_CurrentButtonID) {
m_map[m_Type] = m_CurrentButtonID; // store old tool for this diagram type
m_actions[tbb_Arrow]->toggle();
m_CurrentButtonID = tbb_Arrow;
Q_EMIT sigButtonChanged(m_CurrentButtonID);
if (view)
view->setCursor(currentCursor());
return;
}
m_map[m_Type] = m_CurrentButtonID;
m_actions[m_CurrentButtonID]->toggle();
m_CurrentButtonID = tbb;
Q_EMIT sigButtonChanged(m_CurrentButtonID);
if (view)
view->setCursor(currentCursor());
}
/**
* Returns the current cursor depending on m_CurrentButtonID
*/
QCursor WorkToolBar::currentCursor()
{
return m_cursors[m_CurrentButtonID];
}
/**
* Returns the default cursor
*/
QCursor WorkToolBar::defaultCursor()
{
return Qt::ArrowCursor;
}
void WorkToolBar::slotResetToolBar()
{
if (m_CurrentButtonID == tbb_Undefined)
return;
if (m_CurrentButtonID == tbb_Arrow)
return; // really shouldn't occur
m_actions[m_CurrentButtonID]->toggle();
m_CurrentButtonID = tbb_Arrow;
m_actions[m_CurrentButtonID]->toggle();
Q_EMIT sigButtonChanged(m_CurrentButtonID);
UMLView* view = UMLApp::app()->currentView();
if (view != nullptr) {
view->setCursor(defaultCursor());
}
}
/**
* Sets the current tool to the previously used Tool. This is just
* as if the user had pressed the button for the other tool.
*/
void WorkToolBar::setOldTool()
{
QToolButton *b = (QToolButton*) widgetForAction(m_actions[m_map[m_Type]]);
if (b)
b->animateClick();
}
/**
* Sets the current tool to the default tool. (select tool)
* Calling this function is as if the user had pressed the "arrow"
* button on the toolbar.
*/
void WorkToolBar::setDefaultTool()
{
QToolButton *b = (QToolButton*) widgetForAction(m_actions[tbb_Arrow]);
if (b)
b->animateClick();
}
/**
* Loads toolbar icon and mouse cursor images from disk
*/
void WorkToolBar::loadPixmaps()
{
const struct ButtonInfo {
const ToolBar_Buttons tbb;
const QString btnName;
const Icon_Utils::IconType icon;
const char *slotName;
} buttonInfo[] = {
{ tbb_Arrow, i18nc("selection arrow", "Select"), Icon_Utils::it_Arrow, SLOT(slotArrow()) },
{ tbb_Object, i18n("Object"), Icon_Utils::it_Object, SLOT(slotObject()) },
{ tbb_Seq_Message_Creation, i18n("Creation"), Icon_Utils::it_Message_Creation, SLOT(slotSeq_Message_Creation()) },
{ tbb_Seq_Message_Destroy, i18n("Destroy"), Icon_Utils::it_Message_Destroy, SLOT(slotSeq_Message_Destroy()) },
{ tbb_Seq_Message_Synchronous, i18n("Synchronous Message"), Icon_Utils::it_Message_Sync, SLOT(slotSeq_Message_Synchronous()) },
{ tbb_Seq_Message_Asynchronous, i18n("Asynchronous Message"), Icon_Utils::it_Message_Async, SLOT(slotSeq_Message_Asynchronous()) },
{ tbb_Seq_Message_Found, i18n("Found Message"), Icon_Utils::it_Message_Found, SLOT(slotSeq_Message_Found()) },
{ tbb_Seq_Message_Lost, i18n("Lost Message"), Icon_Utils::it_Message_Lost, SLOT(slotSeq_Message_Lost()) },
{ tbb_Seq_Combined_Fragment, i18n("Combined Fragment"), Icon_Utils::it_Combined_Fragment, SLOT(slotSeq_Combined_Fragment()) },
{ tbb_Seq_Precondition, i18n("Precondition"), Icon_Utils::it_Precondition, SLOT(slotSeq_Precondition()) },
{ tbb_Association, i18n("Association"), Icon_Utils::it_Association, SLOT(slotAssociation()) },
{ tbb_Containment, i18n("Containment"), Icon_Utils::it_Containment, SLOT(slotContainment()) },
{ tbb_Anchor, i18n("Anchor"), Icon_Utils::it_Anchor, SLOT(slotAnchor()) },
{ tbb_Text, i18n("Label"), Icon_Utils::it_Text, SLOT(slotText()) },
{ tbb_Note, i18n("Note"), Icon_Utils::it_Note, SLOT(slotNote()) },
{ tbb_Box, i18n("Box"), Icon_Utils::it_Box, SLOT(slotBox()) },
{ tbb_Actor, i18n("Actor"), Icon_Utils::it_Actor, SLOT(slotActor()) },
{ tbb_Dependency, i18n("Dependency"), Icon_Utils::it_Dependency, SLOT(slotDependency()) },
{ tbb_Aggregation, i18n("Aggregation"), Icon_Utils::it_Aggregation, SLOT(slotAggregation()) },
{ tbb_Relationship, i18n("Relationship"), Icon_Utils::it_Relationship, SLOT(slotRelationship()) },
{ tbb_UniAssociation, i18n("Directional Association"), Icon_Utils::it_Directional_Association, SLOT(slotUniAssociation()) },
{ tbb_Generalization, i18n("Generalization"), Icon_Utils::it_Generalisation, SLOT(slotGeneralization()) },
{ tbb_Composition, i18n("Composition"), Icon_Utils::it_Composition, SLOT(slotComposition()) },
{ tbb_UseCase, i18n("Use Case"), Icon_Utils::it_UseCase, SLOT(slotUseCase()) },
{ tbb_Class, i18nc("UML class", "Class"), Icon_Utils::it_Class, SLOT(slotClass()) },
{ tbb_Initial_State, i18n("Initial State"), Icon_Utils::it_InitialState, SLOT(slotInitial_State()) },
{ tbb_Region, i18n("Region"), Icon_Utils::it_Region, SLOT(slotRegion()) },
{ tbb_End_State, i18n("End State"), Icon_Utils::it_EndState, SLOT(slotEnd_State()) },
{ tbb_Branch, i18n("Branch/Merge"), Icon_Utils::it_Branch, SLOT(slotBranch()) },
{ tbb_Send_Signal, i18n("Send signal"), Icon_Utils::it_Send_Signal, SLOT(slotSend_Signal()) },
{ tbb_Accept_Signal, i18n("Accept signal"), Icon_Utils::it_Accept_Signal, SLOT(slotAccept_Signal()) },
{ tbb_Accept_Time_Event, i18n("Accept time event"), Icon_Utils::it_Accept_TimeEvent, SLOT(slotAccept_Time_Event()) },
{ tbb_Fork, i18n("Fork/Join"), Icon_Utils::it_Fork_Join, SLOT(slotFork()) },
{ tbb_Package, i18n("Package"), Icon_Utils::it_Package, SLOT(slotPackage()) },
{ tbb_Component, i18n("Component"), Icon_Utils::it_Component, SLOT(slotComponent()) },
{ tbb_Node, i18n("Node"), Icon_Utils::it_Node, SLOT(slotNode()) },
{ tbb_Artifact, i18n("Artifact"), Icon_Utils::it_Artifact, SLOT(slotArtifact()) },
{ tbb_Interface, i18n("Interface"), Icon_Utils::it_Interface, SLOT(slotInterface()) },
{ tbb_Interface_Provider, i18n("Interface Provider"), Icon_Utils::it_Interface_Provider, SLOT(slotInterfaceProvider()) },
{ tbb_Interface_Requirement, i18n("Interface required"), Icon_Utils::it_Interface_Requirement, SLOT(slotInterfaceRequired()) },
{ tbb_Datatype, i18n("Datatype"), Icon_Utils::it_Datatype, SLOT(slotDatatype()) },
{ tbb_Enum, i18n("Enum"), Icon_Utils::it_Enum, SLOT(slotEnum()) },
{ tbb_Entity, i18n("Entity"), Icon_Utils::it_Entity, SLOT(slotEntity()) },
{ tbb_DeepHistory, i18n("Deep History"), Icon_Utils::it_History_Deep, SLOT(slotDeepHistory()) },
{ tbb_ShallowHistory, i18n("Shallow History"), Icon_Utils::it_History_Shallow, SLOT(slotShallowHistory()) },
{ tbb_StateJoin, i18nc("join states", "Join"), Icon_Utils::it_Join, SLOT(slotStateJoin()) },
{ tbb_StateFork, i18n("Fork"), Icon_Utils::it_Fork_State, SLOT(slotStateFork()) },
{ tbb_SubSystem, i18n("Subsystem"), Icon_Utils::it_Subsystem, SLOT(slotSubsystem()) },
{ tbb_Junction, i18n("Junction"), Icon_Utils::it_Junction, SLOT(slotJunction()) },
{ tbb_Choice, i18nc("state choice", "Choice"), Icon_Utils::it_Choice_Rhomb, SLOT(slotChoice()) },
//:TODO: let the user decide which symbol he wants (setting an option)
//{ tbb_Choice, i18n("Choice"), Icon_Utils::it_Choice_Round, SLOT(slotChoice()) }, //NotYetImplemented
{ tbb_Andline, i18n("And Line"), Icon_Utils::it_And_Line, SLOT(slotAndline()) }, //NotYetImplemented
{ tbb_State_Transition, i18n("State Transition"), Icon_Utils::it_State_Transition, SLOT(slotState_Transition()) },
{ tbb_Activity_Transition, i18n("Activity Transition"), Icon_Utils::it_Activity_Transition, SLOT(slotActivity_Transition()) },
{ tbb_Activity, i18n("Activity"), Icon_Utils::it_Activity, SLOT(slotActivity()) },
{ tbb_State, i18nc("state diagram", "State"), Icon_Utils::it_State, SLOT(slotState()) },
{ tbb_End_Activity, i18n("End Activity"), Icon_Utils::it_Activity_End, SLOT(slotEnd_Activity()) },
{ tbb_Final_Activity, i18n("Final Activity"), Icon_Utils::it_Activity_Final, SLOT(slotFinal_Activity()) },
{ tbb_Pin, i18n("Pin"), Icon_Utils::it_Pin, SLOT(slotPin()) },
{ tbb_Port, i18n("Port"), Icon_Utils::it_Pin, SLOT(slotPort()) },
{ tbb_Initial_Activity, i18n("Initial Activity"), Icon_Utils::it_Activity_Initial, SLOT(slotInitial_Activity()) },
{ tbb_Coll_Mesg_Sync, i18n("Synchronous Message"), Icon_Utils::it_Message_Synchronous, SLOT(slotColl_Mesg_Sync()) },
{ tbb_Coll_Mesg_Async, i18n("Asynchronous Message"), Icon_Utils::it_Message_Asynchronous, SLOT(slotColl_Mesg_Async()) },
{ tbb_Exception, i18n("Exception"), Icon_Utils::it_Exception, SLOT(slotException()) },
{ tbb_Object_Node, i18n("Object Node"), Icon_Utils::it_Object_Node, SLOT(slotObject_Node()) },
{ tbb_PrePostCondition, i18n("Pre/Post condition"), Icon_Utils::it_Condition_PrePost, SLOT(slotPrePostCondition()) },
{ tbb_Category, i18n("Category"), Icon_Utils::it_Category, SLOT(slotCategory()) },
{ tbb_Category2Parent, i18n("Category to Parent"), Icon_Utils::it_Category_Parent, SLOT(slotCategory2Parent()) },
{ tbb_Child2Category, i18n("Child to Category"), Icon_Utils::it_Category_Child, SLOT(slotChild2Category()) },
{ tbb_Instance, i18n("Instance"), Icon_Utils::it_Instance, SLOT(slotInstance()) }
};
const size_t n_buttonInfos = sizeof(buttonInfo) / sizeof(ButtonInfo);
KActionCollection *collection = UMLApp::app()->actionCollection();
for (uint i = 0; i < n_buttonInfos; ++i) {
const ButtonInfo& info = buttonInfo[i];
QString key = QLatin1String(ENUM_NAME(WorkToolBar, ToolBar_Buttons, info.tbb));
QAction *action = collection->addAction(key, this, info.slotName);
action->setIcon(Icon_Utils::BarIcon(info.icon));
action->setText(info.btnName);
m_actions[info.tbb] = action;
m_cursors[info.tbb] = Icon_Utils::Cursor(info.icon);
}
// umbrello code use qt provided arrow cursor
m_cursors[tbb_Arrow] = defaultCursor();
setupActions();
}
/**
* These slots are triggered by the buttons. They call buttonChanged with
* the button id
*/
void WorkToolBar::slotArrow() { buttonChanged(tbb_Arrow); }
void WorkToolBar::slotGeneralization() { buttonChanged(tbb_Generalization); }
void WorkToolBar::slotAggregation() { buttonChanged(tbb_Aggregation); }
void WorkToolBar::slotDependency() { buttonChanged(tbb_Dependency); }
void WorkToolBar::slotAssociation() { buttonChanged(tbb_Association); }
void WorkToolBar::slotContainment() { buttonChanged(tbb_Containment); }
void WorkToolBar::slotColl_Mesg_Sync() { buttonChanged(tbb_Coll_Mesg_Sync); }
void WorkToolBar::slotColl_Mesg_Async() { buttonChanged(tbb_Coll_Mesg_Async); }
void WorkToolBar::slotSeq_Message_Creation() { buttonChanged(tbb_Seq_Message_Creation); }
void WorkToolBar::slotSeq_Message_Destroy() { buttonChanged(tbb_Seq_Message_Destroy); }
void WorkToolBar::slotSeq_Message_Synchronous() { buttonChanged(tbb_Seq_Message_Synchronous); }
void WorkToolBar::slotSeq_Message_Asynchronous() { buttonChanged(tbb_Seq_Message_Asynchronous); }
void WorkToolBar::slotSeq_Message_Found() { buttonChanged(tbb_Seq_Message_Found); }
void WorkToolBar::slotSeq_Message_Lost() { buttonChanged(tbb_Seq_Message_Lost); }
void WorkToolBar::slotSeq_Combined_Fragment() { buttonChanged(tbb_Seq_Combined_Fragment); }
void WorkToolBar::slotSeq_Precondition() { buttonChanged(tbb_Seq_Precondition); }
void WorkToolBar::slotComposition() { buttonChanged(tbb_Composition); }
void WorkToolBar::slotRelationship() { buttonChanged(tbb_Relationship); }
void WorkToolBar::slotUniAssociation() { buttonChanged(tbb_UniAssociation); }
void WorkToolBar::slotState_Transition() { buttonChanged(tbb_State_Transition); }
void WorkToolBar::slotActivity_Transition() { buttonChanged(tbb_Activity_Transition); }
void WorkToolBar::slotAnchor() { buttonChanged(tbb_Anchor); }
void WorkToolBar::slotNote() { buttonChanged(tbb_Note); }
void WorkToolBar::slotBox() { buttonChanged(tbb_Box); }
void WorkToolBar::slotText() { buttonChanged(tbb_Text); }
void WorkToolBar::slotActor() { buttonChanged(tbb_Actor); }
void WorkToolBar::slotUseCase() { buttonChanged(tbb_UseCase); }
void WorkToolBar::slotClass() { buttonChanged(tbb_Class); }
void WorkToolBar::slotInterface() { buttonChanged(tbb_Interface); }
void WorkToolBar::slotInterfaceProvider() { buttonChanged(tbb_Interface_Provider); }
void WorkToolBar::slotInterfaceRequired() { buttonChanged(tbb_Interface_Requirement); }
void WorkToolBar::slotDatatype() { buttonChanged(tbb_Datatype); }
void WorkToolBar::slotEnum() { buttonChanged(tbb_Enum); }
void WorkToolBar::slotEntity() { buttonChanged(tbb_Entity); }
void WorkToolBar::slotPackage() { buttonChanged(tbb_Package); }
void WorkToolBar::slotComponent() { buttonChanged(tbb_Component); }
void WorkToolBar::slotNode() { buttonChanged(tbb_Node); }
void WorkToolBar::slotArtifact() { buttonChanged(tbb_Artifact); }
void WorkToolBar::slotObject() { buttonChanged(tbb_Object); }
void WorkToolBar::slotInitial_State() { buttonChanged(tbb_Initial_State); }
void WorkToolBar::slotState() { buttonChanged(tbb_State); }
void WorkToolBar::slotSend_Signal() { buttonChanged(tbb_Send_Signal); }
void WorkToolBar::slotAccept_Signal() { buttonChanged(tbb_Accept_Signal); }
void WorkToolBar::slotAccept_Time_Event() { buttonChanged(tbb_Accept_Time_Event); }
void WorkToolBar::slotEnd_State() { buttonChanged(tbb_End_State); }
void WorkToolBar::slotRegion() { buttonChanged(tbb_Region); }
void WorkToolBar::slotInitial_Activity() { buttonChanged(tbb_Initial_Activity); }
void WorkToolBar::slotActivity() { buttonChanged(tbb_Activity); }
void WorkToolBar::slotEnd_Activity() { buttonChanged(tbb_End_Activity); }
void WorkToolBar::slotFinal_Activity() { buttonChanged(tbb_Final_Activity); }
void WorkToolBar::slotBranch() { buttonChanged(tbb_Branch); }
void WorkToolBar::slotFork() { buttonChanged(tbb_Fork); }
void WorkToolBar::slotDeepHistory() { buttonChanged(tbb_DeepHistory); }
void WorkToolBar::slotShallowHistory() { buttonChanged(tbb_ShallowHistory); }
void WorkToolBar::slotStateJoin() { buttonChanged(tbb_StateJoin); }
void WorkToolBar::slotPin() { buttonChanged(tbb_Pin); }
void WorkToolBar::slotPort() { buttonChanged(tbb_Port); }
void WorkToolBar::slotStateFork() { buttonChanged(tbb_StateFork); }
void WorkToolBar::slotJunction() { buttonChanged(tbb_Junction); }
void WorkToolBar::slotChoice() { buttonChanged(tbb_Choice); }
void WorkToolBar::slotAndline() { buttonChanged(tbb_Andline); }
void WorkToolBar::slotException() { buttonChanged(tbb_Exception); }
void WorkToolBar::slotObject_Node() { buttonChanged(tbb_Object_Node); }
void WorkToolBar::slotPrePostCondition() { buttonChanged(tbb_PrePostCondition); }
void WorkToolBar::slotCategory() { buttonChanged(tbb_Category); }
void WorkToolBar::slotCategory2Parent() { buttonChanged(tbb_Category2Parent); }
void WorkToolBar::slotChild2Category() { buttonChanged(tbb_Child2Category); }
void WorkToolBar::slotInstance() { buttonChanged(tbb_Instance); }
void WorkToolBar::slotSubsystem() { buttonChanged(tbb_SubSystem); }
/**
* Setup actions after reading shortcuts from settings
*/
void WorkToolBar::setupActions()
{
for(QAction *action : m_actions) {
if (!action->shortcut().isEmpty()) {
action->setToolTip(action->text() + QStringLiteral("\t[") +
action->shortcut().toString() + QStringLiteral("]"));
}
else
action->setToolTip(action->text());
}
}
| 27,414
|
C++
|
.cpp
| 459
| 54.093682
| 165
| 0.580866
|
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,273
|
umlappprivate.cpp
|
KDE_umbrello/umbrello/umlappprivate.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlappprivate.h"
#define DBG_SRC QStringLiteral("UMLAppPrivate")
#include "debug_utils.h"
#include <KFilterDev>
DEBUG_REGISTER(UMLAppPrivate)
/**
* Find welcome.html file for displaying in the welcome window.
*
* @return path to welcome file or empty if not found
*/
QString UMLAppPrivate::findWelcomeFile()
{
QStringList dirList;
// from build dir
dirList.append(QCoreApplication::applicationDirPath() + QStringLiteral("/../doc/apphelp"));
// determine path from installation
QString name = QLocale().name();
QStringList lang = name.split(QLatin1Char('_'));
QStringList langList;
langList.append(lang[0]);
if (lang.size() > 1)
langList.append(name);
// from custom install
for(const QString &lang : langList) {
dirList.append(QCoreApplication::applicationDirPath() + QString(QStringLiteral("/../share/doc/HTML/%1/umbrello/apphelp")).arg(lang));
}
dirList.append(QCoreApplication::applicationDirPath() + QStringLiteral("/../share/doc/HTML/en/umbrello/apphelp"));
QStringList locations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
// from real installation
for(const QString &location : locations) {
for (const QString &lang : langList) {
dirList.append(QString(QStringLiteral("%1/doc/HTML/%2/umbrello/apphelp")).arg(location).arg(lang));
}
dirList.append(QString(QStringLiteral("%1/doc/HTML/en/umbrello/apphelp")).arg(location));
}
for(const QString &dir : dirList) {
QString filePath = dir + QStringLiteral("/index.cache.bz2");
QFileInfo fi(filePath);
if (fi.exists()) {
DEBUG() << "UMLAppPrivate::findWelcomeFile found " << filePath;
return filePath;
}
DEBUG() << "UMLAppPrivate::findWelcomeFile tried " << filePath << " (not found)";
}
return QString();
}
/**
* Read welcome file for displaying in the welcome window.
*
* This method also patches out some unrelated stuff from
* the html file intended or being displayed with khelpcenter.
*
* @return html content of welcome file
*/
QString UMLAppPrivate::readWelcomeFile(const QString &file)
{
QString html;
if (file.endsWith(QStringLiteral(".cache.bz2"))) {
QIODevice *d = KFilterDev::deviceForFile(file);
if (!d->open(QIODevice::ReadOnly)) {
uError() << "could not open archive " << file;
return QString();
}
QByteArray data = d->readAll();
html = QString::fromUtf8(data);
d->close();
delete d;
} else {
QFile f(file);
if (!f.open(QIODevice::ReadOnly))
return QString();
QTextStream in(&f);
html = in.readAll();
}
if (html.isEmpty()) {
uError() << "Empty welcome page loaded" << file;
return QString();
}
html.replace(QStringLiteral("<FILENAME filename=\"index.html\">"),QStringLiteral(""));
html.replace(QStringLiteral("</FILENAME>"),QStringLiteral(""));
//#define WITH_HEADER
#ifndef WITH_HEADER
#ifdef WEBKIT_WELCOMEPAGE
html.replace(QStringLiteral("<div id=\"header\""),QStringLiteral("<div id=\"header\" hidden"));
html.replace(QStringLiteral("<div class=\"navCenter\""),QStringLiteral("<div id=\"navCenter\" hidden"));
html.replace(QStringLiteral("<div id=\"footer\""), QStringLiteral("<div id=\"footer\" hidden"));
#else
html.replace(QStringLiteral("<div id=\"header\""), QStringLiteral("<!-- <div id=\"header\""));
html.replace(QStringLiteral("<div id=\"contentBody\""), QStringLiteral("--> <div id=\"contentBody\""));
html.replace(QStringLiteral("<div id=\"footer\""), QStringLiteral("<!-- <div id=\"footer\""));
html.replace(QStringLiteral("</div></body>"), QStringLiteral("--> </div></body>"));
#endif
#else
// replace help:/ urls in html file to be able to find css files and images from kde help system
QString path;
QStringList locations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
for(const QString &l : locations) {
QString a = QString(QStringLiteral("%1/doc/HTML/en/")).arg(l);
QFileInfo fi(a);
if (fi.exists()) {
path = a;
break;
}
}
QUrl url(QUrl::fromLocalFile(path));
QByteArray a = url.toEncoded();
html.replace(QStringLiteral("help:/"), QString::fromLocal8Bit(a));
#endif
return html;
}
bool UMLAppPrivate::openFileInEditor(const QUrl &file, int startCursor, int endCursor)
{
if (editor == nullptr) {
uError() << "could not get editor instance, which indicates an installation problem, see for kate[4]-parts package";
return false;
}
if (file.isLocalFile()) {
QFileInfo fi(file.toLocalFile());
if (!fi.exists())
return false;
}
if (!editorWindow) {
editorWindow = new QDockWidget(QStringLiteral("Editor"));
parent->addDockWidget(Qt::RightDockWidgetArea, editorWindow);
}
if (document) {
editorWindow->setWidget(nullptr);
delete view;
delete document;
}
document = editor->createDocument(nullptr);
view = document->createView(parent);
view->document()->openUrl(file);
view->document()->setReadWrite(false);
if (startCursor != endCursor)
view->setCursorPosition(KTextEditor::Cursor(startCursor, endCursor));
KTextEditor::ConfigInterface *iface = qobject_cast<KTextEditor::ConfigInterface*>(view);
if(iface)
iface->setConfigValue(QString::fromLatin1("line-numbers"), true);
editorWindow->setWidget(view);
editorWindow->setVisible(true);
return true;
}
| 5,831
|
C++
|
.cpp
| 147
| 33.938776
| 141
| 0.66602
|
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,274
|
toolbarstatepool.cpp
|
KDE_umbrello/umbrello/toolbarstatepool.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstatepool.h"
/**
* Destroys this ToolBarStatePool.
*/
ToolBarStatePool::~ToolBarStatePool()
{
}
/**
* Sets the current button and inits the tool.
* If the current button is the same to the button to set, the tool isn't
* initialized.
*
* @param button The button to set.
*/
void ToolBarStatePool::setButton(const WorkToolBar::ToolBar_Buttons &button)
{
if (button != m_ToolBarButton) {
m_ToolBarButton = button;
init(); // Go back to the initial state.
}
}
/**
* Returns the current button.
*
* @return The current button.
*/
WorkToolBar::ToolBar_Buttons ToolBarStatePool::getButton() const
{
return m_ToolBarButton;
}
/**
* Creates a new ToolBarStatePool.
* Protected to avoid classes other than derived to create objects of this
* class.
*
* @param umlScene The UMLScene to use.
*/
ToolBarStatePool::ToolBarStatePool(UMLScene *umlScene)
: ToolBarState(umlScene)
{
m_ToolBarButton = WorkToolBar::tbb_Arrow;
}
| 1,145
|
C++
|
.cpp
| 47
| 21.93617
| 92
| 0.734189
|
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,275
|
umllistviewitem.cpp
|
KDE_umbrello/umbrello/umllistviewitem.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umllistviewitem.h"
// definition required by debug_utils.h
#define DBG_SRC QStringLiteral("UMLListViewItem")
// app includes
#include "debug_utils.h"
#include "folder.h"
#include "classifier.h"
#include "entity.h"
#include "template.h"
#include "attribute.h"
#include "operation.h"
#include "instanceattribute.h"
#include "entityconstraint.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umlobjectlist.h"
#include "umlscene.h"
#include "umlview.h"
#include "model_utils.h"
#include "uniqueid.h"
#include "uml.h"
#include "cmds.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QDrag>
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
#include <QXmlStreamWriter>
// system includes
#include <cstdlib>
DEBUG_REGISTER(UMLListViewItem)
UMLListViewItem::ChildObjectMap* UMLListViewItem::s_comap;
/**
* Sets up an instance.
*
* @param parent The parent to this instance.
* @param name The name of this instance.
* @param t The type of this instance.
* @param o The object it represents.
*/
UMLListViewItem::UMLListViewItem(UMLListView * parent, const QString &name,
ListViewType t, UMLObject* o)
: QTreeWidgetItem(parent)
{
init();
if (parent == nullptr) {
logDebug0("UMLListViewItem constructor called with a null listview parent");
}
m_type = t;
m_object = o;
if (o) {
m_id = o->id();
}
setIcon(Icon_Utils::it_Home);
setText(name);
}
/**
* Sets up an instance for subsequent loadFromXMI().
*
* @param parent The parent to this instance.
*/
UMLListViewItem::UMLListViewItem(UMLListView * parent)
: QTreeWidgetItem(parent)
{
init();
if (parent == nullptr) {
logDebug0("UMLListViewItem constructor called with a NULL listview parent");
}
}
/**
* Sets up an instance for subsequent loadFromXMI().
*
* @param parent The parent to this instance.
*/
UMLListViewItem::UMLListViewItem(UMLListViewItem * parent)
: QTreeWidgetItem(parent)
{
init();
}
/**
* Sets up an instance.
*
* @param parent The parent to this instance.
* @param name The name of this instance.
* @param t The type of this instance.
* @param o The object it represents.
*/
UMLListViewItem::UMLListViewItem(UMLListViewItem * parent, const QString &name, ListViewType t, UMLObject *o)
: QTreeWidgetItem(parent)
{
init();
m_type = t;
m_object = o;
if (!o) {
m_id = Uml::ID::None;
updateFolder();
} else {
parent->addChildItem(o, this);
updateObject();
m_id = o->id();
}
setText(name);
if (!Model_Utils::typeIsRootView(t)) {
setFlags(flags() | Qt::ItemIsEditable);
}
}
/**
* Sets up an instance.
*
* @param parent The parent to this instance.
* @param name The name of this instance.
* @param t The type of this instance.
* @param id The id of this instance.
*/
UMLListViewItem::UMLListViewItem(UMLListViewItem * parent, const QString &name, ListViewType t, Uml::ID::Type id)
: QTreeWidgetItem(parent)
{
init();
m_type = t;
m_id = id;
switch (m_type) {
case lvt_Collaboration_Diagram:
setIcon(Icon_Utils::it_Diagram_Collaboration);
break;
case lvt_Class_Diagram:
setIcon(Icon_Utils::it_Diagram_Class);
break;
case lvt_State_Diagram:
setIcon(Icon_Utils::it_Diagram_State);
break;
case lvt_Activity_Diagram:
setIcon(Icon_Utils::it_Diagram_Activity);
break;
case lvt_Sequence_Diagram:
setIcon(Icon_Utils::it_Diagram_Sequence);
break;
case lvt_Component_Diagram:
setIcon(Icon_Utils::it_Diagram_Component);
break;
case lvt_Deployment_Diagram:
setIcon(Icon_Utils::it_Diagram_Deployment);
break;
case lvt_UseCase_Diagram:
setIcon(Icon_Utils::it_Diagram_Usecase);
break;
case lvt_Object_Diagram:
setIcon(Icon_Utils::it_Diagram_Object);
break;
default:
setIcon(Icon_Utils::it_Diagram);
}
// Constructor also used by folder so just make sure we don't need to
// to set pixmap to folder. doesn't hurt diagrams.
updateFolder();
setText(name);
setFlags(flags() | Qt::ItemIsEditable);
}
/**
* Initializes key variables of the class.
*/
void UMLListViewItem::init()
{
m_type = lvt_Unknown;
m_object = nullptr;
m_id = Uml::ID::None;
if (!s_comap)
s_comap = new ChildObjectMap();
}
/**
* Returns the signature of items that are operations.
* @return signature of an operation item, else an empty string
*/
QString UMLListViewItem::toolTip() const
{
UMLObject *obj = umlObject();
if (obj) {
switch (obj->baseType()) {
case UMLObject::ot_Class:
return obj->doc();
case UMLObject::ot_Operation:
{
const UMLOperation *op = obj->asUMLOperation();
return op->toString(Uml::SignatureType::ShowSig);
}
case UMLObject::ot_Attribute:
{
const UMLAttribute *at = obj->asUMLAttribute();
return at->toString(Uml::SignatureType::ShowSig);
}
default:
return QString();
}
}
else {
return QString();
}
}
/**
* Returns the type this instance represents.
*
* @return The type this instance represents.
*/
UMLListViewItem::ListViewType UMLListViewItem::type() const
{
return m_type;
}
/**
* Adds to the child object cache the child listview item representing the given UMLObject.
* @param child Pointer to UMLObject serving as the key into s_comap
* @param item Pointer to UMLListViewItem to be returned as the value keyed by @ref child
*/
void UMLListViewItem::addChildItem(UMLObject *child, UMLListViewItem *childItem)
{
if (!child) {
logError0("UMLListViewItem::addChildItem called with null child");
return;
}
(*s_comap)[child] = childItem;
}
/**
* Deletes the child listview item representing the given UMLObject.
*/
void UMLListViewItem::deleteChildItem(UMLObject *child)
{
if (!child) {
logError0("UMLListViewItem::deleteChildItem called with null child");
return;
}
UMLListViewItem *childItem = findChildObject(child);
if (childItem == nullptr) {
logError1("UMLListViewItem::deleteChildItem: child listview item %1 not found", child->name());
return;
}
s_comap->remove(child);
removeChild(childItem);
delete childItem;
}
/**
* Deletes the given child listview item representing a UMLObject.
*/
void UMLListViewItem::deleteItem(UMLListViewItem *childItem)
{
if (!childItem)
return;
const UMLObject *obj = s_comap->key(childItem);
if (obj)
s_comap->remove(obj);
delete childItem;
}
void UMLListViewItem::setVisible(bool state)
{
setHidden(!state);
}
/**
* Returns the id this class represents.
*
* @return The id this class represents.
*/
Uml::ID::Type UMLListViewItem::ID() const
{
if (m_object) {
return m_object->id();
}
return m_id;
}
/**
* Sets the id this class represents.
* This only sets the ID locally, not at the UMLObject that is perhaps
* associated to this UMLListViewItem.
* @param id the id this class represents
*/
void UMLListViewItem::setID(Uml::ID::Type id)
{
if (m_object) {
Uml::ID::Type oid = m_object->id();
if (id != Uml::ID::None && oid != id) {
logDebug2("UMLListViewItem::setID: new id %1 does not agree with object id %2",
Uml::ID::toString(id), Uml::ID::toString(oid));
}
}
m_id = id;
}
/**
* Set the UMLObject associated with this instance.
*
* @param obj The object this class represents.
*/
void UMLListViewItem::setUMLObject(UMLObject * obj)
{
m_object = obj;
}
/**
* Return the UMLObject associated with this instance.
*
* @return The object this class represents.
*/
UMLObject * UMLListViewItem::umlObject() const
{
return m_object;
}
/**
* Returns true if the UMLListViewItem of the given ID is a parent of
* this UMLListViewItem.
*/
bool UMLListViewItem::isOwnParent(Uml::ID::Type listViewItemID)
{
UMLListView* listView = static_cast<UMLListView*>(treeWidget());
QTreeWidgetItem *lvi = static_cast<QTreeWidgetItem*>(listView->findItem(listViewItemID));
if (lvi == nullptr) {
logError1("UMLListViewItem::isOwnParent: listView->findItem(%1) returns null",
Uml::ID::toString(listViewItemID));
return true;
}
for (QTreeWidgetItem *self = static_cast<QTreeWidgetItem*>(this); self; self = self->parent()) {
if (lvi == self)
return true;
}
return false;
}
/**
* Updates the representation of the object.
*/
void UMLListViewItem::updateObject()
{
if (m_object == nullptr)
return;
// check if parent has been changed, remap parent if so
UMLListViewItem *oldParent = dynamic_cast<UMLListViewItem*>(parent());
if (oldParent && oldParent->m_object != m_object->parent() &&
dynamic_cast<UMLPackage*>(m_object->parent())) {
UMLListViewItem *newParent = UMLApp::app()->listView()->findUMLObject(m_object->umlPackage());
if (newParent) {
oldParent->removeChild(this);
newParent->addChild(this);
}
}
Uml::Visibility::Enum scope = m_object->visibility();
UMLObject::ObjectType ot = m_object->baseType();
QString modelObjText = m_object->name();
if (Model_Utils::isClassifierListitem(ot)) {
const UMLClassifierListItem *pNarrowed = m_object->asUMLClassifierListItem();
modelObjText = pNarrowed->toString(Uml::SignatureType::SigNoVis);
} else if (ot == UMLObject::ot_InstanceAttribute) {
const UMLInstanceAttribute *pNarrowed = m_object->asUMLInstanceAttribute();
modelObjText = pNarrowed->toString();
}
setText(modelObjText);
Icon_Utils::IconType icon = Icon_Utils::it_Home;
switch (ot) {
case UMLObject::ot_Package:
if (m_object->stereotype() == QStringLiteral("subsystem"))
icon = Icon_Utils::it_Subsystem;
else
icon = Icon_Utils::it_Package;
break;
case UMLObject::ot_Operation:
if (scope == Uml::Visibility::Public)
icon = Icon_Utils::it_Public_Method;
else if (scope == Uml::Visibility::Private)
icon = Icon_Utils::it_Private_Method;
else if (scope == Uml::Visibility::Implementation)
icon = Icon_Utils::it_Private_Method;
else
icon = Icon_Utils::it_Protected_Method;
break;
case UMLObject::ot_Attribute:
case UMLObject::ot_EntityAttribute:
case UMLObject::ot_InstanceAttribute:
if (scope == Uml::Visibility::Public)
icon = Icon_Utils::it_Public_Attribute;
else if (scope == Uml::Visibility::Private)
icon = Icon_Utils::it_Private_Attribute;
else if (scope == Uml::Visibility::Implementation)
icon = Icon_Utils::it_Private_Attribute;
else
icon = Icon_Utils::it_Protected_Attribute;
break;
case UMLObject::ot_UniqueConstraint:
m_type = Model_Utils::convert_OT_LVT(umlObject());
icon = Model_Utils::convert_LVT_IT(m_type);
break;
case UMLObject::ot_Class:
icon = Model_Utils::convert_LVT_IT(m_type, m_object);
break;
case UMLObject::ot_Association:
icon = Model_Utils::convert_LVT_IT(m_type, m_object);
break;
default:
icon = Model_Utils::convert_LVT_IT(m_type);
break;
}//end switch
if (icon)
setIcon(icon);
}
/**
* Updates the icon on a folder.
*/
void UMLListViewItem::updateFolder()
{
Icon_Utils::IconType icon = Model_Utils::convert_LVT_IT(m_type, m_object);
if (icon) {
if (Model_Utils::typeIsFolder(m_type)) {
icon = (Icon_Utils::IconType)((int)icon + (int)isExpanded());
}
setIcon(icon);
}
}
/**
* Overrides default method.
* Will call default method but also makes sure correct icon is shown.
*/
void UMLListViewItem::setOpen(bool expand)
{
QTreeWidgetItem::setExpanded(expand);
updateFolder();
}
/**
* Changes the current text of column 0.
*/
void UMLListViewItem::setText(const QString &newText)
{
setText(0, newText);
}
/**
* Changes the current text.
*/
void UMLListViewItem::setText(int column, const QString &newText)
{
m_label = newText;
QTreeWidgetItem::setText(column, newText);
}
/**
* Returns the saved text.
*/
QString UMLListViewItem::getSavedText() const
{
return m_label;
}
/**
* Set the pixmap corresponding to the given IconType.
*/
void UMLListViewItem::setIcon(Icon_Utils::IconType iconType)
{
QPixmap p = Icon_Utils::SmallIcon(iconType);
if (!p.isNull()) {
QTreeWidgetItem::setIcon(0, QIcon(p));
}
}
/**
* This slot is called to finish item editing
*/
void UMLListViewItem::slotEditFinished(const QString &newText)
{
m_label = text(0);
logDebug1("UMLListViewItem::slotEditFinished: text=%1", newText);
UMLListView* listView = static_cast<UMLListView*>(treeWidget());
UMLDoc* doc = listView->document();
if (newText == m_label) {
return;
}
if (newText.isEmpty()) {
cancelRenameWithMsg();
return;
}
switch (m_type) {
case lvt_UseCase:
case lvt_Actor:
case lvt_Class:
case lvt_Package:
case lvt_UseCase_Folder:
case lvt_Logical_Folder:
case lvt_Component_Folder:
case lvt_Deployment_Folder:
case lvt_EntityRelationship_Folder:
case lvt_Entity:
case lvt_Interface:
case lvt_Datatype:
case lvt_Enum:
case lvt_EnumLiteral:
case lvt_Subsystem:
case lvt_Component:
case lvt_Port:
case lvt_Node:
case lvt_Category:
if (m_object == nullptr || !doc->isUnique(newText)) {
cancelRenameWithMsg();
return;
}
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(m_object, newText));
doc->setModified(true);
m_label = newText;
break;
case lvt_Operation: {
if (m_object == nullptr) {
cancelRenameWithMsg();
return;
}
UMLOperation *op = m_object->asUMLOperation();
if (!op) {
cancelRenameWithMsg();
return;
}
UMLClassifier *parent = op->umlParent()->asUMLClassifier();
Model_Utils::OpDescriptor od;
Model_Utils::Parse_Status st = Model_Utils::parseOperation(newText, od, parent);
if (st == Model_Utils::PS_OK) {
// TODO: Check that no operation with the exact same profile exists.
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(op, od.m_name));
op->setType(od.m_pReturnType);
UMLAttributeList parmList = op->getParmList();
const int newParmListCount = parmList.count();
if (newParmListCount > od.m_args.count()) {
// Remove parameters at end of of list that no longer exist.
for (int i = od.m_args.count(); i < newParmListCount; i++) {
UMLAttribute *a = parmList.at(i);
op->removeParm(a, false);
}
}
Model_Utils::NameAndType_ListIt lit = od.m_args.begin();
for (int i = 0; lit != od.m_args.end(); ++lit, ++i) {
const Model_Utils::NameAndType& nm_tp = *lit;
UMLAttribute *a;
if (i < newParmListCount) {
a = parmList.at(i);
} else {
a = new UMLAttribute(op);
a->setID(UniqueID::gen());
}
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(a, nm_tp.m_name));
a->setType(nm_tp.m_type);
a->setParmKind(nm_tp.m_direction);
a->setInitialValue(nm_tp.m_initialValue);
if (i >= newParmListCount) {
op->addParm(a);
}
}
m_label = op->toString(Uml::SignatureType::SigNoVis);
} else {
KMessageBox::error(nullptr,
Model_Utils::psText(st),
i18n("Rename canceled"));
}
setText(m_label);
break;
}
case lvt_Attribute:
case lvt_EntityAttribute:
case lvt_InstanceAttribute: {
if (m_object == nullptr) {
cancelRenameWithMsg();
return;
}
UMLClassifier *parent = m_object->umlParent()->asUMLClassifier();
Model_Utils::NameAndType nt;
Uml::Visibility::Enum vis;
Model_Utils::Parse_Status st;
st = Model_Utils::parseAttribute(newText, nt, parent, &vis);
if (st == Model_Utils::PS_OK) {
UMLObject *exists = parent ? parent->findChildObject(newText) : nullptr;
if (exists) {
cancelRenameWithMsg();
return;
}
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(m_object, nt.m_name));
UMLAttribute *pAtt = m_object->asUMLAttribute();
pAtt->setType(nt.m_type);
pAtt->setVisibility(vis);
pAtt->setParmKind(nt.m_direction);
pAtt->setInitialValue(nt.m_initialValue);
m_label = pAtt->toString(Uml::SignatureType::SigNoVis);
} else {
KMessageBox::error(nullptr,
Model_Utils::psText(st),
i18n("Rename canceled"));
}
setText(m_label);
break;
}
case lvt_PrimaryKeyConstraint:
case lvt_UniqueConstraint:
case lvt_ForeignKeyConstraint:
case lvt_CheckConstraint: {
if (m_object == nullptr) {
cancelRenameWithMsg();
return;
}
UMLEntity *parent = m_object->umlParent()->asUMLEntity();
QString name;
Model_Utils::Parse_Status st;
st = Model_Utils::parseConstraint(newText, name, parent);
if (st == Model_Utils::PS_OK) {
UMLObject *exists = parent->findChildObject(name);
if (exists) {
cancelRenameWithMsg();
return;
}
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(m_object, name));
UMLEntityConstraint* uec = m_object->asUMLEntityConstraint();
m_label = uec->toString(Uml::SignatureType::SigNoVis);
} else {
KMessageBox::error(nullptr,
Model_Utils::psText(st),
i18n("Rename canceled"));
}
setText(m_label);
break;
}
case lvt_Template: {
if (m_object == nullptr) {
cancelRenameWithMsg();
return;
}
UMLClassifier *parent = m_object->umlParent()->asUMLClassifier();
Model_Utils::NameAndType nt;
Model_Utils::Parse_Status st = Model_Utils::parseTemplate(newText, nt, parent);
if (st == Model_Utils::PS_OK) {
UMLObject *exists = parent ? parent->findChildObject(newText) : nullptr;
if (exists) {
cancelRenameWithMsg();
return;
}
UMLApp::app()->executeCommand(new Uml::CmdRenameUMLObject(m_object, nt.m_name));
UMLTemplate *tmpl = m_object->asUMLTemplate();
tmpl->setType(nt.m_type);
m_label = tmpl->toString(Uml::SignatureType::SigNoVis);
} else {
KMessageBox::error(nullptr,
Model_Utils::psText(st),
i18n("Rename canceled"));
}
setText(m_label);
break;
}
case lvt_UseCase_Diagram:
case lvt_Class_Diagram:
case lvt_Sequence_Diagram:
case lvt_Collaboration_Diagram:
case lvt_State_Diagram:
case lvt_Activity_Diagram:
case lvt_Component_Diagram:
case lvt_Deployment_Diagram:
case lvt_Object_Diagram:{
UMLView *view = doc->findView(ID());
if (view == nullptr) {
cancelRenameWithMsg();
return;
}
UMLView *anotherView = doc->findView(view->umlScene()->type(), newText);
if (anotherView && anotherView->umlScene()->ID() == ID()) {
anotherView = nullptr;
}
if (anotherView) {
cancelRenameWithMsg();
return;
}
view->umlScene()->setName(newText);
setText(newText);
doc->signalDiagramRenamed(view);
break;
}
default:
KMessageBox::error(nullptr,
i18n("Renaming an item of listview type %1 is not yet implemented.", m_type),
i18n("Function Not Implemented"));
setText(m_label);
break;
}
doc->setModified(true);
}
/**
* Auxiliary method for okRename().
*/
void UMLListViewItem::cancelRenameWithMsg()
{
logDebug1("UMLListViewItem::cancelRenameWithMsg - column=:TODO:col, text=%1", text(0));
KMessageBox::error(nullptr,
i18n("The name you entered was invalid.\nRenaming process has been canceled."),
i18n("Name Not Valid"));
setText(m_label);
}
/**
* Overrides the default sorting to sort by item type.
* Sort the listview items by type and position within the corresponding list
* of UMLObjects. If the item does not have a UMLObject then place it last.
*/
#if 0
int UMLListViewItem::compare(QTreeWidgetItem *other, int col, bool ascending) const
{
UMLListViewItem *ulvi = other->asUMLListViewItem();
ListViewType ourType = type();
ListViewType otherType = ulvi->type();
if (ourType < otherType)
return -1;
if (ourType > otherType)
return 1;
// ourType == otherType
const bool subItem = Model_Utils::typeIsClassifierList(ourType);
const int alphaOrder = key(col, ascending).compare(other->key(col, ascending));
int retval = 0;
QString dbgPfx = "compare(type=" + QString::number((int)ourType)
+ ", self=" + text() + ", other=" + ulvi->text()
+ "): return ";
UMLObject *otherObj = ulvi->umlObject();
if (m_object == 0) {
retval = (subItem ? 1 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (m_object==0)", dbgPfx, retval);
#endif
return retval;
}
if (otherObj == 0) {
retval = (subItem ? -1 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (otherObj==0)", dbgPfx, retval);
#endif
return retval;
}
UMLClassifier *ourParent = m_object->umlParent()->asUMLClassifier();
UMLClassifier *otherParent = otherObj->umlParent()->asUMLClassifier();
if (ourParent == 0) {
retval = (subItem ? 1 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (ourParent==0)", dbgPfx, retval);
#endif
return retval;
}
if (otherParent == 0) {
retval = (subItem ? -1 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (otherParent==0)", dbgPfx, retval);
#endif
return retval;
}
if (ourParent != otherParent) {
retval = (subItem ? 0 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (ourParent != otherParent)",
dbgPfx, retval);
#endif
return retval;
}
UMLClassifierListItem *thisUmlItem = m_object->asUMLClassifierListItem();
UMLClassifierListItem *otherUmlItem = otherObj->asUMLClassifierListItem();
if (thisUmlItem == 0) {
retval = (subItem ? 1 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (thisUmlItem==0)", dbgPfx, retval);
#endif
return retval;
}
if (otherUmlItem == 0) {
retval = (subItem ? -1 : alphaOrder);
#ifdef DEBUG_LVITEM_INSERTION_ORDER
logDebug2("UMLListViewItem::%1 %2 because (otherUmlItem==0)", dbgPfx, retval);
#endif
return retval;
}
UMLClassifierListItemList items = ourParent->getFilteredList(thisUmlItem->baseType());
int myIndex = items.indexOf(thisUmlItem);
int otherIndex = items.indexOf(otherUmlItem);
if (myIndex < 0) {
retval = (subItem ? -1 : alphaOrder);
logError2("UMLListViewItem::%1 %2 because (myIndex < 0)", dbgPfx, retval);
return retval;
}
if (otherIndex < 0) {
retval = (subItem ? 1 : alphaOrder);
logError2("UMLListViewItem::%1 %2 because (otherIndex < 0)", dbgPfx, retval);
return retval;
}
return (myIndex < otherIndex ? -1 : myIndex > otherIndex ? 1 : 0);
}
#endif
/**
* Create a deep copy of this UMLListViewItem, but using the
* given parent instead of the parent of this UMLListViewItem.
* Return the new UMLListViewItem created.
*/
UMLListViewItem* UMLListViewItem::deepCopy(UMLListViewItem *newParent)
{
QString nm = text(0);
ListViewType t = type();
UMLObject *o = umlObject();
UMLListViewItem* newItem;
if (o) {
newItem = new UMLListViewItem(newParent, nm, t, o);
(*s_comap)[o] = newItem;
} else {
newItem = new UMLListViewItem(newParent, nm, t, m_id);
}
for (int i=0; i < childCount(); i++) {
UMLListViewItem *childItem = static_cast<UMLListViewItem*>(child(i));
childItem->deepCopy(newItem);
}
return newItem;
}
/**
* Find the UMLListViewItem that is related to the given UMLObject
* in the tree rooted at the current UMLListViewItem.
* Return a pointer to the item or NULL if not found.
*/
UMLListViewItem* UMLListViewItem::findUMLObject(const UMLObject *o)
{
if (!o) {
logError0("UMLListViewItem::findUMLObject: null argument given (returning null)");
return nullptr;
}
if (m_object == o)
return this;
ChildObjectMap::iterator it = s_comap->find(o);
if (it != s_comap->end()) {
return *it;
}
logDebug1("UMLListViewItem::findUMLObject: %1 was not found in comap, trying recursive search",
o->name());
return findUMLObject_r(o);
}
/**
* Auxiliary function for findUMLObject: Search recursively in child hierarchy.
*/
UMLListViewItem* UMLListViewItem::findUMLObject_r(const UMLObject *o)
{
if (m_object == o)
return this;
for (int i = 0; i < childCount(); i++) {
UMLListViewItem *item = dynamic_cast<UMLListViewItem*>(child(i));
if (!item)
continue;
UMLListViewItem *testItem = item->findUMLObject_r(o);
if (testItem) {
logDebug1("UMLListViewItem::findUMLObject_r(%1) : Object was found by recursive search, "
"should have been found in comap (?)", o->name());
return testItem;
}
}
return nullptr;
}
/**
* Find the UMLListViewItem that represents the given UMLObject in the
* children of the current UMLListViewItem.
* Return a pointer to the item or NULL if not found.
*/
UMLListViewItem* UMLListViewItem::findChildObject(const UMLObject *child)
{
ChildObjectMap::iterator it = s_comap->find(child);
if (it != s_comap->end()) {
return *it;
}
return nullptr;
}
/**
* Find the UMLListViewItem of the given ID in the tree rooted at
* the current UMLListViewItem.
* Return a pointer to the item or NULL if not found.
*
* @param id The ID to search for.
* @return The item with the given ID or NULL if not found.
*/
UMLListViewItem * UMLListViewItem::findItem(Uml::ID::Type id)
{
if (ID() == id) {
return this;
}
for (int i = 0; i < childCount(); ++i) {
UMLListViewItem *childItem = static_cast<UMLListViewItem*>(child(i));
UMLListViewItem *inner = childItem->findItem(id);
if (inner) {
return inner;
}
}
return nullptr;
}
/**
* Saves the listview item to a "listitem" tag.
*/
void UMLListViewItem::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("listitem"));
Uml::ID::Type id = ID();
QString idStr = Uml::ID::toString(id);
//logDebug2("UMLListViewItem::saveToXMI: id = %1, type =%2", idStr, m_type);
if (id != Uml::ID::None)
writer.writeAttribute(QStringLiteral("id"), idStr);
writer.writeAttribute(QStringLiteral("type"), QString::number(m_type));
if (m_object == nullptr) {
if (! Model_Utils::typeIsDiagram(m_type) && m_type != lvt_View)
logError1("UMLListViewItem::saveToXMI(%1) : m_object is NULL", text(0));
if (m_type != lvt_View)
writer.writeAttribute(QStringLiteral("label"), text(0));
} else if (m_object->id() == Uml::ID::None) {
if (text(0).isEmpty()) {
logDebug0("UMLListViewItem::saveToXMI(: Skipping empty item");
return;
}
logDebug1("UMLListViewItem::saveToXMI saving local label %1 because umlobject ID is not set",
text(0));
if (m_type != lvt_View)
writer.writeAttribute(QStringLiteral("label"), text(0));
} else if (m_object->baseType() == UMLObject::ot_Folder) {
const UMLFolder *extFolder = m_object->asUMLFolder();
if (!extFolder->folderFile().isEmpty()) {
writer.writeAttribute(QStringLiteral("open"), QStringLiteral("0"));
writer.writeEndElement();
return;
}
}
writer.writeAttribute(QStringLiteral("open"), QString::number(isExpanded()));
for (int i = 0; i < childCount(); i++) {
UMLListViewItem *childItem = static_cast<UMLListViewItem*>(child(i));
childItem->saveToXMI(writer);
}
writer.writeEndElement();
}
/**
* Loads a "listitem" tag, this is only used by the clipboard currently.
*/
bool UMLListViewItem::loadFromXMI(QDomElement& qElement)
{
QString id = qElement.attribute(QStringLiteral("id"), QStringLiteral("-1"));
QString type = qElement.attribute(QStringLiteral("type"), QStringLiteral("-1"));
QString label = qElement.attribute(QStringLiteral("label"));
QString open = qElement.attribute(QStringLiteral("open"), QStringLiteral("1"));
if (!label.isEmpty())
setText(label);
else if (id == QStringLiteral("-1")) {
logError1("UMLListViewItem::saveToXMI: Item of type %1 has neither ID nor label", type);
return false;
}
m_id = Uml::ID::fromString(id);
if (m_id != Uml::ID::None) {
UMLListView* listView = static_cast<UMLListView*>(treeWidget());
m_object = listView->document()->findObjectById(m_id);
}
m_type = (ListViewType)(type.toInt());
if (m_object)
updateObject();
setOpen((bool)open.toInt());
return true;
}
UMLListViewItem* UMLListViewItem::childItem(int i)
{
return static_cast<UMLListViewItem*>(child(i));
}
QString UMLListViewItem::toString(ListViewType type)
{
switch (type) {
case lvt_View:
return QStringLiteral("lvt_View");
case lvt_Logical_View:
return QStringLiteral("lvt_Logical_View");
case lvt_UseCase_View:
return QStringLiteral("lvt_UseCase_View");
case lvt_Logical_Folder:
return QStringLiteral("lvt_Logical_Folder");
case lvt_UseCase_Folder:
return QStringLiteral("lvt_UseCase_Folder");
case lvt_UseCase_Diagram:
return QStringLiteral("lvt_UseCase_Diagram");
case lvt_Collaboration_Diagram:
return QStringLiteral("lvt_Collaboration_Diagram");
case lvt_Class_Diagram:
return QStringLiteral("lvt_Class_Diagram");
case lvt_State_Diagram:
return QStringLiteral("lvt_State_Diagram");
case lvt_Activity_Diagram:
return QStringLiteral("lvt_Activity_Diagram");
case lvt_Sequence_Diagram:
return QStringLiteral("lvt_Sequence_Diagram");
case lvt_Object_Diagram:
return QStringLiteral("lvt_Object_Diagram");
case lvt_Actor:
return QStringLiteral("lvt_Actor");
case lvt_Association:
return QStringLiteral("lvt_Association");
case lvt_UseCase:
return QStringLiteral("lvt_UseCase");
case lvt_Class:
return QStringLiteral("lvt_Class");
case lvt_Attribute:
return QStringLiteral("lvt_Attribute");
case lvt_Operation:
return QStringLiteral("lvt_Operation");
case lvt_Template:
return QStringLiteral("lvt_Template");
case lvt_Interface:
return QStringLiteral("lvt_Interface");
case lvt_Package:
return QStringLiteral("lvt_Package");
case lvt_Component_Diagram:
return QStringLiteral("lvt_Component_Diagram");
case lvt_Component_Folder:
return QStringLiteral("lvt_Component_Folder");
case lvt_Component_View:
return QStringLiteral("lvt_Component_View");
case lvt_Component:
return QStringLiteral("lvt_Component");
case lvt_Diagrams:
return QStringLiteral("lvt_Diagrams");
case lvt_Artifact:
return QStringLiteral("lvt_Artifact");
case lvt_Deployment_Diagram:
return QStringLiteral("lvt_Deployment_Diagram");
case lvt_Deployment_Folder:
return QStringLiteral("lvt_Deployment_Folder");
case lvt_Deployment_View:
return QStringLiteral("lvt_Deployment_View");
case lvt_Port:
return QStringLiteral("lvt_Port");
case lvt_Node:
return QStringLiteral("lvt_Node");
case lvt_Datatype:
return QStringLiteral("lvt_Datatype");
case lvt_Datatype_Folder:
return QStringLiteral("lvt_Datatype_Folder");
case lvt_Enum:
return QStringLiteral("lvt_Enum");
case lvt_Entity:
return QStringLiteral("lvt_Entity");
case lvt_EntityAttribute:
return QStringLiteral("lvt_EntityAttribute");
case lvt_EntityRelationship_Diagram:
return QStringLiteral("lvt_EntityRelationship_Diagram");
case lvt_EntityRelationship_Folder:
return QStringLiteral("lvt_EntityRelationship_Folder");
case lvt_EntityRelationship_Model:
return QStringLiteral("lvt_EntityRelationship_Model");
case lvt_Subsystem:
return QStringLiteral("lvt_Subsystem");
case lvt_Model:
return QStringLiteral("lvt_Model");
case lvt_EnumLiteral:
return QStringLiteral("lvt_EnumLiteral");
case lvt_UniqueConstraint:
return QStringLiteral("lvt_UniqueConstraint");
case lvt_PrimaryKeyConstraint:
return QStringLiteral("lvt_PrimaryKeyConstraint");
case lvt_ForeignKeyConstraint:
return QStringLiteral("lvt_ForeignKeyConstraint");
case lvt_CheckConstraint:
return QStringLiteral("lvt_CheckConstraint");
case lvt_Category:
return QStringLiteral("lvt_Category");
case lvt_Properties:
return QStringLiteral("lvt_Properties");
case lvt_Unknown:
return QStringLiteral("lvt_Unknown");
case lvt_Instance:
return QStringLiteral("lvt_Instance");
case lvt_InstanceAttribute:
return QStringLiteral("lvt_InstanceAttribute");
default:
return QStringLiteral("? ListViewType ?");
}
}
/**
* Overloading operator for debugging output.
*/
QDebug operator<<(QDebug dbg, const UMLListViewItem& item)
{
dbg.nospace() << "UMLListViewItem: " << item.text(0)
<< ", type=" << UMLListViewItem::toString(item.type())
<< ", id=" << Uml::ID::toString(item.ID())
<< ", children=" << item.childCount();
return dbg.space();
}
| 36,343
|
C++
|
.cpp
| 1,073
| 26.966449
| 113
| 0.627187
|
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,276
|
toolbarstatearrow.cpp
|
KDE_umbrello/umbrello/toolbarstatearrow.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "toolbarstatearrow.h"
// app includes
#include "associationwidget.h"
#include "umlscene.h"
#include "umlwidget.h"
/**
* Creates a new ToolBarStateArrow.
*
* @param umlScene The UMLScene to use.
*/
ToolBarStateArrow::ToolBarStateArrow(UMLScene *umlScene)
: ToolBarState(umlScene)
{
init();
}
/**
* Destroys this ToolBarStateArrow.
*/
ToolBarStateArrow::~ToolBarStateArrow()
{
cleanup();
}
/**
* Goes back to the initial state.
*/
void ToolBarStateArrow::init()
{
ToolBarState::init();
cleanup();
}
/**
* Clean up anything before deletion.
*/
void ToolBarStateArrow::cleanup()
{
while (!m_selectionRect.isEmpty())
delete m_selectionRect.takeFirst();
m_selectionRect.clear();
}
/**
* Called when the press event happened on an association.
* Delivers the event to the association.
*/
void ToolBarStateArrow::mousePressAssociation()
{
currentAssociation()->mousePressEvent(m_pMouseEvent);
}
/**
* Called when the press event happened on a widget.
* Delivers the event to the widget.
*/
void ToolBarStateArrow::mousePressWidget()
{
currentWidget()->mousePressEvent(m_pMouseEvent);
}
/**
* Called when the press event happened on an empty space.
* Calls base method and, if left button was pressed, prepares the selection
* rectangle.
*/
void ToolBarStateArrow::mousePressEmpty()
{
if (!m_pMouseEvent)
return;
if (m_pMouseEvent->button() != Qt::LeftButton) {
// Leave widgets selected upon RMB press on empty diagram area.
// The popup menu is activated upon RMB release.
return;
}
ToolBarState::mousePressEmpty();
// Starts the selection rectangle
// TODO: let QGraphicsScene show the selection rectangle
if (m_selectionRect.count() == 0) {
m_startPosition = m_pMouseEvent->scenePos();
for (int i = 0; i < 4; i++) {
QGraphicsLineItem* line = new QGraphicsLineItem();
m_pUMLScene->addItem(line);
line->setLine(m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y(),
m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y());
line->setPen(QPen(QColor("grey"), 0, Qt::DotLine));
line->setVisible(true);
line->setZValue(100);
m_selectionRect.append(line);
}
}
}
/**
* Called when the release event happened on an association.
* Delivers the event to the association.
*/
void ToolBarStateArrow::mouseReleaseAssociation()
{
currentAssociation()->mouseReleaseEvent(m_pMouseEvent);
}
/**
* Called when the release event happened on a widget.
* Delivers the event to the widget.
*/
void ToolBarStateArrow::mouseReleaseWidget()
{
currentWidget()->mouseReleaseEvent(m_pMouseEvent);
}
/**
* Called when the release event happened on an empty space.
* If selection rectangle is active, it is cleared. Else, if the right
* button was released, it shows the pop up menu for the diagram.
*/
void ToolBarStateArrow::mouseReleaseEmpty()
{
cleanup();
}
/**
* Called when the double click event happened on an association.
* Delivers the event to the association.
*/
void ToolBarStateArrow::mouseDoubleClickAssociation()
{
currentAssociation()->mouseDoubleClickEvent(m_pMouseEvent);
}
/**
* Called when the double click event happened on a widget.
* Delivers the event to the widget.
*/
void ToolBarStateArrow::mouseDoubleClickWidget()
{
currentWidget()->mouseDoubleClickEvent(m_pMouseEvent);
}
/**
* Called when the move event happened when an association is
* currently available.
* Delivers the event to the association.
*/
void ToolBarStateArrow::mouseMoveAssociation()
{
currentAssociation()->mouseMoveEvent(m_pMouseEvent);
}
/**
* Called when the move event happened when a widget is
* currently available.
* Delivers the event to the widget.
*/
void ToolBarStateArrow::mouseMoveWidget()
{
currentWidget()->mouseMoveEvent(m_pMouseEvent);
}
/**
* Called when the move event happened when no association nor
* widget are currently available.
* Updates the selection rectangle to the new position and selectes all the
* widgets in the rectangle.
*
* @todo Fix selection
*/
void ToolBarStateArrow::mouseMoveEmpty()
{
if (m_selectionRect.count() == 4) {
QGraphicsLineItem* line = m_selectionRect.at(0);
line->setLine(m_startPosition.x(), m_startPosition.y(),
m_pMouseEvent->scenePos().x(), m_startPosition.y());
line = m_selectionRect.at(1);
line->setLine(m_pMouseEvent->scenePos().x(), m_startPosition.y(),
m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y());
line = m_selectionRect.at(2);
line->setLine(m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y(),
m_startPosition.x(), m_pMouseEvent->scenePos().y());
line = m_selectionRect.at(3);
line->setLine(m_startPosition.x(), m_pMouseEvent->scenePos().y(),
m_startPosition.x(), m_startPosition.y());
m_pUMLScene->selectWidgets(m_startPosition.x(), m_startPosition.y(),
m_pMouseEvent->scenePos().x(), m_pMouseEvent->scenePos().y());
}
}
/**
* Overridden from base class to do nothing, as arrow is the default tool.
*/
void ToolBarStateArrow::changeTool()
{
}
/**
* Sets the widget currently in use.
* It ensures that the widget is only set if there is no other widget set
* already.
* It avoids things like moving a big widget over a little one, clicking
* right button to cancel the movement and the little widget getting the
* event, thus not canceling the movement in the big widget.
*/
void ToolBarStateArrow::setCurrentWidget(UMLWidget* widget)
{
if (widget != nullptr && currentWidget() != nullptr) {
return;
}
ToolBarState::setCurrentWidget(widget);
}
| 6,061
|
C++
|
.cpp
| 198
| 26.641414
| 97
| 0.69712
|
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,277
|
umlviewimageexportermodel.cpp
|
KDE_umbrello/umbrello/umlviewimageexportermodel.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlviewimageexportermodel.h"
// application specific includes
#define DBG_SRC QStringLiteral("UMLViewImageExporterModel")
#include "debug_utils.h"
#include "dotgenerator.h"
#include "model_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
// kde include files
#include <KIO/Job>
#include <KJobWidgets>
#include <KIO/MkdirJob>
#include <KLocalizedString>
// include files for Qt
#include <QApplication>
#include <QDesktopWidget>
#include <QDir>
#include <QImage>
#include <QImageWriter>
#include <QPainter>
#include <QPicture>
#include <QPrinter>
#include <QRect>
#include <QSvgGenerator>
#include <QTemporaryFile>
#include <KIO/FileCopyJob>
#include <KIO/StatJob>
DEBUG_REGISTER(UMLViewImageExporterModel)
QStringList *UMLViewImageExporterModel::s_supportedImageTypesList;
QStringList *UMLViewImageExporterModel::s_supportedMimeTypesList;
/**
* Returns a QStringList containing all the supported image types to use when exporting.
* All the types will be lower case.
*
* @return A QStringList containing all the supported image types to use when exporting.
*/
QStringList UMLViewImageExporterModel::supportedImageTypes()
{
if (!s_supportedImageTypesList) {
s_supportedImageTypesList = new QStringList();
// QT supported formats
QList<QByteArray> qImageFormats = QImageWriter::supportedImageFormats();
for(const QByteArray& it : qImageFormats) {
const QString format = QString::fromLatin1(it.toLower());
if (!s_supportedImageTypesList->contains(format))
*s_supportedImageTypesList << format;
}
// specific supported formats
if (!s_supportedImageTypesList->contains(QStringLiteral("dot")))
*s_supportedImageTypesList << QStringLiteral("dot");
if (!s_supportedImageTypesList->contains(QStringLiteral("eps")))
*s_supportedImageTypesList << QStringLiteral("eps");
if (!s_supportedImageTypesList->contains(QStringLiteral("svg")))
*s_supportedImageTypesList << QStringLiteral("svg");
}
s_supportedImageTypesList->sort();
return *s_supportedImageTypesList;
}
/**
* Returns a QStringList containing all the supported mime types to use when exporting.
* All the types will be lower case.
*
* @return A QStringList containing all the supported mime types to use when exporting.
*/
QStringList UMLViewImageExporterModel::supportedMimeTypes()
{
if (!s_supportedMimeTypesList) {
s_supportedMimeTypesList = new QStringList();
const QStringList imageTypes = UMLViewImageExporterModel::supportedImageTypes();
for (QStringList::ConstIterator it = imageTypes.begin(); it != imageTypes.end(); ++it) {
QString mimeType = imageTypeToMimeType(*it);
if (!mimeType.isNull())
s_supportedMimeTypesList->append(mimeType);
}
}
return *s_supportedMimeTypesList;
}
/**
* Returns the mime type for an image type.
* The supported image types are those that the diagrams can be exported to.
*
* @param imageType The type of the image.
* @return A QString with the equivalent mime type, or QString() if
* it's unknown.
*/
QString UMLViewImageExporterModel::imageTypeToMimeType(const QString& imageType)
{
const QString imgType = imageType.toLower();
struct lut_t { const char *key, *value; };
const struct lut_t lut[] =
{ { "bmp", "image/bmp" },
{ "dot", "image/x-dot" },
{ "jpeg","image/jpeg" },
{ "pbm", "image/x-portable-bitmap" },
{ "pgm", "image/x-portable-graymap" },
{ "png", "image/png" },
{ "ppm", "image/x-portable-pixmap" },
{ "xbm", "image/x-xbitmap" },
{ "xpm", "image/x-xpixmap" },
{ "eps", "image/x-eps" },
{ "svg", "image/svg+xml" } };
const size_t lut_len = sizeof(lut) / sizeof(lut_t);
for (size_t i = 0; i < lut_len; i++) {
const lut_t& ent = lut[i];
if (imgType == QString::fromLatin1(ent.key))
return QString::fromLatin1(ent.value);
}
return QString();
}
/**
* Returns the image type for a mime type.
* The supported image types are those that the diagrams can be exported to.
*
* @param mimeType The mime type.
* @return A lowercase QString with the equivalent image type, or QString()
* if it's unknown.
*/
QString UMLViewImageExporterModel::mimeTypeToImageType(const QString& mimeType)
{
struct lut_t { const char *key, *value; };
const struct lut_t lut[] =
{ { "image/bmp", "bmp" },
{ "image/x-dot", "dot" },
{ "image/jpeg", "jpeg"},
{ "image/x-portable-bitmap", "pbm" },
{ "image/x-portable-graymap", "pgm" },
{ "image/png", "png" },
{ "image/x-portable-pixmap", "ppm" },
{ "image/x-xbitmap", "xbm" },
{ "image/x-xpixmap", "xpm" },
{ "image/x-eps", "eps" },
{ "image/svg+xml", "svg" } };
const size_t lut_len = sizeof(lut) / sizeof(lut_t);
for (size_t i = 0; i < lut_len; i++) {
const lut_t& ent = lut[i];
if (mimeType == QString::fromLatin1(ent.key))
return QString::fromLatin1(ent.value);
}
return QString();
}
/**
* Constructor for UMLViewImageExporterModel.
* @param resolution resolution of export in DPI (default 0.0 means export type related default)
*/
UMLViewImageExporterModel::UMLViewImageExporterModel(float resolution)
: m_resolution(resolution)
{
}
/**
* Destructor for UMLViewImageExporterModel.
*/
UMLViewImageExporterModel::~UMLViewImageExporterModel()
{
}
/**
* Exports views in the document to the directory specified in the url
* using the 'imageType' for the images.
* The name of the exported images will be like their view's name and using the
* 'imageType' as extension.
*
* The views are stored in folders in the document. The same tree structure used
* in the document to store the views can be created in the target directory with
* 'useFolders'. Only the folders made by the user are created in the target
* directory (Logical view, use case view and so on aren't created).
*
* This method creates the specified target directory if needed. If there was an
* existing file with the same path as one to be created overwrites it without asking.
* The url used can be local or remote, using supported KIO slaves.
*
* @param views The list of views to export.
* @param imageType The type of the images the views will be exported to.
* @param directory The url of the directory where the images will be saved.
* @param useFolders If the tree structure of the views in the document must be created
* in the target directory.
* @return A QStringList with all the error messages that occurred during export.
* If the list is empty, all the views were exported successfully.
*/
QStringList UMLViewImageExporterModel::exportViews(const UMLViewList &views, const QString &imageType, const QUrl &directory, bool useFolders) const
{
// contains all the error messages returned by exportView calls
QStringList errors;
for(UMLView *view : views) {
QUrl url = QUrl::fromLocalFile(directory.path() + QLatin1Char('/') +
getDiagramFileName(view->umlScene(), imageType, useFolders));
QString returnString = exportView(view->umlScene(), imageType, url);
if (!returnString.isNull()) {
// [PORT]
errors.append(view->umlScene()->name() + QStringLiteral(": ") + returnString);
}
}
return errors;
}
/**
* Exports the view to the url using the 'imageType' for the image.
*
* This method creates the needed directories, if any. If there was an existing
* file in the specified url overwrites it without asking.
* The url used can be local or remote, using supported KIO slaves.
*
* If some problem occurs when exporting, an error message is returned.
*
* @param scene The UMLScene to export.
* @param imageType The type of the image the view will be exported to.
* @param url The url where the image will be saved.
* @return The error message if some problem occurred when exporting, or
* QString() if all went fine.
*/
QString UMLViewImageExporterModel::exportView(UMLScene* scene, const QString &imageType, const QUrl &url) const
{
if (!scene) {
return i18n("Empty scene");
}
// create the needed directories
if (!prepareDirectory(url)) {
return i18n("Cannot create directory: %1", url.path());
}
// The fileName will be used when exporting the image. If the url isn't local,
// the fileName is the name of a temporary local file to export the image to, and then
// upload it to its destiny
QString fileName;
QTemporaryFile tmpFile;
if (url.isLocalFile()) {
fileName = url.toLocalFile();
} else {
tmpFile.open();
fileName = tmpFile.fileName();
}
// exporting the view to the file
if (!exportViewTo(scene, imageType, fileName)) {
return i18n("A problem occurred while saving diagram in %1", fileName);
}
// if the file wasn't local, upload the temp file to the target
if (!url.isLocalFile()) {
KIO::FileCopyJob *job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url);
KJobWidgets::setWindow(job, UMLApp::app());
job->exec();
if (job->error()) {
return i18n("There was a problem saving file: %1", url.path());
}
}
return QString();
}
/**
* Returns the diagram file name.
* @param scene the diagram
* @param imageType the image type as file name extension
* @param useFolders flag whether to add folder to the file name
* @return the file name with extension
*/
QString UMLViewImageExporterModel::getDiagramFileName(UMLScene* scene, const QString &imageType, bool useFolders /* = false */) const
{
if (scene == nullptr) {
logWarn0("UMLViewImageExporterModel::getDiagramFileName: Scene is null!");
return QString();
}
if (useFolders) {
qApp->processEvents(); //:TODO: still needed ???
return Model_Utils::treeViewBuildDiagramName(scene->ID()) + QLatin1Char('.') + imageType.toLower();
}
return scene->name() + QLatin1Char('.') + imageType.toLower();
}
/**
* Creates, if it doesn't exist, the directory to save the file.
* It also creates all the needed parent directories.
*
* @param url The url where the image will be saved.
* @return True if the operation was successful,
* false if the directory didn't exist and couldn't be created.
*/
bool UMLViewImageExporterModel::prepareDirectory(const QUrl &url) const
{
// the KUrl is copied to get protocol, user and so on and then the path is cleaned
QUrl directory = url;
directory.setPath(QString());
// creates the directory and any needed parent directories
QStringList dirs = url.adjusted(QUrl::RemoveFilename).path().split(QDir::separator(), QString::SkipEmptyParts);
for (QStringList::ConstIterator it = dirs.constBegin() ; it != dirs.constEnd(); ++it) {
directory.setPath(directory.path() + QLatin1Char('/') + *it);
KIO::StatJob *statJob = KIO::stat(directory, KIO::StatJob::SourceSide, KIO::StatDetails(0));
KJobWidgets::setWindow(statJob, UMLApp::app());
statJob->exec();
if (statJob->error()) {
KIO::MkdirJob* job = KIO::mkdir(directory);
if (!job->exec()) {
return false;
}
}
}
return true;
}
/**
* Exports the scene to the file 'fileName' as the specified type.
*
* @param scene The scene to export.
* @param imageType The type of the image the scene will be exported to.
* @param fileName The name of the file where the image will be saved.
* @return True if the operation was successful,
* false if a problem occurred while exporting.
*/
bool UMLViewImageExporterModel::exportViewTo(UMLScene* scene, const QString &imageType, const QString &fileName) const
{
if (!scene) {
logWarn0("UMLViewImageExporterModel::exportViewTo: Scene is null!");
return false;
}
// remove 'blue squares' from exported picture.
scene->clearSelected();
QString imageMimeType = UMLViewImageExporterModel::imageTypeToMimeType(imageType);
if (imageMimeType == QStringLiteral("image/x-dot")) {
if (!exportViewToDot(scene, fileName)) {
return false;
}
} else if (imageMimeType == QStringLiteral("image/x-eps")) {
if (!exportViewToEps(scene, fileName)) {
return false;
}
} else if (imageMimeType == QStringLiteral("image/svg+xml")) {
if (!exportViewToSvg(scene, fileName)) {
return false;
}
} else {
if (!exportViewToPixmap(scene, imageType, fileName)) {
return false;
}
}
return true;
}
/**
* Exports the view to the file 'fileName' as a dot file.
*
* @param scene The scene to export.
* @param fileName The name of the file where the image will be saved.
* @return True if the operation was successful,
* false if a problem occurred while exporting.
*/
bool UMLViewImageExporterModel::exportViewToDot(UMLScene* scene, const QString &fileName) const
{
if (!scene) {
logWarn0("UMLViewImageExporterModel::exportViewToDot: Scene is null!");
return false;
}
DotGenerator dot;
bool result = dot.createDotFile(scene, fileName, QStringLiteral("export"));
logDebug2("UMLViewImageExporterModel::exportViewToDot saving to file %1 : %2",
fileName, result);
return result;
}
/**
* Exports the view to the file 'fileName' as EPS.
*
* @param scene The scene to export.
* @param fileName The name of the file where the image will be saved.
* @return True if the operation was successful,
* false if a problem occurred while exporting.
*/
bool UMLViewImageExporterModel::exportViewToEps(UMLScene* scene, const QString &fileName) const
{
if (!scene) {
logWarn0("UMLViewImageExporterModel::exportViewToEps: Scene is null!");
return false;
}
qreal border = 0.01; // mm
QRectF rect = scene->diagramRect();
if (rect.isEmpty()) {
rect = QRectF(0,0, 10, 10);
}
QSizeF paperSize(rect.size() * 25.4f / qApp->desktop()->logicalDpiX());
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFileName(fileName);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setColorMode(QPrinter::Color);
printer.setPaperSize(paperSize, QPrinter::Millimeter);
printer.setPageMargins(paperSize.width() * border, paperSize.height() * border, 0, 0, QPrinter::Millimeter);
printer.setResolution(qApp->desktop()->logicalDpiX());
printer.setOrientation(paperSize.width() < paperSize.height() ? QPrinter::Landscape : QPrinter::Portrait);
// do not call printer.setup(); because we want no user
// interaction here
QPainter painter(&printer);
// add border around image
painter.scale(1 - border, 1 - border);
// make sure the widget sizes will be according to the
// actually used printer font, important for diagramRect()
// and the actual painting
scene->forceUpdateWidgetFontMetrics(&painter);
scene->getDiagram(painter, rect);
// next painting will most probably be to a different device (i.e. the screen)
scene->forceUpdateWidgetFontMetrics(nullptr);
return true;
}
/**
* Exports the view to the file 'fileName' as SVG.
*
* @param scene The scene to export.
* @param fileName The name of the file where the image will be saved.
* @return True if the operation was successful,
* false if a problem occurred while exporting.
*/
bool UMLViewImageExporterModel::exportViewToSvg(UMLScene* scene, const QString &fileName) const
{
if (!scene) {
logWarn0("UMLViewImageExporterModel::exportViewToSvg: Scene is null!");
return false;
}
bool exportSuccessful;
QRectF rect = scene->diagramRect();
if (rect.isEmpty()) {
rect = QRectF(0,0, 10, 10);
}
QSvgGenerator generator;
generator.setFileName(fileName);
generator.setSize(rect.toRect().size());
generator.setResolution(qApp->desktop()->logicalDpiX());
generator.setViewBox(QRect(0, 0, rect.width(), rect.height()));
QPainter painter(&generator);
// make sure the widget sizes will be according to the
// actually used printer font, important for diagramRect()
// and the actual painting
// scene->forceUpdateWidgetFontMetrics(&painter);
//Note: The above was commented out because other exportViewTo...
// do not have it and it forces a resize of the widgets,
// which is not correctly implemented for now.
painter.translate(0, 0);
scene->getDiagram(painter, rect);
painter.end();
//FIXME: Determine the status of svg generation.
exportSuccessful = true;
// next painting will most probably be to a different device (i.e. the screen)
// scene->forceUpdateWidgetFontMetrics(0);
//Note: See comment above.
logDebug2("UMLViewImageExporterModel::exportViewToSvg saving to file %1 "
"successful=%2", fileName, exportSuccessful);
return exportSuccessful;
}
/**
* Exports the view to the file 'fileName' as a pixmap of the specified type.
* The valid types are those supported by QPixmap save method.
*
* @param scene The scene to export.
* @param imageType The type of the image the view will be exported to.
* @param fileName The name of the file where the image will be saved.
* @return True if the operation was successful,
* false if a problem occurred while exporting.
*/
bool UMLViewImageExporterModel::exportViewToPixmap(UMLScene* scene, const QString &imageType, const QString &fileName) const
{
if (!scene) {
logWarn0("UMLViewImageExporterModel::exportViewToPixmap: Scene is null!");
return false;
}
QRectF rect = scene->diagramRect();
if (rect.isEmpty()) {
rect = QRectF(0,0, 10, 10);
}
float scale = !qFuzzyIsNull(m_resolution) ? m_resolution / qApp->desktop()->logicalDpiX()
: 72.0f / qApp->desktop()->logicalDpiX();
QSizeF size = rect.size() * scale;
QPixmap diagram(size.toSize());
scene->getDiagram(diagram, rect);
bool exportSuccessful = diagram.save(fileName, qPrintable(imageType.toUpper()));
logDebug5("UMLViewImageExporterModel::exportViewToPixmap saving to file %1, "
"imageType=%2, width=%3, height=%4, successful=%5",
fileName, imageType, rect.width(), rect.height(), exportSuccessful);
return exportSuccessful;
}
| 19,365
|
C++
|
.cpp
| 471
| 35.825902
| 148
| 0.670595
|
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,278
|
petaltree2uml.cpp
|
KDE_umbrello/umbrello/petaltree2uml.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "petaltree2uml.h"
// app includes
#define DBG_SRC QStringLiteral("Import_Rose")
#include "debug_utils.h"
#include "petalnode.h"
#include "model_utils.h"
#include "object_factory.h"
#include "import_rose.h"
#include "uniqueid.h"
#include "package.h"
#include "folder.h"
#include "classifier.h"
#include "attribute.h"
#include "operation.h"
#include "datatype.h"
#include "enum.h"
#include "enumliteral.h"
#include "association.h"
#include "umlrole.h"
#include "actor.h"
#include "usecase.h"
#include "component.h"
#include "node.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "activitywidget.h"
#include "associationwidget.h"
#include "boxwidget.h"
#include "classifierwidget.h"
#include "floatingtextwidget.h"
#include "forkjoinwidget.h"
#include "notewidget.h"
#include "objectnodewidget.h"
#include "statewidget.h"
#include "umlwidgetlist.h"
#include "widget_factory.h"
// qt includes
#include <QtGlobal>
#include <QFile>
#include <QRegularExpression>
DEBUG_REGISTER(petalTree2Uml)
namespace Import_Rose {
/**
* The Rose diagram coordinate system is roughly twice the scale of Qt.
* I.e. when going from Rose diagram-object location/width/height to Qt,
* we need to shrink everything.
* The exact factor can be configured here.
*/
const qreal Rose2Qt = 0.5;
typedef QMap<QString, UMLWidget*> ViewTagToWidget_Map;
// map of diagram objects (is reset on each diagram parsed)
ViewTagToWidget_Map viewTagToWidget;
/**
* Return the given string without surrounding quotation marks.
* Also remove a possible prefix "Logical View::", it is not modeled in Umbrello.
*/
QString clean(const QString& s)
{
if (s.isNull())
return QString();
QString str = s;
str.remove(QLatin1Char('\"'));
str.remove(QRegularExpression(QStringLiteral("^.+::")));
return str;
}
/**
* Extract the quid attribute from a petal node and return it as a Uml::ID::Type.
*/
Uml::ID::Type quid(const PetalNode *node)
{
QString quidStr = node->findAttribute(QStringLiteral("quid")).string;
if (quidStr.isEmpty())
return Uml::ID::None;
quidStr.remove(QLatin1Char('\"'));
return Uml::ID::fromString(quidStr);
}
/**
* Extract the quidu attribute from a petal node.
*/
QString quidu(const PetalNode *node)
{
QString quiduStr = node->findAttribute(QStringLiteral("quidu")).string;
if (quiduStr.isEmpty())
return QString();
quiduStr.remove(QLatin1Char('\"'));
return quiduStr;
}
/**
* Extract the location attribute from a petal node.
* The extracted X,Y coordinates will be adjusted by the factor Rose2Qt
* unless width and/or height are given as 0.
*/
QPointF fetchLocation(const PetalNode *node, qreal width, qreal height)
{
QString location = node->findAttribute(QStringLiteral("location")).string;
if (location.isEmpty())
return QPointF();
QStringList a = location.split(QLatin1Char(' '));
if (a.size() != 2) {
return QPointF();
}
bool ok;
qreal x = a[0].toDouble(&ok);
if (!ok) {
return QPointF();
}
qreal y = a[1].toDouble(&ok);
if (!ok) {
return QPointF();
}
if (qFuzzyIsNull(width) || qFuzzyIsNull(height))
return QPointF(x, y);
x *= Rose2Qt; // adjust scale to Qt
y *= Rose2Qt; // adjust scale to Qt
// Rose diagram locations denote the object _center_ thus:
// - for X we must subtract width/2
// - for Y we must subtract height/2
return QPointF(x - width / 2.0, y - height / 2.0);
}
/**
* Extract a double attribute from a petal node.
*/
qreal fetchDouble(const PetalNode *node, const QString &attribute, bool applyRose2Qt = true)
{
bool ok;
QString s = node->findAttribute(attribute).string;
if (s.isEmpty()) {
logDebug1("fetchDouble(%1) : attribute not found, returning 0.0", attribute);
return 0.0;
}
qreal value = s.toDouble(&ok);
if (!ok) {
logDebug2("fetchDouble(%1) value \"%2\" : error on converting to double (returning 0.0)",
attribute, s);
return 0.0;
}
if (applyRose2Qt)
value *= Rose2Qt;
return value;
}
/**
* Extract an int attribute from a petal node.
*/
qreal fetchInt(const PetalNode *node, const QString &attribute, int defaultValue = 0)
{
bool ok;
QString s = node->findAttribute(attribute).string;
qreal value = s.toInt(&ok);
return ok ? value : defaultValue;
}
/**
* Determine the model type corresponding to a name.
* If the given name consists only of letters, digits, underscores, and
* scope separators then return ot_Class, else return ot_Datatype.
*/
UMLObject::ObjectType typeToCreate(const QString& name)
{
QString n = name;
n.remove(QRegularExpression(QStringLiteral("^.*::"))); // don't consider the scope prefix, it may contain spaces
UMLObject::ObjectType t = (n.contains(QRegularExpression(QStringLiteral("\\W"))) ? UMLObject::ot_Datatype
: UMLObject::ot_Class);
return t;
}
/**
* Transfer the Rose attribute "exportControl" to the Umbrello object given.
*
* @param from Pointer to PetalNode from which to read the "exportControl" attribute
* @param to Pointer to UMLObject in which to set the Uml::Visibility
*/
void transferVisibility(const PetalNode *from, UMLObject *to)
{
QString vis = from->findAttribute(QStringLiteral("exportControl")).string;
if (!vis.isEmpty()) {
Uml::Visibility::Enum v = Uml::Visibility::fromString(clean(vis.toLower()));
to->setVisibilityCmd(v);
}
}
/**
* ClassifierListReader factors the common processing for attributes, operations,
* and operation parameters.
*/
class ClassifierListReader
{
public:
/// constructor
ClassifierListReader(const char* attributeTag,
const char* elementName,
const char* itemTypeDesignator) :
m_attributeTag(QLatin1String(attributeTag)),
m_elementName(QLatin1String(elementName)),
m_itemTypeDesignator(QLatin1String(itemTypeDesignator)) {
}
/// destructor
virtual ~ClassifierListReader() {}
/**
* Return a UMLClassifierListItem of the specific type desired.
* Abstract method to be implemented by inheriting classes.
*/
virtual UMLObject *createListItem() = 0;
virtual void setTypeReferences(UMLObject *item,
const QString& quid, const QString& type) {
if (!quid.isEmpty()) {
item->setSecondaryId(quid);
}
if (!type.isEmpty()) {
item->setSecondaryFallback(type);
}
}
/**
* Insert the given UMLClassifierListItem at the parent Umbrello object.
* Abstract method to be implemented by inheriting classes.
* NB the parent Umbrello object is not included in the ClassifierListReader
* class - it must be added at inheriting classes.
*
* @param node The PetalNode which corresponds to the parent Umbrello object.
* @param o The UMLObject to insert.
*/
virtual void insertAtParent(const PetalNode *node, UMLObject *o) = 0;
/**
* Iterate over the attributes of the given PetalNode and for each recognized
* attribute do the following:
* - invoke createListItem()
* - fill common properties such as name, unique ID, visibility, etc. into
* the new UMLClassifierListItem
* - invoke insertAtParent() with the new classifier list item as the argument
* This is the user entry point.
*/
void read(const PetalNode *node, const QString& name)
{
PetalNode *attributes = node->findAttribute(m_attributeTag).node;
if (attributes == nullptr) {
#ifdef VERBOSE_DEBUGGING
logDebug2("petaltree2uml ClassifierListReader::read(%1): no %2 found",
name, m_attributeTag);
#endif
return;
}
PetalNode::NameValueList attributeList = attributes->attributes();
for (int i = 0; i < attributeList.count(); ++i) {
PetalNode *attNode = attributeList[i].second.node;
QStringList initialArgs = attNode->initialArgs();
if (attNode->name() != m_elementName) {
logDebug3("petaltree2uml ClassifierListReader::read(%1): expecting %2, found %3",
name, m_elementName, initialArgs[0]);
continue;
}
UMLObject *item = createListItem();
if (initialArgs.count() > 1)
item->setName(clean(initialArgs[1]));
item->setID(quid(attNode));
QString quidref = quidu(attNode);
QString type = clean(attNode->findAttribute(m_itemTypeDesignator).string);
if (quidref.isEmpty() && !type.isEmpty()) {
Object_Factory::assignUniqueIdOnCreation(true);
UMLDatatype *dt = UMLApp::app()->document()->createDatatype(type);
Object_Factory::assignUniqueIdOnCreation(false);
quidref = Uml::ID::toString(dt->id());
}
setTypeReferences(item, quidref, type);
transferVisibility(attNode, item);
item->setDoc(attNode->documentation());
insertAtParent(attNode, item);
}
}
protected:
const QString m_attributeTag, m_elementName, m_itemTypeDesignator;
};
class AttributesReader : public ClassifierListReader
{
public:
AttributesReader(UMLClassifier *c)
: ClassifierListReader("class_attributes", "ClassAttribute", "type") {
m_classifier = c;
}
virtual ~AttributesReader() {}
UMLObject *createListItem() {
return new UMLAttribute(m_classifier);
}
void insertAtParent(const PetalNode *, UMLObject *item) {
logDebug2("petaltree2uml AttributesReader::insertAtParent(%1): Adding attribute %2",
m_classifier->name(), item->name());
m_classifier->addAttribute(item->asUMLAttribute());
}
protected:
UMLClassifier *m_classifier;
};
class LiteralsReader : public ClassifierListReader
{
public:
LiteralsReader(UMLEnum *e)
: ClassifierListReader("class_attributes", "ClassAttribute", "type") {
m_enum = e;
}
virtual ~LiteralsReader() {}
UMLObject *createListItem() {
return new UMLEnumLiteral(m_enum);
}
void insertAtParent(const PetalNode *, UMLObject *item) {
UMLEnumLiteral *el = item->asUMLEnumLiteral();
if (el) {
logDebug2("petaltree2uml LiteralsReader::insertAtParent(%1): Adding enumliteral %2",
m_enum->name(), item->name());
m_enum->addEnumLiteral(el);
} else {
logError1("petaltree2uml LiteralsReader insertAtParent: Cannot cast %1 to UMLEnumLiteral",
item->name());
}
}
protected:
UMLEnum *m_enum;
};
class ParametersReader : public ClassifierListReader
{
public:
ParametersReader(UMLOperation *op)
: ClassifierListReader("parameters", "Parameter", "type") {
m_operation = op;
}
virtual ~ParametersReader() {}
UMLObject *createListItem() {
return new UMLAttribute(m_operation);
}
void insertAtParent(const PetalNode *, UMLObject *item) {
if (item->id() == Uml::ID::None)
item->setID(UniqueID::gen());
logDebug2("petaltree2uml ParametersReader::insertAtParent(%1): Adding parameter %2",
m_operation->name(), item->name());
m_operation->addParm(item->asUMLAttribute());
}
protected:
UMLOperation *m_operation;
};
class OperationsReader : public ClassifierListReader
{
public:
OperationsReader(UMLClassifier *c)
: ClassifierListReader("operations", "Operation", "result") {
m_classifier = c;
}
virtual ~OperationsReader() {}
UMLObject *createListItem() {
return new UMLOperation(m_classifier);
}
void insertAtParent(const PetalNode *node, UMLObject *item) {
logDebug2("petaltree2uml OperationsReader::insertAtParent(%1): Adding operation %2",
m_classifier->name(), item->name());
UMLOperation *op = item->asUMLOperation();
ParametersReader parmReader(op);
parmReader.read(node, m_classifier->name());
m_classifier->addOperation(op);
}
protected:
UMLClassifier *m_classifier;
};
class SuperclassesReader : public ClassifierListReader
{
public:
SuperclassesReader(UMLClassifier *c)
: ClassifierListReader("superclasses", "Inheritance_Relationship", "supplier") {
m_classifier = c;
}
virtual ~SuperclassesReader() {}
UMLObject *createListItem() {
return new UMLAssociation(Uml::AssociationType::Generalization);
}
/**
* Override parent implementation: The secondary data is not for the
* UMLAssociation itself but for its role B object.
*/
void setTypeReferences(UMLObject *item,
const QString& quid, const QString& type) {
UMLAssociation *assoc = item->asUMLAssociation();
if (!quid.isEmpty()) {
assoc->getUMLRole(Uml::RoleType::B)->setSecondaryId(quid);
}
if (!type.isEmpty()) {
assoc->getUMLRole(Uml::RoleType::B)->setSecondaryFallback(type);
}
}
void insertAtParent(const PetalNode *, UMLObject *item) {
UMLAssociation *assoc = item->asUMLAssociation();
assoc->setObject(m_classifier, Uml::RoleType::A);
assoc->setUMLPackage(m_classifier->umlPackage());
UMLApp::app()->document()->addAssociation(assoc);
}
protected:
UMLClassifier *m_classifier;
};
class RealizationsReader : public ClassifierListReader
{
public:
RealizationsReader(UMLClassifier *c)
: ClassifierListReader("realized_interfaces", "Realize_Relationship", "supplier") {
m_classifier = c;
}
virtual ~RealizationsReader() {}
UMLObject *createListItem() {
return new UMLAssociation(Uml::AssociationType::Realization);
}
/**
* Override parent implementation: The secondary data is not for the
* UMLAssociation itself but for its role B object.
*/
void setTypeReferences(UMLObject *item,
const QString& quid, const QString& type) {
UMLAssociation *assoc = item->asUMLAssociation();
if (!quid.isEmpty()) {
assoc->getUMLRole(Uml::RoleType::B)->setSecondaryId(quid);
}
if (!type.isEmpty()) {
assoc->getUMLRole(Uml::RoleType::B)->setSecondaryFallback(type);
}
}
void insertAtParent(const PetalNode *, UMLObject *item) {
UMLAssociation *assoc = item->asUMLAssociation();
assoc->setObject(m_classifier, Uml::RoleType::A);
assoc->setUMLPackage(m_classifier->umlPackage());
UMLApp::app()->document()->addAssociation(assoc);
}
protected:
UMLClassifier *m_classifier;
};
class UsesReader : public ClassifierListReader
{
public:
UsesReader(UMLClassifier *c)
: ClassifierListReader("used_nodes", "Uses_Relationship", "supplier") {
m_classifier = c;
}
virtual ~UsesReader() {}
UMLObject *createListItem() {
return new UMLAssociation(Uml::AssociationType::Dependency);
}
/**
* Override parent implementation: The secondary data is not for the
* UMLAssociation itself but for its role B object.
*/
void setTypeReferences(UMLObject *item,
const QString& quid, const QString& type) {
UMLAssociation *assoc = item->asUMLAssociation();
if (!quid.isEmpty()) {
assoc->getUMLRole(Uml::RoleType::B)->setSecondaryId(quid);
}
if (!type.isEmpty()) {
assoc->getUMLRole(Uml::RoleType::B)->setSecondaryFallback(type);
}
}
void insertAtParent(const PetalNode *, UMLObject *item) {
UMLAssociation *assoc = item->asUMLAssociation();
assoc->setObject(m_classifier, Uml::RoleType::A);
assoc->setUMLPackage(m_classifier->umlPackage());
UMLApp::app()->document()->addAssociation(assoc);
}
protected:
UMLClassifier *m_classifier;
};
/**
* Handle a controlled unit.
*
* @param node Pointer to the PetalNode which may contain a controlled unit
* @param name Name of the current node
* @param id QUID of the current node
* @param parentPkg Pointer to the current parent UMLPackage or UMLFolder.
* @return Pointer to UMLFolder created for controlled unit on success;
* NULL on error.
*/
UMLPackage* handleControlledUnit(PetalNode *node, const QString& name,
Uml::ID::Type id, UMLPackage * parentPkg)
{
Q_UNUSED(id);
if (node->findAttribute(QStringLiteral("is_unit")).string != QStringLiteral("TRUE"))
return nullptr;
//bool is_loaded = (node->findAttribute(QStringLiteral("is_loaded")).string != QStringLiteral("FALSE"));
QString file_name = node->findAttribute(QStringLiteral("file_name")).string;
if (file_name.isEmpty()) {
logError1("Import_Rose::handleControlledUnit(%1): attribute file_name not found (?)", name);
return nullptr;
}
file_name = file_name.mid(1, file_name.length() - 2); // remove surrounding ""
/* I wanted to use
file_name.replace(QRegularExpression(QStringLiteral("\\\\+") "/"));
but this did not work using Qt 4.6.3. Workaround:
*/
file_name.replace(QStringLiteral("\\\\"), QStringLiteral("/"));
file_name.replace(QRegularExpression(QStringLiteral("/+")), QStringLiteral("/"));
/* End of workaround */
if (file_name.startsWith(QStringLiteral("$"))) {
logDebug2("handleControlledUnit(%1) file_name before pathmap subst: %2",
name, file_name);
const int firstSlash = file_name.indexOf(QLatin1Char('/'));
QString envVarName;
if (firstSlash < 0) {
envVarName = file_name.mid(1);
} else {
envVarName = file_name.mid(1, firstSlash - 1);
}
QByteArray envVarBA = qgetenv(envVarName.toLatin1().data());
if (envVarBA.isNull() || envVarBA.isEmpty()) {
logError3("handleControlledUnit(%1): cannot process file_name %2 because env var %3 is not set",
name, file_name, envVarName);
return nullptr;
}
QString envVar(QString::fromLatin1(envVarBA));
logDebug3("handleControlledUnit(%1) : envVar %2 contains %3", name, envVarName, envVar);
if (envVar.endsWith(QLatin1Char('/')))
envVar.chop(1);
if (firstSlash < 0)
file_name = envVar;
else
file_name = envVar + file_name.mid(firstSlash);
logDebug2("handleControlledUnit(%1) file_name after pathmap subst: %2",
name, file_name);
} else {
logDebug2("handleControlledUnit(%1) file_name: %2", name, file_name);
}
QFileInfo fi(file_name);
if (!fi.isAbsolute()) {
// Must have an absolute path by now.
// If we don't then use the directory of the .mdl file.
file_name = Import_Rose::mdlPath() + file_name;
}
QFile file(file_name);
if (!file.exists()) {
logError2("Import_Rose::handleControlledUnit(%1): file_name %2 not found", name, file_name);
return nullptr;
}
if (!file.open(QIODevice::ReadOnly)) {
logError2("Import_Rose::handleControlledUnit(%1): file_name %2 cannot be opened", name, file_name);
return nullptr;
}
UMLPackage *controlledUnit = loadFromMDL(file, parentPkg);
return controlledUnit;
}
void handleAssocView(PetalNode *attr,
const PetalNode::NameValueList& parentAttrs,
Uml::AssociationType::Enum assocType,
UMLView *view,
UMLObject *umlAssoc = nullptr)
{
QString assocStr = Uml::AssociationType::toString(assocType);
PetalNode *roleview_list = attr->findAttribute(QStringLiteral("roleview_list")).node;
QString supplier, client;
if (roleview_list) {
PetalNode::StringOrNode supElem, cliElem;
PetalNode::NameValueList roles = roleview_list->attributes();
if (roles.length() < 2) {
logError1("Import_Rose::handleAssocView: %1 roleview_list should have 2 elements", assocStr);
return;
}
PetalNode *supNode = roles[0].second.node;
PetalNode *cliNode = roles[1].second.node;
if (supNode && cliNode) {
supElem = supNode->findAttribute(QStringLiteral("supplier"));
cliElem = cliNode->findAttribute(QStringLiteral("supplier")); // not a typo, really "supplier"
} else {
logError1("Import_Rose::handleAssocView: %1 roleview_list roles are incomplete", assocStr);
return;
}
supplier = supElem.string;
client = cliElem.string;
} else {
supplier = attr->findAttribute(QStringLiteral("supplier")).string;
client = attr->findAttribute(QStringLiteral("client")).string;
}
if (supplier.isEmpty()) {
logError1("Import_Rose::handleAssocView: %1 attribute 'supplier' non-existent or empty", assocStr);
return;
}
if (client.isEmpty()) {
logError1("Import_Rose::handleAssocView: %1 attribute 'client' non-existent or empty", assocStr);
return;
}
UMLWidget *supW = nullptr;
UMLWidget *cliW = nullptr;
if (viewTagToWidget.contains(supplier))
supW = viewTagToWidget[supplier];
else
logDebug1("handleAssocView: %1 attribute 'supplier' not in viewTagToWidget", assocStr);
if (viewTagToWidget.contains(client))
cliW = viewTagToWidget[client];
else
logDebug1("handleAssocView: %1 attribute 'client' not in viewTagToWidget", assocStr);
if (!supW || !cliW) {
PetalNode *sup = nullptr, *cli = nullptr;
for (int c = 0; c < parentAttrs.count(); ++c) {
PetalNode *n = parentAttrs[c].second.node;
QStringList initArgs = n->initialArgs();
QString tag = initArgs.last();
if (tag == client)
cli = n;
else if (tag == supplier)
sup = n;
}
if (!sup || !cli) {
logError2("Import_Rose::handleAssocView: %1 could not find client with tag %2", assocStr, client);
return;
}
QString spIdStr = quidu(sup);
Uml::ID::Type spId = Uml::ID::fromString(spIdStr);
QString clIdStr = quidu(cli);
Uml::ID::Type clId = Uml::ID::fromString(clIdStr);
if (spId == Uml::ID::None || clId == Uml::ID::None) {
logError3("Import_Rose::handleAssocView: %1 bad or nonexistent quidu at client %2 (%3)",
assocStr, client, cli->name());
return;
}
supW = view->umlScene()->widgetOnDiagram(spId);
cliW = view->umlScene()->widgetOnDiagram(clId);
if (supW == nullptr) {
logError2("Import_Rose::handleAssocView: %1 supplier widget %2 is not on diagram (?)",
assocStr, spIdStr);
return;
}
if (cliW == nullptr) {
logError2("Import_Rose::handleAssocView: %1 client widget is not on diagram (?)",
assocStr, clIdStr);
return;
}
}
AssociationWidget *aw = AssociationWidget::create (view->umlScene(), cliW, assocType,
supW, umlAssoc);
view->umlScene()->addAssociation(aw);
}
Uml::DiagramType::Enum diagramType(QString objType)
{
Uml::DiagramType::Enum dt;
dt = (objType == QStringLiteral("ClassDiagram") ? Uml::DiagramType::Class :
objType == QStringLiteral("UseCaseDiagram") ? Uml::DiagramType::UseCase :
objType == QStringLiteral("State_Diagram") ? Uml::DiagramType::State :
objType == QStringLiteral("ActivityDiagram") ? Uml::DiagramType::Activity :
objType == QStringLiteral("Module_Diagram") ? Uml::DiagramType::Component :
objType == QStringLiteral("Process_Diagram") ? Uml::DiagramType::Deployment :
// not yet implemented: InteractionDiagram (Sequence),
// ObjectDiagram (Collaboration)
Uml::DiagramType::Undefined);
return dt;
}
/**
* Create an Umbrello object from a PetalNode.
*
* @return True for success.
* Given a PetalNode for which the mapping to Umbrello is not yet
* implemented umbrellify() is a no-op but also returns true.
*/
bool umbrellify(PetalNode *node, UMLPackage *parentPkg)
{
if (node == nullptr) {
logError0("Import_Rose::umbrellify: node is NULL");
return false;
}
QStringList args = node->initialArgs();
QString objType = args[0];
QString name = clean(args[1]);
Uml::ID::Type id = quid(node);
Uml::DiagramType::Enum dt = Uml::DiagramType::Undefined;
if (objType == QStringLiteral("Class_Category") || objType == QStringLiteral("SubSystem")) {
const bool isSubsystem = (objType == QStringLiteral("SubSystem"));
QString modelsAttr(isSubsystem ? QStringLiteral("physical_models")
: QStringLiteral("logical_models"));
// statemachine (object State_Machine "State/Activity Model"
PetalNode *statemachine = node->findAttribute(QStringLiteral("statemachine")).node;
PetalNode *models = node->findAttribute(modelsAttr).node;
UMLObject *o = nullptr;
if (models) {
PetalNode::NameValueList atts = models->attributes();
QString presAttr(isSubsystem ? QStringLiteral("physical_presentations")
: QStringLiteral("logical_presentations"));
PetalNode::NameValueList pratts;
PetalNode *pres = node->findAttribute(presAttr).node;
if (pres) {
pratts = pres->attributes();
}
UMLObject::ObjectType containerType = UMLObject::ot_Package;
if (!pratts.isEmpty() || statemachine)
containerType = UMLObject::ot_Folder;
o = Object_Factory::createUMLObject(containerType, name, parentPkg);
o->setID(id);
UMLPackage *localParent = o->asUMLPackage();
for (int i = 0; i < atts.count(); ++i) {
umbrellify(atts[i].second.node, localParent);
}
for (int i = 0; i < pratts.count(); ++i) {
umbrellify(pratts[i].second.node, localParent);
}
} else {
o = handleControlledUnit(node, name, id, parentPkg);
if (o == nullptr) {
logWarn2("Import_Rose::umbrellify: %1 handleControlledUnit(%2) returns error",
objType, name);
return false;
}
}
if (isSubsystem)
o->setStereotypeCmd(QStringLiteral("subsystem"));
parentPkg->addObject(o);
if (statemachine) {
// statediagrams (list StateDiagrams
PetalNode *statediagrams = statemachine->findAttribute(QStringLiteral("statediagrams")).node;
PetalNode::NameValueList diagramList = statediagrams->attributes();
UMLPackage *localParent = static_cast<UMLPackage*>(o);
for (int i = 0; i < diagramList.count(); ++i) {
umbrellify(diagramList[i].second.node, localParent);
}
}
} else if (objType == QStringLiteral("Class")) {
QString stereotype = clean(node->findAttribute(QStringLiteral("stereotype")).string);
UMLObject *o = nullptr;
if (stereotype == QStringLiteral("Actor")) {
o = Object_Factory::createUMLObject(UMLObject::ot_Actor, name, parentPkg, false);
o->setID(id);
} else if (stereotype.contains(QStringLiteral("enum"), Qt::CaseInsensitive)) {
o = Object_Factory::createUMLObject(UMLObject::ot_Enum, name, parentPkg, false);
o->setID(id);
UMLEnum *e = o->asUMLEnum();
// set stereotype
if (stereotype.compare(QStringLiteral("enumeration"), Qt::CaseInsensitive) &&
stereotype.compare(QStringLiteral("enum"), Qt::CaseInsensitive) ) {
e->setStereotypeCmd(stereotype);
}
// insert literals
LiteralsReader litReader(e);
litReader.read(node, e->name());
} else {
o = Object_Factory::createUMLObject(UMLObject::ot_Class, name, parentPkg, false);
o->setID(id);
UMLClassifier *c = o->asUMLClassifier();
// set stereotype
if (!stereotype.isEmpty()) {
if (stereotype.toLower() == QStringLiteral("interface")) {
c->setBaseType(UMLObject::ot_Interface);
} else {
if (stereotype == QStringLiteral("CORBAInterface"))
c->setBaseType(UMLObject::ot_Interface);
c->setStereotypeCmd(stereotype);
}
}
// insert attributes
AttributesReader attReader(c);
attReader.read(node, c->name());
// insert operations
OperationsReader opReader(c);
opReader.read(node, c->name());
// insert generalizations
SuperclassesReader superReader(c);
superReader.read(node, c->name());
// insert realizations
RealizationsReader realReader(c);
realReader.read(node, c->name());
// insert dependency associations
UsesReader usesReader(c);
usesReader.read(node, c->name());
}
o->setDoc(node->documentation());
parentPkg->addObject(o);
} else if (objType == QStringLiteral("UseCase")) {
UMLObject *o = Object_Factory::createUMLObject(UMLObject::ot_UseCase, name, parentPkg, false);
o->setID(id);
o->setDoc(node->documentation());
parentPkg->addObject(o);
} else if (objType == QStringLiteral("Component") || objType == QStringLiteral("module")) {
UMLObject *o = Object_Factory::createUMLObject(UMLObject::ot_Component, name, parentPkg, false);
o->setID(id);
o->setDoc(node->documentation());
parentPkg->addObject(o);
} else if (objType == QStringLiteral("Association")) {
PetalNode *roles = node->findAttribute(QStringLiteral("roles")).node;
if (roles == nullptr) {
logError1("Import_Rose::umbrellify: cannot find roles of Association quid=%1",
Uml::ID::toString(id));
return false;
}
UMLAssociation *assoc = new UMLAssociation(Uml::AssociationType::UniAssociation);
PetalNode::NameValueList roleList = roles->attributes();
for (uint i = 0; i <= 1; ++i) {
PetalNode *roleNode = roleList[i].second.node;
if (roleNode == nullptr) {
logError1("Import_Rose::umbrellify: roleNode of Association %1 is NULL",
Uml::ID::toString(id));
return false;
}
if (roleNode->name() != QStringLiteral("Role")) {
logDebug2("umbrellify(%1): expecting Role, found '%2'", name, roleNode->name());
continue;
}
// index 0 corresponds to Umbrello roleB
// index 1 corresponds to Umbrello roleA
UMLRole *role = assoc->getUMLRole(Uml::RoleType::fromInt(!i));
QStringList initialArgs = roleNode->initialArgs();
if (initialArgs.count() > 1) {
QString roleName = clean(initialArgs[1]);
if (! roleName.startsWith(QStringLiteral("$UNNAMED")))
role->setName(roleName);
}
role->setID(quid(roleNode));
QString quidref = quidu(roleNode);
QString type = clean(roleNode->findAttribute(QStringLiteral("supplier")).string);
if (!quidref.isEmpty()) {
role->setSecondaryId(quidref);
}
if (!type.isEmpty()) {
role->setSecondaryFallback(type);
}
QString label = clean(roleNode->findAttribute(QStringLiteral("label")).string);
if (!label.isEmpty()) {
role->setName(label);
}
QString client_cardinality = clean(roleNode->findAttribute(QStringLiteral("client_cardinality")).string);
if (!client_cardinality.isEmpty()) {
role->setMultiplicity(client_cardinality);
}
QString is_navigable = clean(roleNode->findAttribute(QStringLiteral("is_navigable")).string);
if (is_navigable == QStringLiteral("FALSE")) {
assoc->setAssociationType(Uml::AssociationType::Association);
}
QString is_aggregate = clean(roleNode->findAttribute(QStringLiteral("is_aggregate")).string);
if (is_aggregate == QStringLiteral("TRUE")) {
assoc->setAssociationType(Uml::AssociationType::Aggregation);
}
QString containment = clean(roleNode->findAttribute(QStringLiteral("Containment")).string);
if (containment == QStringLiteral("By Value")) {
assoc->setAssociationType(Uml::AssociationType::Composition);
}
role->setDoc(roleNode->documentation());
}
assoc->setUMLPackage(parentPkg);
UMLApp::app()->document()->addAssociation(assoc);
} else if ((dt = diagramType(objType)) != Uml::DiagramType::Undefined) {
if (parentPkg->baseType() != UMLObject::ot_Folder) {
logError1("Import_Rose::umbrellify diagramType %1: internal error - "
"parentPkg must be UMLFolder for diagrams", dt);
return false;
}
viewTagToWidget.clear();
UMLDoc *umlDoc = UMLApp::app()->document();
UMLFolder *rootFolder = parentPkg->asUMLFolder();
UMLView *view = umlDoc->createDiagram(rootFolder, dt, name, id);
PetalNode *items = node->findAttribute(QStringLiteral("items")).node;
if (items == nullptr) {
logError2("Import_Rose::umbrellify: diagramType %1 object %2 attribute 'items' not found",
dt, objType);
return false;
}
PetalNode::NameValueList atts = items->attributes();
UMLWidgetList swimlanes; // auxiliary list for adjusting the final swimlane height to contain all widgets
qreal maxY = 0.0;
for (int i = 0; i < atts.count(); ++i) {
PetalNode *attr = atts[i].second.node;
QStringList args = attr->initialArgs();
QString objType = args[0];
QString name = clean(args[1]);
QString widgetId = attr->viewTag();
qreal width = 0.0;
qreal height = 0.0;
UMLWidget *w = nullptr;
if (objType == QStringLiteral("CategoryView")
|| objType == QStringLiteral("ClassView")
|| objType == QStringLiteral("UseCaseView")
|| objType == QStringLiteral("ModView")
|| objType == QStringLiteral("SubSysView")) {
QString objID = quidu(attr);
UMLObject *o = umlDoc->findObjectById(Uml::ID::fromString(objID));
if (!o) {
logError2("Import_Rose::umbrellify: %1 object with quidu %2 not found",
objType, objID);
continue;
}
w = Widget_Factory::createWidget(view->umlScene(), o);
width = fetchDouble(attr, QStringLiteral("width"));
if (width == 0) {
// Set default value to get it displayed at all.
width = name.length() * 12; // to be verified
logError3("Import_Rose::umbrellify: %1 %2: no width found, using default %3",
objType, name, width);
}
height = fetchDouble(attr, QStringLiteral("height"));
if (height == 0) {
// Set default value to get it displayed at all.
height = 100.0;
logError3("Import_Rose::umbrellify: %1 %2: no height found, using default %3",
objType, name, height);
}
w->setSize(width, height);
const QString icon = clean(attr->findAttribute(QStringLiteral("icon")).string);
if (icon == QStringLiteral("Interface")) {
ClassifierWidget *cw = dynamic_cast<ClassifierWidget*>(w);
if (cw)
cw->setVisualProperty(ClassifierWidget::DrawAsCircle);
else
logDebug2("Import_Rose::umbrellify(%1) : Setting %2 to circle is not yet implemented",
objType, name);
}
} else if (objType == QStringLiteral("InheritView") ||
objType == QStringLiteral("RealizeView") ||
objType == QStringLiteral("UsesView")) {
QString idStr = quidu(attr);
Uml::ID::Type assocID = Uml::ID::fromString(idStr);
if (assocID == Uml::ID::None) {
logError2("Import_Rose::umbrellify: %1 has illegal id %2", objType, idStr);
} else {
UMLObject *o = umlDoc->findObjectById(assocID);
if (o) {
if (o->baseType() != UMLObject::ot_Association) {
logError3("Import_Rose::umbrellify: %1 (%2) has wrong type %3",
objType, idStr, o->baseType());
} else {
Uml::AssociationType::Enum t = Uml::AssociationType::Generalization;
if (objType == QStringLiteral("RealizeView"))
t = Uml::AssociationType::Realization;
else if (objType == QStringLiteral("UsesView"))
t = Uml::AssociationType::Dependency;
handleAssocView(attr, atts, t, view, o);
}
} else {
logError2("Import_Rose::umbrellify: %1 with id %2 not found", objType, idStr);
}
}
} else if (objType == QStringLiteral("AssociationViewNew")) {
QString idStr = quidu(attr);
Uml::ID::Type assocID = Uml::ID::fromString(idStr);
if (assocID == Uml::ID::None) {
logError2("Import_Rose::umbrellify: %1 has illegal id %2", objType, idStr);
} else {
UMLObject *o = umlDoc->findObjectById(assocID);
Uml::AssociationType::Enum t = Uml::AssociationType::UniAssociation;
// @todo check if we need to change `t' to a different type for certain associations
handleAssocView(attr, atts, t, view, o);
}
} else if (objType == QStringLiteral("AttachView")) {
QString idStr = quidu(attr);
Uml::ID::Type assocID = Uml::ID::fromString(idStr);
if (assocID == Uml::ID::None) {
logError1("Import_Rose::umbrellify: AttachView has illegal id %1", idStr);
} else {
handleAssocView(attr, atts, Uml::AssociationType::Anchor, view);
}
} else if (objType == QStringLiteral("TransView")) {
Uml::AssociationType::Enum assocType = Uml::AssociationType::UniAssociation;
if (dt == Uml::DiagramType::Activity)
assocType = Uml::AssociationType::Activity;
else if (dt == Uml::DiagramType::State)
assocType = Uml::AssociationType::State;
const QString clientTag = attr->findAttribute(QStringLiteral("client")).string;
if (clientTag.isEmpty()) {
logError1("umbrellify: TransView %1 is missing client viewTag", attr->viewTag());
continue;
}
UMLWidget *clientW = viewTagToWidget[clientTag];
if (clientW == nullptr) {
logError2("umbrellify TransView %1 : clientTag %2 not found in viewTagToWidget",
attr->viewTag(), clientTag);
continue;
}
const QString supplierTag = attr->findAttribute(QStringLiteral("supplier")).string;
if (supplierTag.isEmpty()) {
logError1("umbrellify: TransView %1 is missing supplier viewTag", attr->viewTag());
continue;
}
UMLWidget *supplierW = viewTagToWidget[supplierTag];
if (supplierW == nullptr) {
logError2("umbrellify TransView %1 : supplierTag %2 not found in viewTagToWidget",
attr->viewTag(), supplierTag);
continue;
}
// (object TransView "" @19
// label (object SegLabel @20
// Parent_View @19
// location (1788, 1438)
// anchor_loc 1
// nlines 1
// max_width 597
// justify 0
// label "END / cntx.sayGoodBye"
// pctDist 0.523534
// height 47
// orientation 0)
// stereotype TRUE
// quidu "3D6780CD005D"
// client @4
// supplier @3
// vertices (list Points
// (1921, 801)
// (1921, 1391)
// (1130, 1391))
// line_style 3
// origin_attachment (1921, 801)
// terminal_attachment (1130, 1391)
// x_offset FALSE)
//
AssociationWidget * aw = AssociationWidget::create
(view->umlScene(), clientW, assocType, supplierW);
view->umlScene()->addAssociation(aw);
continue;
} else if (objType == QStringLiteral("NoteView")) {
w = new NoteWidget(view->umlScene(), NoteWidget::Normal);
width = fetchDouble(attr, QStringLiteral("width"));
height = fetchDouble(attr, QStringLiteral("height"));
if (width > 0 && height > 0)
w->setSize(width, height);
PetalNode *lblNode = attr->findAttribute(QStringLiteral("label")).node;
if (lblNode) {
QString label = clean(lblNode->findAttribute(QStringLiteral("label")).string);
w->setDocumentation(label);
}
// Add an artificial "quidu" attribute onto `attr' because
// handling of AttachView depends on it:
PetalNode::NameValueList innerAtts = attr->attributes();
PetalNode::StringOrNode value;
value.string = Uml::ID::toString(w->id());
PetalNode::NameValue synthQuidu(QStringLiteral("quidu"), value);
innerAtts.append(synthQuidu);
attr->setAttributes(innerAtts);
} else if (objType == QStringLiteral("Label")) {
QString label = clean(attr->findAttribute(QStringLiteral("label")).string);
w = new FloatingTextWidget(view->umlScene(), Uml::TextRole::Floating, label);
int nlines = fetchInt(attr, QStringLiteral("nlines"));
width = fetchDouble(attr, QStringLiteral("max_width"));
height = nlines * 12; // TODO check line height
w->setSize(width, height);
} else if (objType == QStringLiteral("Swimlane")) {
QString idStr = quidu(attr);
Uml::ID::Type id = Uml::ID::fromString(idStr);
width = fetchDouble(attr, QStringLiteral("width"));
height = 880; // initial guess, will be adjusted after loading (see UMLWidgetList swimlanes)
// (object Swimlane "Operator" @627
// location (2716, 0) // optional, if missing it's the first (leftmost)
// line_color 3342489
// quidu "3ADE7D250155"
// width 980)
w = new BoxWidget(view->umlScene(), id);
w->setSize(width, height);
QPointF pos = fetchLocation(attr, 0.0, 0.0); // use 0 for width and height
if (pos.isNull()) {
pos = QPointF(1.0, 1.0);
} else {
pos.setX(pos.x() * Rose2Qt);
pos.setY(1.0);
}
w->setPos(pos);
logDebug4("umbrellify(Swimlane %1) : x=%2, width=%3, m_attributes size=%4",
name, pos.x(), width, attr->attributes().size());
view->umlScene()->setupNewWidget(w, false);
swimlanes.append(w);
// Create FloatingText for the swimlane title.
qreal xOffset = (width - (name.length() * 12)) / 2.0;
QPointF textPos(pos.x() + xOffset, 12.0);
logDebug5("umbrellify(Swimlane %1) : x=%2 , y=%3 , w=%4 , h=%5",
name, textPos.x(), textPos.y(), width, height);
UMLWidget *textW = new FloatingTextWidget(view->umlScene(), Uml::TextRole::Floating, name);
textW->setSize(4.0 + (name.length() * 12.0), 14.0);
textW->setPos(textPos);
logDebug3("umbrellify(Swimlane %1) : textW width=%2 , height=%3", name, textW->width(), textW->height());
view->umlScene()->setupNewWidget(textW, false);
w = nullptr; // Setup of `w` is all done, setting it to null to inform the code below.
} else if (objType == QStringLiteral("ActivityStateView")) {
QString idStr = quidu(attr);
Uml::ID::Type id = Uml::ID::fromString(idStr);
w = new ActivityWidget(view->umlScene(), ActivityWidget::ActivityType::Normal, id);
width = fetchDouble(attr, QStringLiteral("width"));
if (qFuzzyIsNull(width)) {
width = 50.0 + (name.length() * 12);
}
height = fetchDouble(attr, QStringLiteral("height"));
if (qFuzzyIsNull(height)) {
height = 50.0;
}
w->setSize(width, height);
w->setName(name);
// (object ActivityStateView "Extract image" @628
// Parent_View @627
// location (501, 659)
// font (object Font
// size 10
// ........
// default_color TRUE)
// label (object ItemLabel
// Parent_View @628
// location (501, 653)
// fill_color 13434879
// anchor_loc 1
// nlines 2
// max_width 293
// justify 0
// label "Extract image")
// icon_style "Icon"
// line_color 3342489
// fill_color 13434879
// quidu "3ADE77DE00BD"
// width 411
// height 124
// annotation 1
// autoResize TRUE)
} else if (objType == QStringLiteral("StateView")) {
QString idStr = quidu(attr);
Uml::ID::Type id = Uml::ID::fromString(idStr);
const bool isInitial = (name == QStringLiteral("StartState"));
const bool isEnd = (name == QStringLiteral("EndState"));
if (dt == Uml::DiagramType::Activity) {
ActivityWidget::ActivityType type = ActivityWidget::ActivityType::Normal;
if (isInitial)
type = ActivityWidget::ActivityType::Initial;
else if (isEnd)
type = ActivityWidget::ActivityType::End;
w = new ActivityWidget(view->umlScene(), type, id);
} else {
// dt == Uml::DiagramType::State
StateWidget::StateType type = StateWidget::StateType::Normal;
if (isInitial)
type = StateWidget::StateType::Initial;
else if (isEnd)
type = StateWidget::StateType::End;
w = new StateWidget(view->umlScene(), type, id);
}
width = w->width();
height = w->height();
const bool isNormal = (!isInitial && !isEnd);
if (isNormal) {
PetalNode *lblNode = attr->findAttribute(QStringLiteral("label")).node;
if (lblNode) {
name = clean(lblNode->findAttribute(QStringLiteral("label")).string);
}
width = fetchDouble(attr, QStringLiteral("width"));
if (qFuzzyIsNull(width)) {
width = 50.0 + (name.length() * 12);
logDebug3("umbrellify(%1 %2) : width not given, defaulting to %3",
objType, name, width);
}
height = fetchDouble(attr, QStringLiteral("height"));
if (qFuzzyIsNull(height)) {
height = 50.0;
logDebug3("umbrellify(%1 %2) : height not given, defaulting to %3",
objType, name, height);
}
if (!qFuzzyIsNull(width) && !qFuzzyIsNull(height))
w->setSize(width, height);
w->setName(name);
}
} else if (objType == QStringLiteral("ObjectView")) {
QString idStr = quidu(attr);
Uml::ID::Type id = Uml::ID::fromString(idStr);
width = fetchDouble(attr, QStringLiteral("width"));
height = fetchDouble(attr, QStringLiteral("height"));
if (name.isEmpty()) {
PetalNode *lblNode = attr->findAttribute(QStringLiteral("label")).node;
if (lblNode) {
name = clean(lblNode->findAttribute(QStringLiteral("label")).string);
}
}
w = new ObjectNodeWidget(view->umlScene(), ObjectNodeWidget::ObjectNodeType::Normal, id);
const int nameWidth = (name.length() + 1) * 12.0; // to be verified
if (width < nameWidth)
width = nameWidth;
if (height < 12.0)
height = 12.0;
logDebug4("umbrellify(%1 %2) : width=%3, height=%4", objType, name, width, height);
w->setSize(width, height);
w->setName(name);
w->setInstanceName(name);
} else if (objType == QStringLiteral("DecisionView")) {
// (object DecisionView "Check image quality" @629
// Parent_View @3997
// location (1008, 1504)
// icon_style "Icon"
// line_color 3342489
// fill_color 13434879
// quidu "4385B29C023B"
// autoResize TRUE)
QString idStr = quidu(attr);
Uml::ID::Type id = Uml::ID::fromString(idStr);
w = new ActivityWidget(view->umlScene(), ActivityWidget::ActivityType::Branch, id);
width = height = 40.0;
w->setSize(width, height);
if (!name.isEmpty() && !name.startsWith(QStringLiteral("$UNNAMED$")))
w->setName(name);
} else if (objType == QStringLiteral("SynchronizationView")) {
Qt::Orientation ori = Qt::Horizontal;
QString sync_is_horizontal = attr->findAttribute(QStringLiteral("sync_is_horizontal")).string;
if (sync_is_horizontal == QStringLiteral("FALSE"))
ori = Qt::Vertical;
// (object SynchronizationView "$UNNAMED$193" @656
// location (500, 843)
// font (object Font
// size 10
// face "Arial"
// bold FALSE
// italics FALSE
// underline FALSE
// strike FALSE
// color 0
// default_color TRUE)
// label (object ItemLabel
// Parent_View @656
// location (662, 772)
// nlines 2
// max_width 300
// label "")
// icon_style "Icon"
// line_color 3342489
// quidu "3ADE7F9500D1"
// autoResize TRUE
// sync_flow_direction 1
// sync_is_horizontal TRUE)
w = new ForkJoinWidget(view->umlScene(), ori, id);
width = w->width();
height = w->height();
} else {
// CHECK: ConnectionView DataFlowView DependencyView InterfaceView
// InterObjView LinkView
logDebug2("umbrellify(%1) unsupported object type %2", name, objType);
}
if (!w)
continue;
QPointF pos = fetchLocation(attr, width, height);
if (!pos.isNull()) {
w->setPos(pos);
if (pos.y() + height > maxY)
maxY = pos.y() + height;
}
QString line_color = attr->findAttribute(QStringLiteral("line_color")).string;
if (!line_color.isEmpty()) {
unsigned int lineColor = line_color.toUInt();
const QString hexColor = QString::number(lineColor, 16);
QString hexRGB = QString(QStringLiteral("%1")).arg(hexColor, 6, QLatin1Char('0'));
logDebug3("%1 %2 : lineColor %3", objType, name, hexRGB);
QColor c(QLatin1Char('#') + hexRGB);
w->setLineColorCmd(c);
}
QString fill_color = attr->findAttribute(QStringLiteral("fill_color")).string;
if (fill_color.isEmpty()) {
w->setUseFillColor(false);
} else {
unsigned int fillColor = fill_color.toUInt();
const QString hexColor = QString::number(fillColor, 16);
QString hexRGB = QString(QStringLiteral("%1")).arg(hexColor, 6, QLatin1Char('0'));
logDebug3("%1 %2 : fillColor %3", objType, name, hexRGB);
QColor f(QLatin1Char('#') + hexRGB);
w->setFillColorCmd(f);
}
if (!widgetId.isEmpty())
w->setLocalID(Uml::ID::fromString(widgetId));
view->umlScene()->setupNewWidget(w, pos.isNull());
viewTagToWidget[widgetId] = w;
}
// Adjust swimlane Y extent to encompass all widgets
maxY += 20.0; // add a bottom margin
for(UMLWidget *bw : swimlanes) {
if (maxY > bw->height()) {
logDebug2("Adjusting swimlane %1 to height %2", bw->name(), maxY);
QRectF rect = bw->rect();
rect.setHeight(maxY);
bw->setRect(rect);
}
}
} else {
logDebug2("umbrellify(%1): object type %2 is not yet implemented", name, objType);
}
return true;
}
/**
* Auxiliary function for UseCase/Component/Deployment view import
*/
bool importView(PetalNode *root,
UMLPackage *parent,
const QString& rootName,
const QString& modelsName,
const QString& firstNodeName,
const QString& presentationsName)
{
PetalNode *viewRoot = root->findAttribute(rootName).node;
if (viewRoot == nullptr) {
logDebug1("petaltree2uml importView: cannot find %1", rootName);
return false;
}
if (viewRoot->name() != firstNodeName) {
logError3("Import_Rose::importView %1 : expecting first node name %2, found: %3",
modelsName, firstNodeName, viewRoot->name());
return false;
}
PetalNode *models = viewRoot->findAttribute(modelsName).node;
if (models == nullptr) {
logError2("Import_Rose::importView: cannot find %1 of %2", rootName, modelsName);
return false;
}
parent->setDoc(viewRoot->documentation());
PetalNode::NameValueList atts = models->attributes();
bool status = true;
for (int i = 0; i < atts.count(); ++i) {
if (!umbrellify(atts[i].second.node, parent))
status = false;
}
if (!status)
return false;
// statemachine (object State_Machine "State/Activity Model"
PetalNode *statemachine = viewRoot->findAttribute(QStringLiteral("statemachine")).node;
if (statemachine) {
// states (list States
// partitions (list Partitions
// objects (list Objects
// We don't decode these because Umbrello does not have structural elements for the
// states; they are diagram objects only. Luckily, the widgets in Rose's activity
// diagram save format duplicate all the structural information needed.
//
// statediagrams (list StateDiagrams
PetalNode *statediagrams = statemachine->findAttribute(QStringLiteral("statediagrams")).node;
PetalNode::NameValueList diagramList = statediagrams->attributes();
for (int i = 0; i < diagramList.count(); ++i) {
umbrellify(diagramList[i].second.node, parent);
}
}
if (presentationsName.isEmpty())
return true;
PetalNode *presentations = viewRoot->findAttribute(presentationsName).node;
if (presentations == nullptr) {
logError2("Import_Rose::importView %1: cannot find %2", modelsName, presentationsName);
return false;
}
PetalNode::NameValueList pratts = presentations->attributes();
for (int i = 0; i < pratts.count(); ++i) {
umbrellify(pratts[i].second.node, parent);
}
return true;
}
/**
* Auxiliary method for loadFromMDL() loading of controlled unit.
* Is kept in a separate file to reflect the fact that it is not
* coupled with the parser (other than by the PetalNode.)
*
* @param root the root of the tree
* @param parentPkg the owning package within which objects are created
* @return pointer to the newly created UMLPackage on success, NULL on error
*/
UMLPackage * petalTree2Uml(PetalNode *root, UMLPackage *parentPkg)
{
if (root == nullptr) {
logError0("petalTree2Uml: root is NULL");
return nullptr;
}
UMLPackage *rootPkg = Model_Utils::rootPackage(parentPkg);
if (rootPkg == nullptr) {
logError0("petalTree2Uml: internal error - rootPkg is NULL");
return nullptr;
}
UMLDoc *umlDoc = UMLApp::app()->document();
Uml::ModelType::Enum mt = umlDoc->rootFolderType(rootPkg);
QString modelsAttr(mt == Uml::ModelType::Component ? QStringLiteral("physical_models")
: QStringLiteral("logical_models"));
PetalNode *models = root->findAttribute(modelsAttr).node;
if (models == nullptr) {
logError1("petalTree2Uml: cannot find %1", modelsAttr);
return nullptr;
}
QStringList args = root->initialArgs();
QString name = clean(args[1]);
const Uml::ID::Type id = quid(root);
UMLObject *o = Object_Factory::createUMLObject(UMLObject::ot_Folder, name, parentPkg, false);
o->setID(id);
parentPkg = o->asUMLPackage();
PetalNode::NameValueList atts = models->attributes();
for (int i = 0; i < atts.count(); ++i) {
if (!umbrellify(atts[i].second.node, parentPkg)) {
break;
}
}
return parentPkg;
}
} // namespace Import_Rose
| 61,983
|
C++
|
.cpp
| 1,372
| 34.049563
| 121
| 0.566201
|
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,279
|
objectswindow.cpp
|
KDE_umbrello/umbrello/objectswindow.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2016-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "objectswindow.h"
// app includes
#include "models/objectsmodel.h"
#include "uml.h"
#include "umldoc.h"
#include "umlview.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QHeaderView>
#include <QTableView>
#include <QSortFilterProxyModel>
#include <QtDebug>
Q_DECLARE_METATYPE(UMLObject*);
ObjectsWindow::ObjectsWindow(const QString &title, QWidget *parent)
: QDockWidget(title, parent)
{
setObjectName(QStringLiteral("ObjectsWindow"));
m_proxyModel = new QSortFilterProxyModel;
m_proxyModel->setSourceModel(UMLApp::app()->document()->objectsModel());
m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
m_objectsTree = new QTableView;
m_objectsTree->setModel(m_proxyModel);
m_objectsTree->setSortingEnabled(true);
m_objectsTree->verticalHeader()->setDefaultSectionSize(20);
m_objectsTree->verticalHeader()->setVisible(false);
m_objectsTree->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setWidget(m_objectsTree);
connect(m_objectsTree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotObjectsDoubleClicked(QModelIndex)));
connect(m_objectsTree, SIGNAL(clicked(QModelIndex)), this, SLOT(slotObjectsClicked(QModelIndex)));
}
ObjectsWindow::~ObjectsWindow()
{
delete m_objectsTree;
delete m_proxyModel;
}
void ObjectsWindow::modified()
{
UMLObject *o = dynamic_cast<UMLObject*>(QObject::sender());
if (!o)
return;
UMLApp::app()->document()->objectsModel()->emitDataChanged(o);
}
void ObjectsWindow::slotObjectsDoubleClicked(QModelIndex index)
{
QVariant v = m_objectsTree->model()->data(index, Qt::UserRole);
if (v.canConvert<UMLObject*>()) {
UMLObject *o = v.value<UMLObject*>();
o->showPropertiesDialog(this);
}
}
void ObjectsWindow::slotObjectsClicked(QModelIndex index)
{
#if 1
Q_UNUSED(index)
#else
QVariant v = m_objectsTree->model()->data(index, Qt::UserRole);
if (v.canConvert<UMLObject*>()) {
UMLObject *o = v.value<UMLObject*>();
//o->showPropertiesDialog(this);
}
#endif
}
| 2,240
|
C++
|
.cpp
| 67
| 30.014925
| 114
| 0.738084
|
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,280
|
refactoringassistant.cpp
|
KDE_umbrello/umbrello/refactoring/refactoringassistant.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Luis De la Parra <lparrab@gmx.net>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "refactoringassistant.h"
#include "attribute.h"
#include "basictypes.h"
#include "classifier.h"
#include "classpropertiesdialog.h"
#include "debug_utils.h"
#include "object_factory.h"
#include "operation.h"
#include "umlattributedialog.h"
#include "umldoc.h"
#include "umloperationdialog.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include <KLocalizedString>
#include <KMessageBox>
#include <QApplication>
#include <QMenu>
#include <QPoint>
DEBUG_REGISTER(RefactoringAssistant)
/**
* Constructor.
* @param doc the UML document
* @param obj the UML classifier to refactor
* @param parent the parent widget
* @param name the object name
*/
RefactoringAssistant::RefactoringAssistant(UMLDoc *doc, UMLClassifier *obj, QWidget *parent, const QString &name)
: QTreeWidget(parent),
m_doc(doc)
{
setObjectName(name);
setRootIsDecorated(true);
setAcceptDrops(true);
setDropIndicatorShown(true);
setSelectionMode(QAbstractItemView::SingleSelection);
setDragEnabled(true);
setHeaderLabel(i18n("Name"));
setContextMenuPolicy(Qt::CustomContextMenu);
m_menu = new QMenu(this);
connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
this, SLOT(itemExecuted(QTreeWidgetItem*,int)));
connect(this, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
resize(300, 400);
refactor(obj);
}
/**
* Destructor.
*/
RefactoringAssistant::~RefactoringAssistant()
{
m_umlObjectMap.clear();
clear();
}
/**
* Builds up the tree for the classifier.
* @param obj the classifier which has to be refactored
*/
void RefactoringAssistant::refactor(UMLClassifier *obj)
{
clear();
m_umlObjectMap.clear();
m_umlObject = obj;
if (! m_umlObject) {
return;
}
DEBUG() << "called for " << m_umlObject->name();
m_alreadySeen.clear();
addClassifier(obj, nullptr, true, true, true);
QTreeWidgetItem *item = topLevelItem(0);
item->setExpanded(true);
for (int i = 0; i < item->childCount(); ++i) {
item->setExpanded(true);
}
}
/**
* Find UML object from tree item.
* @param item the item from the tree widget
* @return the UML object behind the item
*/
UMLObject* RefactoringAssistant::findUMLObject(const QTreeWidgetItem *item)
{
if (!item) {
return nullptr;
}
QTreeWidgetItem *i = const_cast<QTreeWidgetItem*>(item);
if (m_umlObjectMap.find(i) == m_umlObjectMap.end()) {
logWarn1("RefactoringAssistant::findUMLObject: Item with text %1 not found in uml map",
item->text(0));
return nullptr;
}
return m_umlObjectMap[i];
}
/**
* Find tree item from UML object.
* @param obj the UML object to search in tree
* @return the found tree widget item or 0
*/
QTreeWidgetItem* RefactoringAssistant::findListViewItem(const UMLObject *obj)
{
QMapIterator<QTreeWidgetItem*, UMLObject*> it(m_umlObjectMap);
while (it.hasNext()) {
it.next();
if (it.value() == obj) {
return it.key();
}
}
logWarn1("RefactoringAssistant::findUMLObject: Object id %1 does not have an item in the tree",
Uml::ID::toString(obj->id()));
return nullptr;
}
/**
* Slot for double clicking on a tree widget item.
* @param item tree widget item on which the user clicked
* @param column the column of the tree on which the user clicked.
*/
void RefactoringAssistant::itemExecuted(QTreeWidgetItem *item, int column)
{
Q_UNUSED(column);
UMLObject *obj = findUMLObject(item);
if (obj) {
editProperties();
}
}
/**
* Set the icon representing the visibility of the given item.
* @param item the tree item
* @param obj the UML object behind the tree item
*/
void RefactoringAssistant::setVisibilityIcon(QTreeWidgetItem *item, const UMLObject *obj)
{
UMLObject::ObjectType t = obj->baseType();
switch (obj->visibility()) {
case Uml::Visibility::Public:
if (t == UMLObject::ot_Operation) {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Public_Method));
}
else {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Public_Attribute));
}
break;
case Uml::Visibility::Protected:
if (t == UMLObject::ot_Operation) {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Protected_Method));
}
else {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Protected_Attribute));
}
break;
case Uml::Visibility::Private:
if (t == UMLObject::ot_Operation) {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Private_Method));
}
else {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Private_Attribute));
}
break;
case Uml::Visibility::Implementation:
if (t == UMLObject::ot_Operation) {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Implementation_Method));
}
else {
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Implementation_Attribute));
}
break;
default:
break;
}
}
/**
* Slot for updating the tree item properties according to the given UML object.
*/
void RefactoringAssistant::objectModified()
{
const UMLObject *obj = dynamic_cast<const UMLObject*>(sender());
if (!obj)
return;
QTreeWidgetItem *item = findListViewItem(obj);
if (!item) {
return;
}
item->setText(0, obj->name());
if (typeid(*obj) == typeid(UMLOperation) ||
typeid(*obj) == typeid(UMLAttribute)) {
setVisibilityIcon(item, obj);
}
}
/**
* Slot for adding an operation to the tree.
* @param listItem the new operation to add
*/
void RefactoringAssistant::operationAdded(UMLClassifierListItem *listItem)
{
UMLOperation *op = listItem->asUMLOperation();
DEBUG() << "operation = " << op->name(); //:TODO:
UMLClassifier *parent = op->umlParent()->asUMLClassifier();
if (!parent) {
logWarn1("RefactoringAssistant::operationAdded(%1): Parent of operation is not a classifier",
op->name());
return;
}
QTreeWidgetItem *item = findListViewItem(parent);
if (!item) {
return;
}
for (int i = 0; i < item->childCount(); ++i) {
QTreeWidgetItem *folder = item->child(i);
if (folder->text(1) == QStringLiteral("operations")) {
item = new QTreeWidgetItem(folder, QStringList(op->name()));
m_umlObjectMap[item] = op;
connect(op, SIGNAL(modified()), this, SLOT(objectModified()));
setVisibilityIcon(item, op);
DEBUG() << "operation = " << op->name() << " added!"; //:TODO:
break;
}
}
}
/**
* Slot for removing an operation from the tree.
* @param listItem the operation to be removed
*/
void RefactoringAssistant::operationRemoved(UMLClassifierListItem *listItem)
{
UMLOperation *op = listItem->asUMLOperation();
QTreeWidgetItem *item = findListViewItem(op);
if (!item) {
return;
}
disconnect(op, SIGNAL(modified()), this, SLOT(objectModified()));
m_umlObjectMap.remove(item);
delete item;
}
/**
* Slot for adding an attribute to the tree.
* @param listItem the new attribute to add
*/
void RefactoringAssistant::attributeAdded(UMLClassifierListItem *listItem)
{
UMLAttribute *att = listItem->asUMLAttribute();
DEBUG() << "attribute = " << att->name(); //:TODO:
UMLClassifier *parent = att->umlParent()->asUMLClassifier();
if (!parent) {
logWarn1("RefactoringAssistant::attributeAdded(%1): Parent of attribute is not a classifier",
att->name());
return;
}
QTreeWidgetItem *item = findListViewItem(parent);
if (!item) {
logWarn1("RefactoringAssistant::attributeAdded(%1): Parent is not in tree", att->name());
return;
}
for (int i = 0; i < item->childCount(); ++i) {
QTreeWidgetItem *folder = item->child(i);
if (folder->text(1) == QStringLiteral("attributes")) {
item = new QTreeWidgetItem(folder, QStringList(att->name()));
m_umlObjectMap[item] = att;
connect(att, SIGNAL(modified()), this, SLOT(objectModified()));
setVisibilityIcon(item, att);
DEBUG() << "attribute = " << att->name() << " added!"; //:TODO:
break;
}
}
}
/**
* Slot for removing an attribute from the tree.
* @param listItem the attribute to be removed
*/
void RefactoringAssistant::attributeRemoved(UMLClassifierListItem *listItem)
{
UMLAttribute *att = listItem->asUMLAttribute();
DEBUG() << "attribute = " << att->name(); //:TODO:
QTreeWidgetItem *item = findListViewItem(att);
if (!item) {
logWarn1("RefactoringAssistant::attributeRemoved(%1): Attribute is not in tree", att->name());
return;
}
disconnect(att, SIGNAL(modified()), this, SLOT(objectModified()));
m_umlObjectMap.remove(item);
delete item;
DEBUG() << "attribute = " << att->name() << " deleted!"; //:TODO:
}
/**
* Slot for calling editProperties with the current item.
*/
void RefactoringAssistant::editProperties()
{
QTreeWidgetItem* item = currentItem();
if (item) {
UMLObject* obj = findUMLObject(item);
if (obj) {
editProperties(obj);
}
}
}
/**
* Show the dialog with data from the given UML object.
* @param obj the UML object to edit
*/
void RefactoringAssistant::editProperties(UMLObject *obj)
{
QDialog *dia(nullptr);
UMLObject::ObjectType t = obj->baseType();
if (t == UMLObject::ot_Class || t == UMLObject::ot_Interface) {
ClassPropertiesDialog *dialog = new ClassPropertiesDialog(this, obj, true);
if (dialog && dialog->exec()) {
// need to update something?
}
delete dialog;
}
else if (t == UMLObject::ot_Operation) {
dia = new UMLOperationDialog(this, obj->asUMLOperation());
}
else if (t == UMLObject::ot_Attribute) {
dia = new UMLAttributeDialog(this, obj->asUMLAttribute());
}
else {
logWarn1("RefactoringAssistant::editProperties called for unknown type %1", UMLObject::toString(t));
return;
}
if (dia && dia->exec()) {
// need to update something?
}
delete dia;
}
/**
* Slot for deleting an item called from the popup menu.
*/
void RefactoringAssistant::deleteItem()
{
QTreeWidgetItem *item = currentItem();
if (item) {
UMLObject *o = findUMLObject(item);
if (o) {
deleteItem(item, o);
}
}
}
/**
* Delete an item from the tree.
* @param item the tree widget item
* @param obj the uml object
*/
void RefactoringAssistant::deleteItem(QTreeWidgetItem *item, UMLObject *obj)
{
UMLObject::ObjectType t = obj->baseType();
if (t == UMLObject::ot_Class || t == UMLObject::ot_Interface) {
DEBUG() << "Delete class or interface - not yet implemented!"; //:TODO:
}
else if (t == UMLObject::ot_Operation) {
QTreeWidgetItem *opNode = item->parent();
if (opNode) {
QTreeWidgetItem *parent = opNode->parent();
UMLClassifier* c = findUMLObject(parent)->asUMLClassifier();
if (!c) {
logWarn0("No classifier - cannot delete!");
return;
}
UMLOperation* op = obj->asUMLOperation();
c->removeOperation(op);
}
}
else if (t == UMLObject::ot_Attribute) {
QTreeWidgetItem *attrNode = item->parent();
if (attrNode) {
QTreeWidgetItem *parent = attrNode->parent();
UMLClassifier* c = findUMLObject(parent)->asUMLClassifier();
if (!c) {
logWarn0("No classifier - cannot delete!");
return;
}
UMLAttribute* attr = obj->asUMLAttribute();
c->removeAttribute(attr);
}
}
else {
logWarn1("RefactoringAssistant::deleteItem called for unknown type %1", UMLObject::toString(t));
}
}
/**
* Create an action for an entry in the context menu.
* @param text the text of the action
* @param method the method to call when triggered
* @param icon the shown icon
* @return the created action
*/
QAction* RefactoringAssistant::createAction(const QString& text, const char * method, const Icon_Utils::IconType icon)
{
Q_UNUSED(method);
QAction* action = new QAction(this);
action->setText(text);
if (icon != Icon_Utils::N_ICONTYPES) {
action->setIcon(Icon_Utils::SmallIcon(icon));
}
return action;
}
/**
* Slot for the context menu by right clicking in the tree widget.
* @param p point of the right click inside the tree widget
*/
void RefactoringAssistant::showContextMenu(const QPoint& p)
{
QTreeWidgetItem* item = itemAt(p);
if (!item) {
return;
}
m_menu->clear();
UMLObject *obj = findUMLObject(item);
if (obj) { // Menu for UMLObjects
UMLObject::ObjectType t = obj->baseType();
if (t == UMLObject::ot_Class) {
m_menu->addAction(createAction(i18n("Add Base Class"), SLOT(addBaseClassifier()), Icon_Utils::it_Generalisation));
m_menu->addAction(createAction(i18n("Add Derived Class"), SLOT(addDerivedClassifier()), Icon_Utils::it_Uniassociation));
// m_menu->addAction(createAction(i18n("Add Interface Implementation"), SLOT(addInterfaceImplementation()), Icon_Utils::it_Implementation));
m_menu->addAction(createAction(i18n("Add Operation"), SLOT(createOperation()), Icon_Utils::it_Public_Method));
m_menu->addAction(createAction(i18n("Add Attribute"), SLOT(createAttribute()), Icon_Utils::it_Public_Attribute));
}
else if (t == UMLObject::ot_Interface) {
m_menu->addAction(createAction(i18n("Add Base Interface"), SLOT(addSuperClassifier()), Icon_Utils::it_Generalisation));
m_menu->addAction(createAction(i18n("Add Derived Interface"), SLOT(addDerivedClassifier()), Icon_Utils::it_Uniassociation));
m_menu->addAction(createAction(i18n("Add Operation"), SLOT(createOperation()), Icon_Utils::it_Public_Method));
}
// else {
// DEBUG() << "No context menu for objects of type " << typeid(*obj).name();
// return;
// }
m_menu->addSeparator();
m_menu->addAction(createAction(i18n("Properties"), SLOT(editProperties()), Icon_Utils::it_Properties));
m_menu->addAction(createAction(i18n("Delete"), SLOT(deleteItem()), Icon_Utils::it_Delete));
}
else { //menu for other ViewItems
if (item->text(1) == QStringLiteral("operations")) {
m_menu->addAction(createAction(i18n("Add Operation"), SLOT(createOperation()), Icon_Utils::it_Public_Method));
}
else if (item->text(1) == QStringLiteral("attributes")) {
m_menu->addAction(createAction(i18n("Add Attribute"), SLOT(createAttribute()), Icon_Utils::it_Public_Attribute));
}
else {
logWarn0("Called for unsupported item.");
return;
}
}
m_menu->exec(mapToGlobal(p) + QPoint(0, 20));
}
/**
* Slot for adding a base classifier.
*/
void RefactoringAssistant::addBaseClassifier()
{
QTreeWidgetItem *item = currentItem();
if (!item) {
logWarn0("Called with no item selected");
return;
}
UMLObject *obj = findUMLObject(item);
if (!obj->asUMLClassifier()) {
logWarn0("Called for a non-classifier object.");
return;
}
//classes have classes and interfaces interfaces as super/derived classifiers
UMLObject::ObjectType t = obj->baseType();
UMLClassifier *super = Object_Factory::createUMLObject(t)->asUMLClassifier();
if (!super) {
return;
}
m_doc->createUMLAssociation(obj, super, Uml::AssociationType::Generalization);
////////////////////// Manually add the classifier to the assistant - would be nicer to do it with
///////////////////// a signal, like operations and attributes
QTreeWidgetItem *baseFolder = nullptr;
for (int i = 0; i < item->childCount(); ++i) {
baseFolder = item->child(i);
if (!baseFolder) {
logWarn0("Cannot find base folder!");
return;
}
if (baseFolder->text(0) == i18n("Base Classifiers")) {
item = new QTreeWidgetItem(baseFolder, QStringList(super->name()));
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Generalisation));
item->setExpanded(true);
m_umlObjectMap[item] = super;
addClassifier(super, item, true, false, true);
break;
}
}
/////////////////////////
}
/**
* Slot for adding a derived classifier.
*/
void RefactoringAssistant::addDerivedClassifier()
{
QTreeWidgetItem *item = currentItem();
if (!item) {
logWarn0("Called with no item selected.");
return;
}
UMLObject *obj = findUMLObject(item);
if (!obj->asUMLClassifier()) {
logWarn0("Called for a non-classifier object.");
return;
}
//classes have classes and interfaces have interfaces as super/derived classifiers
UMLObject::ObjectType t = obj->baseType();
UMLClassifier *derived = Object_Factory::createUMLObject(t)->asUMLClassifier();
if (!derived) {
return;
}
m_doc->createUMLAssociation(derived, obj, Uml::AssociationType::Generalization);
////////////////////// Manually add the classifier to the assistant - would be nicer to do it with
///////////////////// a signal, like operations and attributes
QTreeWidgetItem *derivedFolder = nullptr;
for (int i = 0; i < item->childCount(); ++i) {
derivedFolder = item->child(i);
if (!derivedFolder) {
logWarn0("Cannot find derived folder!");
return;
}
if (derivedFolder->text(0) == i18n("Derived Classifiers")) {
item = new QTreeWidgetItem(derivedFolder, QStringList(derived->name()));
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Uniassociation));
item->setExpanded(true);
m_umlObjectMap[item] = derived;
addClassifier(derived, item, false, true, true);
}
}
/////////////////////////
}
/**
* Slot for adding an interface implementation.
* @todo not yet implemented, needs addSuperClassifier() first
*/
void RefactoringAssistant::addInterfaceImplementation()
{
logWarn0("Not implemented... finish addSuperClassifier() first!!");
return;
// QTreeWidgetItem *item = selectedListViewItem();
// UMLObject *obj = findUMLObject(item);
// if(!obj->asUMLClassifier())
// return;
// UMLObject *n = Object_Factory::createUMLObject(UMLObject::ot_Interface));
// if (!n) {
// return;
// }
// m_doc->createUMLAssociation(n, obj, UMLObject::at_Realization);
// //refresh, add classifier to assistant
}
/**
* Create new operation.
*/
void RefactoringAssistant::createOperation()
{
QTreeWidgetItem *item = currentItem();
if (!item) {
logWarn0("Called with no item selected.");
return;
}
UMLClassifier *c = findUMLObject(item)->asUMLClassifier();
if (!c) { // find parent
QTreeWidgetItem *parent = item->parent();
c = findUMLObject(parent)->asUMLClassifier();
if (!c) {
logWarn0("No classifier - cannot create!");
return;
}
}
c->createOperation();
}
/**
* Create new attribute.
*/
void RefactoringAssistant::createAttribute()
{
QTreeWidgetItem *item = currentItem();
if (!item) {
logWarn0("Called with no item selected.");
return;
}
UMLClassifier *c = findUMLObject(item)->asUMLClassifier();
if (!c) { // find parent
QTreeWidgetItem *parent = item->parent();
c = findUMLObject(parent)->asUMLClassifier();
if (!c) {
logWarn0("No classifier - cannot create!");
return;
}
}
c->createAttribute();
}
/**
* Add a classifier to the data structure.
* @param classifier the classifier to add
* @param parent the tree item under which the classifier is placed
* @param addSuper add it to the base classifier folder
* @param addSub add it to the derived classifier folder
* @param recurse ...
*/
void RefactoringAssistant::addClassifier(UMLClassifier *classifier, QTreeWidgetItem *parent, bool addSuper, bool addSub, bool recurse)
{
if (!classifier) {
logWarn0("No classifier given - do nothing!");
return;
}
DEBUG() << classifier->name() << " added.";
QTreeWidgetItem *classifierItem, *item;
if (parent) {
classifierItem = parent;
}
else {
classifierItem = new QTreeWidgetItem(this, QStringList(classifier->name()));
m_umlObjectMap[classifierItem] = classifier;
}
m_alreadySeen << classifier;
connect(classifier, SIGNAL(modified()),
this, SLOT(objectModified()));
// add attributes
connect(classifier, SIGNAL(attributeAdded(UMLClassifierListItem*)),
this, SLOT(attributeAdded(UMLClassifierListItem*)));
connect(classifier, SIGNAL(attributeRemoved(UMLClassifierListItem*)),
this, SLOT(attributeRemoved(UMLClassifierListItem*)));
QStringList itemTextAt;
itemTextAt << i18n("Attributes") << QStringLiteral("attributes");
QTreeWidgetItem *attsFolder = new QTreeWidgetItem(classifierItem, itemTextAt);
attsFolder->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Folder_Orange));
attsFolder->setExpanded(true);
UMLAttributeList atts(classifier->getAttributeList());
for(UMLAttribute *att : atts) {
attributeAdded(att);
}
// add operations
connect(classifier, SIGNAL(operationAdded(UMLClassifierListItem*)),
this, SLOT(operationAdded(UMLClassifierListItem*)));
connect(classifier, SIGNAL(operationRemoved(UMLClassifierListItem*)),
this, SLOT(operationRemoved(UMLClassifierListItem*)));
QStringList itemTextOp;
itemTextOp << i18n("Operations") << QStringLiteral("operations");
QTreeWidgetItem *opsFolder = new QTreeWidgetItem(classifierItem, itemTextOp);
opsFolder->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Folder_Orange));
opsFolder->setExpanded(true);
UMLOperationList ops(classifier->getOpList());
for(UMLOperation *op : ops) {
operationAdded(op);
}
if (addSuper) { // add base classifiers
QTreeWidgetItem *superFolder = new QTreeWidgetItem(classifierItem, QStringList(i18n("Base Classifiers")));
superFolder->setExpanded(true);
UMLClassifierList super = classifier->findSuperClassConcepts();
for(UMLClassifier *cl : super) {
item = new QTreeWidgetItem(superFolder, QStringList(cl->name()));
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Generalisation));
item->setExpanded(true);
m_umlObjectMap[item] = cl;
if (recurse) {
if (m_alreadySeen.contains(cl)) {
DEBUG() << "super class already seen" << cl;
continue;
}
addClassifier(cl, item, true, false, true);
}
}
}
if (addSub) { // add derived classifiers
QTreeWidgetItem *derivedFolder = new QTreeWidgetItem(classifierItem, QStringList(i18n("Derived Classifiers")));
derivedFolder->setExpanded(true);
UMLClassifierList derived = classifier->findSubClassConcepts();
for(UMLClassifier *d : derived) {
item = new QTreeWidgetItem(derivedFolder, QStringList(d->name()));
item->setIcon(0, Icon_Utils::SmallIcon(Icon_Utils::it_Uniassociation));
item->setExpanded(true);
m_umlObjectMap[item] = d;
if (recurse) {
if (m_alreadySeen.contains(d)) {
DEBUG() << "derived class already seen" << d;
continue;
}
addClassifier(d, item, false, true, true);
}
}
}
}
/**
* Reimplementation of the drag move event.
* @param event the drag move event
*/
void RefactoringAssistant::dragMoveEvent(QDragMoveEvent *event)
{
//first check if we can accept dropping
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
QTreeWidgetItem* target = itemAt(event->pos());
QTreeWidgetItem* item = currentItem();
if (target && item) {
//first check if we can accept dropping
QTreeWidgetItem* parent = item->parent();
if (parent) {
if ((target->text(1) == QStringLiteral("operations")) &&
(parent->text(1) == QStringLiteral("operations"))) {
DEBUG() << "accept operation " << item->text(0); //:TODO:fischer
event->accept();
return;
}
if ((target->text(1) == QStringLiteral("attributes")) &&
(parent->text(1) == QStringLiteral("attributes"))) {
DEBUG() << "accept attribute " << item->text(0); //:TODO:fischer
event->accept();
return;
}
}
}
event->ignore();
} else {
event->acceptProposedAction();
}
}
/**
* Reimplementation of the drop event.
* @param event the drop event
*/
void RefactoringAssistant::dropEvent(QDropEvent *event)
{
QTreeWidgetItem* movingItem = currentItem();
if (!movingItem) {
event->ignore();
return; // no item ?
}
DEBUG() << "dropping=" << movingItem->text(0);
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
DEBUG() << "accept"; //:TODO:fischer
}
else {
event->acceptProposedAction();
DEBUG() << "acceptProposedAction"; //:TODO:fischer
return;
}
QTreeWidgetItem* afterme = itemAt(event->pos());
if (!afterme) {
logWarn0("Drop target not found - aborting drop!");
return;
}
DEBUG() << "Dropping after item = " << afterme->text(0); //:TODO:fischer
// when dropping on a class, we have to put the item in the appropriate folder!
UMLObject *movingObject;
UMLClassifier *newClassifier;
if ((movingItem == afterme) || !(movingObject = findUMLObject(movingItem))) {
logWarn0("Moving item not found or dropping after itself or item not found in uml obj map. aborting. (drop had already been accepted)");
return;
}
QTreeWidgetItem* parentItem = afterme->parent();
UMLObject::ObjectType t = movingObject->baseType();
newClassifier = findUMLObject(parentItem)->asUMLClassifier();
if (!newClassifier) {
const QString parentText = parentItem->text(1);
if ((parentText == QStringLiteral("operations") && t == UMLObject::ot_Operation) ||
(parentText == QStringLiteral("attributes") && t == UMLObject::ot_Attribute)) {
newClassifier = findUMLObject(parentItem->parent())->asUMLClassifier();
}
if (!newClassifier) {
logWarn0("New parent of object is not a Classifier - Drop had already been accepted - check!");
return;
}
}
if (t == UMLObject::ot_Operation) {
DEBUG() << "Moving operation";
UMLOperation *op = movingObject->asUMLOperation();
if (newClassifier->checkOperationSignature(op->name(), op->getParmList())) {
QString msg = i18n("An operation with that signature already exists in %1.\n", newClassifier->name())
+
i18n("Choose a different name or parameter list.");
KMessageBox::error(this, msg, i18n("Operation Name Invalid"));
return;
}
UMLOperation* newOp = op->clone()->asUMLOperation();
UMLClassifier *oldClassifier = op->umlParent()->asUMLClassifier();
if (oldClassifier) {
oldClassifier->removeOperation(op);
DEBUG() << "oldClassifier=" << oldClassifier->name() << " / newClassifier=" << newClassifier->name(); //:TODO:fischer
}
newClassifier->addOperation(newOp);
m_doc->signalUMLObjectCreated(newOp); //:TODO: really?
}
else if (t == UMLObject::ot_Attribute) {
DEBUG() << "Moving attribute";
UMLAttribute *att = movingObject->asUMLAttribute();
if (newClassifier->getAttributeList().contains(att)) {
QString msg = i18n("An attribute with that name already exists in %1.\n", newClassifier->name())
+
i18n("Choose a different name.");
KMessageBox::error(this, msg, i18n("Attribute Name Invalid"));
return;
}
UMLAttribute* newAtt = att->clone()->asUMLAttribute();
UMLClassifier *oldClassifier = att->umlParent()->asUMLClassifier();
if (oldClassifier) {
oldClassifier->removeAttribute(att);
DEBUG() << "oldClassifier=" << oldClassifier->name() << " / newClassifier=" << newClassifier->name(); //:TODO:fischer
}
newClassifier->addAttribute(newAtt);
m_doc->signalUMLObjectCreated(newAtt); //:TODO: really?
}
// Q_EMIT moved();
refactor(m_umlObject); //:TODO:fischer
}
| 29,896
|
C++
|
.cpp
| 806
| 30.454094
| 152
| 0.629262
|
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,281
|
codegenstatuspage.cpp
|
KDE_umbrello/umbrello/codegenwizard/codegenstatuspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Luis De la Parra <luis@delaparra.org>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codegenstatuspage.h"
// app includes
#include "codegenerationwizard.h" //:TODO: circular reference
#include "codegenerator.h"
#include "codegenerationpolicypage.h"
#include "codegenfactory.h"
#include "codegenpolicyext.h"
#include "debug_utils.h"
#include "defaultcodegenpolicypage.h"
#include "model_utils.h"
#include "uml.h"
#include "umldoc.h"
//kde includes
#include <KLocalizedString>
#include <KMessageBox>
//qt includes
#include <QFileDialog>
#include <QListWidget>
/**
* Constructor.
* @param parent the parent (wizard) of this wizard page
*/
CodeGenStatusPage::CodeGenStatusPage(QWidget *parent)
: QWizardPage(parent),
m_generationDone(false)
{
setTitle(i18n("Status of Code Generation Progress"));
setSubTitle(i18n("Press the button Generate to start the code generation.\nCheck the success state for every class."));
setupUi(this);
ui_tableWidgetStatus->setColumnCount(3);
ui_textEditLogger->setReadOnly(true);
connect(ui_pushButtonGenerate, SIGNAL(clicked()), this, SLOT(generateCode()));
connect(ui_pushButtonClear, SIGNAL(clicked()), this, SLOT(loggerClear()));
connect(ui_pushButtonExport, SIGNAL(clicked()), this, SLOT(loggerExport()));
}
/**
* Destructor.
*/
CodeGenStatusPage::~CodeGenStatusPage()
{
}
/**
* Reimplemented QWizardPage method to initialize page after clicking next button.
*/
void CodeGenStatusPage::initializePage()
{
ui_tableWidgetStatus->clearContents();
m_generationDone = false;
populateStatusList();
}
/**
* Fills the status list with the selected classes for generation.
*/
void CodeGenStatusPage::populateStatusList()
{
CodeGenerationWizard* wiz = (CodeGenerationWizard*)wizard();
QListWidget* classListWidget = wiz->getSelectionListWidget();
ui_tableWidgetStatus->setRowCount(classListWidget->count());
for (int index = 0; index < classListWidget->count(); ++index) {
QListWidgetItem* item = classListWidget->item(index);
ui_tableWidgetStatus->setItem(index, 0, new QTableWidgetItem(item->text()));
ui_tableWidgetStatus->setItem(index, 1, new QTableWidgetItem(i18n("Not Yet Generated")));
LedStatus* led = new LedStatus(70, 70);
ui_tableWidgetStatus->setCellWidget(index, 2, led);
}
if (classListWidget->count() > 0) {
ui_pushButtonGenerate->setEnabled(true);
}
else {
ui_pushButtonGenerate->setEnabled(false);
}
}
/**
* Slot for the generate button. Starts the code generation.
*/
void CodeGenStatusPage::generateCode()
{
ui_pushButtonGenerate->setEnabled(false);
setCommitPage(true); //:TODO: disable back and cancel button ?
CodeGenerator* codeGenerator = UMLApp::app()->generator();
UMLDoc* doc = UMLApp::app()->document();
if (codeGenerator) {
connect(codeGenerator, SIGNAL(codeGenerated(UMLClassifier*,bool)),
this, SLOT(classGenerated(UMLClassifier*,bool)));
connect(codeGenerator, SIGNAL(codeGenerated(UMLClassifier*, CodeGenerator::GenerationState)),
this, SLOT(classGenerated(UMLClassifier*, CodeGenerator::GenerationState)));
connect(codeGenerator, SIGNAL(showGeneratedFile(QString)),
this, SLOT(showFileGenerated(QString)));
UMLClassifierList cList;
for (int row = 0; row < ui_tableWidgetStatus->rowCount(); ++row) {
QTableWidgetItem* item = ui_tableWidgetStatus->item(row, 0);
UMLClassifier *classifier = doc->findUMLClassifier(item->text());
if (classifier == nullptr) {
logError1("CodeGenStatusPage::generateCode: Could not find classifier %1 "
"(not included in generated code)", item->text());
continue;
}
cList.append(classifier);
}
codeGenerator->writeCodeToFile(cList);
m_generationDone = true;
setFinalPage(true);
Q_EMIT completeChanged();
}
}
/**
* Reimplemented QWizardPage method the enable / disable the next button.
* @return complete state
*/
bool CodeGenStatusPage::isComplete() const
{
return m_generationDone;
}
/**
* Updates the status of the code generation in the status table.
* @param classifier the class for which the code was generated
* @param generated the status of the generation
*/
void CodeGenStatusPage::classGenerated(UMLClassifier* classifier, bool generated)
{
classGenerated(classifier, generated ? CodeGenerator::Generated : CodeGenerator::Failed);
}
/**
* Updates the status of the code generation in the status table.
* @param classifier the class for which the code was generated
* @param state the state of the generation
*/
void CodeGenStatusPage::classGenerated(UMLClassifier* classifier, CodeGenerator::GenerationState state)
{
QList<QTableWidgetItem*> items = ui_tableWidgetStatus->findItems(classifier->fullyQualifiedName(), Qt::MatchFixedString);
if (items.count() > 0) {
QTableWidgetItem* item = items.at(0);
if (!item) {
logError0("Code Generation Status Page: Error finding class in list view!");
}
else {
int row = ui_tableWidgetStatus->row(item);
QTableWidgetItem* status = ui_tableWidgetStatus->item(row, 1);
LedStatus* led = (LedStatus*)ui_tableWidgetStatus->cellWidget(row, 2);
if (state == CodeGenerator::Generated) {
status->setText(i18n("Code Generated"));
led->setOn(true);
}
else if (state == CodeGenerator::Failed) {
status->setText(i18n("Not Generated"));
led->setColor(Qt::red);
led->setOn(true);
}
else if (state == CodeGenerator::Skipped) {
status->setText(i18n("Skipped"));
led->setColor(Qt::gray);
led->setOn(true);
}
}
}
}
/**
* Writes the content of the just generated file to the logger text widget.
*/
void CodeGenStatusPage::showFileGenerated(const QString& filename)
{
ui_textEditLogger->insertHtml(QStringLiteral("<b>") + filename + QStringLiteral(":</b><br>"));
QFile file(filename);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
ui_textEditLogger->insertHtml(line + QStringLiteral("<br>"));
}
file.close();
}
else {
ui_textEditLogger->insertHtml(i18n("Cannot open file!") + QStringLiteral("<br>"));
}
ui_textEditLogger->insertHtml(QStringLiteral("<br><HR><br>"));
}
/**
* Slot for clicked events generated by the clear button of the logger.
* Clears the logger widget.
*/
void CodeGenStatusPage::loggerClear()
{
ui_textEditLogger->setHtml(QString());
}
/**
* Slot for clicked events generated by the export button of the logger.
* Writes the content of the logger widget to a file.
*/
void CodeGenStatusPage::loggerExport()
{
const QString caption = i18n("Umbrello Code Generation - Logger Export");
QString fileName = QFileDialog::getSaveFileName(this, caption, QStringLiteral("UmbrelloCodeGenerationLogger.html"));
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
out << ui_textEditLogger->toHtml();
file.close();
}
else {
KMessageBox::error(this, i18n("Cannot open file!"), caption);
}
}
}
| 7,824
|
C++
|
.cpp
| 210
| 31.538095
| 125
| 0.679673
|
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,282
|
codegenselectpage.cpp
|
KDE_umbrello/umbrello/codegenwizard/codegenselectpage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codegenselectpage.h"
// app includes
#include "folder.h"
#include "umldoc.h"
#include "uml.h"
#include "classifier.h"
#include "entity.h"
//kde includes
#include <KLocalizedString>
//qt includes
#include <QListWidget>
/**
* Constructor.
* @param parent the parent (wizard) of this wizard page
*/
CodeGenSelectPage::CodeGenSelectPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(i18n("Select Classes"));
setSubTitle(i18n("Place all the classes you want to generate code\nfor in the right hand side list."));
setupUi(this);
connect(ui_addButton, SIGNAL(clicked()), this, SLOT(selectClass()));
connect(ui_removeButton, SIGNAL(clicked()), this, SLOT(deselectClass()));
}
/**
* Destructor.
*/
CodeGenSelectPage::~CodeGenSelectPage()
{
}
/**
* Loads the available classes for selection / deselection
* into the list widget.
* @param classList the available classes for generation
*/
void CodeGenSelectPage::setClassifierList(UMLClassifierList *classList)
{
UMLDoc* doc = UMLApp::app()->document();
UMLClassifierList cList;
ui_listSelected->clear();
if (classList == nullptr) {
Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage();
switch (pl) {
case Uml::ProgrammingLanguage::PostgreSQL:
case Uml::ProgrammingLanguage::MySQL:
for(UMLEntity* ent : doc->entities()) {
cList.append(ent);
}
break;
default:
cList = doc->classesAndInterfaces();
break;
}
classList = &cList;
}
for(UMLClassifier* c : cList) {
new QListWidgetItem(c->fullyQualifiedName(), ui_listSelected);
}
}
/**
* Reimplemented QWizardPage method the enable / disable the next button.
* @return complete state
*/
bool CodeGenSelectPage::isComplete() const
{
bool completed = false;
if (ui_listSelected->count() > 0) {
completed = true;
}
return completed;
}
/**
* Returns the list widget, which holds the classes for generation.
* @return the list widget of the selected classes
*/
QListWidget* CodeGenSelectPage::getSelectionListWidget()
{
return ui_listSelected;
}
/**
* Adds the classes selected in the available classes list to the
* list of classes used to generate the code.
*/
void CodeGenSelectPage::selectClass()
{
moveSelectedItems(ui_listAvailable, ui_listSelected);
Q_EMIT completeChanged();
}
/**
* Removes the classes selected in the selected classes list from the
* list of classes used to generate the code.
*/
void CodeGenSelectPage::deselectClass()
{
moveSelectedItems(ui_listSelected, ui_listAvailable);
Q_EMIT completeChanged();
}
/**
* Moves the selected items from first list to second list.
* The selected items are removed from the first list and added to the
* second. An item is added to the second list only if it isn't already
* there (no duplicated items are created).
* @param fromList the list widget of selected items
* @param toList the target list widget
*/
void CodeGenSelectPage::moveSelectedItems(QListWidget* fromList, QListWidget* toList)
{
for(QListWidgetItem* item : fromList->selectedItems()) {
QString name = item->text();
QList<QListWidgetItem*> foundItems = toList->findItems(name, Qt::MatchExactly);
if (foundItems.isEmpty()) {
new QListWidgetItem(name, toList);
}
// Removed here because it can't (really, shouldn't) be removed while
// iterator is pointing to it
fromList->takeItem(fromList->row(item));
}
}
| 3,812
|
C++
|
.cpp
| 123
| 26.699187
| 107
| 0.694634
|
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,283
|
codegenoptionspage.cpp
|
KDE_umbrello/umbrello/codegenwizard/codegenoptionspage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Luis De la Parra <luis@delaparra.org>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codegenoptionspage.h"
// app includes
#include "codegenerator.h"
#include "codegenerationpolicypage.h"
#include "codegenerators/codegenfactory.h"
#include "codegenerators/codegenpolicyext.h"
#include "defaultcodegenpolicypage.h"
#include "uml.h"
// kde includes
#include <KMessageBox>
#include <KLocalizedString>
// qt includes
#include <QFileDialog>
/**
* Constructor.
* @param parent the parent (wizard) of this wizard page
*/
CodeGenOptionsPage::CodeGenOptionsPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(i18n("Code Generation Options"));
setSubTitle(i18n("Adjust code generation options."));
setupUi(this);
m_pCodePolicyPage = nullptr;
m_parentPolicy = UMLApp::app()->commonPolicy();
CodeGenerator* gen = UMLApp::app()->generator();
ui_forceDoc->setChecked(m_parentPolicy->getCodeVerboseDocumentComments());
ui_writeSectionComments->setCurrentIndex(m_parentPolicy->getSectionCommentsPolicy());
ui_outputDir->setText(m_parentPolicy->getOutputDirectory().absolutePath());
ui_includeHeadings->setChecked(m_parentPolicy->getIncludeHeadings());
ui_headingsDir->setText(m_parentPolicy->getHeadingFileDir());
overwriteToWidget(m_parentPolicy->getOverwritePolicy())->setChecked(true);
ui_SelectEndLineCharsBox->setCurrentIndex(newLineToInteger(m_parentPolicy->getLineEndingType()));
ui_SelectIndentationTypeBox->setCurrentIndex(indentTypeToInteger(m_parentPolicy->getIndentationType()));
ui_SelectIndentationNumber->setValue(m_parentPolicy->getIndentationAmount());
connect(this, SIGNAL(syncCodeDocumentsToParent()), gen, SLOT(syncCodeToDocument()));
connect(this, SIGNAL(languageChanged()), this, SLOT(updateCodeGenerationPolicyTab()));
connect(this, SIGNAL(languageChanged()), this, SLOT(changeLanguage()));
connect(ui_browseOutput, SIGNAL(clicked()), this, SLOT(browseClicked()));
connect(ui_browseHeadings, SIGNAL(clicked()), this, SLOT(browseClicked()));
setupActiveLanguageBox();
//now insert the language-dependent page, should there be one
updateCodeGenerationPolicyTab();
}
/**
* Destructor.
*/
CodeGenOptionsPage::~CodeGenOptionsPage()
{
}
/**
* Fills the language combo box with items and
* sets the currently selected value.
*/
void CodeGenOptionsPage::setupActiveLanguageBox()
{
int indexCounter = 0;
while (indexCounter <= Uml::ProgrammingLanguage::Reserved) {
QString language = Uml::ProgrammingLanguage::toString(Uml::ProgrammingLanguage::fromInt(indexCounter));
ui_SelectLanguageBox->insertItem(indexCounter, language);
indexCounter++;
}
ui_SelectLanguageBox->setCurrentIndex(UMLApp::app()->activeLanguage());
connect(ui_SelectLanguageBox, SIGNAL(activated(int)), this, SLOT(activeLanguageChanged(int)));
}
/**
* Static utility function to convert the indentation type to integer.
* @param value the indentation type
* @return the corresponding integer value
*/
int CodeGenOptionsPage::indentTypeToInteger(CodeGenerationPolicy::IndentationType value)
{
switch (value) {
case CodeGenerationPolicy::NONE:
return 0;
case CodeGenerationPolicy::TAB:
return 1;
case CodeGenerationPolicy::SPACE:
return 2;
default:
return 0;
}
}
/**
* Static utility function to convert the new line type to integer.
* @param value the new line type
* @return the corresponding integer value
*/
int CodeGenOptionsPage::newLineToInteger(CodeGenerationPolicy::NewLineType value)
{
switch (value) {
case CodeGenerationPolicy::UNIX:
return 0;
case CodeGenerationPolicy::DOS:
return 1;
case CodeGenerationPolicy::MAC:
return 2;
default:
return 0;
}
}
/**
* Converts the overwrite policy value to the corresponding widget object.
* @param value the overwrite policy
* @return the corresponding widget obeject
*/
QRadioButton* CodeGenOptionsPage::overwriteToWidget(CodeGenerationPolicy::OverwritePolicy value)
{
switch (value) {
case CodeGenerationPolicy::Ok:
return ui_radioButtonOverwrite;
case CodeGenerationPolicy::Ask:
return ui_radioButtonAsk;
case CodeGenerationPolicy::Never:
return ui_radioButtonChangeName;
default:
return ui_radioButtonAsk;
}
}
/**
* Converts the corresponding widget checked value to the overwrite policy.
* @return the overwrite policy
*/
CodeGenerationPolicy::OverwritePolicy CodeGenOptionsPage::widgetToOverwrite()
{
if (ui_radioButtonOverwrite->isChecked()) {
return CodeGenerationPolicy::Ok;
}
if (ui_radioButtonAsk->isChecked()) {
return CodeGenerationPolicy::Ask;
}
if (ui_radioButtonChangeName->isChecked()) {
return CodeGenerationPolicy::Never;
}
return CodeGenerationPolicy::Ask;
}
/**
* Updates the code generation policy tab.
*/
void CodeGenOptionsPage::updateCodeGenerationPolicyTab()
{
if (m_pCodePolicyPage)
{
ui_tabWidgetMain->removeTab(2);
m_pCodePolicyPage->disconnect();
delete m_pCodePolicyPage;
m_pCodePolicyPage = nullptr;
}
Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromInt(ui_SelectLanguageBox->currentIndex());
CodeGenPolicyExt *policyExt = nullptr;
if (pl != Uml::ProgrammingLanguage::Reserved)
policyExt = CodeGenFactory::newCodeGenPolicyExt(pl);
if (policyExt) {
m_pCodePolicyPage = policyExt->createPage(nullptr, "codelangpolicypage");
}
else {
m_pCodePolicyPage = new DefaultCodeGenPolicyPage(nullptr, "codelangpolicypage");
}
ui_tabWidgetMain->insertTab(2, m_pCodePolicyPage, i18n("Language Options"));
connect(this, SIGNAL(applyClicked()), m_pCodePolicyPage, SLOT(apply()));
}
/**
* Reimplemented QWizardPage method to validate page when user clicks next button.
* @return the validation state
*/
bool CodeGenOptionsPage::validatePage()
{
return save();
}
/**
* Reads the set values from their corresponding widgets, writes them back to
* the data structure, and notifies clients.
*/
void CodeGenOptionsPage::apply()
{
if (m_parentPolicy) {
m_parentPolicy->setCodeVerboseDocumentComments(ui_forceDoc->isChecked());
m_parentPolicy->setSectionCommentsPolicy((CodeGenerationPolicy::WriteSectionCommentsPolicy)
ui_writeSectionComments->currentIndex());
m_parentPolicy->setOutputDirectory(QDir(ui_outputDir->text()));
m_parentPolicy->setIncludeHeadings(ui_includeHeadings->isChecked());
m_parentPolicy->setHeadingFileDir(ui_headingsDir->text());
m_parentPolicy->setOverwritePolicy(widgetToOverwrite());
m_parentPolicy->setLineEndingType((CodeGenerationPolicy::NewLineType) ui_SelectEndLineCharsBox->currentIndex());
m_parentPolicy->setIndentationType((CodeGenerationPolicy::IndentationType) ui_SelectIndentationTypeBox->currentIndex());
m_parentPolicy->setIndentationAmount(ui_SelectIndentationNumber->value());
m_pCodePolicyPage->apply();
// Emit in THIS order. The first signal triggers any sub-class to do its apply
// slot, THEN, once we are all updated, we may sync the parent generator's code
// documents.
Q_EMIT applyClicked();
Q_EMIT syncCodeDocumentsToParent();
}
}
/**
* This function is called when leaving this wizard page.
* Saves the made settings and checks some values.
* @return the success state
*/
bool CodeGenOptionsPage::save()
{
// first save the settings to the selected generator policy
apply();
// before going on to the generation page, check that the output directory
// exists and is writable
// get the policy for the current code generator
CodeGenerationPolicy *policy = UMLApp::app()->commonPolicy();
// get the output directory path
QFileInfo info(policy->getOutputDirectory().absolutePath());
if (info.exists()) {
// directory exists... make sure we can write to it
if (!info.isWritable()) {
KMessageBox::information(this, i18n("The output folder exists, but it is not writable.\nPlease set the appropriate permissions or choose another folder."),
i18n("Error Writing to Output Folder"));
return false;
}
// it exits and we can write... make sure it is a directory
if (!info.isDir()) {
KMessageBox::information(this, i18n("%1 does not seem to be a folder. Please choose a valid folder.", info.filePath()),
i18n("Please Choose Valid Folder"));
return false;
}
}
else {
if (KMessageBox::questionYesNo(this,
i18n("The folder %1 does not exist. Do you want to create it now?", info.filePath()),
i18n("Output Folder Does Not Exist"), KGuiItem(i18n("Create Folder")), KGuiItem(i18n("Do Not Create"))) == KMessageBox::Yes)
{
QDir dir;
if (!dir.mkdir(info.filePath())) {
KMessageBox::information(this, i18n("The folder could not be created.\nPlease make sure you have write access to its parent folder or select another, valid, folder."),
i18n("Error Creating Folder"));
return false;
}
// else, directory created
}
else { // do not create output directory
KMessageBox::information(this, i18n("Please select a valid folder."),
i18n("Output Folder Does Not Exist"));
return false;
}
}
return true;
}
/**
* Transform signal.
* @param id position in combo box
*/
void CodeGenOptionsPage::activeLanguageChanged(int id)
{
Q_UNUSED(id);
Q_EMIT languageChanged();
}
/**
* When the user changes the language, the codegenoptions page
* language-dependent stuff has to be updated.
* The way to do this is to call its "apply" method.
*/
void CodeGenOptionsPage::changeLanguage()
{
QString plStr = getLanguage();
Uml::ProgrammingLanguage::Enum pl = Uml::ProgrammingLanguage::fromString(plStr);
UMLApp::app()->setActiveLanguage(pl);
/* @todo is this needed? if yes adapt to new scheme
m_CodeGenOptionsPage->setCodeGenerator(m_doc->getCurrentCodeGenerator());
*/
apply();
}
/**
* Slot for clicked events of the browse buttons.
* The selected directory is written to its corresponding text field.
*/
void CodeGenOptionsPage::browseClicked()
{
QString button = sender()->objectName();
QString dir = QFileDialog::getExistingDirectory();
if (dir.isEmpty()) {
return;
}
if (button == QStringLiteral("ui_browseOutput")) {
ui_outputDir->setText(dir);
}
else if (button == QStringLiteral("ui_browseHeadings")) {
ui_headingsDir->setText(dir);
}
}
/**
* Returns the user selected language used for code generation.
* @return the programming language name
*/
QString CodeGenOptionsPage::getLanguage()
{
return ui_SelectLanguageBox->currentText();
}
| 11,366
|
C++
|
.cpp
| 300
| 32.623333
| 183
| 0.707445
|
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,284
|
codegenerationwizard.cpp
|
KDE_umbrello/umbrello/codegenwizard/codegenerationwizard.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Paul Hensgen <phensgen@users.sourceforge.net>
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codegenerationwizard.h"
// local includes
#include "codegenselectpage.h"
#include "codegenoptionspage.h"
#include "codegenstatuspage.h"
#include "classifier.h"
#include "icon_utils.h"
#include "uml.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QWizardPage>
/**
* Constructor. Sets up the wizard and loads the wizard pages.
* Each wizard page has its own class.
* @param classList the list of classes, which have to be generated
*/
CodeGenerationWizard::CodeGenerationWizard(UMLClassifierList *classList)
: QWizard((QWidget*)UMLApp::app())
{
setWizardStyle(QWizard::ModernStyle);
setPixmap(QWizard::LogoPixmap, Icon_Utils::DesktopIcon(Icon_Utils::it_Code_Gen_Wizard));
setWindowTitle(i18n("Code Generation Wizard"));
setOption(QWizard::NoBackButtonOnStartPage, true);
setPage(OptionsPage, createOptionsPage());
setPage(SelectionPage, createSelectionPage(classList));
setPage(StatusPage, createStatusPage());
connect(m_OptionsPage, SIGNAL(languageChanged()), this, SLOT(slotLanguageChanged()));
}
/**
* Destructor.
*/
CodeGenerationWizard::~CodeGenerationWizard()
{
}
/**
* Creates the class selection page.
* @param classList the list of classes, which have to be generated
* @return the wizard page
*/
QWizardPage* CodeGenerationWizard::createSelectionPage(UMLClassifierList *classList)
{
m_SelectionPage = new CodeGenSelectPage(this);
m_SelectionPage->setClassifierList(classList);
return m_SelectionPage;
}
/**
* Creates the code generation options page, which allows to tune
* the code generation by setting some parameters.
* @return the wizard page
*/
QWizardPage* CodeGenerationWizard::createOptionsPage()
{
m_OptionsPage = new CodeGenOptionsPage(this);
return m_OptionsPage;
}
/**
* Creates the code generation status page, which shows the progress
* of the generation.
* @return the wizard page
*/
QWizardPage* CodeGenerationWizard::createStatusPage()
{
m_StatusPage = new CodeGenStatusPage(this);
return m_StatusPage;
}
/**
* Returns the list widget, which holds the classes for generation.
* With this function the list of classes to generate can be transferred
* from the select page to the status page.
* @return the list widget
*/
QListWidget* CodeGenerationWizard::getSelectionListWidget()
{
return m_SelectionPage->getSelectionListWidget();
}
/**
* Slot to handle generator language change.
*/
void CodeGenerationWizard::slotLanguageChanged()
{
m_SelectionPage->setClassifierList(nullptr);
}
| 2,834
|
C++
|
.cpp
| 90
| 29.144444
| 92
| 0.770048
|
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,285
|
idchangelog.cpp
|
KDE_umbrello/umbrello/clipboard/idchangelog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "idchangelog.h"
/**
* Constructor.
*/
IDChangeLog::IDChangeLog()
{
}
/**
* Copy constructor.
*/
IDChangeLog::IDChangeLog(const IDChangeLog& Other)
{
m_LogArray = Other.m_LogArray;
}
/**
* Deconstructor.
*/
IDChangeLog::~IDChangeLog()
{
for (uint i = 0; i < m_LogArray.size(); i++) {
delete m_LogArray.point(i);
}
}
/**
* Overloaded '=' operator.
*/
IDChangeLog& IDChangeLog::operator=(const IDChangeLog& Other)
{
m_LogArray = Other.m_LogArray;
return *this;
}
/**
* Overloaded '==' operator.
*/
bool IDChangeLog::operator==(const IDChangeLog& Other) const
{
Q_UNUSED(Other);
/*It needs to be Implemented*/
return false;
}
/**
* Returns the new assigned ID of the object that had OldID as its
* previous id.
*/
Uml::ID::Type IDChangeLog::findNewID(Uml::ID::Type OldID)
{
for (uint i = 0; i < m_LogArray.size(); i++) {
if ((m_LogArray.point(i))->y() == OldID) {
return (m_LogArray.point(i))->x();
}
}
return Uml::ID::None;
}
/**
* Appends another IDChangeLog to this instance of IDChangeLog and
* returns a reference to itself.
*/
IDChangeLog& IDChangeLog::operator+=(const IDChangeLog& Other)
{
//m_LogArray.putpoints(m_LogArray.size(), Other.m_LogArray.size(), Other)
uint count = Other.m_LogArray.size();
for (uint i = 0; i < count; i++) {
addIDChange((Other.m_LogArray.point(i))->y(), (Other.m_LogArray.point(i))->x());
}
return *this;
}
void IDChangeLog::addIDChange(Uml::ID::Type OldID, Uml::ID::Type NewID)
{
uint pos = 0;
if (!findIDChange(OldID, NewID, pos)) {
pos = m_LogArray.size();
m_LogArray.setPoint(pos, NewID, OldID);
} else {
m_LogArray.setPoint(pos, NewID, OldID);
}
}
Uml::ID::Type IDChangeLog::findOldID(Uml::ID::Type NewID)
{
uint count = m_LogArray.size();
for (uint i = 0; i < count; i++) {
if ((m_LogArray.point(i))->x() == NewID) {
return (m_LogArray.point(i))->y();
}
}
return Uml::ID::None;
}
bool IDChangeLog::findIDChange(Uml::ID::Type OldID, Uml::ID::Type NewID, uint& pos)
{
uint count = m_LogArray.size();
for (uint i = 0; i < count; i++) {
if (((m_LogArray.point(i))->y() == OldID) && ((m_LogArray.point(i))->x() == NewID)) {
pos = i;
return true;
}
}
return false;
}
void IDChangeLog::removeChangeByNewID(Uml::ID::Type OldID)
{
uint count = m_LogArray.size();
for (uint i = 0; i < count; i++) {
if ((m_LogArray.point(i))->y() == OldID) {
m_LogArray.setPoint(i, Uml::ID::None, OldID);
}
}
}
| 2,805
|
C++
|
.cpp
| 110
| 21.509091
| 95
| 0.609783
|
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,286
|
umldragdata.cpp
|
KDE_umbrello/umbrello/clipboard/umldragdata.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umldragdata.h"
// local includes
#include "associationwidget.h"
#include "classifier.h"
#include "cmds.h"
#define DBG_SRC QStringLiteral("UMLDragData")
#include "debug_utils.h"
#include "floatingtextwidget.h"
#include "folder.h"
#include "idchangelog.h"
#include "model_utils.h"
#include "object_factory.h"
#include "objectwidget.h"
#include "notewidget.h"
#include "preconditionwidget.h"
#include "messagewidget.h"
#include "uniqueid.h"
#include "uml.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umllistviewitem.h"
#include "umlobject.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
// qt includes
#include <QDomDocument>
#include <QPixmap>
#include <QTextStream>
#include <QXmlStreamWriter>
DEBUG_REGISTER(UMLDragData)
/**
* Constructor.
*/
UMLDragData::UMLDragData(UMLObjectList& objects, QWidget* dragSource /* = nullptr */)
{
Q_UNUSED(dragSource);
setUMLDataClip1(objects);
}
/**
* For use when the user selects UML Object and Diagrams
* from the ListView to be copied, Mime type =
* "application/x-uml-clip2
*/
UMLDragData::UMLDragData(UMLObjectList& objects, UMLViewList& diagrams, QWidget* dragSource /* = nullptr */)
{
Q_UNUSED(dragSource);
setUMLDataClip2(objects, diagrams);
}
/**
* Constructor.
*/
UMLDragData::UMLDragData(UMLListViewItemList& umlListViewItems,
QWidget* dragSource /* = nullptr */)
{
Q_UNUSED(dragSource);
setUMLDataClip3(umlListViewItems);
}
/**
* For use when the user selects UMLObjects from a
* Diagram. The Selected widgets and the relationships
* between only selected widgets will be copied and also
* its respective ListView Items, Mime type =
* "application/x-uml-clip4
*/
UMLDragData::UMLDragData(UMLObjectList& objects,
UMLWidgetList& widgets, AssociationWidgetList& associationDatas,
QPixmap& pngImage, UMLScene *scene, QWidget *dragSource /* = nullptr */)
{
Q_UNUSED(dragSource);
setUMLDataClip4(objects, widgets, associationDatas, pngImage, scene);
}
/**
* For use when the user selects only Operations and/or
* Attributes from the ListView, Mime type =
* "application/x-uml-clip5
*/
UMLDragData::UMLDragData(UMLObjectList& objects, int,
QWidget* dragSource /* = nullptr */)
{
Q_UNUSED(dragSource);
setUMLDataClip5(objects);
}
/**
* Constructor.
*/
UMLDragData::UMLDragData(QWidget* dragSource /* = nullptr */)
{
Q_UNUSED(dragSource);
}
/**
* Deconstructor.
*/
UMLDragData::~UMLDragData()
{
}
/**
* For use when the user selects only UMLObjects from the
* ListView but no diagrams to be copied
*/
void UMLDragData::setUMLDataClip1(UMLObjectList& objects)
{
QString xmiClip;
QXmlStreamWriter stream(&xmiClip);
stream.writeStartElement(QStringLiteral("xmiclip"));
stream.writeStartElement(QStringLiteral("umlobjects"));
UMLObjectListIt object_it(objects);
UMLObject *obj = nullptr;
while (object_it.hasNext()) {
obj = object_it.next();
obj->saveToXMI(stream);
}
stream.writeEndElement(); // umlobjects
stream.writeEndElement(); // xmiclip
setData(QStringLiteral("application/x-uml-clip1"), xmiClip.toUtf8());
}
/**
* For use when the user selects UML Object and Diagrams
* from the ListView to be copied
*/
void UMLDragData::setUMLDataClip2(UMLObjectList& objects, UMLViewList& diagrams)
{
QString xmiClip;
QXmlStreamWriter stream(&xmiClip);
stream.writeStartElement(QStringLiteral("xmiclip"));
stream.writeStartElement(QStringLiteral("umlobjects"));
UMLObjectListIt object_it(objects);
UMLObject *obj = nullptr;
while (object_it.hasNext()) {
obj = object_it.next();
obj->saveToXMI(stream);
}
stream.writeEndElement(); // umlobjects
stream.writeStartElement(QStringLiteral("umlviews"));
for(UMLView* view : diagrams) {
view->umlScene()->saveToXMI(stream);
}
stream.writeEndElement(); // umlviews
stream.writeEndElement(); // xmiclip
setData(QStringLiteral("application/x-uml-clip2"), xmiClip.toUtf8());
}
/**
* For use when the user selects only empty folders from the ListView
* to be copied.
*/
void UMLDragData::setUMLDataClip3(UMLListViewItemList& umlListViewItems)
{
QString xmiClip;
QXmlStreamWriter stream(&xmiClip);
stream.writeStartElement(QStringLiteral("xmiclip"));
stream.writeStartElement(QStringLiteral("umllistviewitems"));
for(UMLListViewItem* item : umlListViewItems) {
item->saveToXMI(stream);
}
stream.writeEndElement(); // umllistviewitems
stream.writeEndElement(); // xmiclip
setData(QStringLiteral("application/x-uml-clip3"), xmiClip.toUtf8());
}
/**
* For use when the user selects UML Objects from a
* Diagram. The Selected widgets and the relationships
* between only selected widgets will be copied and also
* its respective ListView Items
*/
void UMLDragData::setUMLDataClip4(UMLObjectList& objects,
UMLWidgetList& widgets,
AssociationWidgetList& associations,
QPixmap& pngImage, UMLScene *scene)
{
QString xmiClip;
QXmlStreamWriter stream(&xmiClip);
stream.writeStartElement(QStringLiteral("xmiclip"));
stream.writeAttribute(QStringLiteral("diagramtype"), QString::number(scene->type()));
stream.writeAttribute(QStringLiteral("diagramid"), Uml::ID::toString(scene->ID()));
stream.writeStartElement(QStringLiteral("umlobjects"));
for(UMLObject* obj : objects) {
obj->saveToXMI(stream);
}
stream.writeEndElement(); // umlobjects
stream.writeStartElement(QStringLiteral("widgets"));
for(UMLWidget* widget : widgets) {
widget->saveToXMI(stream);
}
stream.writeEndElement(); // widgets
stream.writeStartElement(QStringLiteral("associations"));
for(AssociationWidget* association : associations) {
association->saveToXMI(stream);
}
stream.writeEndElement(); // associations
stream.writeEndElement(); // xmiclip
setData(QStringLiteral("application/x-uml-clip4"), xmiClip.toUtf8());
QImage img = pngImage.toImage();
int l_size = img.sizeInBytes();
QByteArray clipdata;
clipdata.resize(l_size);
QDataStream clipstream(&clipdata, QIODevice::WriteOnly);
clipstream << img;
setImageData(clipdata);
}
/**
* For use when the user selects only Attributes and/or
* Operation from the ListView
*/
void UMLDragData::setUMLDataClip5(UMLObjectList& objects)
{
QString xmiClip;
QXmlStreamWriter stream(&xmiClip);
stream.writeStartElement(QStringLiteral("xmiclip"));
stream.writeStartElement(QStringLiteral("umlobjects"));
for(UMLObject* obj : objects) {
obj->saveToXMI(stream);
}
stream.writeEndElement(); // umlobjects
stream.writeEndElement(); // xmiclip
setData(QStringLiteral("application/x-uml-clip5"), xmiClip.toUtf8());
}
/**
* For use when the user selects only UML Objects
* from the ListView but no diagrams to be
* copied, decodes Mime type =
* "application/x-uml-clip1
*/
bool UMLDragData::decodeClip1(const QMimeData* mimeData, UMLObjectList& objects)
{
if (!mimeData->hasFormat(QStringLiteral("application/x-uml-clip1"))) {
return false;
}
QByteArray payload = mimeData->data(QStringLiteral("application/x-uml-clip1"));
if (!payload.size()) {
return false;
}
QString xmiClip = QString::fromUtf8(payload);
QString error;
int line;
QDomDocument domDoc;
if(!domDoc.setContent(xmiClip, false, &error, &line)) {
logWarn2("UMLDragData::decodeClip1: Cannot set content. Error %1 line %2", error, line);
return false;
}
QDomNode xmiClipNode = domDoc.firstChild();
QDomElement root = xmiClipNode.toElement();
if (root.isNull()) {
return false;
}
// make sure it is an XMI clip
if (root.tagName() != QStringLiteral("xmiclip")) {
return false;
}
QDomNode objectsNode = xmiClipNode.firstChild();
if (!UMLDragData::decodeObjects(objectsNode, objects, false)) {
return false;
}
return true;
}
/**
* For use when the user selects UML Object and Diagrams
* from the ListView to be copied, decodes Mime type =
* "application/x-uml-clip2
*/
bool UMLDragData::decodeClip2(const QMimeData* mimeData, UMLObjectList& objects, UMLViewList& diagrams)
{
if (!mimeData->hasFormat(QStringLiteral("application/x-uml-clip2"))) {
return false;
}
QByteArray payload = mimeData->data(QStringLiteral("application/x-uml-clip2"));
if (!payload.size()) {
return false;
}
QString xmiClip = QString::fromUtf8(payload);
QString error;
int line;
QDomDocument domDoc;
if(!domDoc.setContent(xmiClip, false, &error, &line)) {
logWarn2("UMLDragData::decodeClip2: Cannot set content. Error %1 line %2", error, line);
return false;
}
QDomNode xmiClipNode = domDoc.firstChild();
QDomElement root = xmiClipNode.toElement();
if (root.isNull()) {
return false;
}
// make sure it is an XMI clip
if (root.tagName() != QStringLiteral("xmiclip")) {
return false;
}
// Load UMLObjects
QDomNode objectsNode = xmiClipNode.firstChild();
if (NoteWidget::s_pCurrentNote == nullptr) {
if (!UMLDragData::decodeObjects(objectsNode, objects, true)) {
return false;
}
}
// Load UMLViews (diagrams)
QDomNode umlviewsNode = objectsNode.nextSibling();
if (!UMLDragData::decodeViews(umlviewsNode, diagrams)) {
return false;
}
return true;
}
/**
* Return just the LvTypeAndID of a Clip3.
*
* @param mimeData The encoded source.
* @param typeAndIdList The LvTypeAndID_List decoded from the source.
* @return True if decoding was successful.
*/
bool UMLDragData::getClip3TypeAndID(const QMimeData* mimeData,
LvTypeAndID_List& typeAndIdList)
{
if (!mimeData->hasFormat(QStringLiteral("application/x-uml-clip3"))) {
return false;
}
QByteArray payload = mimeData->data(QStringLiteral("application/x-uml-clip3"));
if (!payload.size()) {
return false;
}
QTextStream clipdata(payload, QIODevice::ReadOnly);
QString xmiClip = QString::fromUtf8(payload);
QString error;
int line;
QDomDocument domDoc;
if(!domDoc.setContent(xmiClip, false, &error, &line)) {
logWarn2("UMLDragData::getClip3TypeAndID: Cannot set content. Error %1 line %2", error, line);
return false;
}
QDomNode xmiClipNode = domDoc.firstChild();
QDomElement root = xmiClipNode.toElement();
if (root.isNull()) {
return false;
}
// make sure it is an XMI clip
if (root.tagName() != QStringLiteral("xmiclip")) {
return false;
}
QDomNode listItemNode = xmiClipNode.firstChild();
QDomNode listItems = listItemNode.firstChild();
QDomElement listItemElement = listItems.toElement();
if (listItemElement.isNull()) {
logWarn0("UMLDragData::getClip3TypeAndID: No listitems in XMI clip.");
return false;
}
while (!listItemElement.isNull()) {
QString typeStr = listItemElement.attribute(QStringLiteral("type"), QStringLiteral("-1"));
if (typeStr == QStringLiteral("-1")) {
logDebug0("UMLDragData::getClip3TypeAndID: bad type.");
return false;
}
QString idStr = listItemElement.attribute(QStringLiteral("id"), QStringLiteral("-1"));
if (idStr == QStringLiteral("-1")) {
logDebug0("UMLDragData::getClip3TypeAndID: bad id");
return false;
}
LvTypeAndID * pData = new LvTypeAndID;
pData->type = (UMLListViewItem::ListViewType)(typeStr.toInt());
pData->id = Uml::ID::fromString(idStr);
typeAndIdList.append(pData);
listItems = listItems.nextSibling();
listItemElement = listItems.toElement();
}
return true;
}
/**
* For use when the user selects UMLObjects from the ListView to be copied,
* decodes Mime type = "application/x-uml-clip3
*/
bool UMLDragData::decodeClip3(const QMimeData* mimeData, UMLListViewItemList& umlListViewItems,
const UMLListView* parentListView)
{
if (!mimeData->hasFormat(QStringLiteral("application/x-uml-clip3"))) {
return false;
}
QByteArray payload = mimeData->data(QStringLiteral("application/x-uml-clip3"));
if (!payload.size()) {
return false;
}
QTextStream clipdata(payload, QIODevice::ReadOnly);
QString xmiClip = QString::fromUtf8(payload);
QString error;
int line;
QDomDocument domDoc;
if(!domDoc.setContent(xmiClip, false, &error, &line)) {
logWarn2("UMLDragData::decodeClip3: Cannot set content. Error %1 line %2", error, line);
return false;
}
QDomNode xmiClipNode = domDoc.firstChild();
QDomElement root = xmiClipNode.toElement();
if (root.isNull()) {
return false;
}
// make sure it is an XMI clip
if (root.tagName() != QStringLiteral("xmiclip")) {
return false;
}
//listviewitems
QDomNode listItemNode = xmiClipNode.firstChild();
QDomNode listItems = listItemNode.firstChild();
QDomElement listItemElement = listItems.toElement();
if (listItemElement.isNull()) {
logWarn0("UMLDragData::decodeClip3: no listitems in XMI clip");
return false;
}
while (!listItemElement.isNull()) {
// Get the ListViewType beforehand so that we can construct an
// UMLListViewItem instance.
QString type = listItemElement.attribute(QStringLiteral("type"), QStringLiteral("-1"));
if (type == QStringLiteral("-1")) {
logDebug0("UMLDragData::decodeClip3: Type not found.");
listItems = listItems.nextSibling();
listItemElement = listItems.toElement();
continue;
}
UMLListViewItem::ListViewType t = (UMLListViewItem::ListViewType)(type.toInt());
UMLListViewItem* parent = parentListView->determineParentItem(t);
UMLListViewItem* itemData = new UMLListViewItem(parent);
if (itemData->loadFromXMI(listItemElement))
umlListViewItems.append(itemData);
else
delete itemData;
listItems = listItems.nextSibling();
listItemElement = listItems.toElement();
}
return true;
}
/**
* For use when the user selects UML Objects from a
* Diagram. The Selected widgets and the relationships
* between only selected widgets will be copied
*
* decodes Mime type = "application/x-uml-clip4"
*/
bool UMLDragData::decodeClip4(const QMimeData* mimeData, UMLObjectList& objects,
UMLWidgetList& widgets,
AssociationWidgetList& associations, Uml::DiagramType::Enum &dType)
{
if (!mimeData->hasFormat(QStringLiteral("application/x-uml-clip4"))) {
return false;
}
QByteArray payload = mimeData->data(QStringLiteral("application/x-uml-clip4"));
if (!payload.size()) {
return false;
}
QString xmiClip = QString::fromUtf8(payload);
QString error;
int line;
QDomDocument domDoc;
if(!domDoc.setContent(xmiClip, false, &error, &line)) {
logWarn2("UMLDragData::decodeClip4: Cannot set content. Error %1 line %2", error, line);
return false;
}
QDomNode xmiClipNode = domDoc.firstChild();
QDomElement root = xmiClipNode.toElement();
if (root.isNull()) {
return false;
}
// make sure it is an XMI clip
if (root.tagName() != QStringLiteral("xmiclip")) {
return false;
}
dType = Uml::DiagramType::fromInt(root.attribute(QStringLiteral("diagramtype"), QStringLiteral("0")).toInt());
QDomNode objectsNode = xmiClipNode.firstChild();
// Load UMLObjects and do not fail if there are none in the clip
bool hasObjects = !objectsNode.firstChild().toElement().isNull();
if (hasObjects && !UMLDragData::decodeObjects(objectsNode, objects, true)) {
return false;
}
UMLDoc *doc = UMLApp::app()->document();
UMLView *view = UMLApp::app()->currentView();
UMLScene *scene = view->umlScene();
QString sourceDiagramID = root.attribute(QStringLiteral("diagramid"), QStringLiteral(""));
UMLView *sourceView = doc->findView(Uml::ID::fromString(sourceDiagramID));
bool fromSameDiagram = sourceView && sourceView->umlScene()->ID() == scene->ID();
bool fromAnotherInstance = !sourceView;
bool fromDifferentDiagramType = dType != scene->type();
// Load widgets
QDomNode widgetsNode = objectsNode.nextSibling();
QDomNode widgetNode = widgetsNode.firstChild();
QDomElement widgetElement = widgetNode.toElement();
if (widgetElement.isNull()) {
logWarn0("UMLDragData::decodeClip4: No widgets in XMI clip.");
return false;
}
while (!widgetElement.isNull()) {
UMLWidget* widget = scene->loadWidgetFromXMI(widgetElement);
if (widget) {
if (fromSameDiagram && widget->isObjectWidget()) {
delete widget;
widgetNode = widgetNode.nextSibling();
widgetElement = widgetNode.toElement();
continue;
}
// check if widget is pastable
if (fromAnotherInstance || fromDifferentDiagramType) {
UMLObject *object = widget->umlObject();
if (object) {
if (!Model_Utils::typeIsAllowedInDiagram(object, scene)) {
delete widget;
widgetNode = widgetNode.nextSibling();
widgetElement = widgetNode.toElement();
continue;
}
}
else if (!Model_Utils::typeIsAllowedInDiagram(widget, scene)) {
delete widget;
widgetNode = widgetNode.nextSibling();
widgetElement = widgetNode.toElement();
continue;
}
} else if (Model_Utils::isCloneable(widget->baseType())) {
if (widget->umlObject()) {
UMLObject *clone = widget->umlObject()->clone();
widget->setUMLObject(clone);
// we do not want to recreate an additional widget,
// which would be the case if calling scene->addUMLObject()
UMLApp::app()->document()->addUMLObject(clone);
UMLApp::app()->listView()->slotObjectCreated(clone);
if (Model_Utils::hasAssociations(clone->baseType()))
{
scene->createAutoAssociations(widget);
scene->createAutoAttributeAssociations2(widget);
}
}
}
// Generate a new unique 'local ID' so a second widget for the same
// UMLObject can be distinguished from the first widget
widget->setLocalID(doc->assignNewID(widget->localID()));
if (widget->isMessageWidget()) {
MessageWidget *w = widget->asMessageWidget();
if (w && w->floatingTextWidget()) {
w->floatingTextWidget()->setLocalID(doc->assignNewID(w->floatingTextWidget()->localID()));
w->floatingTextWidget()->setID(doc->assignNewID(w->floatingTextWidget()->id()));
}
}
// Add the widget to the UMLWidgetList for reference in
// UMLClipboard
widgets.append(widget);
} else {
logWarn1("UMLDragData::decodeClip4: Unable to paste widget %1", widgetElement.tagName());
}
widgetNode = widgetNode.nextSibling();
widgetElement = widgetNode.toElement();
}
if (widgets.size() == 0)
return false;
IDChangeLog* log = doc->changeLog();
// Make sure all object widgets are loaded before adding messages or
// preconditions
if (!fromSameDiagram) {
for(UMLWidget *widget : widgets) {
if (widget->isObjectWidget()) {
executeCreateWidgetCommand(widget);
}
}
}
// Now add all remaining widgets
for(UMLWidget *widget : widgets) {
if (!fromSameDiagram && widget->isMessageWidget()) {
MessageWidget* message = widget->asMessageWidget();
message->resolveObjectWidget(log);
}
if (widget->isPreconditionWidget()) {
PreconditionWidget* precondition = widget->asPreconditionWidget();
precondition->resolveObjectWidget(log);
}
if (!widget->isObjectWidget()) {
executeCreateWidgetCommand(widget);
}
}
// Load AssociationWidgets
QDomNode associationWidgetsNode = widgetsNode.nextSibling();
QDomNode associationWidgetNode = associationWidgetsNode.firstChild();
QDomElement associationWidgetElement = associationWidgetNode.toElement();
while (!associationWidgetElement.isNull()) {
AssociationWidget* associationWidget = AssociationWidget::create(view->umlScene());
if (associationWidget->loadFromXMI(associationWidgetElement, widgets, nullptr))
associations.append(associationWidget);
else {
delete associationWidget;
}
associationWidgetNode = associationWidgetNode.nextSibling();
associationWidgetElement = associationWidgetNode.toElement();
}
return true;
}
/**
* For use when the user selects only Attributes and/or
* Operations from the ListView * copied, decodes Mime
* type = "application/x-uml-clip5
*/
bool UMLDragData::decodeClip5(const QMimeData* mimeData, UMLObjectList& objects,
UMLClassifier* newParent)
{
if (!mimeData->hasFormat(QStringLiteral("application/x-uml-clip5"))) {
return false;
}
QByteArray payload = mimeData->data(QStringLiteral("application/x-uml-clip5"));
if (!payload.size()) {
return false;
}
QString xmiClip = QString::fromUtf8(payload);
QString error;
int line;
QDomDocument domDoc;
if(!domDoc.setContent(xmiClip, false, &error, &line)) {
logWarn2("UMLDragData::decodeClip5: Cannot set content. Error %1 line %2", error, line);
return false;
}
QDomNode xmiClipNode = domDoc.firstChild();
QDomElement root = xmiClipNode.toElement();
if (root.isNull()) {
return false;
}
// make sure it is an XMI clip
if (root.tagName() != QStringLiteral("xmiclip")) {
return false;
}
//UMLObjects
QDomNode objectsNode = xmiClipNode.firstChild();
QDomNode objectElement = objectsNode.firstChild();
QDomElement element = objectElement.toElement();
if (element.isNull()) {
return false;//return ok as it means there is no umlobjects
}
while (!element.isNull()) {
QString type = element.tagName();
UMLClassifierListItem *pObject = newParent->makeChildObject(type);
if(!pObject) {
logWarn1("UMLDragData::decodeClip5 given wrong type of umlobject to create: %1", type);
return false;
}
if(!pObject->loadFromXMI(element)) {
logWarn0("UMLDragData::decodeClip5 failed to load object from XMI.");
return false;
}
pObject->resolveRef();
objects.append(pObject);
objectElement = objectElement.nextSibling();
element = objectElement.toElement();
}
return true;
}
/**
* Execute the CmdCreateWidget undo command
*/
void UMLDragData::executeCreateWidgetCommand(UMLWidget* widget)
{
UMLApp::app()->executeCommand(new Uml::CmdCreateWidget(widget));
}
/**
* Decode UMLObjects from clip
*/
bool UMLDragData::decodeObjects(QDomNode& objectsNode, UMLObjectList& objects, bool skipIfObjectExists)
{
UMLDoc* doc = UMLApp::app()->document();
QDomNode objectElement = objectsNode.firstChild();
QDomElement element = objectElement.toElement();
if (element.isNull()) {
return false;//return ok as it means there is no umlobjects
}
UMLObject *pObject = nullptr;
while (!element.isNull()) {
pObject = nullptr;
QString type = element.tagName();
Uml::ID::Type elmId = Uml::ID::fromString(Model_Utils::getXmiId(element));
QString stereotype = element.attribute(QStringLiteral("stereotype"));
bool objectExists = (doc->findObjectById(elmId) != nullptr);
// This happens when pasting clip4 (widgets): pasting widgets must
// not duplicate the UMLObjects, unless they don't exists (other
// instance of umbrello)
if (skipIfObjectExists && objectExists) {
objectElement = objectElement.nextSibling();
element = objectElement.toElement();
continue;
}
// Remove ownedElements from containers: the clip already contains all children
// as a flat list (UMLClipboard::insertItemChildren)
if (type == QStringLiteral("UML:Package") ||
type == QStringLiteral("UML:Class") ||
type == QStringLiteral("UML:Interface") ||
type == QStringLiteral("UML:Component")) {
QDomNodeList list = element.childNodes();
for (int i = list.length() - 1; i >= 0; i--) {
QDomNode child = list.at(i);
QString tagName = child.toElement().tagName();
if (tagName == QStringLiteral("UML:Namespace.ownedElement") ||
tagName == QStringLiteral("UML:Namespace.contents")) {
element.removeChild(child);
}
}
}
pObject = Object_Factory::makeObjectFromXMI(type, stereotype);
if(!pObject) {
logWarn1("UMLDragData::decodeObjects given wrong type of umlobject to create: %1", type);
return false;
}
Uml::ID::Type oldParentId = Uml::ID::fromString(
element.attribute(QStringLiteral("namespace"), QStringLiteral("-1"))
);
// Determine the parent package of the pasted object
UMLPackage *newParent = nullptr;
if (oldParentId != Uml::ID::None) {
Uml::ID::Type newParentId = doc->changeLog()->findNewID(oldParentId);
if (newParentId == Uml::ID::None) {
// Fallback to parent ID before paste (folder was not pasted in
// this paste operation)
newParentId = oldParentId;
}
newParent = doc->findObjectById(newParentId)->asUMLPackage();
}
if (newParent == nullptr) {
// Package is not in this clip, determine the parent based
// on the selected tree view item
newParent = Model_Utils::treeViewGetPackageFromCurrent();
}
pObject->setUMLPackage(newParent);
// Note: element should not be used after calling loadFromXMI() because
// it can point to an arbitrary child node
if (!pObject->loadFromXMI(element)) {
logWarn1("UMLDragData::decodeObjects failed to load object of type %1 from XMI", type);
delete pObject;
return false;
}
// Assign a new ID if the object already existed before this paste,
// this happens when pasting on listview items in the same document.
if (objectExists) {
pObject->setID(
doc->assignNewID(pObject->id())
);
}
UMLApp::app()->executeCommand(new Uml::CmdCreateUMLObject(pObject));
doc->signalUMLObjectCreated(pObject);
objects.append(pObject);
objectElement = objectElement.nextSibling();
element = objectElement.toElement();
}
return true;
}
/**
* Decode views from clip
*/
bool UMLDragData::decodeViews(QDomNode& umlviewsNode, UMLViewList& diagrams)
{
QDomNode diagramNode = umlviewsNode.firstChild();
QDomElement diagramElement = diagramNode.toElement();
if (diagramElement.isNull()) {
logWarn0("UMLDragData::decodeViews: No diagrams in XMI clip.");
return false;
}
UMLListView *listView = UMLApp::app()->listView();
while (!diagramElement.isNull()) {
if (NoteWidget::s_pCurrentNote) {
QString idStr = diagramElement.attribute(QStringLiteral("xmi.id"), QStringLiteral("-1"));
Uml::ID::Type id = Uml::ID::fromString(idStr);
if (id == Uml::ID::None) {
logDebug0("UMLDragData::decodeViews: Cannot paste diagram hyperlink to note because decoding of xmi.id failed");
return false;
}
NoteWidget::s_pCurrentNote->setDiagramLink(id);
return true;
}
QString type = diagramElement.attribute(QStringLiteral("type"), QStringLiteral("0"));
Uml::DiagramType::Enum dt = Uml::DiagramType::fromInt(type.toInt());
UMLListViewItem *parent = listView->findFolderForDiagram(dt);
if (parent == nullptr)
return false;
UMLObject *po = parent->umlObject();
if (po == nullptr || po->baseType() != UMLObject::ot_Folder) {
logError0("UMLDragData::decodeViews: Bad parent for view.");
return false;
}
UMLFolder *f = po->asUMLFolder();
UMLView* view = new UMLView(f);
view->umlScene()->loadFromXMI(diagramElement);
diagrams.append(view);
diagramNode = diagramNode.nextSibling();
diagramElement = diagramNode.toElement();
}
return true;
}
/**
* Converts application/x-uml-clip[1-5] clip type to an integer
*/
int UMLDragData::getCodingType(const QMimeData* mimeData)
{
int result = 0;
if (mimeData->hasFormat(QStringLiteral("application/x-uml-clip1"))) {
result = 1;
}
if (mimeData->hasFormat(QStringLiteral("application/x-uml-clip2"))) {
result = 2;
}
if (mimeData->hasFormat(QStringLiteral("application/x-uml-clip3"))) {
result = 3;
}
if (mimeData->hasFormat(QStringLiteral("application/x-uml-clip4"))) {
result = 4;
}
if (mimeData->hasFormat(QStringLiteral("application/x-uml-clip5"))) {
result = 5;
}
if (mimeData->hasFormat(QStringLiteral("text/plain"))) {
result = 6;
}
return result;
}
| 30,710
|
C++
|
.cpp
| 809
| 30.882571
| 128
| 0.654498
|
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,287
|
umlclipboard.cpp
|
KDE_umbrello/umbrello/clipboard/umlclipboard.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlclipboard.h"
// local includes
#include "debug_utils.h"
#include "diagram_utils.h"
#include "umldragdata.h"
#include "idchangelog.h"
#include "associationwidget.h"
#include "attribute.h"
#include "classifier.h"
#include "enum.h"
#include "entity.h"
#include "floatingtextwidget.h"
#include "messagewidget.h"
#include "operation.h"
#include "template.h"
#include "enumliteral.h"
#include "entityattribute.h"
#include "model_utils.h"
#include "notewidget.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umllistviewitem.h"
#include "umlobjectlist.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidget.h"
#include "uml.h"
// kde includes
#include <KMessageBox>
#include <KLocalizedString>
// qt includes
#include <QMimeData>
#include <QPixmap>
DEBUG_REGISTER(UMLClipboard)
/**
* Constructor.
*/
UMLClipboard::UMLClipboard()
{
m_type = clip1;
}
/**
* Deconstructor.
*/
UMLClipboard::~UMLClipboard()
{
}
/**
* Copy operation.
* @param fromView flag if it is from view
* @return the mime data
*/
QMimeData* UMLClipboard::copy(bool fromView/*=false*/)
{
// Clear previous copied data
m_AssociationList.clear();
m_ObjectList.clear();
m_ViewList.clear();
UMLDragData *data = nullptr;
QPixmap *png = nullptr;
UMLListView * listView = UMLApp::app()->listView();
if (fromView) {
m_type = clip4;
UMLView *view = UMLApp::app()->currentView();
if (view == nullptr) {
logError0("UMLApp::app()->currentView() is NULL");
return nullptr;
}
UMLScene *scene = view->umlScene();
if (scene == nullptr) {
logError0("UMLClipboard::copy: currentView umlScene() is NULL");
return nullptr;
}
m_WidgetList = scene->selectedWidgetsExt();
//if there is no selected widget then there is no copy action
if (!m_WidgetList.count()) {
return nullptr;
}
m_AssociationList = scene->selectedAssocs();
scene->copyAsImage(png);
// Clip4 needs related widgets.
addRelatedWidgets();
// Clip4 needs UMLObjects because it's possible the UMLObject
// is no longer there when pasting this mime data. This happens for
// example when using cut-paste or pasting to another Umbrello
// instance.
fillObjectListForWidgets(m_WidgetList);
for(WidgetBase *widget : m_AssociationList) {
if (widget->umlObject() != nullptr) {
m_ObjectList.append(widget->umlObject());
}
}
} else {
// The copy action is being performed from the ListView
UMLListViewItemList itemsSelected = listView->selectedItems();
if (itemsSelected.count() <= 0) {
return nullptr;
}
// Set What type of copy operation are we performing and
// also fill m_ViewList with all the selected Diagrams
setCopyType(itemsSelected);
// If we are copying a diagram or part of a diagram, select the items
// on the ListView that correspond to a UseCase, Actor or Concept
// in the Diagram
if (m_type == clip2) {
for(UMLView* view : m_ViewList) {
UMLScene *scene = view->umlScene();
if (scene == nullptr) {
logError0("UMLClipboard::copy: currentView umlScene() is NULL");
continue;
}
fillObjectListForWidgets(scene->widgetList());
AssociationWidgetList associations = scene->associationList();
for(AssociationWidget* association : associations) {
if (association->umlObject() != nullptr) {
m_ObjectList.append(association->umlObject());
}
}
}
} else {
// Clip1, 4 and 5: fill the clip with only the specific objects
// selected in the list view
if (!fillSelectionLists(itemsSelected)) {
return nullptr;
}
if (itemsSelected.count() <= 0) {
return nullptr;
}
}
}
int i = 0;
switch(m_type) {
case clip1:
data = new UMLDragData(m_ObjectList);
break;
case clip2:
data = new UMLDragData(m_ObjectList, m_ViewList);
break;
case clip3:
data = new UMLDragData(m_ItemList);
break;
case clip4:
if (png) {
UMLView *view = UMLApp::app()->currentView();
data = new UMLDragData(m_ObjectList, m_WidgetList,
m_AssociationList, *png, view->umlScene());
} else {
return nullptr;
}
break;
case clip5:
data = new UMLDragData(m_ObjectList, i);
// The int i is used to differentiate
// which UMLDragData constructor gets called.
break;
}
return (QMimeData*)data;
}
/**
* Inserts the clipboard's contents.
*
* @param data Pointer to the MIME format clipboard data.
* @return True for successful operation.
*/
bool UMLClipboard::paste(const QMimeData* data)
{
UMLDoc *doc = UMLApp::app()->document();
int codingType = UMLDragData::getCodingType(data);
if (codingType == 6
&& UMLApp::app()->currentView()) {
return Diagram_Utils::importGraph(data, UMLApp::app()->currentView()->umlScene());
}
QString mimeType = QStringLiteral("application/x-uml-clip") + QString::number(codingType);
logDebug1("UMLClipboard::paste: Pasting mimeType %1", mimeType);
bool result = false;
doc->beginPaste();
switch (codingType) {
case 1:
result = pasteClip1(data);
break;
case 2:
result = pasteClip2(data);
break;
case 3:
result = pasteClip3(data);
break;
case 4:
result = pasteClip4(data);
break;
case 5:
result = pasteClip5(data);
break;
default:
break;
}
doc->endPaste();
return result;
}
/**
* Fills object list based on a selection of widgets
*
* @param UMLWidgetList& widgets
*/
void UMLClipboard::addRelatedWidgets()
{
UMLWidgetList relatedWidgets;
UMLWidget *pWA = nullptr, *pWB = nullptr;
for(UMLWidget* widget : m_WidgetList) {
if (widget->isMessageWidget()) {
MessageWidget * pMessage = widget->asMessageWidget();
pWA = (UMLWidget*)pMessage->objectWidget(Uml::RoleType::A);
pWB = (UMLWidget*)pMessage->objectWidget(Uml::RoleType::B);
if (!relatedWidgets.contains(pWA))
relatedWidgets.append(pWA);
if (!relatedWidgets.contains(pWB))
relatedWidgets.append(pWB);
}
}
for(AssociationWidget *pAssoc : m_AssociationList) {
pWA = pAssoc->widgetForRole(Uml::RoleType::A);
pWB = pAssoc->widgetForRole(Uml::RoleType::B);
if (!relatedWidgets.contains(pWA))
relatedWidgets.append(pWA);
if (!relatedWidgets.contains(pWB))
relatedWidgets.append(pWB);
}
for(UMLWidget *widget : relatedWidgets) {
if (!m_WidgetList.contains(widget))
m_WidgetList.append(widget);
}
}
/**
* Fills object list based on a selection of widgets
*
* @param widgets the UMLWidgetList to fill
*/
void UMLClipboard::fillObjectListForWidgets(const UMLWidgetList& widgets)
{
// The order of the packages in the clip matters. So we collect
// the packages and add them from the root package to the deeper levels
UMLObjectList packages;
for(UMLWidget* widget : widgets) {
UMLObject* widgetObject = widget->umlObject();
if (widgetObject != nullptr) {
packages.clear();
UMLPackage* package = widgetObject->umlPackage();
while (package != nullptr) {
packages.prepend(package);
package = package->umlPackage();
}
for(UMLObject *package : packages) {
if (!m_ObjectList.contains(package)) {
m_ObjectList.append(package);
}
}
if (!m_ObjectList.contains(widgetObject)) {
m_ObjectList.append(widgetObject);
}
}
}
}
/**
* Fills the member lists with all the objects and other
* stuff to be copied to the clipboard.
* @param selectedItems list of selected items
*/
bool UMLClipboard::fillSelectionLists(UMLListViewItemList& selectedItems)
{
UMLListViewItem::ListViewType type;
switch(m_type) {
case clip4:
break;
case clip3:
for(UMLListViewItem *item : selectedItems) {
type = item->type();
if (!Model_Utils::typeIsClassifierList(type)) {
m_ItemList.append(item);
insertItemChildren(item, selectedItems);
}
}
break;
case clip2:
case clip1:
for(UMLListViewItem *item : selectedItems) {
type = item->type();
if (!Model_Utils::typeIsClassifierList(type)) {
if (Model_Utils::typeIsCanvasWidget(type)) {
if (item->umlObject() == nullptr)
logError0("UMLClipboard::fillSelectionLists: selected lvitem has no umlObject");
else
m_ObjectList.append(item->umlObject());
}
insertItemChildren(item, selectedItems);
}
}
break;
case clip5:
for(UMLListViewItem *item : selectedItems) {
type = item->type();
if(Model_Utils::typeIsClassifierList(type)) {
m_ObjectList.append(item->umlObject());
} else {
return false;
}
}
break;
}
return true;
}
/**
* Checks the whole list to determine the copy action
* type to be performed, sets the type in the m_type
* member variable.
* @param selectedItems list of selected items
*/
void UMLClipboard::setCopyType(UMLListViewItemList& selectedItems)
{
bool withDiagrams = false; //If the selection includes diagrams
bool withObjects = false; //If the selection includes objects
bool onlyAttsOps = false; //If the selection only includes Attributes and/or Operations
for(UMLListViewItem *item : selectedItems) {
checkItemForCopyType(item, withDiagrams, withObjects, onlyAttsOps);
}
if (onlyAttsOps) {
m_type = clip5;
} else if (withDiagrams) {
m_type = clip2;
} else if(withObjects) {
m_type = clip1;
} else {
m_type = clip3;
}
}
/**
* Searches the child items of a UMLListViewItem to
* establish which Copy type is to be performed.
* @param item parent of the children
* @param withDiagrams includes diagrams
* @param withObjects includes objects
* @param onlyAttsOps includes only attributes and/or operations
*/
void UMLClipboard::checkItemForCopyType(UMLListViewItem* item, bool & withDiagrams, bool & withObjects,
bool & onlyAttsOps)
{
if(!item) {
return;
}
UMLDoc *doc = UMLApp::app()->document();
onlyAttsOps = true;
UMLView *view = nullptr;
UMLListViewItem *child = nullptr;
UMLListViewItem::ListViewType type = item->type();
if (Model_Utils::typeIsCanvasWidget(type)) {
withObjects = true;
onlyAttsOps = false;
} else if (Model_Utils::typeIsDiagram(type)) {
withDiagrams = true;
onlyAttsOps = false;
view = doc->findView(item->ID());
if (view)
m_ViewList.append(view);
else
logError1("UMLClipboard::checkItemForCopyType: doc->findView(%1) returns NULL",
Uml::ID::toString(item->ID()));
} else if (Model_Utils::typeIsFolder(type)) {
onlyAttsOps = false;
for (int i =0; i < item->childCount(); i++) {
child = (UMLListViewItem*)item->child(i);
checkItemForCopyType(child, withDiagrams, withObjects, onlyAttsOps);
}
}
}
/**
* Traverse children of a UMLListViewItem and add its UMLObjects to the list
*
* @param item parent of the children to insert
* @param selectedItems list of selected items
* @return success flag
*/
bool UMLClipboard::insertItemChildren(UMLListViewItem * item, UMLListViewItemList& selectedItems)
{
if (item->childCount()) {
for(int i = 0; i < item->childCount(); i++) {
UMLListViewItem * child = (UMLListViewItem*)item->child(i);
m_ItemList.append(child);
UMLListViewItem::ListViewType type = child->type();
if (!Model_Utils::typeIsClassifierList(type) &&
!Model_Utils::typeIsDiagram(type)) {
m_ObjectList.append(child->umlObject());
}
// If the child is selected, remove it from the list of selected items
// otherwise it will be inserted twice in m_ObjectList.
if (child->isSelected()) {
selectedItems.removeAll(child);
}
insertItemChildren(child, selectedItems);
}
}
return true;
}
/**
* If clipboard has mime type application/x-uml-clip1,
* Pastes the data from the clipboard into the current Doc.
* @param data mime type
*/
bool UMLClipboard::pasteClip1(const QMimeData* data)
{
UMLObjectList objects;
return UMLDragData::decodeClip1(data, objects);
}
/**
* If clipboard has mime type application/x-uml-clip2,
* Pastes the data from the clipboard into the current Doc.
* @param data mime type
* @return success flag
*/
bool UMLClipboard::pasteClip2(const QMimeData* data)
{
UMLDoc* doc = UMLApp::app()->document();
UMLObjectList objects;
UMLViewList views;
if (!UMLDragData::decodeClip2(data, objects, views)) {
logDebug0("UMLClipboard::pasteClip2: UMLDragData::decodeClip2 returned error");
return false;
}
if (NoteWidget::s_pCurrentNote) {
NoteWidget::s_pCurrentNote = nullptr;
} else {
for(UMLView *pView : views) {
if (!doc->addUMLView(pView)) {
return false;
}
}
}
return true;
}
/**
* If clipboard has mime type application/x-uml-clip3,
* Pastes the data from the clipboard into the current Doc.
*
* Note: clip3 is only used to determine if the selected items can be dragged
* onto the view. Pasting only listview items makes no sense. Clip3 is implemented
* as a fallback-clip when clip 1, 2, 4 or 5 are not applicable. But that should
* never happen.
*
* Todo: remove clip3 altogether.
*
* @param data mime type
* @return success flag
*/
bool UMLClipboard::pasteClip3(const QMimeData* data)
{
UMLDoc *doc = UMLApp::app()->document();
UMLListViewItemList itemdatalist;
IDChangeLog* idchanges = doc->changeLog();
if(!idchanges) {
return false;
}
UMLListView *listView = UMLApp::app()->listView();
return UMLDragData::decodeClip3(data, itemdatalist, listView);
}
/**
* If clipboard has mime type application/x-uml-clip4,
* Pastes the data from the clipboard into the current Doc.
* @param data mime type
* @return success flag
*/
bool UMLClipboard::pasteClip4(const QMimeData* data)
{
UMLDoc *doc = UMLApp::app()->document();
UMLObjectList objects;
UMLWidgetList widgets;
AssociationWidgetList assocs;
IDChangeLog *idchanges = nullptr;
Uml::DiagramType::Enum diagramType;
if(!UMLDragData::decodeClip4(data, objects, widgets, assocs, diagramType)) {
return false;
}
UMLScene *currentScene = UMLApp::app()->currentView()->umlScene();
idchanges = doc->changeLog();
if(!idchanges) {
return false;
}
//make sure the file we are pasting into has the objects
//we need if there are widgets to be pasted
for(UMLObject *obj : objects) {
if(!doc->assignNewIDs(obj)) {
return false;
}
}
//now add any widget we are want to paste
bool objectAlreadyExists = false;
currentScene->beginPartialWidgetPaste();
for(UMLWidget *widget : widgets) {
Uml::ID::Type oldId = widget->id();
Uml::ID::Type newId = idchanges->findNewID(oldId);
// how should findWidget find ::None id, which is returned for the first entry ?
if (currentScene->findWidget(newId)) {
logError2("UMLClipboard::pasteClip4 widget (oldID=%1, newID=%2) already exists in target view",
Uml::ID::toString(oldId), Uml::ID::toString(newId));
widgets.removeAll(widget);
delete widget;
objectAlreadyExists = true;
} else {
if (currentScene->isActivityDiagram() || currentScene->isStateDiagram()) {
widget->setID(doc->assignNewID(widget->id()));
}
}
}
//now paste the associations
for(AssociationWidget *assoc : assocs) {
if (!currentScene->addAssociation(assoc, true)) {
currentScene->endPartialWidgetPaste();
return false;
}
}
currentScene->clearSelected();
currentScene->selectWidgets(widgets);
for(AssociationWidget *assoc : assocs) {
currentScene->selectWidgetsOfAssoc(assoc);
}
//Activate all the pasted associations and widgets
currentScene->activate();
currentScene->endPartialWidgetPaste();
if (objectAlreadyExists) {
pasteItemAlreadyExists();
}
return true;
}
/**
* If clipboard has mime type application/x-uml-clip5,
* Pastes the data from the clipboard into the current Doc.
* @param data mime type
* @return success flag
*/
bool UMLClipboard::pasteClip5(const QMimeData* data)
{
UMLDoc *doc = UMLApp::app()->document();
UMLListView *listView = UMLApp::app()->listView();
UMLListViewItem* lvitem = dynamic_cast<UMLListViewItem *>(listView->currentItem());
if (!lvitem || !Model_Utils::typeIsClassifier(lvitem->type())) {
return false;
}
UMLClassifier *parent = lvitem->umlObject()->asUMLClassifier();
if (parent == nullptr) {
logError0("UMLClipboard::pasteClip5: parent is not a UMLClassifier");
return false;
}
UMLObjectList objects;
IDChangeLog *idchanges = nullptr;
bool result = UMLDragData::decodeClip5(data, objects, parent);
if(!result) {
return false;
}
doc->setModified(true);
idchanges = doc->changeLog();
// Assume success if at least one child object could be pasted
if (objects.count())
result = false;
for(UMLObject *obj : objects) {
obj->setID(doc->assignNewID(obj->id()));
switch(obj->baseType()) {
case UMLObject::ot_Attribute :
{
UMLObject *exist = parent->findChildObject(obj->name(), UMLObject::ot_Attribute);
if (exist) {
QString newName = parent->uniqChildName(UMLObject::ot_Attribute, obj->name());
obj->setName(newName);
}
UMLAttribute *att = obj->asUMLAttribute();
if (parent->addAttribute(att, idchanges)) {
result = true;
} else {
logError2("UMLClipboard::pasteClip5 %1->addAttribute(%2) failed",
parent->name(), att->name());
}
break;
}
case UMLObject::ot_Operation :
{
UMLOperation *op = obj->asUMLOperation();
UMLOperation *exist = parent->checkOperationSignature(op->name(), op->getParmList());
if (exist) {
QString newName = parent->uniqChildName(UMLObject::ot_Operation, obj->name());
op->setName(newName);
}
if (parent->addOperation(op, idchanges)) {
result = true;
} else {
logError2("UMLClipboard::pasteClip5 %1->addOperation(%2) failed",
parent->name(), op->name());
}
break;
}
case UMLObject::ot_Template:
{
UMLTemplate* tp = obj->asUMLTemplate();
UMLTemplate* exist = parent->findTemplate(tp->name());
if (exist) {
QString newName = parent->uniqChildName(UMLObject::ot_Template, obj->name());
tp->setName(newName);
}
if (parent->addTemplate(tp, idchanges)) {
result = true;
} else {
logError2("UMLClipboard::pasteClip5 %1->addTemplate(%2) failed",
parent->name(), tp->name());
}
break;
}
case UMLObject::ot_EnumLiteral:
{
UMLEnum* enumParent = parent->asUMLEnum();
// if parent is not a UMLEnum, bail out immediately;
if (!enumParent) {
result = false;
logError0("UMLClipboard::pasteClip5: Parent is not a UMLEnum");
break;
}
UMLObject* exist = enumParent->findChildObject(obj->name(), UMLObject::ot_EnumLiteral);
if (exist) {
QString newName = enumParent->uniqChildName(UMLObject::ot_EnumLiteral, obj->name());
obj->setName(newName);
}
UMLEnumLiteral* enl = obj->asUMLEnumLiteral();
if (enumParent->addEnumLiteral(enl, idchanges)) {
result = true;
} else {
logError2("UMLClipboard::pasteClip5 %1->addEnumLiteral(%2) failed",
parent->name(), enl->name());
}
break;
}
case UMLObject::ot_EntityAttribute :
{
UMLEntity* entityParent = parent->asUMLEntity();
// if parent is not a UMLEntity, bail out immediately;
if (!entityParent) {
result = false;
logError0("UMLClipboard::pasteClip5: Parent is not a UMLEntity");
break;
}
UMLObject *exist = entityParent->findChildObject(obj->name(), UMLObject::ot_EntityAttribute);
if (exist) {
QString newName = entityParent->uniqChildName(UMLObject::ot_EntityAttribute, obj->name());
obj->setName(newName);
}
UMLEntityAttribute *att = obj->asUMLEntityAttribute();
if (entityParent->addEntityAttribute(att, idchanges)) {
result = true;
} else {
logError2("UMLClipboard::pasteClip5 %1->addEntityAttribute(%2) failed",
parent->name(), att->name());
}
break;
}
default :
logWarn0("pasting unknown children type in clip type 5");
return false;
}
}
return result;
}
/**
* Gives a `sorry' message box if you're pasting an item which
* already exists and can't be duplicated.
*/
void UMLClipboard::pasteItemAlreadyExists()
{
UMLView *currentView = UMLApp::app()->currentView();
KMessageBox::information(currentView,
i18n("At least one of the items in the clipboard "
"could not be pasted because an item of the "
"same name already exists. Any other items "
"have been pasted."),
i18n("Paste Error"));
}
| 24,108
|
C++
|
.cpp
| 682
| 26.721408
| 110
| 0.594407
|
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,288
|
notedialog.cpp
|
KDE_umbrello/umbrello/dialogs/notedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "notedialog.h"
#include "notewidget.h"
// KDE includes
#include <KLocalizedString>
/**
* Constructs an NoteDialog.
*/
NoteDialog::NoteDialog(QWidget * parent, NoteWidget * widget)
: MultiPageDialogBase(parent),
m_widget(widget)
{
setCaption(i18n("Note Properties"));
setupPages();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
void NoteDialog::setupPages()
{
setupGeneralPage(m_widget);
setupStylePage(m_widget);
setupFontPage(m_widget);
}
void NoteDialog::slotOk()
{
slotApply();
}
void NoteDialog::slotApply()
{
if (!apply())
reject();
else
accept();
}
bool NoteDialog::apply()
{
MultiPageDialogBase::apply();
if (m_widget) {
applyFontPage(m_widget);
QString key = QStringLiteral("Diagram:");
QString str = m_widget->documentation();
if (!str.startsWith(key)) {
m_widget->setDiagramLink(QString());
return false;
}
QString diagramName = str.remove(key).trimmed();
m_widget->setDiagramLink(diagramName);
}
return true;
}
| 1,335
|
C++
|
.cpp
| 54
| 20.481481
| 92
| 0.667975
|
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,289
|
umlviewdialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlviewdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlviewdialog.h"
// local includes
#include "classoptionspage.h"
#include "diagrampropertiespage.h"
#include "debug_utils.h"
#include "icon_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "umlscene.h"
#include "umlview.h"
#include "umlwidgetstylepage.h"
// kde includes
#include <kfontchooser.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QFrame>
#include <QHBoxLayout>
DEBUG_REGISTER(UMLViewDialog)
/**
* Constructor.
*/
UMLViewDialog::UMLViewDialog(QWidget * pParent, UMLScene * pScene)
: MultiPageDialogBase(pParent),
m_pOptionsPage(nullptr)
{
setCaption(i18n("Properties"));
m_pScene = pScene;
setupPages();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Destructor.
*/
UMLViewDialog::~UMLViewDialog()
{
}
void UMLViewDialog::apply()
{
slotOk();
}
void UMLViewDialog::slotOk()
{
applyPage(m_pageDiagramItem);
applyPage(m_pageDisplayItem);
applyPage(m_pageFontItem);
applyPage(m_pageStyleItem);
accept();
}
void UMLViewDialog::slotApply()
{
applyPage(currentPage());
}
/**
* Sets up the dialog pages.
*/
void UMLViewDialog::setupPages()
{
setupDiagramPropertiesPage();
setupStylePage();
m_pageFontItem = setupFontPage(m_pScene->optionState().uiState.font);
setupDisplayPage();
}
/**
* Sets up the general Diagram Properties Page
*/
void UMLViewDialog::setupDiagramPropertiesPage()
{
m_diagramPropertiesPage = new DiagramPropertiesPage(nullptr, m_pScene);
m_pageDiagramItem = createPage(i18nc("general settings page", "General"), i18n("General Settings"),
Icon_Utils::it_Properties_General, m_diagramPropertiesPage);
}
/**
* Sets up the display page
*/
void UMLViewDialog::setupDisplayPage()
{
m_pageDisplayItem = nullptr;
// Display page currently only shows class-related display options that are
// applicable for class- and sequence diagram
if (m_pScene->type() != Uml::DiagramType::Class &&
m_pScene->type() != Uml::DiagramType::Sequence) {
return;
}
m_pOptionsPage = new ClassOptionsPage(nullptr, m_pScene);
m_pageDisplayItem = createPage(i18nc("classes display options page", "Display"), i18n("Classes Display Options"),
Icon_Utils::it_Properties_Display, m_pOptionsPage);
}
/**
* Sets up the style page.
*/
void UMLViewDialog::setupStylePage()
{
m_pStylePage = new UMLWidgetStylePage(nullptr, m_pScene);
m_pageStyleItem = createPage(i18nc("diagram style page", "Style"), i18n("Diagram Style"),
Icon_Utils::it_Properties_Color, m_pStylePage);
}
/**
* Applies the properties of the given page.
*/
void UMLViewDialog::applyPage(KPageWidgetItem *item)
{
if (item == nullptr) {
// Page not loaded in this dialog
return;
}
else if (item == m_pageDiagramItem)
{
m_diagramPropertiesPage->apply();
}
else if (item == m_pageStyleItem)
{
logDebug0("UMLViewDialog::applyPage setting colors");
m_pStylePage->apply();
}
else if (item == m_pageFontItem)
{
applyFontPage(m_pScene);
}
else if (item == m_pageDisplayItem)
{
m_pOptionsPage->apply();
}
}
| 3,512
|
C++
|
.cpp
| 130
| 23.069231
| 117
| 0.691028
|
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,290
|
exportallviewsdialog.cpp
|
KDE_umbrello/umbrello/dialogs/exportallviewsdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "exportallviewsdialog.h"
// kde include files
#include <KLocalizedString>
// application specific includes
#include "umlviewimageexportermodel.h"
/**
* Constructor for UMLViewImageExporterModel.
*
* @param parent The parent of the dialog.
* @param name The internal name.
*
* @see QDialog::QDialog
*/
ExportAllViewsDialog::ExportAllViewsDialog(QWidget* parent, const char* name)
: SinglePageDialogBase(parent)
{
setObjectName(QString::fromLatin1(name));
QFrame * frame = new QFrame(this);
setMainWidget(frame);
setupUi(mainWidget());
// create and initialize m_imageType
m_imageType = new ImageTypeWidget(UMLViewImageExporterModel::supportedMimeTypes(), QStringLiteral("image/png"), this);
m_imageResolution = new ResolutionWidget(this);
// Cannot give an object name to the layout when using QtDesigner,
// therefore go and use an editor and add it by hand.
ui_imageTypeLayout->addWidget(m_imageType);
ui_imageResolutionLayout->addWidget(m_imageResolution);
// reload the strings so the m_imageType tooltip is added
languageChange();
connect(m_imageType, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotImageTypeChanged(QString)));
m_kURL->setMode(KFile::Directory | KFile::ExistingOnly);
}
/**
* Destructor for UMLViewImageExporterModel.
*/
ExportAllViewsDialog::~ExportAllViewsDialog()
{
}
/**
* Sets the strings of the subwidgets using the current
* language.
*/
void ExportAllViewsDialog::languageChange()
{
//ExportAllViewsDialogBase::languageChange();
m_imageType->setToolTip(i18n("The format that the images will be exported to"));
}
/**
* Enable image resolution widget only for supported export types.
*
* @param imageType String with selected image type
*/
void ExportAllViewsDialog::slotImageTypeChanged(QString imageType)
{
Q_UNUSED(imageType);
QString mimeType = m_imageType->currentType();
bool hide = mimeType == QStringLiteral("image/x-dot") ||
mimeType == QStringLiteral("image/x-eps") ||
mimeType == QStringLiteral("image/svg+xml");
m_imageResolution->setVisible(!hide);
}
| 2,297
|
C++
|
.cpp
| 66
| 31.712121
| 122
| 0.753493
|
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,291
|
singlepagedialogbase.cpp
|
KDE_umbrello/umbrello/dialogs/singlepagedialogbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "singlepagedialogbase.h"
// app include
#include "debug_utils.h"
#include "uml.h"
// kde include
#include <KLocalizedString>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QPushButton>
DEBUG_REGISTER(SinglePageDialogBase)
/**
* Constructor
*/
SinglePageDialogBase::SinglePageDialogBase(QWidget *parent, bool withApplyButton, bool withSearchButton)
: QDialog(parent),
m_mainWidget(nullptr)
{
setModal(true);
QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Ok | QDialogButtonBox::Cancel;
// buttons |= QDialogButtonBox::Help;
if (withApplyButton)
buttons |= QDialogButtonBox::Apply;
m_buttonBox = new QDialogButtonBox(buttons);
if (withSearchButton)
m_buttonBox->button(QDialogButtonBox::Ok)->setText(i18n("Search"));
connect(m_buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(slotClicked(QAbstractButton*)));
QVBoxLayout *mainLayout = new QVBoxLayout;
setLayout(mainLayout);
QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok);
okButton->setDefault(true);
okButton->setShortcut(Qt::CTRL | Qt::Key_Return);
connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
mainLayout->addWidget(m_buttonBox);
if (withSearchButton)
okButton->setText(i18n("Search"));
okButton->setDefault(true);
connect(okButton, SIGNAL(clicked()), this, SLOT(slotOk()));
if (withApplyButton)
connect(m_buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(slotApply()));
}
SinglePageDialogBase::~SinglePageDialogBase()
{
}
/**
* Apply dialog changes to the related object.
*
* This method could be overridden in derived dialogs to suppport post dialog applying.
*
* @return true apply succeeds
* @return false apply does not succeed
*/
bool SinglePageDialogBase::apply()
{
logDebug0("SinglePageDialogBase::apply: no derived apply() method present, "
"called empty base implementation");
return true;
}
void SinglePageDialogBase::setCaption(const QString &caption)
{
setWindowTitle(caption);
}
/**
* Sets the main widget of the dialog.
*/
void SinglePageDialogBase::setMainWidget(QWidget *widget)
{
if (widget == m_mainWidget)
return;
m_mainWidget = widget;
if (m_mainWidget && m_mainWidget->layout()) {
// Avoid double-margin problem
m_mainWidget ->layout()->setContentsMargins({});
}
delete layout();
if (!m_mainWidget)
return;
QVBoxLayout* vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins({});
vlayout->addWidget(m_mainWidget);
QHBoxLayout* hlayout = new QHBoxLayout;
hlayout->addWidget(m_buttonBox);
hlayout->setContentsMargins (8,0,8,8);
vlayout->addLayout(hlayout);
setLayout(vlayout);
}
/**
* Set the text of a dedicated button.
* @param code button code
* @param text button text
*/
void SinglePageDialogBase::setButtonText(SinglePageDialogBase::ButtonCode code, const QString &text)
{
switch(code) {
case Ok:
m_buttonBox->button(QDialogButtonBox::Ok)->setText(text);
break;
case Apply:
m_buttonBox->button(QDialogButtonBox::Apply)->setText(text);
break;
case Cancel:
m_buttonBox->button(QDialogButtonBox::Cancel)->setText(text);
break;
}
}
/**
* @return The main widget. Will return `this` as the mainWidget
* if none was set before. This way you can write
* \code
* ui.setupUi(mainWidget());
* \endcode
* when using designer.
*/
QWidget *SinglePageDialogBase::mainWidget()
{
if (m_mainWidget)
return m_mainWidget;
return this;
}
/**
* Used when the Apply button is clicked. Calls apply().
*/
void SinglePageDialogBase::slotApply()
{
apply();
done(Apply);
}
/**
* Used when the OK button is clicked. Calls apply().
*/
void SinglePageDialogBase::slotOk()
{
if (!validate())
return;
if (apply()) {
done(Ok);
}
}
/**
* Used when the Cancel button is clicked.
*/
void SinglePageDialogBase::slotCancel()
{
done(Cancel);
}
/**
* Used when the Cancel button is clicked.
*/
void SinglePageDialogBase::slotClicked(QAbstractButton *button)
{
if (button == m_buttonBox->button(QDialogButtonBox::Apply))
slotApply();
else if (button == m_buttonBox->button(QDialogButtonBox::Ok))
slotOk();
else if (button == m_buttonBox->button(QDialogButtonBox::Cancel))
slotCancel();
}
/**
* Enable the ok button.
* @param enable the enable value
*/
void SinglePageDialogBase::enableButtonOk(bool enable)
{
m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enable);
}
/**
* Return state of dialog input validation.
*
* The false state is used to prevent closing the dialog.
*
* @return true if dialog entries are valid
*/
bool SinglePageDialogBase::validate()
{
return true;
}
| 5,106
|
C++
|
.cpp
| 180
| 24.766667
| 106
| 0.709855
|
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,292
|
parameterpropertiesdialog.cpp
|
KDE_umbrello/umbrello/dialogs/parameterpropertiesdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "parameterpropertiesdialog.h"
// local includes
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "documentationwidget.h"
#include "defaultvaluewidget.h"
#include "umldatatypewidget.h"
#include "umlstereotypewidget.h"
#include "umltemplatelist.h"
#include "template.h"
#include "umldoc.h"
#include "dialog_utils.h"
#include "object_factory.h"
#include "stereotype.h"
// kde includes
#include <KComboBox>
#include <QLineEdit>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayout>
#include <QRadioButton>
#include <QVBoxLayout>
/**
* Constructs a ParameterPropertiesDialog.
* @param parent the parent of the dialog
* @param doc UMLDoc instance for access to classifiers and stereotypes
* @param attr the parameter to represent
*/
ParameterPropertiesDialog::ParameterPropertiesDialog(QWidget * parent, UMLDoc * doc, UMLAttribute * attr)
: SinglePageDialogBase(parent)
{
Q_ASSERT(attr);
setCaption(i18n("Parameter Properties"));
m_pUmldoc = doc;
m_pAtt = attr;
int margin = fontMetrics().height();
QFrame *frame = new QFrame(this);
setMainWidget(frame);
QVBoxLayout * topLayout = new QVBoxLayout(frame);
topLayout->setSpacing(10);
topLayout->setContentsMargins(margin, margin, margin, margin);
m_pParmGB = new QGroupBox(i18n("Properties"));
topLayout->addWidget(m_pParmGB);
QGridLayout * propLayout = new QGridLayout(m_pParmGB);
propLayout->setSpacing(10);
propLayout->setContentsMargins(margin, margin, margin, margin);
m_datatypeWidget = new UMLDatatypeWidget(m_pAtt);
m_datatypeWidget->addToLayout(propLayout, 0);
Dialog_Utils::makeLabeledEditField(propLayout, 1,
m_pNameL, i18nc("property name", "&Name:"),
m_pNameLE, attr->name());
m_defaultValueWidget = new DefaultValueWidget(attr->getType(), attr->getInitialValue(), this);
m_defaultValueWidget->addToLayout(propLayout, 2);
connect(m_datatypeWidget, SIGNAL(editTextChanged(QString)), m_defaultValueWidget, SLOT(setType(QString)));
m_stereotypeWidget = new UMLStereotypeWidget(m_pAtt);
m_stereotypeWidget->addToLayout(propLayout, 3);
m_pKindGB = new QGroupBox(i18n("Passing Direction"));
m_pKindGB->setToolTip(i18n("\"in\" is a readonly parameter, \"out\" is a writeonly parameter and \"inout\" is a parameter for reading and writing."));
QHBoxLayout * kindLayout = new QHBoxLayout(m_pKindGB);
kindLayout->setContentsMargins(margin, margin, margin, margin);
m_pIn = new QRadioButton(QString::fromLatin1("in"), m_pKindGB);
kindLayout->addWidget(m_pIn);
m_pInOut = new QRadioButton(QString::fromLatin1("inout"), m_pKindGB);
kindLayout->addWidget(m_pInOut);
m_pOut = new QRadioButton(QString::fromLatin1("out"), m_pKindGB);
kindLayout->addWidget(m_pOut);
topLayout->addWidget(m_pKindGB);
m_docWidget = new DocumentationWidget(m_pAtt);
topLayout->addWidget(m_docWidget);
// Check the proper Kind radiobutton.
Uml::ParameterDirection::Enum kind = attr->getParmKind();
if (kind == Uml::ParameterDirection::Out)
m_pOut->setChecked(true);
else if (kind == Uml::ParameterDirection::InOut)
m_pInOut->setChecked(true);
else
m_pIn->setChecked(true);
// set tab order
setTabOrder(m_pKindGB, m_datatypeWidget);
setTabOrder(m_datatypeWidget, m_pNameLE);
setTabOrder(m_pNameLE, m_defaultValueWidget);
setTabOrder(m_defaultValueWidget, m_stereotypeWidget);
setTabOrder(m_stereotypeWidget, m_pIn);
setTabOrder(m_pIn, m_docWidget);
m_pNameLE->setFocus();
}
/**
* Standard destructor.
*/
ParameterPropertiesDialog::~ParameterPropertiesDialog()
{
}
QString ParameterPropertiesDialog::getName()
{
return m_pNameLE->text();
}
QString ParameterPropertiesDialog::getInitialValue()
{
return m_defaultValueWidget->value();
}
/**
* Return the kind of the parameter (in, out, or inout).
* @return The Uml::ParameterDirection::Enum corresponding to
* the selected "Kind" radiobutton.
*/
Uml::ParameterDirection::Enum ParameterPropertiesDialog::getParmKind()
{
Uml::ParameterDirection::Enum pk = Uml::ParameterDirection::In;
if (m_pOut->isChecked())
pk = Uml::ParameterDirection::Out;
else if (m_pInOut->isChecked())
pk = Uml::ParameterDirection::InOut;
return pk;
}
/**
* Validates the fields in the dialog box.
* @return success state
*/
bool ParameterPropertiesDialog::validate()
{
// currently only validates whether the name is not null.
if (getName().trimmed().length() == 0) {
KMessageBox::error(this, i18n("You have entered an invalid parameter name."),
i18n("Parameter Name Invalid"));
return false;
}
return true;
}
bool ParameterPropertiesDialog::apply()
{
if (m_pAtt != nullptr) {
m_pAtt->setName(getName()); // set the name
m_pAtt->setParmKind(getParmKind()); // set the direction
m_stereotypeWidget->apply();
m_datatypeWidget->apply();
m_docWidget->apply();
m_pAtt->setInitialValue(m_defaultValueWidget->value()); // set the initial value
}
return true;
}
| 5,550
|
C++
|
.cpp
| 151
| 32.331126
| 154
| 0.708884
|
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,293
|
multipagedialogbase.cpp
|
KDE_umbrello/umbrello/dialogs/multipagedialogbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "multipagedialogbase.h"
// local includes
#include "associationgeneralpage.h"
#include "associationrolepage.h"
#include "associationwidget.h"
#include "debug_utils.h"
#include "icon_utils.h"
#include "notepage.h"
#include "messagewidget.h"
#include "uml.h"
#include "selectoperationpage.h"
#include "umlwidget.h"
#include "umlwidgetstylepage.h"
#include <KFontChooser>
#include <KHelpClient>
#include <KLocalizedString>
#include <KPageDialog>
#include <KPageWidget>
// qt includes
#include <QApplication>
#include <QDockWidget>
#include <QFrame>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QVBoxLayout>
DEBUG_REGISTER(MultiPageDialogBase)
/**
* Constructor
*/
MultiPageDialogBase::MultiPageDialogBase(QWidget *parent, bool withDefaultButton)
: QWidget(parent),
m_pAssocGeneralPage(nullptr),
m_notePage(nullptr),
m_operationGeneralPage(nullptr),
m_pRolePage(nullptr),
m_fontChooser(nullptr),
m_pStylePage(nullptr),
m_pageItem(nullptr),
m_pageDialog(nullptr),
m_pageWidget(nullptr),
m_useDialog(!parent || strcmp(parent->metaObject()->className(),"PropertiesWindow") != 0),
m_isModified(false)
{
if (m_useDialog) {
m_pageDialog = new KPageDialog(parent);
m_pageDialog->setModal(true);
m_pageDialog->setFaceType(KPageDialog::List);
m_pageDialog->setStandardButtons(QDialogButtonBox::Ok |
QDialogButtonBox::Apply |
QDialogButtonBox::Cancel |
QDialogButtonBox::Help);
QDialogButtonBox * dlgButtonBox = m_pageDialog->findChild<QDialogButtonBox*>(QStringLiteral("buttonbox"));
if (withDefaultButton) {
QPushButton *defaultButton = new QPushButton(i18n("Default"));
m_pageDialog->addActionButton(defaultButton);
connect(defaultButton, SIGNAL(clicked()), this, SLOT(slotDefaultClicked()));
}
connect(dlgButtonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(slotButtonClicked(QAbstractButton*)));
} else {
m_pageWidget = new KPageWidget(this);
m_pageWidget->setFaceType(KPageView::Tree);
}
}
MultiPageDialogBase::~MultiPageDialogBase()
{
delete m_pageDialog;
delete m_pageWidget;
}
void MultiPageDialogBase::slotEnableButtonOk(bool state)
{
m_pageDialog->button(QDialogButtonBox::Ok)->setEnabled(state);
m_pageDialog->button(QDialogButtonBox::Apply)->setEnabled(state);
}
/**
* Apply all used pages
*/
void MultiPageDialogBase::apply()
{
if (m_pAssocGeneralPage)
m_pAssocGeneralPage->apply();
if (m_notePage)
m_notePage->apply();
if (m_operationGeneralPage)
m_operationGeneralPage->apply();
if (m_pRolePage) {
applyAssociationRolePage();
}
if (m_pStylePage) {
applyStylePage();
}
//TODO include applying font settings data
}
void MultiPageDialogBase::setCaption(const QString &caption)
{
if (m_pageDialog)
m_pageDialog->setWindowTitle(caption);
}
void MultiPageDialogBase::accept()
{
if (m_pageDialog)
m_pageDialog->accept();
}
void MultiPageDialogBase::reject()
{
if (m_pageDialog)
m_pageDialog->reject();
}
KPageWidgetItem *MultiPageDialogBase::currentPage() const
{
if (m_pageDialog)
return m_pageDialog->currentPage();
else
return m_pageWidget->currentPage();
}
void MultiPageDialogBase::addPage(KPageWidgetItem *page)
{
if (m_pageDialog)
m_pageDialog->addPage(page);
else
m_pageWidget->addPage(page);
}
/**
* Set current page.
*
* @param page the page to set
*/
void MultiPageDialogBase::setCurrentPage(KPageWidgetItem *page)
{
if (m_pageDialog)
m_pageDialog->setCurrentPage(page);
else
m_pageWidget->setCurrentPage(page);
}
int MultiPageDialogBase::exec()
{
if (m_pageDialog)
return m_pageDialog->exec();
else {
return 0;
}
}
/**
* Return state if any data has been changed in the dialog.
*
* @return true data has been changed
*/
bool MultiPageDialogBase::isModified() const
{
return m_isModified;
}
/**
* Handle click on ok button.
*/
void MultiPageDialogBase::slotOkClicked()
{
Q_EMIT okClicked();
}
/**
* Handle click on apply button.
*/
void MultiPageDialogBase::slotApplyClicked()
{
Q_EMIT applyClicked();
}
/**
* Handle click on default button, if enabled in constructor.
*/
void MultiPageDialogBase::slotDefaultClicked()
{
Q_EMIT defaultClicked();
}
/**
* Launch khelpcenter.
*/
void MultiPageDialogBase::slotHelpClicked()
{
logDebug0("MultiPageDialogBase::slotHelpClicked is handled directly");
KHelpClient::invokeHelp(QStringLiteral("settings"), QStringLiteral("umbrello"));
}
/**
* Button clicked event handler for the dialog button box.
* @param button the button which was clicked
*/
void MultiPageDialogBase::slotButtonClicked(QAbstractButton *button)
{
if (button == (QAbstractButton*)m_pageDialog->button(QDialogButtonBox::Apply)) {
logDebug0("MultiPageDialogBase::slotButtonClicked: APPLY...");
slotApplyClicked();
}
else if (button == (QAbstractButton*)m_pageDialog->button(QDialogButtonBox::Ok)) {
logDebug0("MultiPageDialogBase::slotButtonClicked: OK...");
slotOkClicked();
}
else if (button == (QAbstractButton*)m_pageDialog->button(QDialogButtonBox::Cancel)) {
logDebug0("MultiPageDialogBase::slotButtonClicked: CANCEL...");
}
else if (button == (QAbstractButton*)m_pageDialog->button(QDialogButtonBox::Help)) {
logDebug0("MultiPageDialogBase::slotButtonClicked: HELP...");
slotHelpClicked();
}
else {
logDebug0("MultiPageDialogBase::slotButtonClicked: unhandled button role");
}
}
/**
* Handle key press event.
*
* @param event key press event
*/
void MultiPageDialogBase::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);
}
/**
* Create a property page
* @param name The Text displayed in the page list
* @param header The Text displayed above the page
* @param icon The icon to display in the page list
* @return Pointer to created frame
*/
QFrame* MultiPageDialogBase::createPage(const QString& name, const QString& header, Icon_Utils::IconType icon)
{
QFrame* page = new QFrame();
m_pageItem = new KPageWidgetItem(page, name);
if (!m_pageWidget) {
m_pageItem->setHeader(header);
m_pageItem->setIcon(QIcon(Icon_Utils::DesktopIcon(icon)));
} else
m_pageItem->setHeader(QString());
addPage(m_pageItem);
//page->setMinimumSize(310, 330);
return page;
}
/**
* create new page using a dedicated widget
* @param name The Text displayed in the page list
* @param header The Text displayed above the page
* @param icon The icon to display in the page list
* @param widget Widget to display in the page
* @return page widget item instance
*/
KPageWidgetItem *MultiPageDialogBase::createPage(const QString& name, const QString& header, Icon_Utils::IconType icon, QWidget *widget)
{
QFrame* page = createPage(name, header, icon);
QHBoxLayout * topLayout = new QHBoxLayout(page);
widget->setParent(page);
topLayout->addWidget(widget);
return m_pageItem;
}
/**
* Sets up the general settings page.
* @param widget The widget to load the initial data from
*/
void MultiPageDialogBase::setupGeneralPage(AssociationWidget *widget)
{
QFrame *page = createPage(i18nc("general settings", "General"), i18n("General Settings"), Icon_Utils::it_Properties_General);
QHBoxLayout *layout = new QHBoxLayout(page);
m_pAssocGeneralPage = new AssociationGeneralPage (page, widget);
layout->addWidget(m_pAssocGeneralPage);
}
/**
* Sets up the general page for operations
* @param widget The widget to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupGeneralPage(MessageWidget *widget)
{
m_operationGeneralPage = new SelectOperationPage(widget->umlScene()->activeView(), widget->lwClassifier(), widget);
connect(m_operationGeneralPage, SIGNAL(enableButtonOk(bool)), this, SLOT(slotEnableButtonOk(bool)));
return createPage(i18nc("general settings", "General"), i18n("General Settings"),
Icon_Utils::it_Properties_General, m_operationGeneralPage);
}
/**
* Sets up the general settings page.
* @param widget The widget to load the initial data from
*/
void MultiPageDialogBase::setupGeneralPage(NoteWidget *widget)
{
QFrame *page = createPage(i18nc("general settings", "General"), i18n("General Settings"), Icon_Utils::it_Properties_General);
QHBoxLayout *layout = new QHBoxLayout(page);
m_notePage = new NotePage (page, widget);
layout->addWidget(m_notePage);
}
/**
* Sets up the font selection page.
* @param font The font to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupFontPage(const QFont &font)
{
m_fontChooser = new KFontChooser(KFontChooser::NoDisplayFlags, this);
m_fontChooser->enableColumn(KFontChooser::StyleList, false);
m_fontChooser->setFont(font);
return createPage(i18n("Font"), i18n("Font Settings"),
Icon_Utils::it_Properties_Font, m_fontChooser);
}
/**
* Sets up the font selection page.
* @param widget The widget to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupFontPage(UMLWidget *widget)
{
return setupFontPage(widget->font());
}
/**
* Sets up the font selection page.
* @param widget The widget to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupFontPage(AssociationWidget *widget)
{
return setupFontPage(widget->font());
}
/**
* Set the font page to show the font from the given widget
* @param widget
*/
void MultiPageDialogBase::resetFontPage(QWidget *widget)
{
Q_ASSERT(m_fontChooser);
m_fontChooser->setFont(widget->font());
}
/**
* updates the font page data
* @param widget Widget to save the font data into
*/
void MultiPageDialogBase::applyFontPage(AssociationWidget *widget)
{
Q_ASSERT(m_fontChooser);
widget->lwSetFont(m_fontChooser->font());
}
void MultiPageDialogBase::applyFontPage(Settings::OptionState *state)
{
Q_ASSERT(m_fontChooser);
state->uiState.font = m_fontChooser->font();
}
/**
* updates the font page data
* @param scene Scene to save the font data into
*/
void MultiPageDialogBase::applyFontPage(UMLScene *scene)
{
Q_ASSERT(m_fontChooser);
scene->setFont(m_fontChooser->font(), true);
}
/**
* updates the font page data
* @param widget Widget to save the font data into
*/
void MultiPageDialogBase::applyFontPage(UMLWidget *widget)
{
Q_ASSERT(m_fontChooser);
widget->setFont(m_fontChooser->font());
}
/**
* Sets up the style page.
* @param widget The widget to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupStylePage(WidgetBase *widget)
{
m_pStylePage = new UMLWidgetStylePage(nullptr, widget);
return createPage(i18nc("widget style page", "Style"), i18n("Widget Style"),
Icon_Utils::it_Properties_Color, m_pStylePage);
}
/**
* Sets up the style page.
* @param widget The widget to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupStylePage(AssociationWidget *widget)
{
m_pStylePage = new UMLWidgetStylePage(nullptr, widget);
return createPage(i18nc("style page name", "Style"), i18n("Line Style"),
Icon_Utils::it_Properties_Color, m_pStylePage);
}
/**
* Updates the style page.
*/
void MultiPageDialogBase::applyStylePage()
{
Q_ASSERT(m_pStylePage);
m_pStylePage->apply();
}
/**
* Sets up the role settings page.
* @param widget The widget to load the initial data from
*/
KPageWidgetItem *MultiPageDialogBase::setupAssociationRolePage(AssociationWidget *widget)
{
m_pRolePage = new AssociationRolePage(nullptr, widget);
return createPage(i18nc("role page name", "Roles"), i18n("Role Settings"),
Icon_Utils::it_Properties_Roles, m_pRolePage);
}
/**
* Save all used pages
*/
void MultiPageDialogBase::applyAssociationRolePage()
{
Q_ASSERT(m_pRolePage);
m_pRolePage->apply();
}
| 12,613
|
C++
|
.cpp
| 408
| 27.098039
| 136
| 0.717305
|
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,294
|
messagewidgetpropertiesdialog.cpp
|
KDE_umbrello/umbrello/dialogs/messagewidgetpropertiesdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2018-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "messagewidgetpropertiesdialog.h"
// local includes
#include "messagewidget.h"
#include "uml.h"
/**
* Sets up an Message Widget Properties Dialog.
* @param parent The parent of the dialog
* @param widget The Message Widget to display properties of.
*/
MessageWidgetPropertiesDialog::MessageWidgetPropertiesDialog (QWidget *parent, MessageWidget * widget)
: MultiPageDialogBase(parent),
m_widget(widget)
{
setupPages();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Standard destructor.
*/
MessageWidgetPropertiesDialog::~MessageWidgetPropertiesDialog()
{
}
void MessageWidgetPropertiesDialog::slotOk()
{
slotApply();
accept();
}
void MessageWidgetPropertiesDialog::slotApply()
{
MultiPageDialogBase::apply();
if (m_widget) {
applyFontPage(m_widget);
}
}
void MessageWidgetPropertiesDialog::setupPages()
{
setupGeneralPage(m_widget);
setupStylePage(m_widget);
setupFontPage(m_widget);
}
| 1,219
|
C++
|
.cpp
| 46
| 23.73913
| 102
| 0.747423
|
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,295
|
umloperationdialog.cpp
|
KDE_umbrello/umbrello/dialogs/umloperationdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umloperationdialog.h"
//app includes
#include "debug_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "operation.h"
#include "classifier.h"
#include "template.h"
#include "dialogspopupmenu.h"
#include "umlattributelist.h"
#include "umldatatypewidget.h"
#include "umlstereotypewidget.h"
#include "classifierlistitem.h"
#include "documentationwidget.h"
#include "umlclassifierlistitemlist.h"
#include "dialog_utils.h"
#include "parameterpropertiesdialog.h"
#include "stereotype.h"
#include "uniqueid.h"
#include "visibilityenumwidget.h"
//kde includes
#include <klineedit.h>
#include <kcombobox.h>
#include <KLocalizedString>
#include <KMessageBox>
//qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayout>
#include <QListWidget>
#include <QPointer>
#include <QPushButton>
#include <QRadioButton>
#include <QToolButton>
#include <QVBoxLayout>
DEBUG_REGISTER(UMLOperationDialog)
/**
* Constructor.
*/
UMLOperationDialog::UMLOperationDialog(QWidget * parent, UMLOperation * pOperation)
: SinglePageDialogBase(parent),
m_pOverrideCB(nullptr)
{
setCaption(i18n("Operation Properties"));
m_operation = pOperation;
m_doc = UMLApp::app()->document();
m_menu = nullptr;
for (int i = 0; i < N_STEREOATTRS; i++) {
m_pTagL [i] = nullptr;
m_pTagLE[i] = nullptr;
}
setupDialog();
}
/**
* Destructor.
*/
UMLOperationDialog::~UMLOperationDialog()
{
}
/**
* Sets up the dialog.
*/
void UMLOperationDialog::setupDialog()
{
QFrame *frame = new QFrame(this);
setMainWidget(frame);
int margin = fontMetrics().height();
QVBoxLayout * topLayout = new QVBoxLayout(frame);
m_pGenGB = new QGroupBox(i18n("General Properties"), frame);
m_pGenLayout = new QGridLayout(m_pGenGB);
m_pGenLayout->setColumnStretch(1, 1);
m_pGenLayout->setColumnStretch(3, 1);
m_pGenLayout->addItem(new QSpacerItem(200, 0), 0, 1);
m_pGenLayout->addItem(new QSpacerItem(200, 0), 0, 3);
m_pGenLayout->setContentsMargins(margin, margin, margin, margin);
m_pGenLayout->setSpacing(10);
Dialog_Utils::makeLabeledEditField(m_pGenLayout, 0,
m_pNameL, i18nc("operation name", "&Name:"),
m_pNameLE, m_operation->name());
m_datatypeWidget = new UMLDatatypeWidget(m_operation);
m_datatypeWidget->addToLayout(m_pGenLayout, 0, 2);
m_stereotypeWidget = new UMLStereotypeWidget(m_operation);
m_stereotypeWidget->addToLayout(m_pGenLayout, 1);
connect(m_stereotypeWidget->editField(), SIGNAL(currentTextChanged(const QString&)),
this, SLOT(slotStereoTextChanged(const QString&)));
Dialog_Utils::makeTagEditFields(m_operation, m_pGenLayout, m_pTagL, m_pTagLE);
bool isInterface = m_operation->umlPackage()->asUMLClassifier()->isInterface();
m_pAbstractCB = new QCheckBox(i18n("&Abstract operation"), m_pGenGB);
m_pAbstractCB->setChecked(m_operation->isAbstract());
m_pAbstractCB->setEnabled(!isInterface);
m_pGenLayout->addWidget(m_pAbstractCB, 2, 0);
m_pStaticCB = new QCheckBox(i18n("Classifier &scope (\"static\")"), m_pGenGB);
m_pStaticCB->setChecked(m_operation->isStatic());
m_pGenLayout->addWidget(m_pStaticCB, 2, 1);
m_pQueryCB = new QCheckBox(i18n("&Query (\"const\")"), m_pGenGB);
m_pQueryCB->setChecked(m_operation->getConst());
m_pGenLayout->addWidget(m_pQueryCB, 2, 2);
m_virtualCB = new QCheckBox(i18n("&virtual"), m_pGenGB);
m_virtualCB->setChecked(m_operation->isVirtual());
m_virtualCB->setEnabled(!isInterface);
m_pGenLayout->addWidget(m_virtualCB, 2, 3);
m_inlineCB = new QCheckBox(i18n("&inline"), m_pGenGB);
m_inlineCB->setChecked(m_operation->isInline());
m_inlineCB->setEnabled(!isInterface);
m_pGenLayout->addWidget(m_inlineCB, 2, 4);
if (Settings::optionState().codeImportState.supportCPP11) {
m_pOverrideCB = new QCheckBox(i18n("&Override"), m_pGenGB);
m_pOverrideCB->setChecked(m_operation->getOverride());
m_pOverrideCB->setEnabled(!isInterface);
m_pGenLayout->addWidget(m_pOverrideCB, 2, 5);
}
m_visibilityEnumWidget = new VisibilityEnumWidget(m_operation, this);
m_visibilityEnumWidget->setEnabled(!isInterface);
m_docWidget = new DocumentationWidget(m_operation, this);
m_pParmsGB = new QGroupBox(i18n("Parameters"), frame);
QVBoxLayout* parmsLayout = new QVBoxLayout(m_pParmsGB);
parmsLayout->setContentsMargins(margin, margin, margin, margin);
parmsLayout->setSpacing(10);
// horizontal box contains the list box and the move up/down buttons
QHBoxLayout* parmsHBoxLayout = new QHBoxLayout();
m_pParmsLW = new QListWidget(m_pParmsGB);
m_pParmsLW->setContextMenuPolicy(Qt::CustomContextMenu);
// the move up/down buttons (another vertical box)
QVBoxLayout* buttonLayout = new QVBoxLayout();
m_pUpButton = new QToolButton(m_pParmsGB);
m_pUpButton->setArrowType(Qt::UpArrow);
m_pUpButton->setEnabled(false);
buttonLayout->addWidget(m_pUpButton);
m_pDownButton = new QToolButton(m_pParmsGB);
m_pDownButton->setArrowType(Qt::DownArrow);
m_pDownButton->setEnabled(false);
buttonLayout->addWidget(m_pDownButton);
QDialogButtonBox* buttonBox = new QDialogButtonBox(m_pParmsGB);
QPushButton* newParam = buttonBox->addButton(i18n("Ne&w Parameter..."), QDialogButtonBox::ActionRole);
connect(newParam, SIGNAL(clicked()), this, SLOT(slotNewParameter()));
m_pDeleteButton = buttonBox->addButton(i18n("&Delete"), QDialogButtonBox::ActionRole);
connect(m_pDeleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteParameter()));
m_pPropertiesButton = buttonBox->addButton(i18n("&Properties"), QDialogButtonBox::ActionRole);
connect(m_pPropertiesButton, SIGNAL(clicked()), this, SLOT(slotParameterProperties()));
parmsHBoxLayout->addWidget(m_pParmsLW);
parmsHBoxLayout->addLayout(buttonLayout);
parmsLayout->addLayout(parmsHBoxLayout);
parmsLayout->addWidget(buttonBox);
topLayout->addWidget(m_pGenGB);
topLayout->addWidget(m_visibilityEnumWidget);
topLayout->addWidget(m_docWidget);
topLayout->addWidget(m_pParmsGB);
m_pDeleteButton->setEnabled(false);
m_pPropertiesButton->setEnabled(false);
m_pUpButton->setEnabled(false);
m_pDownButton->setEnabled(false);
// fill in parm list box
UMLAttributeList list = m_operation->getParmList();
for(UMLAttribute* pAtt : list) {
m_pParmsLW->addItem(pAtt->toString(Uml::SignatureType::SigNoVis));
}
// setup parm list box signals
connect(m_pUpButton, SIGNAL(clicked()), this, SLOT(slotParameterUp()));
connect(m_pDownButton, SIGNAL(clicked()), this, SLOT(slotParameterDown()));
connect(m_pParmsLW, SIGNAL(itemClicked(QListWidgetItem*)),
this, SLOT(slotParamsBoxClicked(QListWidgetItem*)));
connect(m_pParmsLW, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(slotParmRightButtonPressed(QPoint)));
connect(m_pParmsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(slotParmDoubleClick(QListWidgetItem*)));
m_pNameLE->setFocus();
connect(m_pNameLE, SIGNAL(textChanged(QString)), SLOT(slotNameChanged(QString)));
slotNameChanged(m_pNameLE->text());
}
void UMLOperationDialog::slotNameChanged(const QString &_text)
{
enableButtonOk(!_text.isEmpty());
}
void UMLOperationDialog::slotStereoTextChanged(const QString &stereoText)
{
Dialog_Utils::remakeTagEditFields(stereoText, m_operation, m_pGenLayout, m_pTagL, m_pTagLE);
}
void UMLOperationDialog::slotParmRightButtonPressed(const QPoint &p)
{
DialogsPopupMenu::TriggerType type = DialogsPopupMenu::tt_Undefined;
QListWidgetItem* item = m_pParmsLW->itemAt(p);
if (item) // pressed on an item
{
type = DialogsPopupMenu::tt_Parameter_Selected;
} else // pressed into fresh air
{
type = DialogsPopupMenu::tt_New_Parameter;
}
if (m_menu) {
m_menu->hide();
disconnect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(slotMenuSelection(QAction*)));
delete m_menu;
m_menu = nullptr;
}
DialogsPopupMenu popup(this, type);
QAction *triggered = popup.exec(m_pParmsLW->mapToGlobal(p));
slotMenuSelection(triggered);
}
void UMLOperationDialog::slotParmDoubleClick(QListWidgetItem *item)
{
if (!item) {
return;
}
// this happens, when there was no right click in the list widget
DialogsPopupMenu popup(this, DialogsPopupMenu::tt_Parameter_Selected);
QAction *triggered = popup.getAction(DialogsPopupMenu::mt_Properties);
slotMenuSelection(triggered);
}
void UMLOperationDialog::slotMenuSelection(QAction* action)
{
DialogsPopupMenu::MenuType id = DialogsPopupMenu::typeFromAction(action);
if(id == DialogsPopupMenu::mt_Rename || id == DialogsPopupMenu::mt_Properties) {
slotParameterProperties();
} else if(id == DialogsPopupMenu::mt_New_Parameter) {
slotNewParameter();
}
else if(id == DialogsPopupMenu::mt_Delete) {
slotDeleteParameter();
}
}
void UMLOperationDialog::slotNewParameter()
{
UMLAttribute *pAtt = nullptr;
QString currentName = m_operation->getUniqueParameterName();
UMLAttribute* newAttribute = new UMLAttribute(m_operation, currentName, Uml::ID::Reserved);
QPointer<ParameterPropertiesDialog> dlg = new ParameterPropertiesDialog(this, m_doc, newAttribute);
if (dlg->exec()) {
pAtt = m_operation->findParm(newAttribute->name());
if (!pAtt) {
newAttribute->setID(UniqueID::gen());
m_operation->addParm(newAttribute);
m_pParmsLW->addItem(newAttribute->toString(Uml::SignatureType::SigNoVis));
m_doc->setModified(true);
} else {
KMessageBox::information(this, i18n("The parameter name you have chosen\nis already being used in this operation."),
i18n("Parameter Name Not Unique"));
delete newAttribute;
}
} else {
delete newAttribute;
}
delete dlg;
}
void UMLOperationDialog::slotDeleteParameter()
{
UMLAttribute* pOldAtt = m_operation->getParmList().at(m_pParmsLW->row(m_pParmsLW->currentItem()));
m_operation->removeParm(pOldAtt);
m_pParmsLW->takeItem(m_pParmsLW->currentRow());
m_doc->setModified(true);
m_pDeleteButton->setEnabled(false);
m_pPropertiesButton->setEnabled(false);
m_pUpButton->setEnabled(false);
m_pDownButton->setEnabled(false);
}
void UMLOperationDialog::slotParameterProperties()
{
UMLAttribute *pAtt = nullptr, * pOldAtt = nullptr;
int position = m_pParmsLW->row(m_pParmsLW->currentItem());
pOldAtt = m_operation->getParmList().at(position);
if (!pOldAtt) {
logDebug1("UMLOperationDialog::slotParameterProperties: The impossible has occurred for: %1",
m_pParmsLW->currentItem()->text());
return;
} // should never occur
QString oldAttName = pOldAtt->name();
UMLAttribute* tempAttribute = pOldAtt->clone()->asUMLAttribute(); // create a clone of the parameter
// send the clone to the properties dialog box. it will fill in the new parameters.
QPointer<ParameterPropertiesDialog> dlg = new ParameterPropertiesDialog(this, m_doc, tempAttribute);
if (dlg->exec()) {
bool namingConflict = false;
QString newName = tempAttribute->name();
pAtt = m_operation->findParm(newName); // search whether a parameter with this name already exists
if(pAtt && pAtt != pOldAtt) {
KMessageBox::error(this, i18n("The parameter name you have chosen is already being used in this operation."),
i18n("Parameter Name Not Unique"), KMessageBox::Option(0));
namingConflict = true;
}
tempAttribute->copyInto(pOldAtt); // copy all attributes from the clone
if (namingConflict) {
pOldAtt->setName(oldAttName); // reset the name if there was a naming conflict
}
QListWidgetItem* item = m_pParmsLW->currentItem();
item->setText(pOldAtt->toString(Uml::SignatureType::SigNoVis));
m_doc->setModified(true);
}
delete tempAttribute;
delete dlg;
}
void UMLOperationDialog::slotParameterUp()
{
int row = m_pParmsLW->currentRow();
QListWidgetItem* item = m_pParmsLW->currentItem();
if (item) {
UMLAttribute* pOldAtt = m_operation->getParmList().at(m_pParmsLW->row(item));
m_operation->moveParmLeft(pOldAtt);
m_pParmsLW->takeItem(row);
m_pParmsLW->insertItem(row - 1, item);
m_doc->setModified(true);
slotParamsBoxClicked(item);
}
else {
logDebug0("UMLOperationDialog::slotParameterUp: No current item in list widget!?");
}
}
void UMLOperationDialog::slotParameterDown()
{
int row = m_pParmsLW->currentRow();
QListWidgetItem* item = m_pParmsLW->currentItem();
if (item) {
UMLAttribute* pOldAtt = m_operation->getParmList().at(m_pParmsLW->row(item));
m_operation->moveParmRight(pOldAtt);
m_pParmsLW->takeItem(row);
m_pParmsLW->insertItem(row + 1, item);
m_doc->setModified(true);
slotParamsBoxClicked(item);
}
else {
logDebug0("UMLOperationDialog::slotParameterDown: No current item in list widget!?");
}
}
/**
* Enables or disables buttons.
*/
void UMLOperationDialog::slotParamsBoxClicked(QListWidgetItem* parameterItem)
{
if (parameterItem) {
m_pDeleteButton->setEnabled(true);
m_pPropertiesButton->setEnabled(true);
int row = m_pParmsLW->row(parameterItem);
bool hasNext = (row < m_pParmsLW->count() - 1);
bool hasPrev = (row > 0);
m_pUpButton->setEnabled(hasPrev);
m_pDownButton->setEnabled(hasNext);
} else {
m_pDeleteButton->setEnabled(false);
m_pPropertiesButton->setEnabled(false);
m_pUpButton->setEnabled(false);
m_pDownButton->setEnabled(false);
}
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false.
*/
bool UMLOperationDialog::apply()
{
QString name = m_pNameLE->text();
if(name.length() == 0) {
KMessageBox::error(this, i18n("You have entered an invalid operation name."),
i18n("Operation Name Invalid"), KMessageBox::Option(0));
m_pNameLE->setText(m_operation->name());
return false;
}
UMLClassifier *classifier = m_operation->umlParent()->asUMLClassifier();
if(classifier != nullptr &&
classifier->checkOperationSignature(name, m_operation->getParmList(), m_operation))
{
QString msg = i18n("An operation with that signature already exists in %1.\n", classifier->name())
+
i18n("Choose a different name or parameter list.");
KMessageBox::error(this, msg, i18n("Operation Name Invalid"), KMessageBox::Option(0));
return false;
}
m_operation->setName(name);
m_visibilityEnumWidget->apply();
m_datatypeWidget->apply();
m_stereotypeWidget->apply();
Dialog_Utils::updateTagsFromEditFields(m_operation, m_pTagLE);
bool isAbstract = m_pAbstractCB->isChecked();
m_operation->setAbstract(isAbstract);
if (isAbstract) {
/* If any operation is abstract then the owning class needs
to be made abstract.
The inverse is not true: The fact that no operation is
abstract does not mean that the class must be non-abstract.
*/
if (classifier) {
classifier->setAbstract(true);
}
}
m_operation->setStatic(m_pStaticCB->isChecked());
m_operation->setConst(m_pQueryCB->isChecked());
m_operation->setVirtual(m_virtualCB->isChecked());
m_operation->setInline(m_inlineCB->isChecked());
if (m_pOverrideCB)
m_operation->setOverride(m_pOverrideCB->isChecked());
m_docWidget->apply();
return true;
}
| 16,285
|
C++
|
.cpp
| 397
| 35.259446
| 128
| 0.694825
|
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,296
|
selectdiagramdialog.cpp
|
KDE_umbrello/umbrello/dialogs/selectdiagramdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2019-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "selectdiagramdialog.h"
// app includes
#include "selectdiagramwidget.h"
// kde includes
#include <KLocalizedString>
SelectDiagramDialog::SelectDiagramDialog(QWidget *parent, Uml::DiagramType::Enum type, const QString ¤tName, const QString excludeName)
: SinglePageDialogBase(parent)
{
setCaption(i18n("Select diagram"));
m_widget = new SelectDiagramWidget(i18n("Diagram"), this);
m_widget->setupWidget(type, currentName, excludeName, false);
setMainWidget(m_widget);
}
SelectDiagramDialog::~SelectDiagramDialog()
{
}
Uml::ID::Type SelectDiagramDialog::currentID()
{
return m_widget->currentID();
}
| 802
|
C++
|
.cpp
| 25
| 29.6
| 141
| 0.775325
|
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,297
|
umlattributedialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlattributedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlattributedialog.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "documentationwidget.h"
#include "template.h"
#include "umldoc.h"
#include "uml.h"
#include "umldatatypewidget.h"
#include "umlstereotypewidget.h"
#include "visibilityenumwidget.h"
#include "dialog_utils.h"
#include "object_factory.h"
#include "import_utils.h"
// kde includes
#include <klineedit.h>
#include <kcombobox.h>
#include <kcompletion.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayout>
#include <QRadioButton>
#include <QVBoxLayout>
UMLAttributeDialog::UMLAttributeDialog(QWidget * pParent, UMLAttribute * pAttribute)
: SinglePageDialogBase(pParent)
{
setCaption(i18n("Attribute Properties"));
m_pAttribute = pAttribute;
for (int i = 0; i < N_STEREOATTRS; i++) {
m_pTagL [i] = nullptr;
m_pTagLE[i] = nullptr;
}
setupDialog();
}
UMLAttributeDialog::~UMLAttributeDialog()
{
}
/**
* Sets up the dialog
*/
void UMLAttributeDialog::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);
m_pValuesLayout = new QGridLayout(m_pValuesGB);
m_pValuesLayout->setContentsMargins(margin, margin, margin, margin);
m_pValuesLayout->setSpacing(10);
m_datatypeWidget = new UMLDatatypeWidget(m_pAttribute->asUMLClassifierListItem());
m_datatypeWidget->addToLayout(m_pValuesLayout, 0);
Dialog_Utils::makeLabeledEditField(m_pValuesLayout, 1,
m_pNameL, i18nc("attribute name", "&Name:"),
m_pNameLE, m_pAttribute->name());
Dialog_Utils::makeLabeledEditField(m_pValuesLayout, 2,
m_pInitialL, i18n("&Initial value:"),
m_pInitialLE, m_pAttribute->getInitialValue());
m_stereotypeWidget = new UMLStereotypeWidget(m_pAttribute);
m_stereotypeWidget->addToLayout(m_pValuesLayout, 3);
connect(m_stereotypeWidget->editField(), SIGNAL(currentTextChanged(const QString&)),
this, SLOT(slotStereoTextChanged(const QString&)));
Dialog_Utils::makeTagEditFields(m_pAttribute, m_pValuesLayout, m_pTagL, m_pTagLE, 3);
m_pStaticCB = new QCheckBox(i18n("Classifier &scope (\"static\")"), m_pValuesGB);
m_pStaticCB->setChecked(m_pAttribute->isStatic());
m_pValuesLayout->addWidget(m_pStaticCB, 4, 0);
mainLayout->addWidget(m_pValuesGB);
m_visibilityEnumWidget = new VisibilityEnumWidget(m_pAttribute, this);
m_visibilityEnumWidget->addToLayout(mainLayout);
m_docWidget = new DocumentationWidget(m_pAttribute, this);
mainLayout->addWidget(m_docWidget);
m_pNameLE->setFocus();
connect(m_pNameLE, SIGNAL(textChanged(QString)), SLOT(slotNameChanged(QString)));
slotNameChanged(m_pNameLE->text());
}
void UMLAttributeDialog::slotNameChanged(const QString &_text)
{
enableButtonOk(!_text.isEmpty());
}
void UMLAttributeDialog::slotStereoTextChanged(const QString &stereoText)
{
Dialog_Utils::remakeTagEditFields(stereoText, m_pAttribute, m_pValuesLayout, m_pTagL, m_pTagLE);
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false
*/
bool UMLAttributeDialog::apply()
{
QString name = m_pNameLE->text();
if (name.isEmpty()) {
KMessageBox::error(this, i18n("You have entered an invalid attribute name."),
i18n("Attribute Name Invalid"), KMessageBox::Options(0));
m_pNameLE->setText(m_pAttribute->name());
return false;
}
const UMLClassifier * pConcept = m_pAttribute->umlParent()->asUMLClassifier();
UMLObject *o = pConcept ? pConcept->findChildObject(name) : nullptr;
if (o && o != m_pAttribute) {
KMessageBox::error(this, i18n("The attribute name you have chosen is already being used in this operation."),
i18n("Attribute Name Not Unique"), KMessageBox::Options(0));
m_pNameLE->setText(m_pAttribute->name());
return false;
}
m_pAttribute->blockSignals(true);
m_visibilityEnumWidget->apply();
m_pAttribute->setInitialValue(m_pInitialLE->text());
m_stereotypeWidget->apply();
Dialog_Utils::updateTagsFromEditFields(m_pAttribute, m_pTagLE);
m_pAttribute->setStatic(m_pStaticCB->isChecked());
m_datatypeWidget->apply();
m_docWidget->apply();
m_pAttribute->blockSignals(false);
// trigger signals
m_pAttribute->setName(name);
// Set the scope as the default in the option state
Settings::optionState().classState.defaultAttributeScope = m_pAttribute->visibility();
return true;
}
| 5,094
|
C++
|
.cpp
| 130
| 33.9
| 117
| 0.701194
|
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,298
|
settingsdialog.cpp
|
KDE_umbrello/umbrello/dialogs/settingsdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "settingsdialog.h"
// app includes
#include "autolayoutoptionpage.h"
#include "classoptionspage.h"
#include "codeimportoptionspage.h"
#include "codegenoptionspage.h"
#include "uioptionspage.h"
#include "umlwidgetstylepage.h"
#include "codevieweroptionspage.h"
#include "generaloptionpage.h"
#include "dontaskagain.h"
#include "debug_utils.h"
#include "icon_utils.h"
#include "layoutgenerator.h"
#include "umbrellosettings.h"
// kde includes
#include <KColorButton>
// qt includes
#include <QCheckBox>
#include <QFontDialog>
#include <QGroupBox>
SettingsDialog::SettingsDialog(QWidget * parent, Settings::OptionState *state)
: MultiPageDialogBase(parent, true)
{
setCaption(i18n("Umbrello Setup"));
m_bChangesApplied = false;
m_pOptionState = state;
setupGeneralPage();
m_dontAskAgainWidget = DontAskAgainHandler::instance().createWidget();
m_pGeneralPage->layout()->addWidget(m_dontAskAgainWidget);
pageFont = setupFontPage(state->uiState.font);
setupUIPage();
setupClassPage();
setupCodeImportPage();
setupCodeGenPage();
setupCodeViewerPage(state->codeViewerState);
setupAutoLayoutPage();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
connect(this, SIGNAL(defaultClicked()), this, SLOT(slotDefault()));
}
SettingsDialog::~SettingsDialog()
{
}
/**
* Set current page
*
* @param page the page to set
*/
void SettingsDialog::setCurrentPage(PageType page)
{
KPageWidgetItem *currentPage;
switch(page) {
case FontPage:
currentPage = pageFont;
break;
case UserInterfacePage:
currentPage = pageUserInterface;
break;
case AutoLayoutPage:
currentPage = pageAutoLayout;
break;
case CodeImportPage:
currentPage = pageCodeImport;
break;
case CodeGenerationPage:
currentPage = pageCodeGen;
break;
case CodeViewerPage:
currentPage = pageCodeViewer;
break;
case ClassPage:
currentPage = pageClass;
break;
case GeneralPage:
default:
currentPage = pageGeneral;
break;
}
MultiPageDialogBase::setCurrentPage(currentPage);
}
void SettingsDialog::setupUIPage()
{
m_uiOptionsPage = new UIOptionsPage(nullptr, m_pOptionState);
pageUserInterface = createPage(i18n("User Interface"), i18n("User Interface Settings"),
Icon_Utils::it_Properties_UserInterface, m_uiOptionsPage);
}
void SettingsDialog::setupGeneralPage()
{
m_pGeneralPage = new GeneralOptionPage;
pageGeneral = createPage(i18nc("general settings page", "General"), i18n("General Settings"),
Icon_Utils::it_Properties_General, m_pGeneralPage);
m_pGeneralPage->setMinimumSize(310, 330);
}
void SettingsDialog::setupClassPage()
{
m_pClassPage = new ClassOptionsPage(nullptr, m_pOptionState, false);
pageClass = createPage(i18nc("class settings page", "Class"), i18n("Class Settings"),
Icon_Utils::it_Properties_Class, m_pClassPage);
}
void SettingsDialog::setupCodeImportPage()
{
m_pCodeImportPage = new CodeImportOptionsPage;
pageCodeImport = createPage(i18n("Code Importer"), i18n("Code Import Settings"),
Icon_Utils::it_Properties_CodeImport, m_pCodeImportPage);
}
void SettingsDialog::setupCodeGenPage()
{
m_pCodeGenPage = new CodeGenOptionsPage;
connect(m_pCodeGenPage, SIGNAL(languageChanged()), this, SLOT(slotApply()));
pageCodeGen = createPage(i18n("Code Generation"), i18n("Code Generation Settings"),
Icon_Utils::it_Properties_CodeGeneration, m_pCodeGenPage);
}
void SettingsDialog::setupCodeViewerPage(Settings::CodeViewerState options)
{
//setup code generation settings page
m_pCodeViewerPage = new CodeViewerOptionsPage(options);
pageCodeViewer = createPage(i18n("Code Viewer"), i18n("Code Viewer Settings"),
Icon_Utils::it_Properties_CodeViewer, m_pCodeViewerPage);
}
void SettingsDialog::setupAutoLayoutPage()
{
m_pAutoLayoutPage = new AutoLayoutOptionPage;
pageAutoLayout = createPage(i18n("Auto Layout"), i18n("Auto Layout Settings"),
Icon_Utils::it_Properties_AutoLayout, m_pAutoLayoutPage);
}
void SettingsDialog::slotApply()
{
applyPage(currentPage());
//do not emit signal applyClicked in the slot slotApply->infinite loop
//emit applyClicked();
}
void SettingsDialog::slotOk()
{
applyPage(pageClass);
applyPage(pageGeneral);
applyPage(pageUserInterface);
applyPage(pageCodeViewer);
applyPage(pageCodeImport);
applyPage(pageCodeGen);
applyPage(pageFont);
applyPage(pageAutoLayout);
m_pOptionState->save();
UmbrelloSettings::self()->save();
accept();
}
void SettingsDialog::slotDefault()
{
// Defaults hard coded. Make sure that this is alright.
// If defaults are set anywhere else, like in setting up config file, make sure the same.
KPageWidgetItem *current = currentPage();
if (current == pageGeneral)
{
m_pGeneralPage->setDefaults();
m_dontAskAgainWidget->setDefaults();
}
else if (current == pageFont)
{
resetFontPage(parentWidget());
}
else if (current == pageUserInterface)
{
m_uiOptionsPage->setDefaults();
}
else if (current == pageClass)
{
m_pClassPage->setDefaults();
}
else if (current == pageCodeImport)
{
m_pCodeImportPage->setDefaults();
}
else if (current == pageCodeGen)
{
}
else if (current == pageCodeViewer)
{
}
else if (current == pageAutoLayout)
{
m_pAutoLayoutPage->setDefaults();
}
}
void SettingsDialog::applyPage(KPageWidgetItem*item)
{
m_bChangesApplied = true;
if (item == pageGeneral)
{
m_pGeneralPage->apply();
m_dontAskAgainWidget->apply();
}
else if (item == pageFont)
{
applyFontPage(m_pOptionState);
}
else if (item == pageUserInterface)
{
m_uiOptionsPage->apply();
}
else if (item == pageClass)
{
m_pClassPage->apply();
}
else if (item == pageCodeImport)
{
m_pCodeImportPage->apply();
}
else if (item == pageCodeGen)
{
m_pCodeGenPage->apply();
}
else if (item == pageCodeViewer)
{
m_pCodeViewerPage->apply();
m_pOptionState->codeViewerState = m_pCodeViewerPage->getOptions();
}
else if (item == pageAutoLayout)
{
m_pAutoLayoutPage->apply();
}
}
QString SettingsDialog::getCodeGenerationLanguage()
{
return m_pCodeGenPage->getLanguage();
}
| 6,941
|
C++
|
.cpp
| 230
| 24.96087
| 97
| 0.687603
|
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,299
|
umlfiledialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlfiledialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2012-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlfiledialog.h"
#include "umlviewimageexportermodel.h"
// kde includes
#include <KLocalizedString>
UMLFileDialog::UMLFileDialog(const QUrl &startDir, const QString &filter, QWidget *parent, QWidget *widget)
: m_dialog(new QFileDialog(parent, QString(), startDir.toLocalFile(), filter))
{
Q_UNUSED(widget);
}
UMLFileDialog::~UMLFileDialog()
{
delete m_dialog;
}
int UMLFileDialog::exec()
{
return m_dialog->exec();
}
void UMLFileDialog::setCaption(const QString &caption)
{
m_dialog->setWindowTitle(caption);
}
void UMLFileDialog::setAcceptMode(QFileDialog::AcceptMode mode)
{
m_dialog->setAcceptMode(mode);
}
void UMLFileDialog::setMimeTypeFilters(const QStringList &filters)
{
m_dialog->setMimeTypeFilters(filters);
}
void UMLFileDialog::selectUrl(const QUrl &url)
{
m_dialog->selectUrl(url);
}
void UMLFileDialog::setUrl(const QUrl &url)
{
m_dialog->selectUrl(url);
}
QUrl UMLFileDialog::selectedUrl()
{
QList<QUrl> urls = m_dialog->selectedUrls();
if (urls.size() > 0)
return urls.first();
else
return QUrl();
}
void UMLFileDialog::setSelection(const QString &name)
{
m_dialog->selectFile(name);
}
| 1,349
|
C++
|
.cpp
| 54
| 22.388889
| 107
| 0.747467
|
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,300
|
codeviewerdialog.cpp
|
KDE_umbrello/umbrello/dialogs/codeviewerdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Brian Thomas <brian.thomas@gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "codeviewerdialog.h"
// local includes
#include "codedocument.h"
#include "classifiercodedocument.h"
#include "codeeditor.h"
#include "debug_utils.h"
#include "uml.h"
// qt/kde includes
#include <KLocalizedString>
#include <QString>
#include <QTabWidget>
#include <QPushButton>
#include <QDialogButtonBox>
DEBUG_REGISTER(CodeViewerDialog)
CodeViewerDialog::CodeViewerDialog (QWidget* parent, CodeDocument * doc,
Settings::CodeViewerState state)
: SinglePageDialogBase(parent), m_state(state)
{
setModal(false);
setupUi(SinglePageDialogBase::mainWidget());
initGUI();
addCodeDocument(doc);
connect(SinglePageDialogBase::m_buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), mainWidget(), SLOT(close()));
}
CodeViewerDialog::~CodeViewerDialog()
{
// no need to delete child widgets, Qt does it all for us
}
void CodeViewerDialog::initGUI()
{
setFont(state().font);
int margin = fontMetrics().height();
ui_highlightCheckBox->setChecked(state().blocksAreHighlighted);
ui_showHiddenCodeCB->setChecked (state().showHiddenBlocks);
CodeViewerDialogBase::gridLayout->setContentsMargins(margin, margin, margin, margin);
}
/**
* Adds a code document to the tabbed output.
*/
void CodeViewerDialog::addCodeDocument(CodeDocument * doc)
{
CodeEditor * page = new CodeEditor(this, doc);
const QString name = doc->getFileName();
const QString ext = doc->getFileExtension();
logDebug2("CodeViewerDialog::addCodeDocument: name=%1 / ext=%2", name, ext);
ui_tabWidget->addTab(page, (name + (ext.isEmpty() ? QString() : ext)));
connect(ui_highlightCheckBox, SIGNAL(stateChanged(int)), page, SLOT(changeHighlighting(int)));
connect(ui_showHiddenCodeCB, SIGNAL(stateChanged(int)), page, SLOT(changeShowHidden(int)));
}
/**
* Return the code viewer state.
*/
Settings::CodeViewerState CodeViewerDialog::state()
{
return m_state;
}
bool CodeViewerDialog::close()
{
// remember widget size for next time
m_state.height = height() / fontMetrics().lineSpacing();
m_state.width = width() / fontMetrics().maxWidth();
// remember block highlighting
m_state.blocksAreHighlighted = ui_highlightCheckBox->isChecked();
// remember block show status
m_state.showHiddenBlocks = ui_showHiddenCodeCB->isChecked();
// run superclass close now
return QDialog::close();
}
/**
* Sets the strings of the subwidgets using the current
* language.
*/
void CodeViewerDialog::languageChange()
{
Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage();
setWindowTitle(i18n("Code Viewer - %1", Uml::ProgrammingLanguage::toString(pl)));
}
| 2,941
|
C++
|
.cpp
| 83
| 32.120482
| 129
| 0.735935
|
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,301
|
finddialog.cpp
|
KDE_umbrello/umbrello/dialogs/finddialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2014-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent) :
SinglePageDialogBase(parent, false, true)
{
setCaption(i18n("Find"));
QFrame * frame = new QFrame(this);
setMainWidget(frame);
setupUi(mainWidget());
connect(ui_buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(slotFilterButtonClicked(int)));
ui_treeView->setChecked(true);
ui_categoryAll->setChecked(true);
}
FindDialog::~FindDialog()
{
disconnect(ui_buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(slotFilterButtonClicked(int)));
}
/**
* return entered text.
* @return text
*/
QString FindDialog::text() const
{
return ui_searchTerm->text();
}
/**
* Return user selected filter.
* @return filter enum
*/
UMLFinder::Filter FindDialog::filter() const
{
if (ui_treeView->isChecked())
return UMLFinder::TreeView;
else if (ui_CurrentDiagram->isChecked())
return UMLFinder::CurrentDiagram;
else
return UMLFinder::AllDiagrams;
}
/**
* Return user selected category.
* @return category enum
*/
UMLFinder::Category FindDialog::category() const
{
if (ui_categoryAll->isChecked())
return UMLFinder::All;
else if (ui_categoryClass->isChecked())
return UMLFinder::Classes;
else if (ui_categoryPackage->isChecked())
return UMLFinder::Packages;
else if (ui_categoryInterface->isChecked())
return UMLFinder::Interfaces;
else if (ui_categoryOperation->isChecked())
return UMLFinder::Operations;
else if (ui_categoryAttribute->isChecked())
return UMLFinder::Attributes;
else
return UMLFinder::All;
}
/**
* Handles filter radio button group click.
* @param button (-2=Treeview,-3,-4)
*/
void FindDialog::slotFilterButtonClicked(int button)
{
ui_categoryOperation->setEnabled(button == -2);
ui_categoryAttribute->setEnabled(button == -2);
if (button != -2)
ui_categoryAll->setChecked(true);
}
/**
* Override default event handler for show event.
* @param event
*/
void FindDialog::showEvent(QShowEvent *event)
{
ui_searchTerm->setFocus();
QDialog::showEvent(event);
}
| 2,278
|
C++
|
.cpp
| 82
| 24.109756
| 101
| 0.708867
|
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,302
|
codetexthighlighter.cpp
|
KDE_umbrello/umbrello/dialogs/codetexthighlighter.cpp
|
/*
CodeTextHighlighter: Syntax highlighter for the CodeTextEdit widget.
SPDX-FileCopyrightText: 2010 Nokia Corporation and /or its subsidiary(-ies) <qt-info@nokia.com>
Code based on examples of the Qt Toolkit under BSD license,
<http://doc.qt.nokia.com/4.6/richtext-syntaxhighlighter.html>.
SPDX-FileCopyrightText: 2010-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 <QRegularExpression>
#include "codetexthighlighter.h"
#include "codegenerator.h"
#include "codegenfactory.h"
#include "uml.h"
/**
* Constructor.
* Creates the highlighting rule by calling the function keywords().
* @param parent the parent QTextDocument
*/
CodeTextHighlighter::CodeTextHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
m_keywordFormat.setForeground(Qt::darkBlue);
m_keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns = keywords();
for (const QString &pattern : keywordPatterns) {
rule.pattern = QRegularExpression(pattern);
rule.format = m_keywordFormat;
m_highlightingRules.append(rule);
}
m_classFormat.setFontWeight(QFont::Bold);
m_classFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegularExpression(QString::fromLatin1("\\bQ[A-Za-z]+\\b"));
rule.format = m_classFormat;
m_highlightingRules.append(rule);
m_singleLineCommentFormat.setForeground(Qt::red);
rule.pattern = QRegularExpression(QString::fromLatin1("//[^\n]*"));
rule.format = m_singleLineCommentFormat;
m_highlightingRules.append(rule);
m_multiLineCommentFormat.setForeground(Qt::red);
m_quotationFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegularExpression(QString::fromLatin1("\".*\""));
rule.format = m_quotationFormat;
m_highlightingRules.append(rule);
m_functionFormat.setFontItalic(true);
m_functionFormat.setForeground(Qt::blue);
rule.pattern = QRegularExpression(QString::fromLatin1("\\b[A-Za-z0-9_]+(?=\\()"));
rule.format = m_functionFormat;
m_highlightingRules.append(rule);
m_commentStartExpression = QRegularExpression(QString::fromLatin1("/\\*"));
m_commentEndExpression = QRegularExpression(QString::fromLatin1("\\*/"));
}
/**
* Does highlighting the code block.
* @param text the code block to highlight
*/
void CodeTextHighlighter::highlightBlock(const QString &text)
{
for(const HighlightingRule &rule : m_highlightingRules) {
QRegularExpression expression(rule.pattern);
const QRegularExpressionMatch match = expression.match(text);
if (!match.hasMatch()) {
continue;
}
for (int i = 0; i <= match.lastCapturedIndex(); i++) {
setFormat(match.capturedStart(i), match.capturedLength(i), rule.format);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = text.indexOf(m_commentStartExpression);
// TODO: Move this to KSyntaxHighlight
while (startIndex >= 0) {
QRegularExpressionMatch m = m_commentEndExpression.match(text);
int endIndex = m.capturedStart();
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ m.capturedLength();
}
setFormat(startIndex, commentLength, m_multiLineCommentFormat);
startIndex = text.indexOf(m_commentStartExpression, startIndex + commentLength);
}
}
/**
* Create a list of keywords for the selected programming language.
* @return list of keywords
*/
QStringList CodeTextHighlighter::keywords()
{
Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage();
QStringList keywordList;
if (pl == Uml::ProgrammingLanguage::Reserved)
return keywordList; // empty
CodeGenerator* generator = CodeGenFactory::createObject(pl);
keywordList = generator->reservedKeywords();
delete generator;
// if (keywordList.size() <= 0) {
// keywordList << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b"
// << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b"
// << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b"
// << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b"
// << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b"
// << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b"
// << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b"
// << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b"
// << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b"
// << "\\bvoid\\b" << "\\bvolatile\\b";
// }
return keywordList;
}
| 5,021
|
C++
|
.cpp
| 115
| 38.582609
| 99
| 0.64999
|
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,303
|
activitydialog.cpp
|
KDE_umbrello/umbrello/dialogs/activitydialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "activitydialog.h"
//local includes
#include "umlview.h"
#include "activitywidget.h"
#include "dialog_utils.h"
#include "documentationwidget.h"
#include "icon_utils.h"
//kde includes
#include <klineedit.h>
#include <KLocalizedString>
//qt includes
#include <QCheckBox>
#include <QFrame>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QRadioButton>
/**
* Constructor.
*/
ActivityDialog::ActivityDialog(QWidget * parent, ActivityWidget * pWidget)
: MultiPageDialogBase(parent),
m_pActivityWidget(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 ActivityDialog::slotOk()
{
applyPage(pageItemStyle);
applyPage(pageItemFont);
applyPage(pageItemGeneral);
accept();
}
/**
* Entered when Apply button pressed.
*/
void ActivityDialog::slotApply()
{
applyPage(currentPage());
}
void ActivityDialog::slotShowActivityParameter()
{
m_GenPageWidgets.preL->show();
m_GenPageWidgets.preLE->show();
m_GenPageWidgets.postL->show();
m_GenPageWidgets.postLE->show();
if(!m_pActivityWidget->postconditionText().isEmpty()) {
m_GenPageWidgets.postLE->setText(m_pActivityWidget->postconditionText());
}
if (!m_pActivityWidget->preconditionText().isEmpty()) {
m_GenPageWidgets.preLE->setText(m_pActivityWidget->preconditionText());
}
}
void ActivityDialog::slotHideActivityParameter()
{
m_GenPageWidgets.preL->hide();
m_GenPageWidgets.preLE->hide();
m_GenPageWidgets.postL->hide();
m_GenPageWidgets.postLE->hide();
}
/**
* Sets up the pages of the dialog.
*/
void ActivityDialog::setupPages()
{
setupGeneralPage();
pageItemStyle = setupStylePage(m_pActivityWidget);
pageItemFont = setupFontPage(m_pActivityWidget);
}
/**
* Applies changes to the given page.
*/
void ActivityDialog::applyPage(KPageWidgetItem *item)
{
m_bChangesMade = true;
if (item == pageItemGeneral)
{
m_pActivityWidget->setName(m_GenPageWidgets.nameLE->text());
m_GenPageWidgets.docWidget->apply();
m_pActivityWidget->setPreconditionText(m_GenPageWidgets.preLE->text());
m_pActivityWidget->setPostconditionText(m_GenPageWidgets.postLE->text());
ActivityWidget::ActivityType newType = ActivityWidget::Initial;
bool setType = false;
if (m_GenPageWidgets.NormalRB->isChecked()) {
newType = ActivityWidget::Normal;
setType = true;
} else if (m_GenPageWidgets.InvokRB->isChecked()) {
newType = ActivityWidget::Invok;
setType = true;
} else if (m_GenPageWidgets.ParamRB->isChecked()) {
newType = ActivityWidget::Param;
setType = true;
}
if (setType)
m_pActivityWidget->setActivityType (newType);
}
else if (item == pageItemFont)
{
applyFontPage(m_pActivityWidget);
}
else if (item == pageItemStyle)
{
applyStylePage();
}
}
/**
* Sets up the general page of the dialog.
*/
void ActivityDialog::setupGeneralPage()
{
QString types[ ] = { i18n("Initial activity"), i18n("Activity"), i18n("End activity"), i18n("Final activity"), i18n("Branch/Merge"), i18n("Invoke action"), i18n("Parameter activity") };
ActivityWidget::ActivityType type = m_pActivityWidget->activityType();
QWidget *page = new QWidget();
QVBoxLayout* topLayout = new QVBoxLayout();
page->setLayout(topLayout);
pageItemGeneral = createPage(i18nc("general properties 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->setMargin(fontMetrics().height());
QString actType (types[ (int)type ]);
Dialog_Utils::makeLabeledEditField(generalLayout, 0,
m_GenPageWidgets.typeL, i18n("Activity type:"),
m_GenPageWidgets.typeLE, actType);
m_GenPageWidgets.typeLE->setEnabled(false);
Dialog_Utils::makeLabeledEditField(generalLayout, 1,
m_GenPageWidgets.nameL, i18n("Activity name:"),
m_GenPageWidgets.nameLE);
Dialog_Utils::makeLabeledEditField(generalLayout, 5,
m_GenPageWidgets.preL, i18n("Precondition :"),
m_GenPageWidgets.preLE);
Dialog_Utils::makeLabeledEditField(generalLayout, 6,
m_GenPageWidgets.postL, i18n("Postcondition :"),
m_GenPageWidgets.postLE);
m_GenPageWidgets.preL->hide();
m_GenPageWidgets.preLE->hide();
m_GenPageWidgets.postL->hide();
m_GenPageWidgets.postLE->hide();
m_GenPageWidgets.NormalRB = new QRadioButton(i18n("&Normal activity"));
generalLayout->addWidget(m_GenPageWidgets.NormalRB, 3, 0);
m_GenPageWidgets.InvokRB = new QRadioButton(i18n("&Invoke action "));
generalLayout->addWidget(m_GenPageWidgets.InvokRB, 3, 1);
m_GenPageWidgets.ParamRB = new QRadioButton(i18n("&Parameter activity node"));
generalLayout->addWidget(m_GenPageWidgets.ParamRB, 4, 0);
if (type == ActivityWidget::Param)
{
showParameterActivity();
}
connect(m_GenPageWidgets.ParamRB, SIGNAL(clicked()), this, SLOT(slotShowActivityParameter()));
connect(m_GenPageWidgets.NormalRB, SIGNAL(clicked()), this, SLOT(slotHideActivityParameter()));
connect(m_GenPageWidgets.InvokRB, SIGNAL(clicked()), this, SLOT(slotHideActivityParameter()));
ActivityWidget::ActivityType newType = m_pActivityWidget->activityType() ;
m_GenPageWidgets.NormalRB->setChecked(newType == ActivityWidget::Normal);
m_GenPageWidgets.InvokRB->setChecked (newType == ActivityWidget::Invok);
m_GenPageWidgets.ParamRB->setChecked (newType == ActivityWidget::Param);
m_GenPageWidgets.docWidget = new DocumentationWidget(m_pActivityWidget, (QWidget *)page);
generalLayout->addWidget(m_GenPageWidgets.docWidget, 7, 0, 1, 3);
if (type != ActivityWidget::Normal && type != ActivityWidget::Invok && type != ActivityWidget::Param) {
m_GenPageWidgets.nameLE->setEnabled(false);
m_GenPageWidgets.nameLE->setText(QString());
} else
m_GenPageWidgets.nameLE->setText(m_pActivityWidget->name());
m_GenPageWidgets.nameLE->setFocus();
}
/**
* Show the Activity Parameter entry text.
*/
void ActivityDialog::showParameterActivity()
{
m_GenPageWidgets.preL->show();
m_GenPageWidgets.preLE->show();
m_GenPageWidgets.postL->show();
m_GenPageWidgets.postLE->show();
if (!m_pActivityWidget->postconditionText().isEmpty()) {
m_GenPageWidgets.postLE->setText(m_pActivityWidget->postconditionText());
}
if (!m_pActivityWidget->preconditionText().isEmpty()) {
m_GenPageWidgets.preLE->setText(m_pActivityWidget->preconditionText());
}
}
| 7,553
|
C++
|
.cpp
| 195
| 32.707692
| 189
| 0.68779
|
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,304
|
umlcheckconstraintdialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlcheckconstraintdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlcheckconstraintdialog.h"
#include "uml.h"
#include "umldoc.h"
#include "checkconstraint.h"
// kde includes
#include <KLocalizedString>
#include <QTextEdit>
#include <QLineEdit>
// qt includes
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
UMLCheckConstraintDialog::UMLCheckConstraintDialog(QWidget* parent, UMLCheckConstraint* pCheckConstraint)
: SinglePageDialogBase(parent)
{
setCaption(i18n("Check Constraint Properties"));
m_pCheckConstraint = pCheckConstraint;
setupDialog();
}
UMLCheckConstraintDialog::~UMLCheckConstraintDialog()
{
}
/**
* Sets up the dialog
*/
void UMLCheckConstraintDialog::setupDialog()
{
QFrame *frame = new QFrame(this);
setMainWidget(frame);
//main layout contains the name fields, the text field
QVBoxLayout* mainLayout = new QVBoxLayout(frame);
mainLayout->setSpacing(15);
// 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);
QVBoxLayout* checkConditionLayout = new QVBoxLayout();
mainLayout->addItem(checkConditionLayout);
m_pCheckConditionL = new QLabel(i18n("Check Condition :"), frame);
checkConditionLayout->addWidget(m_pCheckConditionL);
m_pCheckConditionTE = new QTextEdit(frame);
checkConditionLayout->addWidget(m_pCheckConditionTE);
// set text of text edit
m_pCheckConditionTE->setText(m_pCheckConstraint->getCheckCondition());
// set text of label
m_pNameLE->setText(m_pCheckConstraint->name());
}
/**
* Apply Changes
*/
bool UMLCheckConstraintDialog::apply()
{
m_pCheckConstraint->setCheckCondition(m_pCheckConditionTE->toPlainText().trimmed());
// set name
m_pCheckConstraint->setName(m_pNameLE->text().trimmed());
// propagate changes to tree view
m_pCheckConstraint->emitModified();
return true;
}
| 2,241
|
C++
|
.cpp
| 68
| 29.514706
| 105
| 0.749187
|
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,305
|
classwizard.cpp
|
KDE_umbrello/umbrello/dialogs/classwizard.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "classwizard.h"
// local includes
#include "attribute.h"
#include "classifier.h"
#include "classifierlistitem.h"
#include "classifierlistpage.h"
#include "classgeneralpage.h"
#include "operation.h"
#include "uml.h"
#include "umldoc.h"
#include "umlclassifierlistitemlist.h"
// kde includes
#include <khelpmenu.h>
#include <KLocalizedString>
// qt includes
#include <QVBoxLayout>
#include <QWizardPage>
/**
* Constructor. Sets up the wizard and loads the wizard pages.
* Each wizard page has its own class.
* @param doc the UML document
*/
ClassWizard::ClassWizard(UMLDoc* doc)
: QWizard((QWidget*)doc->parent())
{
m_doc = doc;
//create a unique class to start with
UMLObject *pTemp = nullptr;
QString name = i18n("new_class");
QString newName = name;
QString num;
int i = 0;
m_pClass = new UMLClassifier(newName);
do {
m_pClass->setName(newName);
pTemp = m_doc->findUMLObject(newName);
num.setNum(++i);
newName = name;
newName.append(QChar::fromLatin1('_')).append(num);
} while(pTemp);
setWizardStyle(QWizard::ModernStyle);
setPixmap(QWizard::LogoPixmap, Icon_Utils::DesktopIcon(Icon_Utils::it_Code_Gen_Wizard));
setWindowTitle(i18n("Class Wizard"));
setOption(QWizard::NoBackButtonOnStartPage, true);
setOption(QWizard::HaveHelpButton, true);
connect(this, SIGNAL(helpRequested()), this, SLOT(showHelp()));
addPage(createGeneralPage());
addPage(createAttributesPage());
addPage(createOperationsPage());
}
/**
* Destructor.
*/
ClassWizard::~ClassWizard()
{
}
/**
* Create page 1 of wizard - the general class info.
*/
QWizardPage* ClassWizard::createGeneralPage()
{
m_GeneralPage = new QWizardPage;
m_GeneralPage->setTitle(i18n("New Class"));
m_GeneralPage->setSubTitle(i18n("Add general info about the new class."));
m_pGenPage = new ClassGeneralPage(m_doc, this, m_pClass);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_pGenPage);
m_GeneralPage->setLayout(layout);
return m_GeneralPage;
}
/**
* Create page 2 of wizard - the class attributes editor.
*/
QWizardPage* ClassWizard::createAttributesPage()
{
m_AttributesPage = new QWizardPage;
m_AttributesPage->setTitle(i18n("Class Attributes"));
m_AttributesPage->setSubTitle(i18n("Add attributes to the new class."));
m_pAttPage = new ClassifierListPage(this, m_pClass, m_doc, UMLObject::ot_Attribute);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_pAttPage);
m_AttributesPage->setLayout(layout);
return m_AttributesPage;
}
/**
* Create page 3 of wizard - the class operations editor.
*/
QWizardPage* ClassWizard::createOperationsPage()
{
m_OperationsPage = new QWizardPage;
m_OperationsPage->setTitle(i18n("Class Operations"));
m_OperationsPage->setSubTitle(i18n("Add operations to the new class."));
m_pOpPage = new ClassifierListPage(this, m_pClass, m_doc, UMLObject::ot_Operation);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_pOpPage);
m_OperationsPage->setLayout(layout);
return m_OperationsPage;
}
/**
* Advances to the next page. Is called when the next button is pressed.
*/
void ClassWizard::next()
{
QWizardPage* page = currentPage();
if (page == m_GeneralPage) {
m_pGenPage->apply();
} else if (page == m_AttributesPage) {
m_pAttPage->apply();
}
QWizard::next();
}
/**
* Back button was called.
*/
void ClassWizard::back()
{
QWizardPage* page = currentPage();
if (page == m_AttributesPage) {
m_pAttPage->apply();
} else if (page == m_OperationsPage) {
m_pOpPage->apply();
}
QWizard::back();
}
/**
* Finish button was called.
* @todo Calling m_pGenPage->apply() twice is ugly,
* but without the first call the documentation of the class is cleared.
*/
void ClassWizard::accept()
{
m_pGenPage->apply();
m_doc->addUMLObject(m_pClass);
m_doc->signalUMLObjectCreated(m_pClass);
// call apply of General Page again so as to bind to package
// now that the classifier object is in the document.
m_pGenPage->apply();
QWizard::accept();
}
/**
* Cancel button was called.
*/
void ClassWizard::reject()
{
m_doc->removeUMLObject(m_pClass, true);
QWizard::reject();
}
/**
* Opens Umbrello handbook. Is called when help button is pressed.
*/
void ClassWizard::showHelp()
{
KHelpMenu helpMenu(this);
helpMenu.appHelpActivated();
}
| 4,681
|
C++
|
.cpp
| 160
| 25.80625
| 92
| 0.703984
|
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,306
|
overwritedialog.cpp
|
KDE_umbrello/umbrello/dialogs/overwritedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "overwritedialog.h"
// kde includes
#include <KLocalizedString>
// qt includes
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QLabel>
#include <QLayout>
#include <QPushButton>
#include <QVBoxLayout>
/**
* Constructor sets up the dialog, adding checkbox and label.
*/
OverwriteDialog::OverwriteDialog(const QString& fileName, const QString& outputDirectory,
bool applyToAllRemaining, QWidget* parent)
: SinglePageDialogBase(parent, true)
{
setCaption(i18n("Destination File Already Exists"));
setButtonText(Ok, i18n("&Overwrite"));
setButtonText(Apply, i18n("&Generate Similar File Name"));
setButtonText(Cancel, i18n("&Do Not Generate File"));
setModal(true);
QFrame *frame = new QFrame(this);
QVBoxLayout* layout = new QVBoxLayout(frame);
layout->setContentsMargins({});
QLabel* dialogueLabel = new QLabel(i18n("The file %1 already exists in %2.\n\nUmbrello can overwrite the file, generate a similar\nfile name or not generate this file.", fileName, outputDirectory));
layout->addWidget(dialogueLabel);
m_applyToAllRemaining = new QCheckBox(i18n("&Apply to all remaining files"));
m_applyToAllRemaining->setChecked(applyToAllRemaining);
layout->addWidget(m_applyToAllRemaining);
setMainWidget(frame);
}
/**
* Destructor.
*/
OverwriteDialog::~OverwriteDialog()
{
}
/**
* @return the value of the Apply To All Remaining Files checkbox
*/
bool OverwriteDialog::applyToAllRemaining()
{
return m_applyToAllRemaining->isChecked();
}
| 1,719
|
C++
|
.cpp
| 50
| 31.02
| 202
| 0.743976
|
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,307
|
umlenumliteraldialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlenumliteraldialog.cpp
|
/*
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2015 Tzvetelin Katchov <katchov@gmail.com>
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlenumliteraldialog.h"
// app includes
#include "enumliteral.h"
#include "classifier.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "uml.h" // Only needed for log{Warn,Error}
// kde includes
#include <klineedit.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QGridLayout>
#include <QGroupBox>
#include <QVBoxLayout>
UMLEnumLiteralDialog::UMLEnumLiteralDialog(QWidget * pParent, UMLEnumLiteral * pEnumLiteral)
: SinglePageDialogBase(pParent)
{
setCaption(i18n("EnumLiteral Properties"));
m_pEnumLiteral = pEnumLiteral;
setupDialog();
}
UMLEnumLiteralDialog::~UMLEnumLiteralDialog()
{
}
/**
* Sets up the dialog
*/
void UMLEnumLiteralDialog::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);
Dialog_Utils::makeLabeledEditField(valuesLayout, 0,
m_pNameL, i18nc("literal name", "&Name:"),
m_pNameLE, m_pEnumLiteral->name());
Dialog_Utils::makeLabeledEditField(valuesLayout, 1,
m_pValueL, i18n("&Value:"),
m_pValueLE, m_pEnumLiteral->value());
mainLayout->addWidget(m_pValuesGB);
m_pNameLE->setFocus();
connect(m_pNameLE, SIGNAL(textChanged(QString)), SLOT(slotNameChanged(QString)));
slotNameChanged(m_pNameLE->text());
}
void UMLEnumLiteralDialog::slotNameChanged(const QString &_text)
{
enableButtonOk(!_text.isEmpty());
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false
*/
bool UMLEnumLiteralDialog::apply()
{
QString name = m_pNameLE->text();
if (name.isEmpty()) {
KMessageBox::error(this, i18n("You have entered an invalid attribute name."),
i18n("Attribute Name Invalid"), KMessageBox::Option(0));
m_pNameLE->setText(m_pEnumLiteral->name());
return false;
}
const UMLClassifier * pConcept = m_pEnumLiteral->umlParent()->asUMLClassifier();
if (!pConcept) {
logError1("UMLEnumLiteralDialog::apply: Could not get parent of enum literal '%1'",
m_pEnumLiteral->name());
return false;
}
UMLObject *o = pConcept->findChildObject(name);
if (o && o != m_pEnumLiteral) {
KMessageBox::error(this, i18n("The attribute name you have chosen is already being used in this operation."),
i18n("Attribute Name Not Unique"), KMessageBox::Option(0));
m_pNameLE->setText(m_pEnumLiteral->name());
return false;
}
m_pEnumLiteral->setName(name);
m_pEnumLiteral->setValue(m_pValueLE->text());
return true;
}
| 3,268
|
C++
|
.cpp
| 89
| 30.808989
| 117
| 0.675419
|
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,308
|
umlentityattributedialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlentityattributedialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2021 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "umlentityattributedialog.h"
// app includes
#include "entityattribute.h"
#include "classifier.h"
#include "umldoc.h"
#include "uml.h"
#include "umldatatypewidget.h"
#include "defaultvaluewidget.h"
#include "umlstereotypewidget.h"
#include "codegenerator.h"
#include "dialog_utils.h"
#include "object_factory.h"
#include "umlclassifierlist.h"
// kde includes
#include <klineedit.h>
#include <kcombobox.h>
#include <kcompletion.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QApplication>
#include <QCheckBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayout>
#include <QRadioButton>
#include <QVBoxLayout>
UMLEntityAttributeDialog::UMLEntityAttributeDialog(QWidget * pParent, UMLEntityAttribute * pEntityAttribute)
: SinglePageDialogBase(pParent)
{
setCaption(i18n("Entity Attribute Properties"));
m_pEntityAttribute = pEntityAttribute;
setupDialog();
}
UMLEntityAttributeDialog::~UMLEntityAttributeDialog()
{
}
/**
* Sets up the dialog.
*/
void UMLEntityAttributeDialog::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(0, margin, 0, 0);
valuesLayout->setSpacing(10);
m_datatypeWidget = new UMLDatatypeWidget(m_pEntityAttribute);
m_datatypeWidget->addToLayout(valuesLayout, 0);
Dialog_Utils::makeLabeledEditField(valuesLayout, 1,
m_pNameL, i18nc("name of entity attribute", "&Name:"),
m_pNameLE, m_pEntityAttribute->name());
m_defaultValueWidget = new DefaultValueWidget(m_pEntityAttribute->getType(), m_pEntityAttribute->getInitialValue(), this);
m_defaultValueWidget->addToLayout(valuesLayout, 2);
connect(m_datatypeWidget, SIGNAL(editTextChanged(QString)), m_defaultValueWidget, SLOT(setType(QString)));
m_stereotypeWidget = new UMLStereotypeWidget(m_pEntityAttribute);
m_stereotypeWidget->addToLayout(valuesLayout, 3);
Dialog_Utils::makeLabeledEditField(valuesLayout, 4,
m_pValuesL, i18n("Length/Values:"),
m_pValuesLE, m_pEntityAttribute->getValues());
m_pAutoIncrementCB = new QCheckBox(i18n("&Auto increment"), m_pValuesGB);
m_pAutoIncrementCB->setChecked(m_pEntityAttribute->getAutoIncrement());
valuesLayout->addWidget(m_pAutoIncrementCB, 5, 0);
m_pNullCB = new QCheckBox(i18n("Allow &null"), m_pValuesGB);
m_pNullCB->setChecked(m_pEntityAttribute->getNull());
valuesLayout->addWidget(m_pNullCB, 6, 0);
// enable/disable isNull depending on the state of Auto Increment Check Box
slotAutoIncrementStateChanged(m_pAutoIncrementCB->isChecked());
m_pAttributesL = new QLabel(i18n("Attributes:"), m_pValuesGB);
valuesLayout->addWidget(m_pAttributesL, 7, 0);
m_pAttributesCB = new KComboBox(true, m_pValuesGB);
valuesLayout->addWidget(m_pAttributesCB, 7, 1);
m_pAttributesL->setBuddy(m_pAttributesCB);
insertAttribute(m_pEntityAttribute->getAttributes());
insertAttribute(QString::fromLatin1("binary"), m_pAttributesCB->count());
insertAttribute(QString::fromLatin1("unsigned"), m_pAttributesCB->count());
insertAttribute(QString::fromLatin1("unsigned zerofill"), m_pAttributesCB->count());
mainLayout->addWidget(m_pValuesGB);
m_pScopeGB = new QGroupBox(i18n("Indexing"), frame);
QHBoxLayout* scopeLayout = new QHBoxLayout(m_pScopeGB);
scopeLayout->setContentsMargins(margin, margin, margin, margin);;
m_pNoneRB = new QRadioButton(i18n("&Not Indexed"), m_pScopeGB);
scopeLayout->addWidget(m_pNoneRB);
/*
m_pPublicRB = new QRadioButton(i18n("&Primary"), m_pScopeGB);
scopeLayout->addWidget(m_pPublicRB);
m_pProtectedRB = new QRadioButton(i18n("&Unique"), m_pScopeGB);
scopeLayout->addWidget(m_pProtectedRB);
*/
m_pPrivateRB = new QRadioButton(i18n("&Indexed"), m_pScopeGB);
scopeLayout->addWidget(m_pPrivateRB);
mainLayout->addWidget(m_pScopeGB);
UMLEntityAttribute::DBIndex_Type scope = m_pEntityAttribute->indexType();
/*
if (scope == UMLEntityAttribute::Primary)
m_pPublicRB->setChecked(true);
else if(scope == UMLEntityAttribute::Unique)
m_pProtectedRB->setChecked(true);
else */
if (scope == UMLEntityAttribute::Index)
m_pPrivateRB->setChecked(true);
else {
m_pNoneRB->setChecked(true);
}
m_pNameLE->setFocus();
connect(m_pNameLE, SIGNAL(textChanged(QString)), SLOT(slotNameChanged(QString)));
connect(m_pAutoIncrementCB, SIGNAL(clicked(bool)), this, SLOT(slotAutoIncrementStateChanged(bool)));
slotNameChanged(m_pNameLE->text());
}
void UMLEntityAttributeDialog::slotNameChanged(const QString &_text)
{
enableButtonOk(!_text.isEmpty());
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false
*/
bool UMLEntityAttributeDialog::apply()
{
QString name = m_pNameLE->text();
if (name.isEmpty()) {
KMessageBox::error(this, i18n("You have entered an invalid entity attribute name."),
i18n("Entity Attribute Name Invalid"), KMessageBox::Options(0));
m_pNameLE->setText(m_pEntityAttribute->name());
return false;
}
const UMLClassifier * pConcept = m_pEntityAttribute->umlParent()->asUMLClassifier();
UMLObject *o = pConcept ? pConcept->findChildObject(name) : nullptr;
if (o && o != m_pEntityAttribute) {
KMessageBox::error(this, i18n("The entity attribute name you have chosen is already being used in this operation."),
i18n("Entity Attribute Name Not Unique"), KMessageBox::Option(0));
m_pNameLE->setText(m_pEntityAttribute->name());
return false;
}
m_pEntityAttribute->setName(name);
m_pEntityAttribute->setInitialValue(m_defaultValueWidget->value());
m_stereotypeWidget->apply();
m_pEntityAttribute->setValues(m_pValuesLE->text());
m_pEntityAttribute->setAttributes(m_pAttributesCB->currentText());
m_pEntityAttribute->setAutoIncrement(m_pAutoIncrementCB->isChecked());
m_pEntityAttribute->setNull(m_pNullCB->isChecked());
/*
if (m_pPublicRB->isChecked()) {
m_pEntityAttribute->setIndexType(UMLEntityAttribute::Primary);
} else if (m_pProtectedRB->isChecked()) {
m_pEntityAttribute->setIndexType(UMLEntityAttribute::Unique);
} else
*/
if (m_pPrivateRB->isChecked()) {
m_pEntityAttribute->setIndexType(UMLEntityAttribute::Index);
} else {
m_pEntityAttribute->setIndexType(UMLEntityAttribute::None);
}
m_datatypeWidget->apply();
return true;
}
/**
* Inserts @p type into the type-combobox as well as its completion object.
*/
void UMLEntityAttributeDialog::insertAttribute(const QString& type, int index)
{
m_pAttributesCB->insertItem(index, type);
m_pAttributesCB->completionObject()->addItem(type);
}
/**
* Is activated when the auto increment state is changed.
*/
void UMLEntityAttributeDialog::slotAutoIncrementStateChanged(bool checked)
{
if (checked == true) {
m_pNullCB->setChecked(false);
m_pNullCB->setEnabled(false);
} else if (checked == false) {
m_pNullCB->setEnabled(true);
}
}
| 7,706
|
C++
|
.cpp
| 186
| 36.317204
| 126
| 0.716328
|
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,309
|
dialog_utils.cpp
|
KDE_umbrello/umbrello/dialogs/dialog_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 "dialog_utils.h"
// app includes
#include "debug_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "stereotype.h"
#include "umlwidget.h"
#include "dontaskagain.h"
#include "model_utils.h"
#include "widget_utils.h"
// kde includes
#include <KMessageBox>
#include <KLocalizedString>
#include <kcombobox.h>
// qt includes
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QApplication>
#include <QStyle>
DefineDontAskAgainItem(allItem, "all", i18n("Enable all messages"));
DefineDontAskAgainItem(askDeleteAssociationItem, "delete-association", i18n("Enable 'delete association' related messages"));
DefineDontAskAgainItem(askDeleteDiagramItem, "delete-diagram", i18n("Enable 'delete diagram' related messages"));
namespace Dialog_Utils {
/**
* Create a labeled text lineedit widget.
*
* @param layout The QGridLayout to use.
* @param row The row number within the QGridLayout.
* @param label The QLabel object allocated (return value)
* @param labelText The label text.
* @param editField The QLineEdit object allocated (return value)
* @param editFieldText Initialization text in the editField (optional.)
* @param columnOffset Optional column number within the QGridLayout (default: 0)
* @return a pointer to the QLineEdit so you can setFocus() if necessary
*/
QLineEdit* makeLabeledEditField(QGridLayout* layout, int row,
QLabel* &label, const QString& labelText,
QLineEdit* &editField, const QString& editFieldText /* = QString() */,
int columnOffset /* = 0 */)
{
label = new QLabel(labelText);
layout->addWidget(label, row, columnOffset);
editField = new QLineEdit(editFieldText);
layout->addWidget(editField, row, columnOffset + 1);
label->setBuddy(editField);
return editField;
}
/**
* Make labeled edit fields for stereotype tags.
* The label/line-edit pairs are arranged horizontally on the same row.
* The label texts are taken from the AttributeDefs of the object's
* UMLStereotype.
*/
void makeTagEditFields(UMLObject *o, QGridLayout *genLayout,
QLabel *pTagLabel [N_STEREOATTRS],
QLineEdit *pTagLineEdit[N_STEREOATTRS],
int row /* = 1 */)
{
UMLStereotype *stereo = o->umlStereotype();
if (stereo == nullptr)
return;
const UMLStereotype::AttributeDefs& attrDefs = stereo->getAttributeDefs();
const QStringList& tags = o->tags();
for (int i = 0; i < attrDefs.size() && i < N_STEREOATTRS; i++) {
const UMLStereotype::AttributeDef& adef = attrDefs[i];
QString tagInitVal;
if (i < tags.size())
tagInitVal = tags.at(i);
if (tagInitVal.isEmpty())
tagInitVal = adef.defaultVal;
Dialog_Utils::makeLabeledEditField(genLayout, row,
pTagLabel[i], adef.name,
pTagLineEdit[i], tagInitVal, 2 + (i * 2));
}
}
/**
* Remake labeled edit fields for stereotype tags.
* "Remake" means that the existing label/line-edit pairs are deleted
* and new ones are created afresh.
* This is useful when the object's stereotype has changed.
* The label/line-edit pairs are arranged horizontally on the same row.
* The label texts are taken from the AttributeDefs of the object's
* UMLStereotype.
*/
void remakeTagEditFields(const QString &stereoText,
UMLObject *, QGridLayout * genLayout,
QLabel * pTagLabel[N_STEREOATTRS],
QLineEdit * pTagLineEdit[N_STEREOATTRS],
int row /* = 1 */)
{
// Remove existing tag input fields
for (int i = N_STEREOATTRS - 1; i >= 0; --i) {
if (pTagLabel[i]) {
delete pTagLabel [i];
delete pTagLineEdit[i];
pTagLabel [i] = nullptr;
pTagLineEdit[i] = nullptr;
}
}
UMLStereotype *stereo = nullptr;
for(UMLStereotype *st : UMLApp::app()->document()->stereotypes()) {
if (st->name() == stereoText) {
stereo = st;
break;
}
}
if (stereo == nullptr)
return;
const UMLStereotype::AttributeDefs& attrDefs = stereo->getAttributeDefs();
for (int i = 0; i < attrDefs.size() && i < N_STEREOATTRS; i++) {
const UMLStereotype::AttributeDef& adef = attrDefs[i];
QString tagInitVal = adef.defaultVal;
Dialog_Utils::makeLabeledEditField(genLayout, row,
pTagLabel[i], adef.name,
pTagLineEdit[i], tagInitVal, 2 + (i * 2));
}
}
/**
* Update the stereotype tag values of the given UMLObject from the
* corresponding values in the given array of QLineEdit widgets.
* This is useful as the action in the slot method when the Apply or
* OK button is pressed.
*/
void updateTagsFromEditFields(UMLObject * o,
QLineEdit *pTagLineEdit[N_STEREOATTRS])
{
UMLStereotype *stereo = o->umlStereotype();
if (stereo == nullptr)
return;
const UMLStereotype::AttributeDefs& attrDefs = stereo->getAttributeDefs();
QStringList& tags = o->tags();
tags.clear();
for (int i = 0; i < attrDefs.size() && i < N_STEREOATTRS; i++) {
if (pTagLineEdit[i] == nullptr) {
logError3("updateTagsFromEditFields(%1): %2 pTagLineEdit[%3] is null",
o->name(), stereo->name(true), i);
break;
}
QString tag = pTagLineEdit[i]->text();
tags.append(tag);
}
}
/**
* Helper function for requesting a name for a UMLWidget using a dialog.
*
* @param targetWidget By-reference pointer to the widget to request the name for.
* The widget may be deallocated, and the pointer returned
* set to 0, if the user presses Cancel in the dialog.
* @param dialogTitle Title of the dialog.
* @param dialogPrompt Prompt of the dialog.
* @param defaultName Default value of the name field.
*/
void askNameForWidget(UMLWidget * &targetWidget, const QString& dialogTitle,
const QString& dialogPrompt, const QString& defaultName)
{
QString name = defaultName;
if (askName(dialogTitle, dialogPrompt, name)) {
targetWidget->setName(name);
}
else {
delete targetWidget;
targetWidget = nullptr;
}
}
/**
* Helper function for requesting a name using a dialog.
*
* @param title Title of the dialog.
* @param prompt Prompt of the dialog.
* @param name Default value of the name field.
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askName(const QString& title, const QString& prompt, QString& name)
{
bool ok;
name = QInputDialog::getText((QWidget*)UMLApp::app(), title, prompt, QLineEdit::Normal, name, &ok);
name = Model_Utils::normalize(name);
return ok;
}
/**
* Ask the user for permission to delete an association.
*
* @return true - user want to continue
* @return false - user want to cancel
*/
bool askDeleteAssociation()
{
return KMessageBox::warningContinueCancel(
UMLApp::app(),
i18n("You are about to delete an association. Do you really want to continue?"),
i18n("Delete Association"),
KStandardGuiItem::cont(),
KStandardGuiItem::cancel(),
askDeleteAssociationItem.name()) == KMessageBox::Continue;
}
/**
* Ask the user for permission to delete a diagram.
*
* @return true - user want to continue
* @return false - user want to cancel
*/
bool askDeleteDiagram(const QString &name)
{
QString text = name.isEmpty() ? i18n("You are about to delete the entire diagram.\nAre you sure?")
: i18n("Are you sure you want to delete diagram %1?", name);
return KMessageBox::warningContinueCancel(
UMLApp::app(),
text,
i18n("Delete Diagram?"),
KGuiItem(i18n("&Delete")),
KStandardGuiItem::cancel(),
askDeleteDiagramItem.name()) == KMessageBox::Continue;
}
/**
* Ask the user for a new widget name
*
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askNewName(WidgetBase::WidgetType type, QString &name)
{
QString title = Widget_Utils::newTitle(type);
QString text = Widget_Utils::newText(type);
return askName(title, text, name);
}
/**
* Ask the user for renaming a widget name
*
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askRenameName(WidgetBase::WidgetType type, QString &name)
{
QString title = Widget_Utils::renameTitle(type);
QString text = Widget_Utils::renameText(type);
return askName(title, text, name);
}
/**
* Ask the user for a default new widget name
*
* The name is predefined by the widgets type default name
*
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askDefaultNewName(WidgetBase::WidgetType type, QString &name)
{
name = Widget_Utils::defaultWidgetName(type);
return askNewName(type, name);
}
/**
* Ask the user for a new object name
*
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askNewName(UMLObject::ObjectType type, QString &name)
{
QString title = Model_Utils::newTitle(type);
QString text = Model_Utils::newText(type);
return askName(title, text, name);
}
/**
* Ask the user for renaming a widget name
*
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askRenameName(UMLObject::ObjectType type, QString &name)
{
QString title = Model_Utils::renameTitle(type);
QString text = Model_Utils::renameText(type);
return askName(title, text, name);
}
/**
* Ask the user for a default new widget name
*
* The name is predefined by the widgets type default name
*
* @return true on user pressed okay
* @return false on user pressed cancel
*/
bool askDefaultNewName(UMLObject::ObjectType type, QString &name)
{
name = Model_Utils::uniqObjectName(type, nullptr);
return askNewName(type, name);
}
/**
* Helper function for inserting available stereotypes into a KComboBox
*
* @param kcb The KComboBox into which to insert the stereotypes
* @param type The stereotype to activate
*/
void insertStereotypesSorted(KComboBox *kcb, const QString& type)
{
UMLDoc *umldoc = UMLApp::app()->document();
QStringList types;
types << QString(); // an empty stereotype is the default
for(UMLStereotype* ust : umldoc->stereotypes()) {
types << ust->name();
}
// add the given parameter
if (!types.contains(type)) {
types << type;
}
types.sort();
kcb->clear();
kcb->insertItems(-1, types);
// select the given parameter
int currentIndex = kcb->findText(type);
if (currentIndex > -1) {
kcb->setCurrentIndex(currentIndex);
}
kcb->completionObject()->addItem(type);
}
/**
* Returns the number of pixels that should be used between
* widgets inside a dialog according to the KDE standard.
* Source: kdelibs4support/src/kdeui/kdialog.cpp
*/
int spacingHint()
{
return QApplication::style()->pixelMetric(QStyle::QStyle::PM_LayoutVerticalSpacing);
}
} // end namespace Dialog_Utils
| 11,732
|
C++
|
.cpp
| 332
| 30.14759
| 125
| 0.657346
|
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,310
|
associationpropertiesdialog.cpp
|
KDE_umbrello/umbrello/dialogs/associationpropertiesdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "associationpropertiesdialog.h"
// local includes
#include "associationwidget.h"
#include "debug_utils.h"
#include "icon_utils.h"
#include "objectwidget.h"
#include "uml.h"
#include "umlobject.h"
#include "umlview.h"
// kde includes
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QFrame>
#include <QLabel>
#include <QLayout>
#include <QHBoxLayout>
/**
* Sets up an Association Properties Dialog.
* @param parent The parent of the AssociationPropertiesDialog
* @param assocWidget The Association Widget to display properties of.
* @param pageNum The page to show first.
*/
AssociationPropertiesDialog::AssociationPropertiesDialog (QWidget *parent, AssociationWidget * assocWidget, int pageNum)
: MultiPageDialogBase(parent),
m_pAssoc(assocWidget)
{
Q_UNUSED(pageNum)
setCaption(i18n("Association Properties"));
setupPages();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Standard destructor.
*/
AssociationPropertiesDialog::~AssociationPropertiesDialog()
{
}
void AssociationPropertiesDialog::slotOk()
{
slotApply();
accept();
}
void AssociationPropertiesDialog::slotApply()
{
MultiPageDialogBase::apply();
if (m_pAssoc) {
applyFontPage(m_pAssoc);
}
}
void AssociationPropertiesDialog::setupPages()
{
setupGeneralPage(m_pAssoc);
setupAssociationRolePage(m_pAssoc);
setupStylePage(m_pAssoc);
setupFontPage(m_pAssoc);
}
| 1,697
|
C++
|
.cpp
| 63
| 24.396825
| 120
| 0.756473
|
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,311
|
umlforeignkeyconstraintdialog.cpp
|
KDE_umbrello/umbrello/dialogs/umlforeignkeyconstraintdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "umlforeignkeyconstraintdialog.h"
#include "attribute.h"
#include "classifier.h"
#include "classifierlistitem.h"
#include "debug_utils.h"
#include "dialog_utils.h"
#include "entityattribute.h"
#include "enumliteral.h"
#include "enum.h"
#include "entity.h"
#include "foreignkeyconstraint.h"
#include "object_factory.h"
#include "operation.h"
#include "template.h"
#include "uml.h"
#include "umldoc.h"
#include "umlentitylist.h"
#include "uniqueconstraint.h"
#include "icon_utils.h"
#include <kcombobox.h>
#include <klineedit.h>
#include <KLocalizedString>
#include <KMessageBox>
#include <QApplication>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QTreeWidget>
#include <QVBoxLayout>
DEBUG_REGISTER(UMLForeignKeyConstraintDialog)
/**
* Sets up the UMLForeignKeyConstraintDialog
*
* @param parent The parent to the UMLForeignKeyConstraintDialog.
* @param pForeignKeyConstraint The Unique Constraint to show the properties of
*/
UMLForeignKeyConstraintDialog::UMLForeignKeyConstraintDialog(QWidget* parent, UMLForeignKeyConstraint* pForeignKeyConstraint)
: MultiPageDialogBase(parent),
m_doc(UMLApp::app()->document()),
m_pForeignKeyConstraint(pForeignKeyConstraint)
{
setCaption(i18n("Foreign Key Setup"));
setupGeneralPage();
setupColumnPage();
connect(this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect(this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
/**
* Standard destructor.
*/
UMLForeignKeyConstraintDialog::~UMLForeignKeyConstraintDialog()
{
}
/**
* Adds pair to the list.
*/
void UMLForeignKeyConstraintDialog::slotAddPair()
{
// get the index of the selected local column and referenced column
int indexL = m_ColumnWidgets.localColumnCB->currentIndex();
int indexR = m_ColumnWidgets.referencedColumnCB->currentIndex();
if (indexL == -1 || indexR == -1) {
return;
}
// local entity attribute
UMLEntityAttribute* localColumn = m_pLocalAttributeList.at(indexL);
// referenced entity attribute
UMLEntityAttribute* referencedColumn = m_pReferencedAttributeList.at(indexR);
// remove from combo boxes
m_ColumnWidgets.localColumnCB->removeItem(indexL);
m_ColumnWidgets.referencedColumnCB->removeItem(indexR);
// remove from local cache
m_pLocalAttributeList.removeAt(indexL);
m_pReferencedAttributeList.removeAt(indexR);
// add to local cache of mapping
EntityAttributePair pair = qMakePair(localColumn, referencedColumn);
m_pAttributeMapList.append(pair);
// update mapping view
QTreeWidgetItem* mapping = new QTreeWidgetItem(m_ColumnWidgets.mappingTW);
mapping->setText(0, localColumn->toString(Uml::SignatureType::SigNoVis));
mapping->setText(1, referencedColumn->toString(Uml::SignatureType::SigNoVis));
m_ColumnWidgets.mappingTW->addTopLevelItem(mapping);
slotResetWidgetState();
}
/**
* Deletes a pair from the list.
*/
void UMLForeignKeyConstraintDialog::slotDeletePair()
{
// get the index of the selected pair in the view
QTreeWidgetItem* twi = m_ColumnWidgets.mappingTW->currentItem();
int indexP = m_ColumnWidgets.mappingTW->indexOfTopLevelItem(twi);
if (indexP == -1) {
return;
}
//find pair in local cache
EntityAttributePair pair = m_pAttributeMapList.at(indexP);
// remove them from the view and the list
m_ColumnWidgets.mappingTW->takeTopLevelItem(indexP);
m_pAttributeMapList.removeAt(indexP);
// add the attributes to the local caches
m_pLocalAttributeList.append(pair.first);
m_pReferencedAttributeList.append(pair.second);
// add them to the view (combo boxes)
logDebug2("UMLForeignKeyConstraintDialog::slotDeletePair: %1 %2",
pair.first->name(), pair.second->name());
m_ColumnWidgets.localColumnCB->addItem((pair.first)->toString(Uml::SignatureType::SigNoVis));
m_ColumnWidgets.referencedColumnCB->addItem((pair.second)->toString(Uml::SignatureType::SigNoVis));
for(const EntityAttributePair& p : m_pAttributeMapList) {
logDebug4("UMLForeignKeyConstraintDialog::slotDeletePair: AttributeMapList %1 %2 / %3 %4",
p.first->name(), p.first->baseType(), p.second->name(), p.second->baseType());
}
slotResetWidgetState();
}
/**
* Checks if changes are valid and applies them if they are,
* else returns false.
*/
bool UMLForeignKeyConstraintDialog::apply()
{
// set the Referenced Entity
QString entityName = m_GeneralWidgets.referencedEntityCB->currentText();
UMLObject* uo = m_doc->findUMLObjectRecursive(Uml::ModelType::EntityRelationship,
entityName,
UMLObject::ot_Entity);
UMLEntity* ue = uo->asUMLEntity();
if (ue == nullptr) {
logDebug1("UMLForeignKeyConstraintDialog::apply: Could not find UML Entity with name %1",
entityName);
return false;
}
m_pForeignKeyConstraint->setReferencedEntity(ue);
// set all the update and delete actions
UMLForeignKeyConstraint::UpdateDeleteAction updateAction, deleteAction;
updateAction = (UMLForeignKeyConstraint::UpdateDeleteAction) m_GeneralWidgets.updateActionCB->currentIndex();
deleteAction = (UMLForeignKeyConstraint::UpdateDeleteAction) m_GeneralWidgets.deleteActionCB->currentIndex();
m_pForeignKeyConstraint->setUpdateAction(updateAction);
m_pForeignKeyConstraint->setDeleteAction(deleteAction);
// remove all existing mappings first
m_pForeignKeyConstraint->clearMappings();
// add all mappings present in local cache
for(const EntityAttributePair& pair : m_pAttributeMapList) {
if (!m_pForeignKeyConstraint->addEntityAttributePair(pair.first, pair.second)) {
return false;
}
}
// set the name
m_pForeignKeyConstraint->setName(m_GeneralWidgets.nameT->text());
// propagate changes to tree view
m_pForeignKeyConstraint->emitModified();
return true;
}
/**
* Setup the General Page.
*/
void UMLForeignKeyConstraintDialog::setupGeneralPage()
{
//setup General page
QWidget* page = new QWidget();
QVBoxLayout* topLayout = new QVBoxLayout();
page->setLayout(topLayout);
int margin = fontMetrics().height();
pageGeneral = createPage(i18nc("general page title", "General"), i18n("General Settings"),
Icon_Utils::it_Properties_General, page);
m_GeneralWidgets.generalGB = new QGroupBox(i18nc("general group title", "General"));
topLayout->addWidget(m_GeneralWidgets.generalGB);
QGridLayout* generalLayout = new QGridLayout(m_GeneralWidgets.generalGB);
generalLayout->setSpacing(Dialog_Utils::spacingHint());
generalLayout->setContentsMargins(margin, margin, margin, margin);
Dialog_Utils::makeLabeledEditField(generalLayout, 0,
m_GeneralWidgets.nameL, i18nc("label for entering name", "Name"),
m_GeneralWidgets.nameT);
m_GeneralWidgets.referencedEntityL = new QLabel(i18n("Referenced Entity"));
generalLayout->addWidget(m_GeneralWidgets.referencedEntityL, 1, 0);
m_GeneralWidgets.referencedEntityCB = new KComboBox();
generalLayout->addWidget(m_GeneralWidgets.referencedEntityCB, 1, 1);
m_GeneralWidgets.actionGB = new QGroupBox(i18n("Actions"));
topLayout->addWidget(m_GeneralWidgets.actionGB);
QGridLayout* actionLayout = new QGridLayout(m_GeneralWidgets.actionGB);
actionLayout->setSpacing(Dialog_Utils::spacingHint());
actionLayout->setContentsMargins(margin, margin, margin, margin);
m_GeneralWidgets.onUpdateL = new QLabel(i18n("On Update"));
actionLayout->addWidget(m_GeneralWidgets.onUpdateL, 0, 0);
m_GeneralWidgets.updateActionCB = new KComboBox(page);
actionLayout->addWidget(m_GeneralWidgets.updateActionCB, 0, 1);
m_GeneralWidgets.onDeleteL = new QLabel(i18n("On Delete"));
actionLayout->addWidget(m_GeneralWidgets.onDeleteL, 1, 0);
m_GeneralWidgets.deleteActionCB = new KComboBox();
actionLayout->addWidget(m_GeneralWidgets.deleteActionCB, 1, 1);
// set the name
m_GeneralWidgets.nameT->setText(m_pForeignKeyConstraint->name());
// fill up the combo boxes
// reference entity combo box
UMLEntityList entList = m_doc->entities();
for(UMLEntity* ent : entList) {
m_GeneralWidgets.referencedEntityCB->addItem(ent->name());
}
UMLEntity* referencedEntity = m_pForeignKeyConstraint->getReferencedEntity();
int index;
if (referencedEntity != nullptr) {
index = m_GeneralWidgets.referencedEntityCB->findText(referencedEntity->name());
if (index != -1)
m_GeneralWidgets.referencedEntityCB->setCurrentIndex(index);
}
m_pReferencedEntityIndex = m_GeneralWidgets.referencedEntityCB->currentIndex();
// action combo boxes
// do not change order. It is according to enum specification in foreignkeyconstraint.h
QStringList actions;
actions << i18n("No Action") << i18n("Restrict") << i18n("Cascade") << i18n("Set Null")
<< i18n("Set Default");
m_GeneralWidgets.updateActionCB->addItems(actions);
m_GeneralWidgets.deleteActionCB->addItems(actions);
m_GeneralWidgets.updateActionCB->setCurrentIndex(m_pForeignKeyConstraint->getUpdateAction());
m_GeneralWidgets.deleteActionCB->setCurrentIndex(m_pForeignKeyConstraint->getDeleteAction());
connect(m_GeneralWidgets.referencedEntityCB, SIGNAL(activated(int)), this, SLOT(slotReferencedEntityChanged(int)));
}
/**
* Setup Column Page.
*/
void UMLForeignKeyConstraintDialog::setupColumnPage()
{
//setup Columns page
QWidget* page = new QWidget();
QVBoxLayout* topLayout = new QVBoxLayout();
page->setLayout(topLayout);
pageColumn = createPage(i18n("Columns"), i18n("Columns"),
Icon_Utils::it_Properties_Columns, page);
m_ColumnWidgets.mappingTW = new QTreeWidget();
topLayout->addWidget(m_ColumnWidgets.mappingTW);
QStringList headers;
headers << i18nc("column header local", "Local") << i18nc("column header referenced", "Referenced");
m_ColumnWidgets.mappingTW->setHeaderLabels(headers);
QWidget* columns = new QWidget();
topLayout->addWidget(columns);
QGridLayout* columnsLayout = new QGridLayout(columns);
m_ColumnWidgets.localColumnL = new QLabel(i18n("Local Column"));
columnsLayout->addWidget(m_ColumnWidgets.localColumnL, 0, 0);
m_ColumnWidgets.localColumnCB = new KComboBox();
columnsLayout->addWidget(m_ColumnWidgets.localColumnCB, 0, 1);
m_ColumnWidgets.referencedColumnL = new QLabel(i18n("Referenced Column"));
columnsLayout->addWidget(m_ColumnWidgets.referencedColumnL, 1, 0);
m_ColumnWidgets.referencedColumnCB = new KComboBox();
columnsLayout->addWidget(m_ColumnWidgets.referencedColumnCB, 1, 1);
QDialogButtonBox* buttonBox = new QDialogButtonBox();
m_ColumnWidgets.addPB = buttonBox->addButton(i18n("&Add"), QDialogButtonBox::ActionRole);
connect(m_ColumnWidgets.addPB, SIGNAL(clicked()), this, SLOT(slotAddPair()));
m_ColumnWidgets.removePB = buttonBox->addButton(i18n("&Delete"), QDialogButtonBox::ActionRole);
connect(m_ColumnWidgets.removePB, SIGNAL(clicked()), this, SLOT(slotDeletePair()));
columnsLayout->addWidget(buttonBox, 2, 1);
// fill the column boxes and their local cache.
refillLocalAttributeCB();
refillReferencedAttributeCB();
QMap<UMLEntityAttribute*, UMLEntityAttribute*>::iterator i;
QMap<UMLEntityAttribute*, UMLEntityAttribute*> map = m_pForeignKeyConstraint->getEntityAttributePairs();
for (i = map.begin(); i != map.end() ; ++i) {
UMLEntityAttribute* localColumn, *referencedColumn;
localColumn = const_cast<UMLEntityAttribute*>(i.key());
referencedColumn = const_cast<UMLEntityAttribute*>(i.value());
// remove these columns from local cache
int indexL = m_pLocalAttributeList.indexOf(localColumn);
int indexR = m_pReferencedAttributeList.indexOf(referencedColumn);
m_pLocalAttributeList.removeAt(indexL);
m_pReferencedAttributeList.removeAt(indexR);
// remove them from combo boxes
// the conditions may never be violated . Just for safety though
if (indexL >= 0 && indexL < (m_ColumnWidgets.localColumnCB)->count())
m_ColumnWidgets.localColumnCB->removeItem(indexL);
if (indexR >= 0 && indexR < (m_ColumnWidgets.referencedColumnCB)->count())
m_ColumnWidgets.referencedColumnCB->removeItem(indexR);
// add to local cache
m_pAttributeMapList.append(qMakePair(localColumn, referencedColumn));
// add to view
QTreeWidgetItem* mapping = new QTreeWidgetItem(m_ColumnWidgets.mappingTW);
mapping->setText(0, localColumn->toString(Uml::SignatureType::SigNoVis));
mapping->setText(1, referencedColumn->toString(Uml::SignatureType::SigNoVis));
m_ColumnWidgets.mappingTW->insertTopLevelItem(0, mapping);
}
slotResetWidgetState();
connect(m_ColumnWidgets.mappingTW, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotResetWidgetState()));
}
/**
* Used when the Apply button is clicked.
*/
void UMLForeignKeyConstraintDialog::slotApply()
{
apply();
}
/**
* Used when the OK button is clicked. Calls apply().
*/
void UMLForeignKeyConstraintDialog::slotOk()
{
if (apply()) {
accept();
}
}
void UMLForeignKeyConstraintDialog::slotReferencedEntityChanged(int index)
{
if (index == m_pReferencedEntityIndex) {
return;
}
if (!m_pAttributeMapList.empty()) {
int result = KMessageBox::questionYesNo(this, i18n("You are attempting to change the Referenced Entity of this ForeignKey Constraint. Any unapplied changes to the mappings between local and referenced entities will be lost. Are you sure you want to continue ?"));
if (result != KMessageBox::Yes) {
// revert back to old index
m_GeneralWidgets.referencedEntityCB->setCurrentIndex(m_pReferencedEntityIndex);
return;
}
}
// set the referenced entity index to current index
m_pReferencedEntityIndex = index;
m_ColumnWidgets.mappingTW->clear();
refillReferencedAttributeCB();
refillLocalAttributeCB();
}
void UMLForeignKeyConstraintDialog::refillReferencedAttributeCB()
{
m_pReferencedAttributeList.clear();
m_ColumnWidgets.referencedColumnCB->clear();
// fill the combo boxes
UMLObject* uo = m_doc->findUMLObjectRecursive(Uml::ModelType::EntityRelationship,
m_GeneralWidgets.referencedEntityCB->currentText(),
UMLObject::ot_Entity);
const UMLEntity* ue = uo->asUMLEntity();
if (ue) {
UMLClassifierListItemList ual = ue->getFilteredList(UMLObject::ot_EntityAttribute);
for(UMLClassifierListItem* att : ual) {
m_pReferencedAttributeList.append(att->asUMLEntityAttribute());
m_ColumnWidgets.referencedColumnCB->addItem(att->toString(Uml::SignatureType::SigNoVis));
}
}
}
void UMLForeignKeyConstraintDialog::refillLocalAttributeCB()
{
m_pLocalAttributeList.clear();
m_ColumnWidgets.localColumnCB->clear();
// fill the combo boxes
const UMLEntity* ue = m_pForeignKeyConstraint->umlParent()->asUMLEntity();
if (ue) {
UMLClassifierListItemList ual = ue->getFilteredList(UMLObject::ot_EntityAttribute);
for(UMLClassifierListItem* att : ual) {
m_pLocalAttributeList.append(att->asUMLEntityAttribute());
m_ColumnWidgets.localColumnCB->addItem(att->toString(Uml::SignatureType::SigNoVis));
}
}
}
/**
* Enable/Disable the widgets in the Dialog Box.
*/
void UMLForeignKeyConstraintDialog::slotResetWidgetState()
{
m_ColumnWidgets.addPB->setEnabled(true);
m_ColumnWidgets.removePB->setEnabled(true);
m_ColumnWidgets.localColumnCB->setEnabled(true);
m_ColumnWidgets.referencedColumnCB->setEnabled(true);
// If one of the Combo Boxes is empty, then disable the Combo Box
if (m_ColumnWidgets.localColumnCB->count() == 0 || m_ColumnWidgets.referencedColumnCB->count() == 0) {
m_ColumnWidgets.localColumnCB->setEnabled(false);
m_ColumnWidgets.referencedColumnCB->setEnabled(false);
m_ColumnWidgets.addPB->setEnabled(false);
}
// get index of selected Attribute in List Box
if (m_ColumnWidgets.mappingTW->currentItem() == nullptr) {
m_ColumnWidgets.removePB->setEnabled(false);
}
}
| 16,888
|
C++
|
.cpp
| 372
| 39.575269
| 271
| 0.723336
|
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,312
|
selectoperationdialog.cpp
|
KDE_umbrello/umbrello/dialogs/selectoperationdialog.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "selectoperationdialog.h"
// local includes
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "linkwidget.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>
// C++ std
#include <algorithm>
bool caseInsensitiveLessThan(const UMLOperation *s1, const UMLOperation *s2)
{
return s1->name().toLower() < s2->name().toLower();
}
/**
* Constructs a SelectOperationDialog 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 may be associated on diagram
* @param enableAutoIncrement Flag to enable auto increment checkbox
*/
SelectOperationDialog::SelectOperationDialog(UMLView *parent, UMLClassifier * c, LinkWidget *widget, bool enableAutoIncrement)
: SinglePageDialogBase(parent),
m_id(CUSTOM),
m_pView(parent),
m_classifier(c),
m_widget(widget),
m_enableAutoIncrement(enableAutoIncrement)
{
setCaption(i18n("Select Operation"));
QFrame *frame = new QFrame(this);
setMainWidget(frame);
QVBoxLayout * topLayout = new QVBoxLayout(frame);
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);
setupOperationsList();
enableButtonOk(false);
setupDialog();
}
/**
* Standard destructor.
*/
SelectOperationDialog::~SelectOperationDialog()
{
}
/**
* Returns the operation to display.
*
* @return The operation to display.
*/
QString SelectOperationDialog::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 SelectOperationDialog::isClassOp() const
{
return (m_id == OP);
}
/**
* Set the custom operation text.
*
* @param op The operation to set as the custom operation.
*/
void SelectOperationDialog::setCustomOp(const QString &op)
{
m_pOpLE->setText(op);
slotTextChanged(op);
}
/**
* Handle auto increment checkbox click.
*/
void SelectOperationDialog::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 SelectOperationDialog::slotNewOperation()
{
UMLOperation *op = m_classifier->createOperation();
if (!op)
return;
setupOperationsList();
setClassOp(op->toString(Uml::SignatureType::SigNoVis));
enableButtonOk(true);
}
/**
* Handle combox box changes.
*/
void SelectOperationDialog::slotIndexChanged(int index)
{
if (index != -1) {
m_pOpLE->setText(QString());
m_id = OP;
enableButtonOk(true);
}
if (m_pOpCB->currentText().isEmpty()) {
enableButtonOk(false);
}
}
/**
* Handle custom line edit changes.
*/
void SelectOperationDialog::slotTextChanged(const QString &text)
{
if (text.isEmpty()) {
enableButtonOk(false);
}
else {
m_pOpCB->setCurrentIndex(-1);
m_id = CUSTOM;
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 SelectOperationDialog::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 SelectOperationDialog::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 SelectOperationDialog::getSeqNumber()
{
return m_pSeqLE->text();
}
/**
* Set the sequence number text.
*
* @param num The number to set the sequence to.
*/
void SelectOperationDialog::setSeqNumber(const QString &num)
{
m_pSeqLE->setText(num);
}
/**
* Set the flag for auto increment sequence numbering.
* @param state the state of the flag
*/
void SelectOperationDialog::setAutoIncrementSequence(bool state)
{
m_pOpAS->setChecked(state);
}
/**
* Return the flag for auto increment sequence numbering.
*/
bool SelectOperationDialog::autoIncrementSequence()
{
return m_pOpAS->isChecked();
}
/**
* internal setup function
*/
void SelectOperationDialog::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());
}
}
/**
* apply changes to the related instamces
* @return true - success
* @return false - failure
*/
bool SelectOperationDialog::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;
}
| 8,920
|
C++
|
.cpp
| 297
| 25.481481
| 126
| 0.673032
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.